Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Read Garmin FIT activities into the geospatial formats (#451)

SeoJCalive6f3fb67fd96b
diff --git a/README.ar.md b/README.ar.md
index 77342743..2e83d7ce 100644
--- a/README.ar.md
+++ b/README.ar.md
@@ -170,7 +170,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **الخطوط**: TTF, OTF, WOFF, WOFF2, EOT | فيما بينها |
| **البيانات**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | فيما بينها، وإلى CSV وXLSX (للجداول)؛<br>vCard, iCalendar ↔ CSV |
| **النماذج ثلاثية الأبعاد**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY؛<br>وFBX للقراءة | فيما بينها، معاينة PNG |
-| **البيانات الجغرافية المتجهية**: Shapefile, GeoJSON, KML, KMZ, GPX<br>ملفات CSV فيها إحداثيات | فيما بينها، وإلى CSV / XLSX / JSON؛<br>وتُحوَّل البيانات المُسقَطة (UTM, Web Mercator, Lambert, Albers) إلى خطوط الطول والعرض في WGS 84 |
+| **البيانات الجغرافية المتجهية**: Shapefile, GeoJSON, KML, KMZ, GPX<br>ملفات CSV فيها إحداثيات؛<br>وGarmin FIT للقراءة | فيما بينها، وإلى CSV / XLSX / JSON؛<br>وتُحوَّل البيانات المُسقَطة (UTM, Web Mercator, Lambert, Albers) إلى خطوط الطول والعرض في WGS 84 |
الصيغ غير المعلَّمة تعمل مباشرةً، دون Office أو Hancom Office أو LibreOffice.
أما المعلَّمة فتحتاج إلى محرك اختياري لا يُنزَّل إلا عند الحاجة: ¹ Ghostscript، ² LibreOffice، ³ Pandoc، ⁴ calibre، ⁵ FFmpeg ([التفاصيل](docs/ENGINES.md)).
diff --git a/README.es.md b/README.es.md
index 1f868322..1d74252f 100644
--- a/README.es.md
+++ b/README.es.md
@@ -164,7 +164,7 @@ Para deshacerlo, quita esas entradas en Seguridad de Windows → Control de apli
| **Tipografías**: TTF, OTF, WOFF, WOFF2, EOT | entre sí |
| **Datos**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | entre sí, CSV y XLSX (tablas);<br>vCard, iCalendar ↔ CSV |
| **Modelos 3D**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX solo lectura | entre sí, vista previa en PNG |
-| **Datos geoespaciales vectoriales**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV con coordenadas | entre sí y a CSV / XLSX / JSON;<br>los datos proyectados (UTM, Web Mercator, Lambert, Albers) salen como longitud / latitud WGS 84 |
+| **Datos geoespaciales vectoriales**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV con coordenadas;<br>Garmin FIT solo lectura | entre sí y a CSV / XLSX / JSON;<br>los datos proyectados (UTM, Web Mercator, Lambert, Albers) salen como longitud / latitud WGS 84 |
Los formatos sin marca funcionan nada más instalar, sin Office, Hancom Office ni LibreOffice.
Los marcados necesitan un motor opcional, que solo se descarga cuando hace falta: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([detalles](docs/ENGINES.md)).
diff --git a/README.fr.md b/README.fr.md
index be294962..813b3536 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -164,7 +164,7 @@ Pour annuler, supprimez ces entrées dans Sécurité Windows → Contrôle des a
| **Polices** : TTF, OTF, WOFF, WOFF2, EOT | entre elles |
| **Données** : JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | entre eux, CSV et XLSX (tableaux) ;<br>vCard, iCalendar ↔ CSV |
| **Modèles 3D** : GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ;<br>FBX en lecture | entre eux, aperçu PNG |
-| **Données géospatiales vectorielles** : Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV avec coordonnées | entre eux et CSV / XLSX / JSON ;<br>les données projetées (UTM, Web Mercator, Lambert, Albers) sortent en longitude / latitude WGS 84 |
+| **Données géospatiales vectorielles** : Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV avec coordonnées ;<br>Garmin FIT en lecture | entre eux et CSV / XLSX / JSON ;<br>les données projetées (UTM, Web Mercator, Lambert, Albers) sortent en longitude / latitude WGS 84 |
Les formats sans marque fonctionnent d'emblée, sans Office, Hancom Office ni LibreOffice.
Les formats marqués nécessitent un moteur facultatif, téléchargé seulement en cas de besoin : ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([détails](docs/ENGINES.md)).
diff --git a/README.hi.md b/README.hi.md
index 7c3d3d1b..4d4de153 100644
--- a/README.hi.md
+++ b/README.hi.md
@@ -164,7 +164,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **फ़ॉन्ट**: TTF, OTF, WOFF, WOFF2, EOT | आपस में |
| **डेटा**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | आपस में, CSV और XLSX (टेबल);<br>vCard, iCalendar ↔ CSV |
| **3D मॉडल**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX सिर्फ़ पढ़ने के लिए | आपस में, PNG प्रीव्यू |
-| **भू-स्थानिक वेक्टर**: Shapefile, GeoJSON, KML, KMZ, GPX<br>निर्देशांक वाली CSV | आपस में और CSV / XLSX / JSON;<br>प्रोजेक्टेड डेटा (UTM, Web Mercator, Lambert, Albers) WGS 84 देशांतर / अक्षांश में बदलकर आता है |
+| **भू-स्थानिक वेक्टर**: Shapefile, GeoJSON, KML, KMZ, GPX<br>निर्देशांक वाली CSV;<br>Garmin FIT सिर्फ़ पढ़ने के लिए | आपस में और CSV / XLSX / JSON;<br>प्रोजेक्टेड डेटा (UTM, Web Mercator, Lambert, Albers) WGS 84 देशांतर / अक्षांश में बदलकर आता है |
बिना निशान वाले फ़ॉर्मैट तुरंत काम करते हैं, Office, Hancom Office या LibreOffice की ज़रूरत नहीं।
निशान वाले फ़ॉर्मैट के लिए एक वैकल्पिक इंजन चाहिए, जो ज़रूरत पड़ने पर ही डाउनलोड होता है: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([विवरण](docs/ENGINES.md))।
diff --git a/README.ja.md b/README.ja.md
index a23cd78a..d060f6d6 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -167,7 +167,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **フォント**:TTF、OTF、WOFF、WOFF2、EOT | 相互変換 |
| **データ**:JSON、JSON Lines、YAML、TOML、XML<br>vCard、iCalendar | 相互変換、CSVとXLSX(表形式のデータ)。<br>vCard、iCalendar ↔ CSV |
| **3Dモデル**:GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY。<br>FBXは読み込みのみ | 相互変換、PNGプレビュー |
-| **地理空間ベクターデータ**:Shapefile、GeoJSON、KML、KMZ、GPX<br>座標付きのCSV | 相互変換、CSV/XLSX/JSON。<br>投影座標系(UTM、Webメルカトル、ランベルト、アルベルス)のデータはWGS 84の経度/緯度で出力 |
+| **地理空間ベクターデータ**:Shapefile、GeoJSON、KML、KMZ、GPX<br>座標付きのCSV。<br>Garmin FITは読み込みのみ | 相互変換、CSV/XLSX/JSON。<br>投影座標系(UTM、Webメルカトル、ランベルト、アルベルス)のデータはWGS 84の経度/緯度で出力 |
印のない形式は、Office、Hancom Office、LibreOfficeなしですぐに使えます。
印のある形式には追加の変換エンジンが必要で、必要なときにだけダウンロードされます:¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg([詳細](docs/ENGINES.md))。
diff --git a/README.ko.md b/README.ko.md
index 3696688e..2c0d5094 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -165,7 +165,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 |
| **데이터**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | 서로 변환, CSV·XLSX(표 모양 데이터);<br>vCard, iCalendar ↔ CSV |
| **3D 모델**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX는 읽기 | 서로 변환, PNG 미리보기 |
-| **지리 정보(벡터)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>좌표가 있는 CSV | 서로 변환, CSV·XLSX·JSON;<br>투영 좌표계(UTM, 웹 메르카토르, 람베르트, 알버스)는 WGS 84 경위도로 변환 |
+| **지리 정보(벡터)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>좌표가 있는 CSV;<br>Garmin FIT는 읽기 | 서로 변환, CSV·XLSX·JSON;<br>투영 좌표계(UTM, 웹 메르카토르, 람베르트, 알버스)는 WGS 84 경위도로 변환 |
표시가 없는 형식은 오피스·한컴오피스·LibreOffice 없이 바로 변환돼요.
표시가 있는 형식은 추가 엔진이 필요하고, 필요할 때만 내려받아요: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([자세히](docs/ENGINES.md)).
diff --git a/README.md b/README.md
index 065c18a7..fe3b8222 100644
--- a/README.md
+++ b/README.md
@@ -164,7 +164,7 @@ To undo it, remove the entries in Windows Security → App & browser control →
| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other |
| **Data**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | each other, CSV and XLSX (tables);<br>vCard, iCalendar ↔ CSV |
| **3D models**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX read | each other, PNG preview |
-| **Geospatial vectors**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV with coordinates | each other and CSV / XLSX / JSON;<br>projected data (UTM, Web Mercator, Lambert, Albers) comes out as WGS 84 longitude / latitude |
+| **Geospatial vectors**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV with coordinates; Garmin FIT read | each other and CSV / XLSX / JSON;<br>projected data (UTM, Web Mercator, Lambert, Albers) comes out as WGS 84 longitude / latitude |
Unmarked formats work out of the box, without Office, Hancom Office or LibreOffice.
Marked ones need an optional engine, downloaded only when needed: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([details](docs/ENGINES.md)).
diff --git a/README.pl.md b/README.pl.md
index 6ac4148a..228af92e 100644
--- a/README.pl.md
+++ b/README.pl.md
@@ -164,7 +164,7 @@ Aby to cofnąć, usuń te wpisy w Zabezpieczenia Windows → Kontrola aplikacji
| **Czcionki**: TTF, OTF, WOFF, WOFF2, EOT | między sobą |
| **Dane**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | między sobą, CSV i XLSX (tabele);<br>vCard, iCalendar ↔ CSV |
| **Modele 3D**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX tylko odczyt | między sobą, podgląd PNG |
-| **Dane geoprzestrzenne (wektorowe)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV ze współrzędnymi | między sobą oraz CSV / XLSX / JSON;<br>dane w odwzorowaniach (UTM, Web Mercator, Lambert, Albers) wychodzą jako długość / szerokość geograficzna WGS 84 |
+| **Dane geoprzestrzenne (wektorowe)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV ze współrzędnymi;<br>Garmin FIT tylko odczyt | między sobą oraz CSV / XLSX / JSON;<br>dane w odwzorowaniach (UTM, Web Mercator, Lambert, Albers) wychodzą jako długość / szerokość geograficzna WGS 84 |
Formaty bez oznaczenia działają od razu, bez pakietu Office, Hancom Office i LibreOffice.
Oznaczone wymagają opcjonalnego silnika, pobieranego tylko wtedy, gdy jest potrzebny: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([szczegóły](docs/ENGINES.md)).
diff --git a/README.pt-BR.md b/README.pt-BR.md
index 705fde9f..148464d7 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -164,7 +164,7 @@ Para desfazer, remova essas entradas em Segurança do Windows → Controle de ap
| **Fontes**: TTF, OTF, WOFF, WOFF2, EOT | entre si |
| **Dados**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | entre si, CSV e XLSX (tabelas);<br>vCard, iCalendar ↔ CSV |
| **Modelos 3D**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>leitura de FBX | entre si, prévia em PNG |
-| **Vetores geoespaciais**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV com coordenadas | entre si e CSV / XLSX / JSON;<br>dados projetados (UTM, Web Mercator, Lambert, Albers) saem como longitude / latitude em WGS 84 |
+| **Vetores geoespaciais**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV com coordenadas;<br>leitura de Garmin FIT | entre si e CSV / XLSX / JSON;<br>dados projetados (UTM, Web Mercator, Lambert, Albers) saem como longitude / latitude em WGS 84 |
Formatos sem marca funcionam na hora, sem Office, Hancom Office ou LibreOffice.
Os marcados precisam de um motor opcional, baixado só quando necessário: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([detalhes](docs/ENGINES.md)).
diff --git a/README.ru.md b/README.ru.md
index b639565c..d71e55d2 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -164,7 +164,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **Шрифты**: TTF, OTF, WOFF, WOFF2, EOT | друг в друга |
| **Данные**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | друг в друга, CSV и XLSX (таблицы);<br>vCard, iCalendar ↔ CSV |
| **3D-модели**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>FBX только чтение | друг в друга, превью в PNG |
-| **Геоданные (векторные)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV с координатами | друг в друга и CSV / XLSX / JSON;<br>данные в проекциях (UTM, Web Mercator, Ламберта, Альберса) переводятся в долготу / широту WGS 84 |
+| **Геоданные (векторные)**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV с координатами;<br>Garmin FIT только чтение | друг в друга и CSV / XLSX / JSON;<br>данные в проекциях (UTM, Web Mercator, Ламберта, Альберса) переводятся в долготу / широту WGS 84 |
Форматы без пометки работают сразу, без Office, Hancom Office и LibreOffice.
Для помеченных нужен дополнительный движок, который скачивается только при необходимости: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg ([подробнее](docs/ENGINES.md)).
diff --git a/README.th.md b/README.th.md
index d36f0524..9ea1d204 100644
--- a/README.th.md
+++ b/README.th.md
@@ -164,7 +164,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **ฟอนต์**: TTF, OTF, WOFF, WOFF2, EOT | แปลงสลับกันได้ |
| **ข้อมูล**: JSON, JSON Lines, YAML, TOML, XML<br>vCard, iCalendar | แปลงสลับกันได้, CSV และ XLSX (ตาราง);<br>vCard, iCalendar ↔ CSV |
| **โมเดล 3D**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY;<br>อ่าน FBX | แปลงสลับกันได้, แสดงภาพตัวอย่าง PNG |
-| **ข้อมูลเวกเตอร์เชิงพื้นที่**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV พร้อมพิกัด | แปลงสลับกันได้ และเป็น CSV / XLSX / JSON<br>โดยพิกัดโปรเจกชัน (UTM, Web Mercator, Lambert, Albers) จะถูกแปลงเป็น WGS 84 ลองจิจูด/ละติจูด |
+| **ข้อมูลเวกเตอร์เชิงพื้นที่**: Shapefile, GeoJSON, KML, KMZ, GPX<br>CSV พร้อมพิกัด;<br>อ่าน Garmin FIT | แปลงสลับกันได้ และเป็น CSV / XLSX / JSON<br>โดยพิกัดโปรเจกชัน (UTM, Web Mercator, Lambert, Albers) จะถูกแปลงเป็น WGS 84 ลองจิจูด/ละติจูด |
ฟอร์แมตที่ไม่มีเครื่องหมายสามารถใช้งานได้ทันทีโดยไม่ต้องติดตั้งซอฟต์แวร์เสริม<br>
ฟอร์แมตที่มีเครื่องหมายกำกับต้องการเครื่องมือเสริม ซึ่งจะดาวน์โหลดเมื่อจำเป็นเท่านั้น: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre, ⁵ FFmpeg (ดู [รายละเอียด](docs/ENGINES.md))
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ad8e6d03..c5615960 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -164,7 +164,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **字体** TTF、OTF、WOFF、WOFF2、EOT | 互相转换 |
| **数据** JSON、JSON Lines、YAML、TOML、XML<br>vCard、iCalendar | 互相转换、CSV 和 XLSX(表格数据)、<br>vCard、iCalendar ↔ CSV |
| **3D 模型** GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY,<br>FBX 仅读取 | 互相转换、PNG 预览 |
-| **地理信息(矢量)** Shapefile、GeoJSON、KML、KMZ、GPX<br>带坐标的 CSV | 互相转换、CSV / XLSX / JSON,<br>投影坐标系(UTM、Web 墨卡托、兰伯特、阿尔伯斯)会转换为 WGS 84 经纬度 |
+| **地理信息(矢量)** Shapefile、GeoJSON、KML、KMZ、GPX<br>带坐标的 CSV,<br>Garmin FIT 仅读取 | 互相转换、CSV / XLSX / JSON,<br>投影坐标系(UTM、Web 墨卡托、兰伯特、阿尔伯斯)会转换为 WGS 84 经纬度 |
未标注的格式装好即用,无需 Office、韩文办公软件或 LibreOffice。
标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg([详情](docs/ENGINES.md))。
diff --git a/README.zh-TW.md b/README.zh-TW.md
index f9d5ba01..5ebe922b 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -164,7 +164,7 @@ Set-ProcessMitigation -Name filee-cli.exe -Disable UserShadowStack
| **字型** TTF、OTF、WOFF、WOFF2、EOT | 互相轉換 |
| **資料** JSON、JSON Lines、YAML、TOML、XML<br>vCard、iCalendar | 互相轉換、CSV 和 XLSX(表格資料)、<br>vCard、iCalendar ↔ CSV |
| **3D 模型** GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY,<br>FBX 僅讀取 | 互相轉換、PNG 預覽 |
-| **地理資訊(向量)** Shapefile、GeoJSON、KML、KMZ、GPX<br>帶座標的 CSV | 互相轉換、CSV / XLSX / JSON,<br>投影座標系統(UTM、Web 麥卡托、蘭伯特、阿爾伯斯)會轉換為 WGS 84 經緯度 |
+| **地理資訊(向量)** Shapefile、GeoJSON、KML、KMZ、GPX<br>帶座標的 CSV,<br>Garmin FIT 僅讀取 | 互相轉換、CSV / XLSX / JSON,<br>投影座標系統(UTM、Web 麥卡托、蘭伯特、阿爾伯斯)會轉換為 WGS 84 經緯度 |
未標註的格式裝好即用,無需 Office、韓文文書軟體或 LibreOffice。
標註的格式需要可選引擎,只在需要時下載,分別是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg([詳情](docs/ENGINES.md))。
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index d2da97b5..b89100a9 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -27,7 +27,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |
| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX → each of them; → PNG, JPG, … (an isometric preview) |
-| **Geospatial vector data** | built in | **GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV** (longitude / latitude or WKT); projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted to WGS 84; through CSV to XLSX, JSON, … (see below) |
+| **Geospatial vector data** | built in | **GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV** (longitude / latitude or WKT); Garmin FIT (activities, read only) → each of them and CSV; projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted to WGS 84; through CSV to XLSX, JSON, … (see below) |
| rhwp | bundled with the installer (`engines/rhwp`, with the Microsoft C++ runtime, see below) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP (including ANSYS Workbench WBPZ), 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
@@ -1052,7 +1052,7 @@ binary 7.4 and 7.5, plain and compressed arrays, ASCII): a cube under a moved pa
templated material and an embedded or neighbouring texture, Z-up files in metres, rotation orders, concave polygons and
materials by polygon, and every cut or flipped byte of a file, which must read or fail with a clear message.
-## Geospatial data (GeoJSON, KML / KMZ, GPX, Shapefile, CSV)
+## Geospatial data (GeoJSON, KML / KMZ, GPX, Shapefile, CSV, FIT)
`Filee.Engines/Geo` converts geospatial **vector** data between GeoJSON, KML, KMZ, GPX, Shapefile and CSV in managed
code, with no GDAL and no download. Every reader fills one in-memory model (`GeoModel`: features, each with an optional
@@ -1084,6 +1084,36 @@ What each format keeps:
| GPX | 1.0 and 1.1; waypoints (Point), routes (LineString), tracks (LineString, or MultiLineString for several segments); `name`, `cmt`, `desc`, `src`, `sym`, `type`, `number`, `time`; `ele` as the height; `gpx_type` says which of the three a feature was | points as waypoints, lines as one track (several lines are its segments) or, with `gpx_type` = route, as routes; polygon outlines as tracks; only the fields on the left survive |
| Shapefile | Point, MultiPoint, PolyLine, Polygon and their Z types; rings sorted into polygons and holes by direction and containment; `.dbf` text, numbers, true / false, dates; deleted rows skipped; MultiPatch is refused | one Shapefile per kind of geometry present; Z types when any height is present; WGS 84 `.prj`; `.dbf` in UTF-8 with a `.cpg` |
| CSV | a `wkt` / `geom` / `geometry` / `the_geom` column (WKT or EWKT), or longitude and latitude columns (`lon`, `lng`, `long`, `longitude`, `x`; `lat`, `latitude`, `y`; a decimal comma is fine), and `elevation` / `alt` / `z`; other columns become attributes, typed; rows without a usable location are kept without a geometry | `longitude`, `latitude` (+ `elevation`) when every geometry is a point, else a `wkt` column; then the attributes. A dataset that already has a longitude or latitude attribute gets `wkt` so the file reads back unchanged |
+| FIT | Garmin activity files: the positions of the `record` messages (with their time and height) as one LineString, or a Point when there is only one, with the sport as the feature's type | not written |
+
+**FIT activities.** A Garmin FIT activity (from a watch or bike computer) is read only. Its recorded positions become
+one track (a single point when only one position was recorded); a time or a height is kept on the points that have one
+and never made up for the others. The feature gets the sport as its `type` attribute and the start as its `time`
+attribute: the earliest session start, else the first record time (for a single point, that point's time). Each target
+keeps what it can:
+
+- **GPX**: a track (a waypoint for a single position) with `<time>` and `<ele>` on the points that have them, and the
+ sport as `<type>`. A track has no start time of its own: when the start differs from the first point's time, or the
+ first point has no time, a notice says the start was left out.
+- **KML / KMZ**: a Point for a single position. A track is a `gx:Track` when every point has a time and a height;
+ otherwise a LineString, with the point times in a `coordTimes` `Data` entry when any point has one. `type` and `time`
+ are `ExtendedData`.
+- **GeoJSON**: a Point or a LineString, with the point times in a `coordTimes` property when any point has one, beside
+ `type` and `time`.
+- **Shapefile**: the point times are left out; `type` and `time` are `.dbf` columns. When only some points have a
+ height, the heights are dropped with a notice.
+- **CSV**: one row per record that has a time, a position or a sensor value, nine columns: `time` (UTC, ISO 8601),
+ `longitude` and `latitude` (degrees), `elevation` (m), `heart_rate` (bpm), `cadence` (rpm), `power` (W), `speed`
+ (m/s), `distance` (m). An empty cell means the value wasn't recorded or was marked invalid, or the position was out of
+ range.
+
+Left out: heart rate sent in its own messages outside the records, developer fields, laps and pauses (the track isn't
+split at them), pace, FIT files that aren't activities (courses, settings, monitoring), chained FIT files (several FIT
+files joined into one), and files with a bad CRC, which are refused. A file may be up to 64 MiB and 2,000,000
+records.
+
+**Privacy.** The outputs carry positions, times and health values such as heart rate exactly as the watch recorded them.
+Check what you share.
**Coordinate systems.** Geographic systems (degrees) and the projections most projected data uses, read from a `.prj`
(ESRI or OGC WKT 1), a GeoJSON `crs` name or an EPSG code: Transverse Mercator (UTM, Gauss-Krüger, state plane, via
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 3de1151e..9e00e338 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "لا يحتوي أي صف في CSV على موقع صالح للاستخدام",
"error.geo_unsupported_shape": "هذا النوع من الأشكال غير مدعوم",
"error.geo_too_large": "سيتجاوز ملف Shapefile حد الصيغة البالغ 2 غيغابايت",
+ "error.fit_not_fit": "هذا ليس ملف Garmin FIT",
+ "error.fit_damaged": "ملف FIT تالف أو مبتور",
+ "error.fit_chained": "الملفات المتعددة من نوع FIT المتصلة بعضها ببعض غير مدعومة بعد",
+ "error.fit_too_large": "ملف FIT كبير جدًا بحيث لا يمكن تحويله",
+ "error.fit_no_file_id": "لا يحدد ملف FIT نوع الملف",
+ "error.fit_not_activity": "ملف FIT هذا ليس نشاطًا (يتم تحويل الأنشطة فقط)",
+ "error.fit_no_positions": "لا يحتوي النشاط على مواقع مسجلة: حوّله إلى CSV أو XLSX أو JSON",
+ "error.fit_no_records": "لا يحتوي النشاط على بيانات مسجلة",
"notice.pdf_not_smaller": "تعذّر تقليل الحجم، لذا نُسخ الملف كما هو",
"notice.cad_newer_left_out": "حُذفت كائنات لا يدعمها إصدار AutoCAD المختار (أسهم توضيحية متعددة، شبكات …)",
"notice.original_kept": "تم الاحتفاظ بالأصل وحُفظت النتيجة كنسخة",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "بعض الصفوف لا تحتوي على موقع صالح، فتم الاحتفاظ بها دون شكل هندسي",
"notice.geo_field_names": "الحد الأقصى لأسماء حقول Shapefile هو 10 محارف: اختُصرت بعض الأسماء",
"notice.geo_shapefile_split": "تحتفظ Shapefile بنوع واحد من الأشكال، لذا حُفظت النقاط والخطوط والمضلعات في ملفات منفصلة",
+ "notice.geo_heights_dropped": "بعض النقاط بلا ارتفاع، ولا يمكن لملف Shapefile ترك ارتفاع نقطة واحدة فارغًا، لذا حُذفت جميع الارتفاعات",
"engine.reason.not_installed": "غير مثبّت",
"engine.reason.error": "خطأ أثناء التحقق",
"engine.reason.unsupported_platform": "غير متاح على هذا النظام",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 75d0ee92..41d9b1b8 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "No row of the CSV has a usable location",
"error.geo_unsupported_shape": "This kind of shape isn't supported",
"error.geo_too_large": "The Shapefile would pass the format's 2 GB limit",
+ "error.fit_not_fit": "This isn't a Garmin FIT file",
+ "error.fit_damaged": "The FIT file is damaged or cut short",
+ "error.fit_chained": "The file holds several FIT files one after another, which isn't supported yet",
+ "error.fit_too_large": "The FIT file is too large to convert",
+ "error.fit_no_file_id": "The FIT file doesn't say what kind of file it is",
+ "error.fit_not_activity": "This FIT file isn't an activity (only activities are converted)",
+ "error.fit_no_positions": "The activity has no recorded positions: convert it to CSV, XLSX or JSON",
+ "error.fit_no_records": "The activity has no recorded data",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
"notice.cad_newer_left_out": "Objects the chosen AutoCAD version doesn't have (multileaders, meshes …) were left out",
"notice.original_kept": "The original was kept, the result was saved as a copy",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "Some rows have no usable location and were kept without a shape",
"notice.geo_field_names": "Shapefile field names are 10 characters at most: some were shortened",
"notice.geo_shapefile_split": "A Shapefile holds one kind of shape, so points, lines and polygons were saved as separate files",
+ "notice.geo_heights_dropped": "Some points have no height and a Shapefile can't leave one out, so all heights were left out",
"engine.reason.not_installed": "Not installed",
"engine.reason.error": "Error while checking",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index c074a17f..ddb04002 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "Ninguna fila del CSV tiene una ubicación utilizable",
"error.geo_unsupported_shape": "Este tipo de forma no es compatible",
"error.geo_too_large": "El Shapefile superaría el límite de 2 GB del formato",
+ "error.fit_not_fit": "Este archivo no es un Garmin FIT",
+ "error.fit_damaged": "El archivo FIT está dañado o incompleto",
+ "error.fit_chained": "Aún no se admiten varios archivos FIT unidos uno tras otro",
+ "error.fit_too_large": "El archivo FIT es demasiado grande para convertirlo",
+ "error.fit_no_file_id": "El archivo FIT no indica qué tipo de archivo es",
+ "error.fit_not_activity": "Este archivo FIT no es una actividad (solo se convierten actividades)",
+ "error.fit_no_positions": "La actividad no tiene posiciones registradas: conviértela a CSV, XLSX o JSON",
+ "error.fit_no_records": "La actividad no tiene datos registrados",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
"notice.cad_newer_left_out": "Se omitieron objetos que la versión de AutoCAD elegida no tiene (directrices múltiples, mallas…)",
"notice.original_kept": "Se conservó el original, el resultado se guardó como copia",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "Las filas sin ubicación utilizable se guardaron sin forma",
"notice.geo_field_names": "Los nombres de campo de Shapefile tienen 10 caracteres como máximo: se acortaron algunos",
"notice.geo_shapefile_split": "Un Shapefile guarda un solo tipo de forma, así que puntos, líneas y polígonos se guardaron en archivos separados",
+ "notice.geo_heights_dropped": "Algunos puntos no tienen altura y Shapefile no puede omitirla en uno solo, así que se omitieron todas las alturas",
"engine.reason.not_installed": "No instalado",
"engine.reason.error": "Error al comprobar",
"engine.reason.unsupported_platform": "No disponible en esta plataforma",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 68101164..a6ae48dd 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "Aucune ligne du CSV n'a d'emplacement exploitable",
"error.geo_unsupported_shape": "Ce type de forme n'est pas pris en charge",
"error.geo_too_large": "Le Shapefile dépasserait la limite de 2 Go du format",
+ "error.fit_not_fit": "Ce fichier n'est pas un Garmin FIT",
+ "error.fit_damaged": "Le fichier FIT est endommagé ou tronqué",
+ "error.fit_chained": "Les fichiers FIT enchaînés ne sont pas encore pris en charge",
+ "error.fit_too_large": "Le fichier FIT est trop volumineux pour être converti",
+ "error.fit_no_file_id": "Le fichier FIT n'indique pas son type",
+ "error.fit_not_activity": "Ce fichier FIT n'est pas une activité (seules les activités sont converties)",
+ "error.fit_no_positions": "L'activité ne contient aucune position enregistrée : convertissez-la en CSV, XLSX ou JSON",
+ "error.fit_no_records": "L'activité ne contient aucune donnée enregistrée",
"notice.pdf_not_smaller": "Impossible de réduire sa taille : le fichier a été copié tel quel",
"notice.cad_newer_left_out": "Des objets que la version d'AutoCAD choisie n'a pas (multilignes de repère, maillages…) ont été omis",
"notice.original_kept": "L'original a été conservé, le résultat a été enregistré en copie",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "Certaines lignes sans emplacement exploitable ont été conservées sans forme",
"notice.geo_field_names": "Les noms de champs Shapefile font 10 caractères au maximum : certains ont été raccourcis",
"notice.geo_shapefile_split": "Un Shapefile ne contient qu'un type de forme : les points, lignes et polygones ont été enregistrés dans des fichiers distincts",
+ "notice.geo_heights_dropped": "Certains points n'ont pas de hauteur et Shapefile ne peut pas en omettre une seule : toutes les hauteurs ont donc été omises",
"engine.reason.not_installed": "Non installé",
"engine.reason.error": "Erreur lors de la vérification",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 957153f4..90c731c1 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "CSV की किसी भी पंक्ति में इस्तेमाल लायक स्थान नहीं है",
"error.geo_unsupported_shape": "इस तरह का आकार समर्थित नहीं है",
"error.geo_too_large": "Shapefile फ़ॉर्मैट की 2 GB सीमा से बड़ी हो जाएगी",
+ "error.fit_not_fit": "यह Garmin FIT फ़ाइल नहीं है",
+ "error.fit_damaged": "FIT फ़ाइल खराब है या अधूरी है",
+ "error.fit_chained": "एक के बाद एक जुड़ी कई FIT फ़ाइलें अभी समर्थित नहीं हैं",
+ "error.fit_too_large": "FIT फ़ाइल कन्वर्ट करने के लिए बहुत बड़ी है",
+ "error.fit_no_file_id": "FIT फ़ाइल में फ़ाइल का प्रकार नहीं बताया गया है",
+ "error.fit_not_activity": "यह FIT फ़ाइल गतिविधि नहीं है (सिर्फ़ गतिविधियाँ कन्वर्ट होती हैं)",
+ "error.fit_no_positions": "गतिविधि में दर्ज स्थान नहीं हैं: इसे CSV, XLSX या JSON में बदलें",
+ "error.fit_no_records": "गतिविधि में दर्ज डेटा नहीं है",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
"notice.cad_newer_left_out": "चुने गए AutoCAD संस्करण में न होने वाले ऑब्जेक्ट (मल्टीलीडर, मेश …) छोड़ दिए गए",
"notice.original_kept": "मूल फ़ाइल रखी गई, परिणाम कॉपी के रूप में सहेजा गया",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "कुछ पंक्तियों में इस्तेमाल लायक स्थान नहीं है, उन्हें बिना आकार के रखा गया",
"notice.geo_field_names": "Shapefile फ़ील्ड के नाम ज़्यादा से ज़्यादा 10 अक्षरों के होते हैं: कुछ नाम छोटे किए गए",
"notice.geo_shapefile_split": "Shapefile में एक ही तरह का आकार रहता है, इसलिए पॉइंट, लाइन और पॉलीगॉन अलग-अलग फ़ाइलों में सहेजे गए",
+ "notice.geo_heights_dropped": "कुछ बिंदुओं की ऊँचाई नहीं है और Shapefile किसी एक की ऊँचाई खाली नहीं छोड़ सकता, इसलिए सभी ऊँचाइयाँ हटा दी गईं",
"engine.reason.not_installed": "इंस्टॉल नहीं है",
"engine.reason.error": "जाँच के दौरान त्रुटि",
"engine.reason.unsupported_platform": "इस प्लेटफ़ॉर्म पर उपलब्ध नहीं है",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 5dcc03f9..cdd87ede 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "CSVに使える位置情報のある行がありません",
"error.geo_unsupported_shape": "この種類の図形には対応していません",
"error.geo_too_large": "Shapefile形式の上限(2 GB)を超えてしまいます",
+ "error.fit_not_fit": "Garmin FITファイルではありません",
+ "error.fit_damaged": "FITファイルが破損しているか、途中で切れています",
+ "error.fit_chained": "複数のFITファイルを連結した形式にはまだ対応していません",
+ "error.fit_too_large": "FITファイルが大きすぎて変換できません",
+ "error.fit_no_file_id": "FITファイルにファイルの種類が記録されていません",
+ "error.fit_not_activity": "このFITファイルはアクティビティではありません(アクティビティのみ変換できます)",
+ "error.fit_no_positions": "アクティビティに位置情報が記録されていません。CSV、XLSX、JSONに変換してください",
+ "error.fit_no_records": "アクティビティに記録データがありません",
"notice.pdf_not_smaller": "サイズを小さくできなかったため、元のままコピーしました",
"notice.cad_newer_left_out": "選んだ AutoCAD のバージョンにないオブジェクト(マルチ引出線、メッシュ …)を省きました",
"notice.original_kept": "元のファイルを残し、結果をコピーとして保存しました",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "使える位置情報のない行は、図形なしで残しました",
"notice.geo_field_names": "Shapefileのフィールド名は最大10文字です。一部の名前を短くしました",
"notice.geo_shapefile_split": "Shapefileには1種類の図形しか入らないため、ポイント、ライン、ポリゴンを別々のファイルに保存しました",
+ "notice.geo_heights_dropped": "高さが記録されていない点があり、Shapefileでは一部の高さだけ省けないため、すべての高さを省きました",
"engine.reason.not_installed": "未インストール",
"engine.reason.error": "確認中にエラーが発生しました",
"engine.reason.unsupported_platform": "このプラットフォームでは利用できません",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 5e899b54..d2d35ba8 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "위치를 읽을 수 있는 행이 하나도 없어요",
"error.geo_unsupported_shape": "지원하지 않는 도형 종류예요",
"error.geo_too_large": "Shapefile의 한계인 2GB를 넘어요",
+ "error.fit_not_fit": "Garmin FIT 파일이 아니에요",
+ "error.fit_damaged": "FIT 파일이 손상됐거나 잘렸어요",
+ "error.fit_chained": "여러 FIT 파일이 이어 붙은 파일은 아직 지원하지 않아요",
+ "error.fit_too_large": "FIT 파일이 너무 커서 변환할 수 없어요",
+ "error.fit_no_file_id": "FIT 파일에 파일 종류 정보가 없어요",
+ "error.fit_not_activity": "활동 기록이 아닌 FIT 파일이에요 (활동만 변환해요)",
+ "error.fit_no_positions": "위치 기록이 없는 활동이에요. CSV, XLSX, JSON으로 변환하세요",
+ "error.fit_no_records": "활동에 기록된 데이터가 없어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
"notice.cad_newer_left_out": "선택한 AutoCAD 버전에 없는 개체(다중 지시선, 메시 …)는 빼고 저장했어요",
"notice.original_kept": "원본은 그대로 두고 결과를 사본으로 저장했어요",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "위치를 읽을 수 없는 행은 도형 없이 저장했어요",
"notice.geo_field_names": "Shapefile 필드 이름은 10자까지라서 일부를 줄였어요",
"notice.geo_shapefile_split": "Shapefile은 한 종류의 도형만 담아서 점·선·면을 파일로 나눠 저장했어요",
+ "notice.geo_heights_dropped": "일부 점에 높이가 없는데 Shapefile은 점마다 비워 둘 수 없어서 높이를 모두 뺐어요",
"engine.reason.not_installed": "설치되지 않음",
"engine.reason.error": "확인 중 오류",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index a9a85890..bde98e73 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "CSV को कुनै पनि पङ्क्तिमा प्रयोगयोग्य स्थान छैन",
"error.geo_unsupported_shape": "यस प्रकारको आकार समर्थित छैन",
"error.geo_too_large": "Shapefile ढाँचाको २ GB सीमा नाघ्नेछ",
+ "error.fit_not_fit": "यो Garmin FIT फाइल होइन",
+ "error.fit_damaged": "FIT फाइल बिग्रिएको वा अधुरो छ",
+ "error.fit_chained": "लगातार जोडिएका धेरै FIT फाइलहरू अहिले समर्थित छैनन्",
+ "error.fit_too_large": "FIT फाइल रूपान्तरण गर्न धेरै ठूलो छ",
+ "error.fit_no_file_id": "FIT फाइलले फाइलको प्रकार बताउँदैन",
+ "error.fit_not_activity": "यो FIT फाइल गतिविधि होइन (गतिविधिहरू मात्र रूपान्तरण हुन्छन्)",
+ "error.fit_no_positions": "गतिविधिमा रेकर्ड गरिएका स्थान छैनन्: यसलाई CSV, XLSX वा JSON मा रूपान्तरण गर्नुहोस्",
+ "error.fit_no_records": "गतिविधिमा रेकर्ड गरिएको डाटा छैन",
"notice.pdf_not_smaller": "यसलाई सानो बनाउन सकिएन, त्यसैले जस्तो छ त्यस्तै प्रतिलिपि गरियो",
"notice.cad_newer_left_out": "छानिएको AutoCAD संस्करणमा नभएका वस्तुहरू (मल्टिलिडर, मेस …) छोडिए",
"notice.original_kept": "मूल फाइल राखियो, नतिजा प्रतिलिपिको रूपमा सुरक्षित भयो",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "केही पङ्क्तिहरूमा प्रयोगयोग्य स्थान छैन, तिनीहरूलाई आकार बिना राखियो",
"notice.geo_field_names": "Shapefile फिल्ड नामहरू बढीमा १० अक्षरका हुन्छन्: केही छोट्याइए",
"notice.geo_shapefile_split": "Shapefile मा एक प्रकारको आकार मात्र रहन्छ, त्यसैले पोइन्ट, रेखा र पोलिगनहरू छुट्टाछुट्टै फाइलमा सुरक्षित गरिए",
+ "notice.geo_heights_dropped": "केही बिन्दुमा उचाइ छैन र Shapefile ले कुनै एउटाको उचाइ मात्र खाली राख्न सक्दैन, त्यसैले सबै उचाइ हटाइए",
"engine.reason.not_installed": "स्थापना गरिएको छैन",
"engine.reason.error": "जाँच गर्दा त्रुटि भयो",
"engine.reason.unsupported_platform": "यस प्लेटफर्ममा उपलब्ध छैन",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 72f4aa02..2b1aafe9 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "Żaden wiersz pliku CSV nie ma odczytywalnego położenia",
"error.geo_unsupported_shape": "Ten rodzaj kształtu nie jest obsługiwany",
"error.geo_too_large": "Shapefile przekroczyłby limit 2 GB tego formatu",
+ "error.fit_not_fit": "To nie jest plik Garmin FIT",
+ "error.fit_damaged": "Plik FIT jest uszkodzony lub ucięty",
+ "error.fit_chained": "Pliki FIT połączone jeden za drugim nie są jeszcze obsługiwane",
+ "error.fit_too_large": "Plik FIT jest za duży do konwersji",
+ "error.fit_no_file_id": "Plik FIT nie podaje swojego rodzaju",
+ "error.fit_not_activity": "Ten plik FIT nie jest aktywnością (konwertowane są tylko aktywności)",
+ "error.fit_no_positions": "Aktywność nie zawiera zapisanych położeń: przekonwertuj ją do CSV, XLSX lub JSON",
+ "error.fit_no_records": "Aktywność nie zawiera zapisanych danych",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
"notice.cad_newer_left_out": "Pominięto obiekty, których wybrana wersja AutoCAD nie ma (multiodnośniki, siatki…)",
"notice.original_kept": "Oryginał został zachowany, wynik zapisano jako kopię",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "Wiersze bez odczytywalnego położenia zapisano bez kształtu",
"notice.geo_field_names": "Nazwy pól Shapefile mają najwyżej 10 znaków: niektóre skrócono",
"notice.geo_shapefile_split": "Shapefile przechowuje jeden rodzaj kształtu, więc punkty, linie i poligony zapisano w osobnych plikach",
+ "notice.geo_heights_dropped": "Niektóre punkty nie mają wysokości, a Shapefile nie może pominąć tylko jednej, więc pominięto wszystkie wysokości",
"engine.reason.not_installed": "Nie zainstalowano",
"engine.reason.error": "Błąd podczas sprawdzania",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 75099813..513cad8e 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "Nenhuma linha do CSV tem uma localização utilizável",
"error.geo_unsupported_shape": "Este tipo de forma não é compatível",
"error.geo_too_large": "O Shapefile passaria do limite de 2 GB do formato",
+ "error.fit_not_fit": "Este arquivo não é um Garmin FIT",
+ "error.fit_damaged": "O arquivo FIT está danificado ou incompleto",
+ "error.fit_chained": "Arquivos FIT concatenados ainda não são compatíveis",
+ "error.fit_too_large": "O arquivo FIT é grande demais para converter",
+ "error.fit_no_file_id": "O arquivo FIT não informa seu tipo",
+ "error.fit_not_activity": "Este arquivo FIT não é uma atividade (só atividades são convertidas)",
+ "error.fit_no_positions": "A atividade não tem posições registradas: converta-a para CSV, XLSX ou JSON",
+ "error.fit_no_records": "A atividade não tem dados registrados",
"notice.pdf_not_smaller": "Não deu para deixar menor, então foi copiado como está",
"notice.cad_newer_left_out": "Objetos que a versão do AutoCAD escolhida não tem (multilinhas de chamada, malhas…) ficaram de fora",
"notice.original_kept": "O original foi mantido, o resultado foi salvo como cópia",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "Algumas linhas não têm localização utilizável e foram mantidas sem forma",
"notice.geo_field_names": "Nomes de campo de Shapefile têm no máximo 10 caracteres: alguns foram encurtados",
"notice.geo_shapefile_split": "Um Shapefile guarda um tipo de forma, então pontos, linhas e polígonos foram salvos em arquivos separados",
+ "notice.geo_heights_dropped": "Alguns pontos não têm altura e o Shapefile não pode deixá-la de fora em apenas um, então todas as alturas foram omitidas",
"engine.reason.not_installed": "Não instalado",
"engine.reason.error": "Erro ao verificar",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index e6ca7c15..f79086ca 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "Nenhuma linha do CSV tem uma localização utilizável",
"error.geo_unsupported_shape": "Este tipo de geometria não é suportado",
"error.geo_too_large": "O Shapefile ultrapassaria o limite de 2 GB do formato",
+ "error.fit_not_fit": "Este ficheiro não é um ficheiro Garmin FIT",
+ "error.fit_damaged": "O ficheiro FIT está danificado ou incompleto",
+ "error.fit_chained": "O ficheiro contém vários ficheiros FIT seguidos, o que ainda não é suportado",
+ "error.fit_too_large": "O ficheiro FIT é demasiado grande para converter",
+ "error.fit_no_file_id": "O ficheiro FIT não indica que tipo de ficheiro é",
+ "error.fit_not_activity": "Este ficheiro FIT não é uma atividade (só são convertidas atividades)",
+ "error.fit_no_positions": "A atividade não tem posições registadas: converte-a para CSV, XLSX ou JSON",
+ "error.fit_no_records": "A atividade não tem dados registados",
"notice.pdf_not_smaller": "Não foi possível reduzir o tamanho, pelo que o ficheiro foi copiado sem alterações",
"notice.cad_newer_left_out": "Os objetos que a versão de AutoCAD escolhida não suporta (linhas de chamada múltiplas, malhas…) foram omitidos",
"notice.original_kept": "O original foi mantido e o resultado foi guardado como cópia",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "Algumas linhas não têm uma localização utilizável e foram mantidas sem geometria",
"notice.geo_field_names": "Os nomes dos campos Shapefile admitem, no máximo, 10 carateres: alguns foram abreviados",
"notice.geo_shapefile_split": "Um Shapefile guarda apenas um tipo de geometria, pelo que os pontos, linhas e polígonos foram guardados em ficheiros separados",
+ "notice.geo_heights_dropped": "Alguns pontos não têm altura e um Shapefile não pode omiti-la apenas em alguns, pelo que todas as alturas foram omitidas",
"engine.reason.not_installed": "Não instalado",
"engine.reason.error": "Erro na verificação",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 29acdd1e..830c7a1e 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "Ни в одной строке CSV нет пригодного местоположения",
"error.geo_unsupported_shape": "Такой тип фигуры не поддерживается",
"error.geo_too_large": "Shapefile превысил бы предел формата в 2 ГБ",
+ "error.fit_not_fit": "Это не файл Garmin FIT",
+ "error.fit_damaged": "Файл FIT повреждён или обрезан",
+ "error.fit_chained": "Соединённые подряд файлы FIT пока не поддерживаются",
+ "error.fit_too_large": "Файл FIT слишком большой для конвертации",
+ "error.fit_no_file_id": "В файле FIT не указан его тип",
+ "error.fit_not_activity": "Этот файл FIT не является активностью (конвертируются только активности)",
+ "error.fit_no_positions": "В активности нет записанных координат: конвертируйте её в CSV, XLSX или JSON",
+ "error.fit_no_records": "В активности нет записанных данных",
"notice.pdf_not_smaller": "Уменьшить не получилось, файл скопирован как есть",
"notice.cad_newer_left_out": "Объекты, которых нет в выбранной версии AutoCAD (мультивыноски, сети…), не сохранены",
"notice.original_kept": "Оригинал оставлен, результат сохранён как копия",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "В некоторых строках нет пригодного местоположения: они сохранены без фигуры",
"notice.geo_field_names": "Имена полей Shapefile не длиннее 10 символов: некоторые сокращены",
"notice.geo_shapefile_split": "Shapefile хранит фигуры только одного вида, поэтому точки, линии и полигоны сохранены в отдельные файлы",
+ "notice.geo_heights_dropped": "У некоторых точек нет высоты, а Shapefile не может пропустить высоту только у одной точки, поэтому убраны все высоты",
"engine.reason.not_installed": "Не установлен",
"engine.reason.error": "Ошибка при проверке",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index 8c419e6b..1a6b9ded 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "ไม่มีแถวใดใน CSV ที่มีตำแหน่งที่ใช้งานได้",
"error.geo_unsupported_shape": "ไม่รองรับรูปทรงเรขาคณิตประเภทนี้",
"error.geo_too_large": "Shapefile จะมีขนาดเกินขีดจำกัดของฟอร์แมตที่ 2 GB",
+ "error.fit_not_fit": "ไฟล์นี้ไม่ใช่ Garmin FIT",
+ "error.fit_damaged": "ไฟล์ FIT เสียหายหรือถูกตัดไม่ครบ",
+ "error.fit_chained": "ยังไม่รองรับไฟล์ FIT หลายไฟล์ที่นำมาต่อกัน",
+ "error.fit_too_large": "ไฟล์ FIT ใหญ่เกินกว่าจะแปลงได้",
+ "error.fit_no_file_id": "ไฟล์ FIT ไม่ได้ระบุประเภทของไฟล์",
+ "error.fit_not_activity": "ไฟล์ FIT นี้ไม่ใช่กิจกรรม (แปลงได้เฉพาะกิจกรรมเท่านั้น)",
+ "error.fit_no_positions": "กิจกรรมนี้ไม่มีตำแหน่งที่บันทึกไว้ โปรดแปลงเป็น CSV, XLSX หรือ JSON",
+ "error.fit_no_records": "กิจกรรมนี้ไม่มีข้อมูลที่บันทึกไว้",
"notice.pdf_not_smaller": "ไม่สามารถบีบอัดให้เล็กลงได้ จึงคัดลอกไฟล์ตามเดิม",
"notice.cad_newer_left_out": "ละวัตถุที่ AutoCAD เวอร์ชันที่เลือกไม่มี (มัลติลีดเดอร์ เมช …) ไว้",
"notice.original_kept": "เก็บไฟล์ต้นฉบับไว้ และบันทึกผลลัพธ์เป็นสำเนา",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "บางแถวไม่มีตำแหน่งที่ใช้งานได้และถูกเก็บไว้โดยไม่มีรูปทรงเรขาคณิต",
"notice.geo_field_names": "ชื่อฟิลด์ของ Shapefile มีความยาวได้ไม่เกิน 10 ตัวอักษร บางชื่อจึงถูกย่อให้สั้นลง",
"notice.geo_shapefile_split": "Shapefile เก็บรูปทรงเรขาคณิตได้ชนิดเดียวต่อไฟล์ จุด เส้น และโพลีกอนจึงถูกบันทึกแยกเป็นคนละไฟล์",
+ "notice.geo_heights_dropped": "บางจุดไม่มีค่าความสูง และ Shapefile เว้นค่าความสูงไว้เพียงจุดเดียวไม่ได้ จึงตัดค่าความสูงทั้งหมดออก",
"engine.reason.not_installed": "ยังไม่ได้ติดตั้ง",
"engine.reason.error": "เกิดข้อผิดพลาดขณะตรวจสอบ",
"engine.reason.unsupported_platform": "ไม่พร้อมใช้งานบนแพลตฟอร์มนี้",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 62a8e5e1..bdc11d13 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -107,6 +107,14 @@
"error.geo_csv_no_locations": "CSV'nin hiçbir satırında kullanılabilir konum yok",
"error.geo_unsupported_shape": "Bu geometri türü desteklenmiyor",
"error.geo_too_large": "Shapefile, biçimin 2 GB sınırını aşacak",
+ "error.fit_not_fit": "Bu dosya Garmin FIT değil",
+ "error.fit_damaged": "FIT dosyası bozuk veya eksik",
+ "error.fit_chained": "Arka arkaya eklenmiş birden çok FIT dosyası henüz desteklenmiyor",
+ "error.fit_too_large": "FIT dosyası dönüştürülemeyecek kadar büyük",
+ "error.fit_no_file_id": "FIT dosyası türünü belirtmiyor",
+ "error.fit_not_activity": "Bu FIT dosyası bir etkinlik değil (yalnızca etkinlikler dönüştürülür)",
+ "error.fit_no_positions": "Etkinlikte kaydedilmiş konum yok: CSV, XLSX veya JSON'a dönüştürün",
+ "error.fit_no_records": "Etkinlikte kaydedilmiş veri yok",
"notice.pdf_not_smaller": "Küçültülemediği için olduğu gibi kopyalandı",
"notice.cad_newer_left_out": "Seçilen AutoCAD sürümünün desteklemediği nesneler (çoklu kılavuzlar, ağlar…) çıkarıldı",
"notice.original_kept": "Özgün dosya korundu, sonuç kopya olarak kaydedildi",
@@ -129,6 +137,7 @@
"notice.geo_rows_without_location": "Bazı satırların kullanılabilir konumu yok; geometrisiz olarak korundular",
"notice.geo_field_names": "Shapefile alan adları en fazla 10 karakter olabilir; bazıları kısaltıldı",
"notice.geo_shapefile_split": "Shapefile tek bir geometri türü tutar; noktalar, çizgiler ve çokgenler ayrı dosyalara kaydedildi",
+ "notice.geo_heights_dropped": "Bazı noktalarda yükseklik yok ve Shapefile tek bir noktanın yüksekliğini boş bırakamıyor; bu nedenle tüm yükseklikler çıkarıldı",
"engine.reason.not_installed": "Kurulu değil",
"engine.reason.error": "Denetim sırasında hata",
"engine.reason.unsupported_platform": "Bu platformda kullanılamıyor",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 340de83b..69b2e4d9 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "CSV 中没有一行能读出位置",
"error.geo_unsupported_shape": "不支持此类形状",
"error.geo_too_large": "将超过 Shapefile 2 GB 的上限",
+ "error.fit_not_fit": "这不是 Garmin FIT 文件",
+ "error.fit_damaged": "FIT 文件已损坏或不完整",
+ "error.fit_chained": "暂不支持多个 FIT 文件首尾相连的情况",
+ "error.fit_too_large": "FIT 文件太大,无法转换",
+ "error.fit_no_file_id": "FIT 文件未说明文件类型",
+ "error.fit_not_activity": "此 FIT 文件不是活动记录(只能转换活动记录)",
+ "error.fit_no_positions": "活动没有记录位置信息,请转换为 CSV、XLSX 或 JSON",
+ "error.fit_no_records": "活动没有记录数据",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
"notice.cad_newer_left_out": "已省略所选 AutoCAD 版本没有的对象(多重引线、网格……)",
"notice.original_kept": "已保留原文件,结果另存为副本",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "部分行无法读出位置,已不带形状保存",
"notice.geo_field_names": "Shapefile 字段名最多 10 个字符,部分名称已缩短",
"notice.geo_shapefile_split": "Shapefile 只能保存一种形状,因此点、线、面被分别存成了多个文件",
+ "notice.geo_heights_dropped": "部分点没有高度,而 Shapefile 无法只省略其中一个点的高度,因此已省略所有高度",
"engine.reason.not_installed": "未安装",
"engine.reason.error": "检查时出错",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index ee508a74..042c85ae 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -113,6 +113,14 @@
"error.geo_csv_no_locations": "CSV 中沒有任何一列能讀出位置",
"error.geo_unsupported_shape": "不支援此類形狀",
"error.geo_too_large": "將超過 Shapefile 2 GB 的上限",
+ "error.fit_not_fit": "這不是 Garmin FIT 檔案",
+ "error.fit_damaged": "FIT 檔案已損毀或不完整",
+ "error.fit_chained": "暫不支援多個 FIT 檔案首尾相連的情況",
+ "error.fit_too_large": "FIT 檔案太大,無法轉換",
+ "error.fit_no_file_id": "FIT 檔案未說明檔案類型",
+ "error.fit_not_activity": "此 FIT 檔案不是活動記錄(只能轉換活動記錄)",
+ "error.fit_no_positions": "活動沒有記錄位置資訊,請轉換為 CSV、XLSX 或 JSON",
+ "error.fit_no_records": "活動沒有記錄資料",
"notice.pdf_not_smaller": "無法再縮小,已原樣複製",
"notice.cad_newer_left_out": "已略過所選 AutoCAD 版本沒有的物件(複線引線、網格……)",
"notice.original_kept": "已保留原始檔案,結果另存為副本",
@@ -135,6 +143,7 @@
"notice.geo_rows_without_location": "部分列無法讀出位置,已不帶形狀儲存",
"notice.geo_field_names": "Shapefile 欄位名最多 10 個字元,部分名稱已縮短",
"notice.geo_shapefile_split": "Shapefile 只能儲存一種形狀,因此點、線、面被分別存成了多個檔案",
+ "notice.geo_heights_dropped": "部分點沒有高度,而 Shapefile 無法只省略其中一個點的高度,因此已省略所有高度",
"engine.reason.not_installed": "未安裝",
"engine.reason.error": "檢查時出錯",
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 333a0184..c036e172 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -331,6 +331,8 @@ public static class FormatRegistry
new("kmz", "KMZ", FormatCategory.Geo, ["kmz"]),
new("gpx", "GPX", FormatCategory.Geo, ["gpx"]),
new("shp", "Shapefile", FormatCategory.Geo, ["shp"]),
+ // Activity files read by the geo engine (issue #451); .fits/.fts stay FITS.
+ new("fit", "Garmin FIT", FormatCategory.Geo, ["fit"], Writable: false),
];
private static readonly Dictionary<string, FileFormat> ById =
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 21e1defe..380a4898 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -123,7 +123,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 46;
+ public const int CurrentSchemaVersion = 47;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 10a8c0a9..e85a498a 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -872,6 +872,9 @@ internal static class SettingsMigrations
changed = true;
}
}
+ // v47: Garmin FIT activities (.fit) learn the geospatial donut; custom claims stay put.
+ if (from < 47)
+ changed |= LearnExtensions(profiles, out _, ["fit"]);
return changed;
}
diff --git a/src/Filee.Engines/Geo/FitFormat.cs b/src/Filee.Engines/Geo/FitFormat.cs
new file mode 100644
index 00000000..ac4eced1
--- /dev/null
+++ b/src/Filee.Engines/Geo/FitFormat.cs
@@ -0,0 +1,343 @@
+// Garmin FIT activity records. The file and record limits are checked before decoding; fields outside the activity
+// profile (including developer fields) are consumed without adding them to the output.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using Filee.Core.Conversion;
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Geo;
+
+internal sealed record FitRecord(DateTime? Time, double? Latitude, double? Longitude, double? Elevation,
+ int? HeartRate, int? Cadence, int? Power, double? Speed, double? Distance);
+
+internal sealed record FitSession(DateTime? StartTime, int? Sport)
+{
+ public string? SportName => Sport is { } sport ? FitFormat.SportName(sport) : null;
+}
+
+internal sealed class FitActivity
+{
+ public List<FitRecord> Records { get; } = [];
+ public List<FitSession> Sessions { get; } = [];
+}
+
+internal static class FitFormat
+{
+ internal const long MaxFileBytes = 64L << 20;
+ internal const int MaxRecords = 2_000_000;
+ private const long FitEpochOffset = 631065600;
+
+ private static readonly string?[] FileNames = Names(255,
+ (1, "device"), (2, "settings"), (3, "sport"), (4, "activity"), (5, "workout"),
+ (6, "course"), (7, "schedules"), (9, "weight"), (10, "totals"), (11, "goals"),
+ (14, "blood_pressure"), (15, "monitoring_a"), (20, "activity_summary"),
+ (28, "monitoring_daily"), (32, "monitoring_b"), (34, "segment"), (35, "segment_list"),
+ (40, "exd_configuration"), (247, "mfg_range_min"), (254, "mfg_range_max"));
+
+ private static readonly string?[] SportNames = Names(255,
+ (0, "generic"), (1, "running"), (2, "cycling"), (3, "transition"), (4, "fitness_equipment"),
+ (5, "swimming"), (6, "basketball"), (7, "soccer"), (8, "tennis"), (9, "american_football"),
+ (10, "training"), (11, "walking"), (12, "cross_country_skiing"), (13, "alpine_skiing"),
+ (14, "snowboarding"), (15, "rowing"), (16, "mountaineering"), (17, "hiking"), (18, "multisport"),
+ (19, "paddling"), (20, "flying"), (21, "e_biking"), (22, "motorcycling"), (23, "boating"),
+ (24, "driving"), (25, "golf"), (26, "hang_gliding"), (27, "horseback_riding"), (28, "hunting"),
+ (29, "fishing"), (30, "inline_skating"), (31, "rock_climbing"), (32, "sailing"), (33, "ice_skating"),
+ (34, "sky_diving"), (35, "snowshoeing"), (36, "snowmobiling"), (37, "stand_up_paddleboarding"),
+ (38, "surfing"), (39, "wakeboarding"), (40, "water_skiing"), (41, "kayaking"), (42, "rafting"),
+ (43, "windsurfing"), (44, "kitesurfing"), (45, "tactical"), (46, "jumpmaster"), (47, "boxing"),
+ (48, "floor_climbing"), (49, "baseball"), (53, "diving"), (56, "shooting"), (58, "winter_sport"),
+ (59, "grinding"), (62, "hiit"), (63, "video_gaming"), (64, "racket"), (65, "wheelchair_push_walk"),
+ (66, "wheelchair_push_run"), (67, "meditation"), (68, "para_sport"), (69, "disc_golf"),
+ (70, "team_sport"), (71, "cricket"), (72, "rugby"), (73, "hockey"), (74, "lacrosse"),
+ (75, "volleyball"), (76, "water_tubing"), (77, "wakesurfing"), (78, "water_sport"), (79, "archery"),
+ (80, "mixed_martial_arts"), (81, "motor_sports"), (82, "snorkeling"), (83, "dance"),
+ (84, "jump_rope"), (85, "pool_apnea"), (86, "mobility"), (87, "geocaching"), (88, "canoeing"),
+ (254, "all"));
+
+ private static string?[] Names(int count, params (int Value, string Name)[] entries)
+ {
+ var names = new string?[count];
+ foreach (var (value, name) in entries)
+ names[value] = name;
+ return names;
+ }
+
+ internal static string SportName(int sport) =>
+ sport >= 0 && sport < SportNames.Length && SportNames[sport] is { } name
+ ? name : sport.ToString(CultureInfo.InvariantCulture);
+
+ /// <summary>One activity becomes one point or one track; records without positions stay in the CSV only.</summary>
+ public static GeoDataset ToDataset(FitActivity activity, string path)
+ {
+ var positioned = activity.Records.Where(record => record.Latitude is not null && record.Longitude is not null).ToList();
+ if (positioned.Count == 0)
+ throw new ConversionRefusedException("error.fit_no_positions");
+
+ var properties = new List<KeyValuePair<string, object?>>();
+ var sports = activity.Sessions.Select(session => session.SportName).OfType<string>().Distinct().ToArray();
+ if (sports.Length > 0)
+ properties.Add(new("type", string.Join(", ", sports)));
+ DateTime? start = positioned.Count == 1 ? positioned[0].Time
+ : activity.Sessions.Select(session => session.StartTime).Where(time => time is not null).Order().FirstOrDefault()
+ ?? activity.Records.Select(record => record.Time).FirstOrDefault(time => time is not null);
+ if (start is { } time)
+ properties.Add(new("time", time.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)));
+
+ var points = positioned.Select(record => new Coord(record.Longitude!.Value, record.Latitude!.Value,
+ record.Elevation ?? double.NaN)).ToArray();
+ GeoGeometry geometry = points.Length == 1 ? new GeoPoint(points[0]) :
+ new GeoLineString(points, positioned.Any(record => record.Time is not null)
+ ? positioned.Select(record => record.Time).ToArray() : null);
+ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path), SparseHeights = true };
+ dataset.Features.Add(new GeoFeature(geometry, properties));
+ return dataset;
+ }
+
+ /// <summary>Reads one complete, CRC-checked FIT activity in file order.</summary>
+ public static FitActivity Read(string path, CancellationToken ct, long maxBytes = MaxFileBytes, int maxRecords = MaxRecords)
+ {
+ using var stream = File.OpenRead(path);
+ Span<byte> header = stackalloc byte[14];
+ var headerLength = stream.ReadAtLeast(header, 14, throwOnEndOfStream: false);
+ if (headerLength < 12 || header[0] < 12 || !header[8..12].SequenceEqual(".FIT"u8))
+ throw new ConversionRefusedException("error.fit_not_fit");
+ if (stream.Length > maxBytes)
+ throw new ConversionRefusedException("error.fit_too_large", "64 MB");
+ var size = header[0];
+ if (size >= 14 && headerLength >= 14 && BinaryPrimitives.ReadUInt16LittleEndian(header[12..]) is var headerCrc
+ && headerCrc != 0 && headerCrc != FitCrc(header[..12]))
+ throw Damaged("header CRC");
+
+ var dataLength = BinaryPrimitives.ReadUInt32LittleEndian(header[4..8]);
+ var end = (long)size + dataLength;
+ if (end + 2 > stream.Length)
+ throw Damaged("cut short");
+ stream.Position = 0;
+ var bytes = new byte[(int)stream.Length];
+ stream.ReadExactly(bytes);
+ if (FitCrc(bytes.AsSpan(0, (int)end)) != BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan((int)end, 2)))
+ throw Damaged("CRC");
+ if (end + 2 < bytes.Length)
+ throw bytes.Length - end - 2 >= 12 && bytes.AsSpan((int)end + 10, 4).SequenceEqual(".FIT"u8)
+ ? new ConversionRefusedException("error.fit_chained") : Damaged("extra bytes");
+
+ var activity = new FitActivity();
+ var definitions = new Definition?[16];
+ int position = size;
+ var limit = (int)end;
+ uint? lastTime = null;
+ int? fileType = null;
+ var fileIdSeen = false;
+ while (position < limit)
+ {
+ ct.ThrowIfCancellationRequested();
+ var recordHeader = bytes[position++];
+ var compressed = (recordHeader & 0x80) != 0;
+ var local = compressed ? (recordHeader >> 5) & 3 : recordHeader & 15;
+ if (!compressed && (recordHeader & 0x40) != 0)
+ {
+ Require(5);
+ position++; // reserved
+ var architecture = bytes[position++];
+ if (architecture is not (0 or 1))
+ throw Damaged("architecture");
+ var bigEndian = architecture == 1;
+ var message = Read16(bytes.AsSpan(position, 2), bigEndian);
+ position += 2;
+ var fieldCount = bytes[position++];
+ Require(fieldCount * 3);
+ var fields = new Field[fieldCount];
+ for (var i = 0; i < fields.Length; i++)
+ {
+ fields[i] = new Field(bytes[position], bytes[position + 1], bytes[position + 2]);
+ position += 3;
+ }
+ var developerBytes = 0;
+ if ((recordHeader & 0x20) != 0)
+ {
+ Require(1);
+ var count = bytes[position++];
+ Require(count * 3);
+ for (var i = 0; i < count; i++)
+ {
+ developerBytes += bytes[position + 1];
+ position += 3;
+ }
+ }
+ definitions[local] = new Definition(message, bigEndian, fields, developerBytes);
+ continue;
+ }
+
+ var definition = definitions[local] ?? throw Damaged($"undefined local message {local}");
+ uint? time = null;
+ if (compressed && lastTime is { } previous)
+ {
+ var offset = (uint)(recordHeader & 31);
+ var reconstructed = (previous & ~31u) + offset + (offset < (previous & 31) ? 32u : 0u);
+ if (reconstructed >= 0x10000000)
+ time = reconstructed;
+ }
+ double? lat = null, lon = null, height = null, enhancedHeight = null;
+ double? speed = null, enhancedSpeed = null, distance = null;
+ int? heartRate = null, cadence = null, power = null, sport = null;
+ uint? startTime = null;
+ foreach (var field in definition.Fields)
+ {
+ Require(field.Size);
+ var value = ReadNumber(bytes.AsSpan(position, field.Size), field.Type, definition.BigEndian);
+ position += field.Size;
+ if (value is null)
+ continue;
+ if (field.Number == 253 && value is >= 0x10000000 and < 0xFFFFFFFF)
+ {
+ time = (uint)value.Value;
+ lastTime = time;
+ }
+ switch (definition.Message, field.Number)
+ {
+ case (0, 0) when !fileIdSeen && value <= 254: fileType = (int)value.Value; break;
+ case (18, 2) when value is >= 0x10000000 and < 0xFFFFFFFF: startTime = (uint)value.Value; break;
+ case (18, 5) when value <= 254: sport = (int)value.Value; break;
+ case (20, 0): lat = value * 180 / 2147483648.0; break;
+ case (20, 1): lon = value * 180 / 2147483648.0; break;
+ case (20, 2): height = value / 5 - 500; break;
+ case (20, 3): heartRate = (int)value.Value; break;
+ case (20, 4): cadence = (int)value.Value; break;
+ case (20, 5): distance = value / 100; break;
+ case (20, 6): speed = value / 1000; break;
+ case (20, 7): power = (int)value.Value; break;
+ case (20, 73): enhancedSpeed = value / 1000; break;
+ case (20, 78): enhancedHeight = value / 5 - 500; break;
+ }
+ }
+ Require(definition.DeveloperBytes);
+ position += definition.DeveloperBytes;
+ if (time is { } absolute)
+ lastTime = absolute;
+ switch (definition.Message)
+ {
+ case 0: fileIdSeen = true; break;
+ case 18: activity.Sessions.Add(new FitSession(ToDate(startTime), sport)); break;
+ case 20:
+ if (activity.Records.Count >= maxRecords)
+ throw new ConversionRefusedException("error.fit_too_large", "2000000 records");
+ if (lat is < -90 or > 90 || lon is < -180 or > 180 || lat is null || lon is null)
+ lat = lon = null;
+ activity.Records.Add(new FitRecord(ToDate(time), lat, lon, enhancedHeight ?? height,
+ heartRate, cadence, power, enhancedSpeed ?? speed, distance));
+ break;
+ }
+ }
+ if (!fileIdSeen || fileType is null)
+ throw new ConversionRefusedException("error.fit_no_file_id");
+ if (fileType != 4)
+ throw new ConversionRefusedException("error.fit_not_activity",
+ fileType >= 0 && fileType < FileNames.Length && FileNames[fileType.Value] is { } name
+ ? name : $"type {fileType}");
+ return activity;
+
+ void Require(int count)
+ {
+ if (count > limit - position)
+ throw Damaged("cut short");
+ }
+ }
+
+ private static DateTime? ToDate(uint? seconds) =>
+ seconds is { } value ? DateTime.UnixEpoch.AddSeconds(value + FitEpochOffset) : null;
+
+ private static ushort Read16(ReadOnlySpan<byte> bytes, bool bigEndian) =>
+ bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(bytes) : BinaryPrimitives.ReadUInt16LittleEndian(bytes);
+
+ private static double? ReadNumber(ReadOnlySpan<byte> bytes, byte baseType, bool bigEndian)
+ {
+ var type = baseType & 0x1F;
+ var width = type switch
+ {
+ 0 or 1 or 2 or 7 or 10 or 13 => 1,
+ 3 or 4 or 11 => 2,
+ 5 or 6 or 8 or 12 => 4,
+ 9 or 14 or 15 or 16 => 8,
+ _ => 0,
+ };
+ if (width == 0 || bytes.Length < width || bytes.Length % width != 0 || type == 7)
+ return null;
+ bytes = bytes[..width];
+ ulong raw = width switch
+ {
+ 1 => bytes[0],
+ 2 => Read16(bytes, bigEndian),
+ 4 => bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(bytes) : BinaryPrimitives.ReadUInt32LittleEndian(bytes),
+ _ => bigEndian ? BinaryPrimitives.ReadUInt64BigEndian(bytes) : BinaryPrimitives.ReadUInt64LittleEndian(bytes),
+ };
+ if (type is 8 or 9)
+ return raw == (width == 4 ? uint.MaxValue : ulong.MaxValue) ? null
+ : type == 8 ? BitConverter.Int32BitsToSingle((int)raw) : BitConverter.Int64BitsToDouble((long)raw);
+ if (type is 10 or 11 or 12 or 16 && raw == 0)
+ return null;
+ if (type is 1 or 3 or 5 or 14)
+ {
+ var signed = width switch
+ {
+ 1 => (sbyte)raw,
+ 2 => (short)raw,
+ 4 => (int)raw,
+ _ => (long)raw,
+ };
+ return signed == (width switch { 1 => sbyte.MaxValue, 2 => short.MaxValue, 4 => int.MaxValue, _ => long.MaxValue })
+ ? null : signed;
+ }
+ return raw == (width switch { 1 => byte.MaxValue, 2 => ushort.MaxValue, 4 => uint.MaxValue, _ => ulong.MaxValue })
+ && type is not (10 or 11 or 12 or 16) ? null : raw;
+ }
+
+ /// <summary>Writes one nonempty record per CSV row, keeping file order and empty sensor cells.</summary>
+ public static void WriteCsv(FitActivity activity, string path)
+ {
+ var rows = new List<List<string>>
+ {
+ new() { "time", "longitude", "latitude", "elevation", "heart_rate", "cadence", "power", "speed", "distance" },
+ };
+ foreach (var record in activity.Records)
+ {
+ if (record.Time is null && record.Latitude is null && record.Longitude is null
+ && record.HeartRate is null && record.Cadence is null && record.Power is null
+ && record.Speed is null && record.Distance is null)
+ continue;
+ rows.Add([
+ record.Time?.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) ?? "",
+ record.Longitude is { } lon ? GeoText.Degrees(lon) : "",
+ record.Latitude is { } lat ? GeoText.Degrees(lat) : "",
+ record.Elevation is { } height ? GeoText.Height(height) : "",
+ record.HeartRate?.ToString(CultureInfo.InvariantCulture) ?? "",
+ record.Cadence?.ToString(CultureInfo.InvariantCulture) ?? "",
+ record.Power?.ToString(CultureInfo.InvariantCulture) ?? "",
+ record.Speed is { } speed ? GeoText.Number(speed) : "",
+ record.Distance is { } distance ? GeoText.Number(distance) : "",
+ ]);
+ }
+ if (rows.Count == 1)
+ throw new ConversionRefusedException("error.fit_no_records");
+ CsvFormat.WriteRows(rows, path);
+ }
+
+ private static ConversionRefusedException Damaged(string detail) => new("error.fit_damaged", detail);
+
+ private sealed record Definition(int Message, bool BigEndian, Field[] Fields, int DeveloperBytes);
+ private readonly record struct Field(byte Number, byte Size, byte Type);
+
+ /// <summary>FIT's 16-entry nibble CRC over the complete supplied span.</summary>
+ internal static ushort FitCrc(ReadOnlySpan<byte> bytes)
+ {
+ ReadOnlySpan<ushort> table = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
+ 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400];
+ ushort crc = 0;
+ foreach (var value in bytes)
+ {
+ crc = (ushort)((crc >> 4) ^ table[(crc ^ value) & 0xF]);
+ crc = (ushort)((crc >> 4) ^ table[(crc ^ (value >> 4)) & 0xF]);
+ }
+ return crc;
+ }
+}
diff --git a/src/Filee.Engines/Geo/GeoConverter.cs b/src/Filee.Engines/Geo/GeoConverter.cs
index 8fab9957..d1c538f9 100644
--- a/src/Filee.Engines/Geo/GeoConverter.cs
+++ b/src/Filee.Engines/Geo/GeoConverter.cs
@@ -1,5 +1,6 @@
// Geospatial vector data in managed code: GeoJSON, KML, KMZ, GPX, Shapefile and CSV (a WKT column, or longitude and
-// latitude columns) into each other through one in-memory model (GeoModel). Whatever the source's coordinate system
+// latitude columns) into each other through one in-memory model (GeoModel); Garmin FIT activities are read into it too.
+// FIT goes to CSV straight from its records (FitFormat.WriteCsv). Whatever the source's coordinate system
// (a .prj or a GeoJSON crs), every result is longitude / latitude in WGS 84. See docs/ENGINES.md, "Geospatial data",
// for what each format keeps and what it loses.
@@ -10,11 +11,13 @@ using Microsoft.Extensions.Logging.Abstractions;
namespace Filee.Engines.Geo;
-/// <summary>Converts GeoJSON, KML, KMZ, GPX, Shapefile and CSV points / WKT into each other.</summary>
+/// <summary>Converts GeoJSON, KML, KMZ, GPX, Shapefile and CSV points / WKT, and reads Garmin FIT activities.</summary>
public sealed class GeoConverter(ILogger? logger = null) : IConverter
{
/// <summary>The geospatial formats, each readable and writable.</summary>
public static readonly string[] Formats = ["geojson", "kml", "kmz", "gpx", "shp"];
+ /// <summary>The geospatial formats that are only read.</summary>
+ public static readonly string[] ReadOnlyFormats = ["fit"];
private readonly ILogger _logger = logger ?? NullLogger.Instance;
@@ -33,29 +36,47 @@ public sealed class GeoConverter(ILogger? logger = null) : IConverter
new("geojson", "geojson"),
.. Formats.Select(format => new ConversionEdge(format, "csv")),
.. Formats.Select(format => new ConversionEdge("csv", format)),
+ .. ReadOnlyFormats.SelectMany(source => Formats.Select(target => new ConversionEdge(source, target))),
+ .. ReadOnlyFormats.Select(source => new ConversionEdge(source, "csv")),
];
- public EngineStatus GetStatus() => EngineStatus.Available("GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV",
+ public EngineStatus GetStatus() => EngineStatus.Available("GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV; Garmin FIT activities → geospatial formats and CSV",
EngineVersions.BuiltIn);
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
{
var notices = new Notices(step.Notice);
- var dataset = Read(step, cancellationToken);
+ var activity = step.From == "fit" ? FitFormat.Read(step.InputPath, cancellationToken) : null;
+ var dataset = activity is null ? Read(step, cancellationToken)
+ : step.To == "csv" ? null : FitFormat.ToDataset(activity, step.InputPath);
progress?.Report(0.4);
- ToWgs84(dataset, notices);
- if (dataset.Features.Count == 0)
- throw new ConversionRefusedException("error.geo_empty");
- _logger.LogDebug("{File}: {Features} features read as {Format}, {Crs}", step.InputPath, dataset.Features.Count, step.From, dataset.Crs.Name);
- if (dataset.RowsWithoutLocation)
- notices.Add("notice.geo_rows_without_location");
+ if (dataset is not null)
+ {
+ ToWgs84(dataset, notices);
+ if (dataset.Features.Count == 0)
+ throw new ConversionRefusedException("error.geo_empty");
+ _logger.LogDebug("{File}: {Features} features read as {Format}, {Crs}", step.InputPath, dataset.Features.Count, step.From, dataset.Crs.Name);
+ if (dataset.RowsWithoutLocation)
+ notices.Add("notice.geo_rows_without_location");
+ if (activity is not null && step.To == "gpx" && dataset.Features[0].Geometry is GeoLineString line
+ && dataset.Features[0].FindText("time") is { } summary
+ && (line.Times is null || line.Times[0] is not { } first
+ || first.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture) != summary))
+ notices.Add("notice.geo_gpx_lossy");
+ }
progress?.Report(0.6);
var outputs = new List<string>();
try
{
- Write(dataset, step, outputs, notices, cancellationToken);
+ if (dataset is not null)
+ Write(dataset, step, outputs, notices, cancellationToken);
+ else if (activity is not null && step.Output.Allocate("csv") is { } csv)
+ {
+ outputs.Add(csv);
+ FitFormat.WriteCsv(activity, csv);
+ }
}
catch
{
@@ -170,7 +191,12 @@ public sealed class GeoConverter(ILogger? logger = null) : IConverter
continue;
string[] files = [shp, .. Siblings(shp)];
outputs.AddRange(files);
- var losses = ShapefileFormat.Write(group, shp, cancellationToken);
+ var positions = group.Records.SelectMany(record => record.Geometry?.Coordinates() ?? []);
+ var dropHeights = dataset.SparseHeights && positions.Any(point => point.HasZ)
+ && positions.Any(point => !point.HasZ);
+ var losses = ShapefileFormat.Write(group, shp, cancellationToken, dropHeights);
+ if (dropHeights)
+ notices.Add("notice.geo_heights_dropped");
if (losses.TextCut)
notices.Add("notice.geo_text_cut");
if (losses.ColumnsDropped)
@@ -220,7 +246,7 @@ public sealed class GeoConverter(ILogger? logger = null) : IConverter
{
private static readonly string[] Priority =
[
- "notice.geo_datum_assumed", "notice.geo_gpx_lossy", "notice.geo_text_cut", "notice.geo_columns_dropped",
+ "notice.geo_datum_assumed", "notice.geo_gpx_lossy", "notice.geo_heights_dropped", "notice.geo_text_cut", "notice.geo_columns_dropped",
"notice.geo_rows_without_location", "notice.geo_field_names", "notice.geo_shapefile_split",
];
diff --git a/src/Filee.Engines/Geo/GeoJsonFormat.cs b/src/Filee.Engines/Geo/GeoJsonFormat.cs
index c29fed16..7a427864 100644
--- a/src/Filee.Engines/Geo/GeoJsonFormat.cs
+++ b/src/Filee.Engines/Geo/GeoJsonFormat.cs
@@ -210,7 +210,7 @@ internal static class GeoJsonFormat
cancellationToken.ThrowIfCancellationRequested();
buffer.Clear();
writer.Reset(buffer);
- WriteFeature(writer, dataset.Features[i]);
+ WriteFeature(writer, dataset.Features[i], dataset.SparseHeights);
writer.Flush();
if (i > 0)
stream.Write(",\n"u8);
@@ -219,24 +219,39 @@ internal static class GeoJsonFormat
stream.Write("\n]}\n"u8);
}
- private static void WriteFeature(Utf8JsonWriter writer, GeoFeature feature)
+ private static void WriteFeature(Utf8JsonWriter writer, GeoFeature feature, bool sparseHeights)
{
writer.WriteStartObject();
writer.WriteString("type", "Feature");
writer.WriteStartObject("properties");
var written = new HashSet<string>(StringComparer.Ordinal);
+ var times = (feature.Geometry as GeoLineString)?.Times;
foreach (var (key, value) in feature.Properties)
{
+ if (times is not null && key.Equals("coordTimes", StringComparison.OrdinalIgnoreCase))
+ continue;
// A repeated name (two columns that only differ in case elsewhere) would make duplicate JSON keys.
if (!written.Add(key))
continue;
writer.WritePropertyName(key);
WriteValue(writer, value);
}
+ if (times is not null)
+ {
+ writer.WriteStartArray("coordTimes");
+ foreach (var time in times)
+ {
+ if (time is { } value)
+ writer.WriteStringValue(value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
+ else
+ writer.WriteNullValue();
+ }
+ writer.WriteEndArray();
+ }
writer.WriteEndObject();
writer.WritePropertyName("geometry");
if (feature.Geometry is { } geometry)
- WriteGeometry(writer, geometry);
+ WriteGeometry(writer, geometry, sparseHeights);
else
writer.WriteNullValue();
writer.WriteEndObject();
@@ -270,7 +285,7 @@ internal static class GeoJsonFormat
}
}
- private static void WriteGeometry(Utf8JsonWriter writer, GeoGeometry geometry)
+ private static void WriteGeometry(Utf8JsonWriter writer, GeoGeometry geometry, bool sparseHeights)
{
writer.WriteStartObject();
writer.WriteString("type", geometry.TypeName);
@@ -278,7 +293,7 @@ internal static class GeoJsonFormat
{
writer.WriteStartArray("geometries");
foreach (var member in collection.Geometries)
- WriteGeometry(writer, member);
+ WriteGeometry(writer, member, sparseHeights);
writer.WriteEndArray();
writer.WriteEndObject();
return;
@@ -288,55 +303,55 @@ internal static class GeoJsonFormat
switch (geometry)
{
case GeoPoint point:
- WritePosition(writer, point.Position, hasZ);
+ WritePosition(writer, point.Position, hasZ, sparseHeights);
break;
case GeoMultiPoint multiPoint:
- WriteLine(writer, multiPoint.Points, hasZ);
+ WriteLine(writer, multiPoint.Points, hasZ, sparseHeights);
break;
case GeoLineString line:
- WriteLine(writer, line.Points, hasZ);
+ WriteLine(writer, line.Points, hasZ, sparseHeights);
break;
case GeoMultiLineString lines:
writer.WriteStartArray();
foreach (var part in lines.Lines)
- WriteLine(writer, part, hasZ);
+ WriteLine(writer, part, hasZ, sparseHeights);
writer.WriteEndArray();
break;
case GeoPolygon polygon:
- WritePolygon(writer, polygon, hasZ);
+ WritePolygon(writer, polygon, hasZ, sparseHeights);
break;
case GeoMultiPolygon polygons:
writer.WriteStartArray();
foreach (var part in polygons.Polygons)
- WritePolygon(writer, part, hasZ);
+ WritePolygon(writer, part, hasZ, sparseHeights);
writer.WriteEndArray();
break;
}
writer.WriteEndObject();
}
- private static void WritePolygon(Utf8JsonWriter writer, GeoPolygon polygon, bool hasZ)
+ private static void WritePolygon(Utf8JsonWriter writer, GeoPolygon polygon, bool hasZ, bool sparseHeights)
{
writer.WriteStartArray();
for (var i = 0; i < polygon.Rings.Count; i++)
- WriteLine(writer, GeoRings.Oriented(polygon.Rings[i], counterClockwise: i == 0), hasZ);
+ WriteLine(writer, GeoRings.Oriented(polygon.Rings[i], counterClockwise: i == 0), hasZ, sparseHeights);
writer.WriteEndArray();
}
- private static void WriteLine(Utf8JsonWriter writer, IReadOnlyList<Coord> points, bool hasZ)
+ private static void WriteLine(Utf8JsonWriter writer, IReadOnlyList<Coord> points, bool hasZ, bool sparseHeights)
{
writer.WriteStartArray();
foreach (var point in points)
- WritePosition(writer, point, hasZ);
+ WritePosition(writer, point, hasZ, sparseHeights);
writer.WriteEndArray();
}
- private static void WritePosition(Utf8JsonWriter writer, Coord position, bool hasZ)
+ private static void WritePosition(Utf8JsonWriter writer, Coord position, bool hasZ, bool sparseHeights)
{
writer.WriteStartArray();
writer.WriteRawValue(GeoText.Degrees(position.X));
writer.WriteRawValue(GeoText.Degrees(position.Y));
- if (hasZ)
+ if (hasZ && (!sparseHeights || position.HasZ))
writer.WriteRawValue(GeoText.Height(position.HasZ ? position.Z : 0));
writer.WriteEndArray();
}
diff --git a/src/Filee.Engines/Geo/GeoModel.cs b/src/Filee.Engines/Geo/GeoModel.cs
index b1d42b0f..03325381 100644
--- a/src/Filee.Engines/Geo/GeoModel.cs
+++ b/src/Filee.Engines/Geo/GeoModel.cs
@@ -54,12 +54,14 @@ internal sealed class GeoMultiPoint(IReadOnlyList<Coord> points) : GeoGeometry
public override IEnumerable<GeoGeometry> Parts() => Points.Select(p => new GeoPoint(p));
}
-internal sealed class GeoLineString(IReadOnlyList<Coord> points) : GeoGeometry
+internal sealed class GeoLineString(IReadOnlyList<Coord> points, IReadOnlyList<DateTime?>? times = null) : GeoGeometry
{
public IReadOnlyList<Coord> Points { get; } = points;
+ /// <summary>UTC times aligned with <see cref="Points"/>, or null when point times are unknown.</summary>
+ public IReadOnlyList<DateTime?>? Times { get; } = times;
public override string TypeName => "LineString";
public override IEnumerable<Coord> Coordinates() => Points;
- public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoLineString(Map(Points, map));
+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoLineString(Map(Points, map), Times);
}
internal sealed class GeoMultiLineString(IReadOnlyList<IReadOnlyList<Coord>> lines) : GeoGeometry
@@ -144,6 +146,9 @@ internal sealed class GeoDataset
/// <summary>True if some rows of a CSV had no usable location and so have no geometry.</summary>
public bool RowsWithoutLocation { get; set; }
+ /// <summary>True when a missing height must stay absent rather than be written as zero.</summary>
+ public bool SparseHeights { get; set; }
+
/// <summary>The attribute names of all features, in the order they first appear.</summary>
public List<string> Columns()
{
diff --git a/src/Filee.Engines/Geo/GpxFormat.cs b/src/Filee.Engines/Geo/GpxFormat.cs
index d60d9289..34bd4db4 100644
--- a/src/Filee.Engines/Geo/GpxFormat.cs
+++ b/src/Filee.Engines/Geo/GpxFormat.cs
@@ -2,7 +2,8 @@
// into a LineString (one segment) or MultiLineString (several), with name, comment, description, source, symbol, type,
// time and the point's elevation (as the height). "gpx_type" says which of the three a feature was. Per-point times of
// tracks are not kept. Writing puts Points into waypoints, lines into tracks (or routes when gpx_type says "route"),
-// and the outlines of polygons into tracks, since GPX has no areas; only the fields above survive. GPX is WGS 84.
+// and the outlines of polygons into tracks, since GPX has no areas; only the fields above survive. Writing keeps
+// point times when a line has them. GPX is WGS 84.
using System.Globalization;
using System.Xml;
@@ -111,7 +112,7 @@ internal static class GpxFormat
var asRoute = string.Equals(feature.FindText("gpx_type"), "route", StringComparison.OrdinalIgnoreCase);
// Points become waypoints; every line, and the outline of every polygon, is a segment of the feature's track
// (or a route of its own), so one feature stays one track.
- var lines = new List<IReadOnlyList<Coord>>();
+ var lines = new List<GeoLineString>();
var outlines = false;
foreach (var part in geometry.Parts())
{
@@ -121,11 +122,11 @@ internal static class GpxFormat
WritePoint(writer, "wpt", point.Position, feature, withFields: true);
break;
case GeoLineString line:
- lines.Add(line.Points);
+ lines.Add(line);
break;
case GeoPolygon polygon:
lossy = outlines = true;
- lines.AddRange(polygon.Rings);
+ lines.AddRange(polygon.Rings.Select(ring => new GeoLineString(ring)));
break;
}
}
@@ -137,7 +138,7 @@ internal static class GpxFormat
return lossy;
}
- private static void WriteLines(XmlWriter writer, IReadOnlyList<IReadOnlyList<Coord>> lines, GeoFeature feature, bool route)
+ private static void WriteLines(XmlWriter writer, IReadOnlyList<GeoLineString> lines, GeoFeature feature, bool route)
{
if (route)
{
@@ -146,7 +147,7 @@ internal static class GpxFormat
{
writer.WriteStartElement("rte");
WriteFields(writer, feature, trackFields: true);
- foreach (var point in line)
+ foreach (var point in line.Points)
WritePoint(writer, "rtept", point, feature, withFields: false);
writer.WriteEndElement();
}
@@ -157,20 +158,22 @@ internal static class GpxFormat
foreach (var line in lines)
{
writer.WriteStartElement("trkseg");
- foreach (var point in line)
- WritePoint(writer, "trkpt", point, feature, withFields: false);
+ for (var i = 0; i < line.Points.Count; i++)
+ WritePoint(writer, "trkpt", line.Points[i], feature, withFields: false, pointTime: line.Times?[i]);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
- private static void WritePoint(XmlWriter writer, string element, Coord point, GeoFeature feature, bool withFields)
+ private static void WritePoint(XmlWriter writer, string element, Coord point, GeoFeature feature, bool withFields, DateTime? pointTime = null)
{
writer.WriteStartElement(element);
writer.WriteAttributeString("lat", GeoText.Degrees(point.Y));
writer.WriteAttributeString("lon", GeoText.Degrees(point.X));
if (point.HasZ)
writer.WriteElementString("ele", GeoText.Height(point.Z));
+ if (pointTime is { } timestamp)
+ writer.WriteElementString("time", timestamp.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
if (withFields)
{
if (Time(feature.FindText("time")) is { } time)
diff --git a/src/Filee.Engines/Geo/KmlFormat.cs b/src/Filee.Engines/Geo/KmlFormat.cs
index 6eaf51d1..c6c35c37 100644
--- a/src/Filee.Engines/Geo/KmlFormat.cs
+++ b/src/Filee.Engines/Geo/KmlFormat.cs
@@ -2,9 +2,13 @@
// name, description and ExtendedData (Data and SimpleData) as attributes, and Point, LineString, LinearRing, Polygon,
// MultiGeometry and Google's gx:Track as geometry. Styles, icons, overlays, network links and time spans are not data
// of the features and are left out. KMZ is a ZIP with the .kml inside (doc.kml first). Writing makes one Document with
-// a Placemark per feature; attributes go to ExtendedData. KML positions are always WGS 84 longitude, latitude, height.
+// a Placemark per feature; attributes go to ExtendedData. A line with a time and a height on every point (a FIT activity)
+// is written as a gx:Track; other timed lines keep their times as coordTimes data. KML positions are always WGS 84
+// longitude, latitude, height.
+using System.Globalization;
using System.IO.Compression;
+using System.Text.Json;
using System.Xml;
using System.Xml.Linq;
@@ -13,6 +17,7 @@ namespace Filee.Engines.Geo;
internal static class KmlFormat
{
private static readonly XNamespace Kml = "http://www.opengis.net/kml/2.2";
+ private const string Gx = "http://www.google.com/kml/ext/2.2";
/// <summary>The largest .kml a KMZ may hold, declared or really unpacked: a ZIP of a few KB can claim far more.</summary>
internal const long MaxKmlBytes = 256L << 20;
@@ -254,24 +259,27 @@ internal static class KmlFormat
foreach (var feature in dataset.Features)
{
cancellationToken.ThrowIfCancellationRequested();
- WritePlacemark(writer, feature);
+ WritePlacemark(writer, feature, dataset.SparseHeights);
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
- private static void WritePlacemark(XmlWriter writer, GeoFeature feature)
+ private static void WritePlacemark(XmlWriter writer, GeoFeature feature, bool sparseHeights)
{
writer.WriteStartElement("Placemark");
+ var line = feature.Geometry as GeoLineString;
+ var track = line is not null && IsTrack(line);
var name = feature.FindText("name", "title", "label");
if (name is not null)
writer.WriteElementString("name", GeoXml.Clean(name));
var description = feature.FindText("description", "desc", "comment");
if (description is not null)
writer.WriteElementString("description", GeoXml.Clean(description));
- var extra = feature.Properties.Where(p => !IsNameOrDescription(p.Key, name, description, feature)).ToList();
- if (extra.Count > 0)
+ var extra = feature.Properties.Where(p => !IsNameOrDescription(p.Key, name, description, feature)
+ && (line?.Times is null || !p.Key.Equals("coordTimes", StringComparison.OrdinalIgnoreCase))).ToList();
+ if (extra.Count > 0 || line?.Times is not null && !track)
{
writer.WriteStartElement("ExtendedData");
var used = new HashSet<string>(StringComparer.Ordinal);
@@ -284,10 +292,18 @@ internal static class KmlFormat
writer.WriteElementString("value", GeoXml.Clean(GeoText.ToText(value)));
writer.WriteEndElement();
}
+ if (line?.Times is not null && !track)
+ {
+ writer.WriteStartElement("Data");
+ writer.WriteAttributeString("name", "coordTimes");
+ writer.WriteElementString("value", JsonSerializer.Serialize(line.Times.Select(t =>
+ t?.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))));
+ writer.WriteEndElement();
+ }
writer.WriteEndElement();
}
if (feature.Geometry is { } geometry)
- WriteGeometry(writer, geometry);
+ WriteGeometry(writer, geometry, sparseHeights);
writer.WriteEndElement();
}
@@ -310,53 +326,70 @@ internal static class KmlFormat
return null;
}
- private static void WriteGeometry(XmlWriter writer, GeoGeometry geometry)
+ private static void WriteGeometry(XmlWriter writer, GeoGeometry geometry, bool sparseHeights)
{
switch (geometry)
{
case GeoPoint point:
writer.WriteStartElement("Point");
- WriteCoordinates(writer, [point.Position]);
+ WriteCoordinates(writer, [point.Position], sparseHeights);
writer.WriteEndElement();
break;
case GeoLineString line:
- writer.WriteStartElement("LineString");
- WriteCoordinates(writer, line.Points);
+ if (line.Times is { } times && IsTrack(line))
+ {
+ writer.WriteStartElement("gx", "Track", Gx);
+ foreach (var time in times)
+ writer.WriteElementString("when", time!.Value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
+ foreach (var point in line.Points)
+ writer.WriteElementString("gx", "coord", Gx,
+ $"{GeoText.Degrees(point.X)} {GeoText.Degrees(point.Y)} {GeoText.Height(point.Z)}");
+ }
+ else
+ {
+ writer.WriteStartElement("LineString");
+ WriteCoordinates(writer, line.Points, sparseHeights);
+ }
writer.WriteEndElement();
break;
case GeoPolygon polygon:
- WritePolygon(writer, polygon);
+ WritePolygon(writer, polygon, sparseHeights);
break;
default:
// Several parts of one feature: MultiGeometry holds the simple geometries.
writer.WriteStartElement("MultiGeometry");
foreach (var part in geometry.Parts())
- WriteGeometry(writer, part);
+ WriteGeometry(writer, part, sparseHeights);
writer.WriteEndElement();
break;
}
}
- private static void WritePolygon(XmlWriter writer, GeoPolygon polygon)
+ /// <summary>gx:Track needs a time and a height for every point: Google's reference reads gx:coord as
+ /// longitude, latitude and altitude, and a missing height is not made up.</summary>
+ private static bool IsTrack(GeoLineString line) =>
+ line.Times is not null && line.Times.All(t => t.HasValue) && line.Points.All(p => p.HasZ);
+
+ private static void WritePolygon(XmlWriter writer, GeoPolygon polygon, bool sparseHeights)
{
writer.WriteStartElement("Polygon");
for (var i = 0; i < polygon.Rings.Count; i++)
{
writer.WriteStartElement(i == 0 ? "outerBoundaryIs" : "innerBoundaryIs");
writer.WriteStartElement("LinearRing");
- WriteCoordinates(writer, GeoRings.Oriented(polygon.Rings[i], counterClockwise: i == 0));
+ WriteCoordinates(writer, GeoRings.Oriented(polygon.Rings[i], counterClockwise: i == 0), sparseHeights);
writer.WriteEndElement();
writer.WriteEndElement();
}
writer.WriteEndElement();
}
- private static void WriteCoordinates(XmlWriter writer, IReadOnlyList<Coord> points)
+ private static void WriteCoordinates(XmlWriter writer, IReadOnlyList<Coord> points, bool sparseHeights)
{
var hasZ = points.Any(p => p.HasZ);
writer.WriteStartElement("coordinates");
writer.WriteString(string.Join(' ', points.Select(p =>
- hasZ ? $"{GeoText.Degrees(p.X)},{GeoText.Degrees(p.Y)},{GeoText.Height(p.HasZ ? p.Z : 0)}" : $"{GeoText.Degrees(p.X)},{GeoText.Degrees(p.Y)}")));
+ hasZ && (!sparseHeights || p.HasZ) ? $"{GeoText.Degrees(p.X)},{GeoText.Degrees(p.Y)},{GeoText.Height(p.HasZ ? p.Z : 0)}" : $"{GeoText.Degrees(p.X)},{GeoText.Degrees(p.Y)}")));
writer.WriteEndElement();
}
}
diff --git a/src/Filee.Engines/Geo/ShapefileFormat.cs b/src/Filee.Engines/Geo/ShapefileFormat.cs
index 2b83126e..5597cc7d 100644
--- a/src/Filee.Engines/Geo/ShapefileFormat.cs
+++ b/src/Filee.Engines/Geo/ShapefileFormat.cs
@@ -332,10 +332,10 @@ internal static class ShapefileFormat
};
/// <summary>Writes <paramref name="group"/> as <paramref name="shpPath"/> with its .shx, .dbf, .prj and .cpg beside it.</summary>
- public static DbfLosses Write(ShapefileGroup group, string shpPath, CancellationToken cancellationToken)
+ public static DbfLosses Write(ShapefileGroup group, string shpPath, CancellationToken cancellationToken, bool dropHeights = false)
{
var shapes = group.Records;
- var hasZ = shapes.Any(r => r.Geometry?.HasZ == true);
+ var hasZ = !dropHeights && shapes.Any(r => r.Geometry?.HasZ == true);
var multiPoint = group.Kind == ShapeKind.Point && shapes.Any(r => r.Geometry is GeoMultiPoint { Points.Count: not 1 });
var shapeType = group.Kind switch
{
diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs
index c268796a..88ad21cd 100644
--- a/tests/Filee.Cli.Tests/CliTests.cs
+++ b/tests/Filee.Cli.Tests/CliTests.cs
@@ -1,6 +1,8 @@
// End-to-end tests of the "filee" command: real engines, a temporary settings folder, files in a temporary folder.
+using System.Buffers.Binary;
using System.Text.Json;
+using System.Xml.Linq;
using Filee.Core.Presets;
namespace Filee.Cli.Tests;
@@ -32,6 +34,67 @@ public sealed class CliTests : IDisposable
return (code, output.ToString(), errors.ToString());
}
+ private static readonly ushort[] FitCrcTable =
+ [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400];
+
+ private static ushort FitCrc(IEnumerable<byte> bytes)
+ {
+ ushort crc = 0;
+ foreach (var b in bytes)
+ {
+ crc = (ushort)((crc >> 4) ^ FitCrcTable[crc & 0xF] ^ FitCrcTable[b & 0xF]);
+ crc = (ushort)((crc >> 4) ^ FitCrcTable[crc & 0xF] ^ FitCrcTable[b >> 4]);
+ }
+ return crc;
+ }
+
+ /// <summary>A FIT activity built from the protocol: a 14-byte header, an activity file_id, one record
+ /// definition (timestamp, latitude, longitude) with a message per point, and the header and file CRCs.</summary>
+ private static byte[] FitActivity(params (uint Time, int Lat, int Lon)[] points)
+ {
+ var data = new List<byte> { 0x40, 0, 0, 0, 0, 1, 0, 1, 0, 0x00, 4 };
+ data.AddRange([0x41, 0, 0, 20, 0, 3, 253, 4, 0x86, 0, 4, 0x85, 1, 4, 0x85]);
+ var value = new byte[4];
+ foreach (var (time, lat, lon) in points)
+ {
+ data.Add(0x01);
+ BinaryPrimitives.WriteUInt32LittleEndian(value, time);
+ data.AddRange(value);
+ BinaryPrimitives.WriteInt32LittleEndian(value, lat);
+ data.AddRange(value);
+ BinaryPrimitives.WriteInt32LittleEndian(value, lon);
+ data.AddRange(value);
+ }
+ var file = new List<byte> { 14, 0x10, 0x34, 0x08 };
+ BinaryPrimitives.WriteInt32LittleEndian(value, data.Count);
+ file.AddRange(value);
+ file.AddRange(".FIT"u8.ToArray());
+ var headerCrc = FitCrc(file);
+ file.AddRange([(byte)headerCrc, (byte)(headerCrc >> 8)]);
+ file.AddRange(data);
+ var fileCrc = FitCrc(file);
+ file.AddRange([(byte)fileCrc, (byte)(fileCrc >> 8)]);
+ return [.. file];
+ }
+
+ [Fact]
+ public async Task Fit_activity_converts_to_gpx_with_point_times_using_the_builtin_preset()
+ {
+ var fit = Path.Combine(_folder, "ride.fit");
+ File.WriteAllBytes(fit, FitActivity((0x1000003B, 0x20000000, 0x40000000), (0x1000003C, 0x30000000, 0x30000000),
+ (0x1000003D, 0x40000000, 0x20000000)));
+
+ var (code, output, errors) = await Run("convert", fit, "--preset", "to-gpx");
+
+ Assert.Equal(Cli.Success, code);
+ Assert.Equal("", errors);
+ Assert.Contains("Converted 1 of 1", output);
+ var gpx = XDocument.Load(Path.Combine(_folder, "ride.gpx"));
+ var points = gpx.Descendants().Where(element => element.Name.LocalName == "trkpt").ToArray();
+ Assert.Equal(3, points.Length);
+ Assert.All(points, point => Assert.Single(point.Elements(), element => element.Name.LocalName == "time"));
+ }
+
[Fact]
public async Task Converts_files_and_wildcards_into_an_output_folder()
{
diff --git a/tests/Filee.Core.Tests/FitFormatRegistrationTests.cs b/tests/Filee.Core.Tests/FitFormatRegistrationTests.cs
new file mode 100644
index 00000000..8e89f0c0
--- /dev/null
+++ b/tests/Filee.Core.Tests/FitFormatRegistrationTests.cs
@@ -0,0 +1,55 @@
+// Garmin FIT activities (#451): read-only geospatial input, learned by existing libraries.
+
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class FitFormatRegistrationTests
+{
+ [Theory]
+ [InlineData("ride.fit")]
+ [InlineData("RIDE.FIT")]
+ public void Fit_is_a_read_only_geospatial_format(string file)
+ {
+ var format = FormatRegistry.Detect(file);
+
+ Assert.NotNull(format);
+ Assert.Equal(("fit", FormatCategory.Geo, false), (format.Id, format.Category, format.Writable));
+ }
+
+ [Fact]
+ public void Fresh_profiles_open_the_geospatial_donut_for_fit() =>
+ Assert.Equal("geo", ProfileSelector.Select(BuiltInData.CreateProfiles(), ["a.fit"])?.Id);
+
+ [Fact]
+ public void Version_46_libraries_learn_fit_once()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles();
+ var geo = profiles.Single(p => p.Id == "geo");
+ geo.Extensions.Remove("fit");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(46, presets, profiles));
+
+ Assert.Contains("fit", geo.Extensions);
+ Assert.False(SettingsMigrations.ApplyToLibrary(46, presets, profiles));
+ }
+
+ [Fact]
+ public void Version_46_migration_keeps_a_custom_fit_claim()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles();
+ var geo = profiles.Single(p => p.Id == "geo");
+ geo.Extensions.Remove("fit");
+ profiles.Insert(0, new ToolbarProfile { Id = "activities", Extensions = ["fit"] });
+
+ SettingsMigrations.ApplyToLibrary(46, presets, profiles);
+
+ Assert.DoesNotContain("fit", geo.Extensions);
+ Assert.Equal("activities", ProfileSelector.Select(profiles, ["ride.fit"])?.Id);
+ }
+}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 15d907f1..eb523f94 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -874,7 +874,7 @@ public class UserDataStoreTests
Assert.Equal(ids.IndexOf("models") + 1, ids.IndexOf("geo"));
Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("geo"));
var geo = profiles.Single(p => p.Id == "geo");
- Assert.Equal(["geojson", "kml", "kmz", "gpx", "shp"], geo.Extensions);
+ Assert.Equal(["geojson", "kml", "kmz", "gpx", "shp", "fit"], geo.Extensions);
Assert.Equal(BuiltInData.GeoProfile().PresetIds, geo.PresetIds);
Assert.All(geo.PresetIds, id => Assert.Contains(presets, p => p.Id == id));
Assert.False(SettingsMigrations.ApplyToLibrary(24, presets, profiles)); // once only
@@ -888,10 +888,10 @@ public class UserDataStoreTests
profiles.Insert(0, new ToolbarProfile { Id = "earth", Name = "Earth", Extensions = ["kml", "kmz"] });
Assert.True(SettingsMigrations.ApplyToLibrary(24, presets, profiles));
- Assert.Equal(["geojson", "gpx", "shp"], profiles.Single(p => p.Id == "geo").Extensions);
+ Assert.Equal(["geojson", "gpx", "shp", "fit"], profiles.Single(p => p.Id == "geo").Extensions);
var taken = BuiltInData.CreateProfiles().Where(p => p.Id != "geo").ToList();
- taken.Insert(0, new ToolbarProfile { Id = "all", Name = "All", Extensions = ["geojson", "kml", "kmz", "gpx", "shp"] });
+ taken.Insert(0, new ToolbarProfile { Id = "all", Name = "All", Extensions = ["geojson", "kml", "kmz", "gpx", "shp", "fit"] });
var geoIds = BuiltInData.GeoPresets().Select(p => p.Id).ToHashSet();
var withoutPresets = BuiltInData.CreatePresets().Where(p => !geoIds.Contains(p.Id)).ToList();
@@ -914,7 +914,7 @@ public class UserDataStoreTests
var geo = profiles.Single(p => p.Id == "geo");
Assert.Equal(["to-kml"], geo.PresetIds);
// The extensions of the default donut that no donut takes yet are added to it, after the user's own.
- Assert.Equal(["kml", "geojson", "kmz", "gpx", "shp"], geo.Extensions);
+ Assert.Equal(["kml", "geojson", "kmz", "gpx", "shp", "fit"], geo.Extensions);
}
[Fact]
diff --git a/tests/Filee.Engines.Tests/FitBuilder.cs b/tests/Filee.Engines.Tests/FitBuilder.cs
new file mode 100644
index 00000000..9923ebea
--- /dev/null
+++ b/tests/Filee.Engines.Tests/FitBuilder.cs
@@ -0,0 +1,164 @@
+// Creates FIT protocol samples in memory; no device recordings are checked into the repository.
+
+using System.Buffers.Binary;
+using Filee.Engines.Geo;
+
+namespace Filee.Engines.Tests;
+
+internal sealed class FitBuilder
+{
+ private readonly List<byte> data = [];
+ private readonly Dictionary<int, (FitField[] Fields, int[] DeveloperSizes)> definitions = [];
+
+ internal readonly record struct FitField(byte Number, byte Type, byte[] Value);
+ internal readonly record struct DeveloperField(byte Number, byte[] Value, byte Index = 0);
+
+ public static FitField U8(byte number, byte value, byte type = 0) => new(number, type, [value]);
+ public static FitField U16(byte number, ushort value, bool big = false) => new(number, 0x84, Bytes(value, big));
+ public static FitField U32(byte number, uint value, bool big = false) => new(number, 0x86, Bytes(value, big));
+ public static FitField S32(byte number, int value, bool big = false) => new(number, 0x85, Bytes((uint)value, big));
+
+ private static byte[] Bytes(ushort value, bool big)
+ {
+ var bytes = new byte[2];
+ if (big) BinaryPrimitives.WriteUInt16BigEndian(bytes, value);
+ else BinaryPrimitives.WriteUInt16LittleEndian(bytes, value);
+ return bytes;
+ }
+
+ private static byte[] Bytes(uint value, bool big)
+ {
+ var bytes = new byte[4];
+ if (big) BinaryPrimitives.WriteUInt32BigEndian(bytes, value);
+ else BinaryPrimitives.WriteUInt32LittleEndian(bytes, value);
+ return bytes;
+ }
+
+ /// <summary>Defines a local message, including optional developer fields which the reader must skip.</summary>
+ public FitBuilder Define(int local, ushort message, bool big = false, byte architecture = 0,
+ DeveloperField[]? developer = null, params FitField[] fields)
+ {
+ data.Add((byte)(0x40 | local | (developer is { Length: > 0 } ? 0x20 : 0)));
+ data.Add(0);
+ data.Add(big ? (byte)1 : architecture);
+ data.AddRange(Bytes(message, big));
+ data.Add((byte)fields.Length);
+ foreach (var field in fields)
+ {
+ data.Add(field.Number);
+ data.Add((byte)field.Value.Length);
+ data.Add(field.Type);
+ }
+ if (developer is { Length: > 0 })
+ {
+ data.Add((byte)developer.Length);
+ foreach (var field in developer)
+ {
+ data.Add(field.Number);
+ data.Add((byte)field.Value.Length);
+ data.Add(field.Index);
+ }
+ }
+ definitions[local] = (fields, developer?.Select(f => f.Value.Length).ToArray() ?? []);
+ return this;
+ }
+
+ /// <summary>Writes a data message in definition order, including the developer field payloads.</summary>
+ public FitBuilder Message(int local, FitField[] fields, params DeveloperField[] developer) =>
+ AddMessage((byte)local, local, fields, developer);
+
+ public FitBuilder Compressed(int local, byte offset, FitField[] fields, params DeveloperField[] developer) =>
+ AddMessage((byte)(0x80 | (local << 5) | (offset & 31)), local, fields, developer);
+
+ private FitBuilder AddMessage(byte header, int local, FitField[] fields, DeveloperField[] developer)
+ {
+ var definition = definitions[local];
+ if (definition.Fields.Length != fields.Length || definition.DeveloperSizes.Length != developer.Length)
+ throw new ArgumentException("The message must match its definition.");
+ data.Add(header);
+ for (var i = 0; i < fields.Length; i++)
+ {
+ if (fields[i].Value.Length != definition.Fields[i].Value.Length)
+ throw new ArgumentException("The field must match its definition's size.");
+ data.AddRange(fields[i].Value);
+ }
+ for (var i = 0; i < developer.Length; i++)
+ {
+ if (developer[i].Value.Length != definition.DeveloperSizes[i])
+ throw new ArgumentException("The developer field must match its definition's size.");
+ data.AddRange(developer[i].Value);
+ }
+ return this;
+ }
+
+ public FitBuilder FileId(byte type = 4, int local = 15)
+ {
+ var field = U8(0, type);
+ return Define(local, 0, fields: [field]).Message(local, [field]);
+ }
+
+ public FitBuilder Session(uint start, byte sport, int local = 2, bool big = false)
+ {
+ var fields = new[] { U32(2, start, big), U8(5, sport) };
+ return Define(local, 18, big: big, fields: fields).Message(local, fields);
+ }
+
+ /// <summary>Builds a complete 12- or 14-byte header with optional zero header CRC and a valid file CRC.</summary>
+ public byte[] Build(int headerSize = 14, bool headerCrc = true)
+ {
+ if (headerSize is not (12 or 14))
+ throw new ArgumentOutOfRangeException(nameof(headerSize));
+ var bytes = new byte[headerSize + data.Count + 2];
+ bytes[0] = (byte)headerSize;
+ bytes[1] = 0x10;
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), (uint)data.Count);
+ ".FIT"u8.CopyTo(bytes.AsSpan(8));
+ if (headerSize == 14 && headerCrc)
+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(12), FitFormat.FitCrc(bytes.AsSpan(0, 12)));
+ data.CopyTo(bytes, headerSize);
+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(headerSize + data.Count), FitFormat.FitCrc(bytes.AsSpan(0, headerSize + data.Count)));
+ return bytes;
+ }
+
+ public static byte[] FlipHeaderCrc(byte[] bytes)
+ {
+ var copy = (byte[])bytes.Clone();
+ copy[12] ^= 1;
+ return copy;
+ }
+
+ public static byte[] FlipFileCrc(byte[] bytes)
+ {
+ var copy = (byte[])bytes.Clone();
+ copy[^1] ^= 1;
+ return copy;
+ }
+
+ public static byte[] CutShort(byte[] bytes) => bytes[..^1];
+ public static byte[] ExtraBytes(byte[] bytes) => [.. bytes, 0x42];
+ public static byte[] Chained(byte[] bytes) => [.. bytes, .. bytes];
+
+ /// <summary>A valid CRC around malformed data, to exercise structural refusals rather than the CRC gate.</summary>
+ public static byte[] RawData(params byte[] payload)
+ {
+ var bytes = new byte[14 + payload.Length + 2];
+ bytes[0] = 14;
+ bytes[1] = 0x10;
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), (uint)payload.Length);
+ ".FIT"u8.CopyTo(bytes.AsSpan(8));
+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(12), FitFormat.FitCrc(bytes.AsSpan(0, 12)));
+ payload.CopyTo(bytes, 14);
+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(14 + payload.Length), FitFormat.FitCrc(bytes.AsSpan(0, 14 + payload.Length)));
+ return bytes;
+ }
+
+ public static byte[] InvalidArchitecture() => RawData(0x40, 0, 2, 0, 0, 0);
+ public static byte[] UndefinedLocal(int local = 3) => RawData((byte)local);
+
+ public static string Save(string folder, byte[] bytes, string name = "sample.fit")
+ {
+ var path = Path.Combine(folder, name);
+ File.WriteAllBytes(path, bytes);
+ return path;
+ }
+}
diff --git a/tests/Filee.Engines.Tests/FitFormatTests.cs b/tests/Filee.Engines.Tests/FitFormatTests.cs
new file mode 100644
index 00000000..35ac5138
--- /dev/null
+++ b/tests/Filee.Engines.Tests/FitFormatTests.cs
@@ -0,0 +1,383 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text.Json;
+using System.Xml.Linq;
+using Filee.Core.Formats;
+using Filee.Engines.Geo;
+
+namespace Filee.Engines.Tests;
+
+public class FitFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const uint First = 0x1000003B;
+ private static DateTime Utc(uint seconds) => DateTime.UnixEpoch.AddSeconds(seconds + 631065600L);
+ private static string Stamp(uint seconds) => Utc(seconds).ToString("yyyy-MM-ddTHH:mm:ssZ");
+
+ private string Save(FitBuilder builder) => FitBuilder.Save(fx.NewFolder(), builder.Build(), "ride.fit");
+
+ private string Track(params (uint? Time, int? Lat, int? Lon, ushort? Height)[] records) =>
+ Save(Append(new FitBuilder().FileId(), records));
+
+ private static FitBuilder Append(FitBuilder builder, params (uint? Time, int? Lat, int? Lon, ushort? Height)[] records)
+ {
+ foreach (var (time, lat, lon, height) in records)
+ {
+ var fields = new List<FitBuilder.FitField>();
+ if (time is { } t) fields.Add(FitBuilder.U32(253, t));
+ if (lat is { } y) fields.Add(FitBuilder.S32(0, y));
+ if (lon is { } x) fields.Add(FitBuilder.S32(1, x));
+ if (height is { } z) fields.Add(FitBuilder.U16(2, z));
+ builder.Define(0, 20, fields: [.. fields]).Message(0, [.. fields]);
+ }
+ return builder;
+ }
+
+ private static (uint?, int?, int?, ushort?)[] Three(bool times = true, bool heights = true) =>
+ [
+ (times ? First : null, 0x20000000, 0x40000000, heights ? (ushort)3000 : null),
+ (times ? First + 1 : null, 0x30000000, 0x20000000, heights ? (ushort)3010 : null),
+ (times ? First + 2 : null, 0x10000000, 0x30000000, heights ? (ushort)3020 : null),
+ ];
+
+ private static XElement[] Elements(string path, string name) =>
+ [.. XDocument.Load(path).Descendants().Where(e => e.Name.LocalName == name)];
+
+ private static string? Child(XElement element, string name) =>
+ element.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value;
+
+ private static JsonElement Feature(JsonDocument document) =>
+ document.RootElement.GetProperty("features")[0];
+
+ /// <summary>Converts the FIT file to CSV, XLSX and JSON, checks that the XLSX (read back as CSV) and the JSON hold
+ /// the same rows and values as the CSV, and returns the CSV lines.</summary>
+ private async Task<string[]> SameTables(string input)
+ {
+ var csv = File.ReadAllLines((await fx.ConvertOkAsync(input, "csv")).Single());
+ var xlsx = (await fx.ConvertOkAsync(input, "xlsx")).Single();
+ Assert.Equal(csv, File.ReadAllLines((await fx.ConvertOkAsync(xlsx, "csv")).Single()));
+ using var json = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "json")).Single());
+ var header = csv[0].Split(',');
+ Assert.Equal(csv[1..], json.RootElement.EnumerateArray().Select(row => string.Join(",", header.Select(column =>
+ row.GetProperty(column) is { ValueKind: JsonValueKind.String } text ? text.GetString() : row.GetProperty(column).GetRawText()))));
+ return csv;
+ }
+
+ [Fact]
+ public async Task Fit_track_to_gpx_keeps_order_coordinates_heights_and_point_times()
+ {
+ var gpx = (await fx.ConvertOkAsync(Track(Three()), "gpx")).Single();
+ var points = Elements(gpx, "trkpt");
+ Assert.Single(Elements(gpx, "trk"));
+ Assert.Equal(3, points.Length);
+ Assert.Equal(["45", "67.5", "22.5"], points.Select(p => (string?)p.Attribute("lat")));
+ Assert.Equal(["90", "45", "67.5"], points.Select(p => (string?)p.Attribute("lon")));
+ Assert.Equal(["100", "102", "104"], points.Select(p => Child(p, "ele")));
+ Assert.Equal([Stamp(First), Stamp(First + 1), Stamp(First + 2)], points.Select(p => Child(p, "time")));
+ Assert.Equal([45.0, 67.5, 22.5], Assert.IsType<GeoLineString>(
+ Assert.Single(GpxFormat.Read(gpx, CancellationToken.None).Features).Geometry).Points.Select(p => p.Y));
+ }
+
+ [Fact]
+ public async Task Gpx_only_reports_a_different_or_unrepresentable_summary_start()
+ {
+ var records = Three();
+ foreach (var (start, notice) in new (uint?, string?)[]
+ {
+ (null, null), (First - 10, "notice.geo_gpx_lossy"),
+ })
+ {
+ var builder = new FitBuilder().FileId();
+ if (start is { } t) builder.Session(t, 1);
+ var input = Save(Append(builder, records));
+ var job = await fx.ConvertAsync(input, "gpx");
+ Assert.Equal(notice, job.Files.Single().NoticeKey);
+ }
+ var withoutTimes = Save(Append(new FitBuilder().FileId().Session(First, 1), Three(times: false)));
+ Assert.Equal("notice.geo_gpx_lossy", (await fx.ConvertAsync(withoutTimes, "gpx")).Files.Single().NoticeKey);
+ var point = (await fx.ConvertOkAsync(Track((First, 0x20000000, 0x40000000, 3000)), "gpx")).Single();
+ Assert.Equal(Stamp(First), Child(Assert.Single(Elements(point, "wpt")), "time"));
+ }
+
+ [Fact]
+ public async Task Single_position_is_a_point_in_each_spatial_format()
+ {
+ foreach (var height in new ushort?[] { 3000, null })
+ {
+ var input = Track((First, 0x20000000, 0x40000000, height));
+ var gpx = (await fx.ConvertOkAsync(input, "gpx")).Single();
+ Assert.Single(Elements(gpx, "wpt"));
+ var kml = (await fx.ConvertOkAsync(input, "kml")).Single();
+ Assert.Single(Elements(kml, "Point"));
+ using var json = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single());
+ Assert.Equal("Point", Feature(json).GetProperty("geometry").GetProperty("type").GetString());
+ Assert.Equal(Stamp(First), Feature(json).GetProperty("properties").GetProperty("time").GetString());
+ var shp = (await fx.ConvertOkAsync(input, "shp")).Single(p => p.EndsWith(".shp", StringComparison.Ordinal));
+ Assert.Equal(height is null ? 1 : 11, BinaryPrimitives.ReadInt32LittleEndian(File.ReadAllBytes(shp).AsSpan(32)));
+ var position = Assert.IsType<GeoPoint>(Assert.Single(ShapefileFormat.Read(shp, CancellationToken.None).Features).Geometry).Position;
+ Assert.Equal(90, position.X);
+ Assert.Equal(45, position.Y);
+ Assert.Equal(height is null ? double.NaN : 100, position.Z);
+ }
+ }
+
+ [Fact]
+ public async Task No_positions_refuses_spatial_outputs_but_keeps_tabular_records()
+ {
+ var input = Track((First, null, null, null), (First + 1, null, null, 3000));
+ foreach (var target in new[] { "gpx", "kml", "kmz", "geojson", "shp" })
+ {
+ Assert.Equal("error.fit_no_positions", (await fx.ConvertFailsAsync(input, target)).Key);
+ Assert.Equal([input], Directory.GetFiles(Path.GetDirectoryName(input)!));
+ }
+ Assert.Equal(["time,longitude,latitude,elevation,heart_rate,cadence,power,speed,distance",
+ $"{Stamp(First)},,,,,,,,", $"{Stamp(First + 1)},,,100,,,,,"], await SameTables(input));
+ }
+
+ [Fact]
+ public async Task Kml_tracks_and_kmz_payload_keep_all_point_times()
+ {
+ var input = Track(Three());
+ var kml = (await fx.ConvertOkAsync(input, "kml")).Single();
+ var xml = XDocument.Load(kml);
+ Assert.Single(xml.Descendants(), e => e.Name.LocalName == "Track");
+ Assert.Equal([Stamp(First), Stamp(First + 1), Stamp(First + 2)],
+ xml.Descendants().Where(e => e.Name.LocalName == "when").Select(e => e.Value));
+ Assert.Equal(["90 45 100", "45 67.5 102", "67.5 22.5 104"],
+ xml.Descendants().Where(e => e.Name.LocalName == "coord").Select(e => e.Value));
+ Assert.Equal(3, Assert.IsType<GeoLineString>(Assert.Single(KmlFormat.Read(kml, false, CancellationToken.None).Features).Geometry).Points.Count);
+ using var archive = ZipFile.OpenRead((await fx.ConvertOkAsync(input, "kmz")).Single());
+ using var stream = archive.GetEntry("doc.kml")!.Open();
+ using var copy = new MemoryStream();
+ stream.CopyTo(copy);
+ Assert.Equal(File.ReadAllBytes(kml), copy.ToArray());
+ }
+
+ [Fact]
+ public async Task Geojson_times_follow_each_line_position_and_survive_reading()
+ {
+ var output = (await fx.ConvertOkAsync(Track(Three()), "geojson")).Single();
+ using var doc = GeoFixtures.ReadJson(output);
+ var times = Feature(doc).GetProperty("properties").GetProperty("coordTimes");
+ Assert.Equal([Stamp(First), Stamp(First + 1), Stamp(First + 2)], times.EnumerateArray().Select(t => t.GetString()));
+ Assert.Equal(3, Feature(doc).GetProperty("geometry").GetProperty("coordinates").GetArrayLength());
+ Assert.Equal(times.GetRawText(), Assert.Single(GeoJsonFormat.Read(output, CancellationToken.None).Features).FindText("coordTimes"));
+ }
+
+ [Fact]
+ public async Task Partly_missing_times_keep_every_position_without_inventing_times()
+ {
+ var first = new[] { FitBuilder.S32(0, 0x20000000), FitBuilder.S32(1, 0x40000000), FitBuilder.U16(2, 3000) };
+ var invalid = new[] { FitBuilder.U32(253, uint.MaxValue), FitBuilder.S32(0, 0x30000000),
+ FitBuilder.S32(1, 0x20000000), FitBuilder.U16(2, 3010) };
+ var last = new[] { FitBuilder.U32(253, First + 2), FitBuilder.S32(0, 0x10000000),
+ FitBuilder.S32(1, 0x30000000), FitBuilder.U16(2, 3020) };
+ var input = Save(new FitBuilder().FileId().Define(1, 20, fields: first).Compressed(1, 0, first)
+ .Define(0, 20, fields: invalid).Message(0, invalid).Message(0, last));
+ var gpx = (await fx.ConvertOkAsync(input, "gpx")).Single();
+ Assert.Equal([null, null, Stamp(First + 2)], Elements(gpx, "trkpt").Select(p => Child(p, "time")));
+ var kml = (await fx.ConvertOkAsync(input, "kml")).Single();
+ Assert.Empty(Elements(kml, "Track"));
+ Assert.Equal(3, Assert.IsType<GeoLineString>(Assert.Single(KmlFormat.Read(kml, false, CancellationToken.None).Features).Geometry).Points.Count);
+ Assert.Equal($"[null,null,\"{Stamp(First + 2)}\"]", Assert.Single(Elements(kml, "Data"),
+ data => (string?)data.Attribute("name") == "coordTimes").Value);
+ using var json = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single());
+ var times = Feature(json).GetProperty("properties").GetProperty("coordTimes");
+ Assert.Equal(JsonValueKind.Null, times[0].ValueKind);
+ Assert.Equal(JsonValueKind.Null, times[1].ValueKind);
+ Assert.Equal(3, times.GetArrayLength());
+ }
+
+ [Fact]
+ public async Task Completely_missing_times_leave_tracks_without_time_attributes()
+ {
+ var input = Track(Three(times: false));
+ Assert.Empty(Elements((await fx.ConvertOkAsync(input, "gpx")).Single(), "time"));
+ var kml = (await fx.ConvertOkAsync(input, "kml")).Single();
+ Assert.Empty(Elements(kml, "Track"));
+ Assert.Empty(Elements(kml, "Data"));
+ Assert.Single(Elements(kml, "LineString"));
+ using var json = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single());
+ Assert.False(Feature(json).GetProperty("properties").TryGetProperty("coordTimes", out _));
+ Assert.Equal(3, Feature(json).GetProperty("geometry").GetProperty("coordinates").GetArrayLength());
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task Sparse_heights_are_never_fabricated_and_shapefile_drops_them_with_notice(bool times)
+ {
+ var records = Three(times);
+ records[1].Item4 = null;
+ var input = Track(records);
+ var gpx = (await fx.ConvertOkAsync(input, "gpx")).Single();
+ Assert.Equal(["100", null, "104"], Elements(gpx, "trkpt").Select(p => Child(p, "ele")));
+ var kml = (await fx.ConvertOkAsync(input, "kml")).Single();
+ Assert.Equal("90,45,100 45,67.5 67.5,22.5,104", Assert.Single(Elements(kml, "coordinates")).Value);
+ Assert.Empty(Elements(kml, "Track"));
+ Assert.Equal(times, Elements(kml, "Data").Any(data => (string?)data.Attribute("name") == "coordTimes"));
+ using var json = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single());
+ Assert.Equal([3, 2, 3], Feature(json).GetProperty("geometry").GetProperty("coordinates")
+ .EnumerateArray().Select(position => position.GetArrayLength()));
+ var csv = File.ReadAllLines((await fx.ConvertOkAsync(input, "csv")).Single());
+ Assert.Equal("", csv[2].Split(',')[3]);
+ var job = await fx.ConvertAsync(input, "shp");
+ Assert.Equal("notice.geo_heights_dropped", job.Files.Single().NoticeKey);
+ var shp = job.Outputs.Single(p => p.EndsWith(".shp", StringComparison.Ordinal));
+ Assert.Equal(3, BinaryPrimitives.ReadInt32LittleEndian(File.ReadAllBytes(shp).AsSpan(32)));
+ Assert.Equal([90.0, 45, 67.5], Assert.IsType<GeoLineString>(
+ Assert.Single(ShapefileFormat.Read(shp, CancellationToken.None).Features).Geometry).Points.Select(p => p.X));
+ var full = await fx.ConvertAsync(Track(Three(times)), "shp");
+ Assert.NotEqual("notice.geo_heights_dropped", full.Files.Single().NoticeKey);
+ Assert.Equal(13, BinaryPrimitives.ReadInt32LittleEndian(File.ReadAllBytes(
+ full.Outputs.Single(p => p.EndsWith(".shp", StringComparison.Ordinal))).AsSpan(32)));
+ }
+
+ [Fact]
+ public async Task Fit_csv_has_fixed_columns_units_and_skips_empty_records()
+ {
+ var fields = new[] { FitBuilder.U32(253, First), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000), FitBuilder.U16(2, 3000), FitBuilder.U8(3, 72),
+ FitBuilder.U8(4, 88), FitBuilder.U16(7, 210), FitBuilder.U16(6, 4321), FitBuilder.U32(5, 12345) };
+ var builder = new FitBuilder().FileId().Define(0, 20, fields: fields).Message(0, fields)
+ .Define(3, 132, fields: [FitBuilder.U8(3, 99)]).Message(3, [FitBuilder.U8(3, 99)]);
+ var input = Save(Append(builder, (null, null, null, 3000), (null, null, null, null)));
+ var csv = File.ReadAllText((await fx.ConvertOkAsync(input, "csv")).Single());
+ Assert.StartsWith("time,longitude,latitude,elevation,heart_rate,cadence,power,speed,distance\r\n", csv);
+ Assert.Contains($"{Stamp(First)},90,45,100,72,88,210,4.321,123.45\r\n", csv);
+ Assert.Equal(2, csv.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Length);
+ Assert.DoesNotContain(",99,", csv);
+ var noRecords = Track((null, null, null, 3000), (null, null, null, null));
+ foreach (var target in new[] { "csv", "xlsx", "json" })
+ Assert.Equal("error.fit_no_records", (await fx.ConvertFailsAsync(noRecords, target)).Key);
+ Assert.Equal([noRecords], Directory.GetFiles(Path.GetDirectoryName(noRecords)!));
+ }
+
+ [Fact]
+ public async Task Csv_xlsx_and_json_contain_the_same_records_including_missing_locations()
+ {
+ var fields = new[] { FitBuilder.U32(253, First), FitBuilder.S32(0, 0x20000000), FitBuilder.S32(1, 0x40000000) };
+ var missing = new[] { FitBuilder.U32(253, First + 1), FitBuilder.S32(0, int.MaxValue), FitBuilder.S32(1, 0x40000000) };
+ var input = Save(new FitBuilder().FileId().Define(0, 20, fields: fields).Message(0, fields).Message(0, missing));
+ var csv = await SameTables(input);
+ Assert.Equal(3, csv.Length);
+ Assert.StartsWith($"{Stamp(First)},90,45,", csv[1]);
+ Assert.StartsWith(Stamp(First + 1) + ",,,,", csv[2]);
+ }
+
+ [Fact]
+ public async Task Header_endianness_compressed_time_and_developer_fields_keep_output_equal()
+ {
+ var ordinary = new[] { FitBuilder.U32(253, First), FitBuilder.S32(0, 0x20000000), FitBuilder.S32(1, 0x40000000) };
+ var baseline = new FitBuilder().FileId().Define(0, 20, fields: ordinary).Message(0, ordinary);
+ var expectedCsv = File.ReadAllBytes((await fx.ConvertOkAsync(Save(baseline), "csv")).Single());
+ var expectedGpx = File.ReadAllBytes((await fx.ConvertOkAsync(Save(baseline), "gpx")).Single());
+ foreach (var (headerSize, crc, big, developer) in new[]
+ {
+ (12, false, false, false), (14, false, false, false), (14, true, true, false),
+ (14, true, false, true),
+ })
+ {
+ var fields = new[] { FitBuilder.U32(253, First, big), FitBuilder.S32(0, 0x20000000, big),
+ FitBuilder.S32(1, 0x40000000, big) };
+ var sample = new FitBuilder().FileId().Define(0, 20, big: big,
+ developer: developer ? [new(9, [1])] : null, fields: fields)
+ .Message(0, fields, developer ? [new(9, [1])] : []);
+ var input = FitBuilder.Save(fx.NewFolder(), sample.Build(headerSize, crc), "ride.fit");
+ Assert.Equal(expectedCsv, File.ReadAllBytes((await fx.ConvertOkAsync(input, "csv")).Single()));
+ Assert.Equal(expectedGpx, File.ReadAllBytes((await fx.ConvertOkAsync(input, "gpx")).Single()));
+ }
+ var position = new[] { FitBuilder.S32(0, 0x20000000), FitBuilder.S32(1, 0x40000000) };
+ var compressed = Save(new FitBuilder().FileId().Define(0, 20, fields: ordinary).Message(0, ordinary)
+ .Define(1, 20, fields: position).Compressed(1, 0x1C, position));
+ Assert.Equal([Stamp(First), Stamp(First + 1)], Elements(
+ (await fx.ConvertOkAsync(compressed, "gpx")).Single(), "trkpt").Select(p => Child(p, "time")));
+ FitBuilder.FitField[] ordinaryValues = [.. ordinary, FitBuilder.U16(2, 3000), FitBuilder.U16(6, 4321)];
+ FitBuilder.FitField[] enhancedValues = [.. ordinary, FitBuilder.U32(78, 3000), FitBuilder.U32(73, 4321)];
+ var ordinaryInput = Save(new FitBuilder().FileId().Define(0, 20, fields: ordinaryValues).Message(0, ordinaryValues));
+ var enhancedInput = Save(new FitBuilder().FileId().Define(0, 20, fields: enhancedValues).Message(0, enhancedValues));
+ foreach (var target in new[] { "csv", "gpx" })
+ Assert.Equal(File.ReadAllBytes((await fx.ConvertOkAsync(ordinaryInput, target)).Single()),
+ File.ReadAllBytes((await fx.ConvertOkAsync(enhancedInput, target)).Single()));
+ }
+
+ [Fact]
+ public void Planner_uses_every_real_engine_to_match_gpx_reachability()
+ {
+ var planner = fx.Catalog.CreatePlanner();
+ foreach (var target in FormatRegistry.Known.Where(format => format.Writable))
+ Assert.Equal(target.Id == "gpx" || planner.Plan("gpx", target.Id) is not null,
+ planner.Plan("fit", target.Id) is not null);
+ }
+
+ [Fact]
+ public async Task Session_sport_and_earliest_start_are_feature_properties()
+ {
+ var records = Three();
+ var input = Save(Append(new FitBuilder().FileId().Session(First - 5, 1)
+ .Session(First - 10, 2).Session(First - 3, 1), records));
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single());
+ var properties = Feature(doc).GetProperty("properties");
+ Assert.Equal(["type", "time", "coordTimes"], properties.EnumerateObject().Select(p => p.Name));
+ Assert.Equal("running, cycling", properties.GetProperty("type").GetString());
+ Assert.Equal(Stamp(First - 10), properties.GetProperty("time").GetString());
+ var noSession = Track(records);
+ using var plain = GeoFixtures.ReadJson((await fx.ConvertOkAsync(noSession, "geojson")).Single());
+ Assert.Equal(Stamp(First), Feature(plain).GetProperty("properties").GetProperty("time").GetString());
+ using var timeless = GeoFixtures.ReadJson((await fx.ConvertOkAsync(Track(Three(times: false)), "geojson")).Single());
+ Assert.False(Feature(timeless).GetProperty("properties").TryGetProperty("time", out _));
+ using var unknown = GeoFixtures.ReadJson((await fx.ConvertOkAsync(Save(Append(
+ new FitBuilder().FileId().Session(First, 200), records)), "geojson")).Single());
+ Assert.Equal("200", Feature(unknown).GetProperty("properties").GetProperty("type").GetString());
+ }
+
+ [Fact]
+ public async Task Relative_timestamps_remain_empty_in_csv_and_gpx()
+ {
+ var input = Track((0x0FFFFFFF, 0x20000000, 0x40000000, 3000));
+ Assert.StartsWith("time,longitude", File.ReadAllText((await fx.ConvertOkAsync(input, "csv")).Single()));
+ Assert.StartsWith(",90,45", File.ReadAllLines((await fx.ConvertOkAsync(input, "csv")).Single())[1]);
+ Assert.Empty(Elements((await fx.ConvertOkAsync(input, "gpx")).Single(), "time"));
+ var position = new[] { FitBuilder.S32(0, 0x30000000), FitBuilder.S32(1, 0x40000000) };
+ var relative = new[] { FitBuilder.U32(253, 0x0FFFFFFF), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000) };
+ var unknown = Save(new FitBuilder().FileId().Define(0, 20, fields: relative).Message(0, relative)
+ .Define(1, 20, fields: position).Compressed(1, 0, position));
+ Assert.Empty(Elements((await fx.ConvertOkAsync(unknown, "gpx")).Single(), "time"));
+ var absolute = relative.Select(field => field.Number == 253 ? FitBuilder.U32(253, First) : field).ToArray();
+ var following = Save(new FitBuilder().FileId().Define(0, 20, fields: absolute).Message(0, absolute)
+ .Message(0, relative).Define(1, 20, fields: position).Compressed(1, 0x1D, position));
+ Assert.Equal([Stamp(First), null, Stamp(First + 2)],
+ Elements((await fx.ConvertOkAsync(following, "gpx")).Single(), "trkpt").Select(p => Child(p, "time")));
+ }
+
+ [Fact]
+ public async Task Existing_geo_inputs_do_not_gain_fit_times_or_sparse_height_rules()
+ {
+ const string mixed = """{"type":"LineString","coordinates":[[10,20,100],[11,21],[12,22,300]]}""";
+ var input = GeoFixtures.WriteText(fx, "mixed.geojson", mixed);
+ var job = await fx.ConvertAsync(input, "shp");
+ Assert.NotEqual("notice.geo_heights_dropped", job.Files.Single().NoticeKey);
+ Assert.Equal(13, BinaryPrimitives.ReadInt32LittleEndian(File.ReadAllBytes(
+ job.Outputs.Single(p => p.EndsWith(".shp", StringComparison.Ordinal))).AsSpan(32)));
+ Assert.Contains("11,21,0", File.ReadAllText((await fx.ConvertOkAsync(input, "kml")).Single()));
+ using (var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(input, "geojson")).Single()))
+ Assert.Equal(0, Feature(doc).GetProperty("geometry").GetProperty("coordinates")[1][2].GetDouble());
+ const string gpx = """<gpx><trk><trkseg><trkpt lat="20" lon="10"><time>2026-10-24T00:00:00Z</time></trkpt><trkpt lat="21" lon="11"><time>2026-10-24T00:01:00Z</time></trkpt></trkseg></trk></gpx>""";
+ var old = GeoFixtures.WriteText(fx, "old.gpx", gpx);
+ Assert.Empty(Elements((await fx.ConvertOkAsync(old, "kml")).Single(), "Track"));
+ using var result = GeoFixtures.ReadJson((await fx.ConvertOkAsync(old, "geojson")).Single());
+ Assert.False(Feature(result).GetProperty("properties").TryGetProperty("coordTimes", out _));
+ var rewritten = Path.Combine(fx.NewFolder(), "rewritten.gpx");
+ GpxFormat.Write(GpxFormat.Read(old, CancellationToken.None), rewritten, CancellationToken.None);
+ Assert.Empty(Elements(rewritten, "time"));
+ var storedTimes = GeoFixtures.WriteText(fx, "stored.geojson",
+ """{"type":"Feature","properties":{"coordTimes":["2026-10-24T00:00:00Z",null]},"geometry":{"type":"LineString","coordinates":[[10,20],[11,21]]}}""");
+ using var preserved = GeoFixtures.ReadJson((await fx.ConvertOkAsync(storedTimes, "geojson")).Single());
+ Assert.Equal("""["2026-10-24T00:00:00Z",null]""",
+ Feature(preserved).GetProperty("properties").GetProperty("coordTimes").GetString());
+ var kept = (await fx.ConvertOkAsync(storedTimes, "kml")).Single();
+ Assert.Equal("""["2026-10-24T00:00:00Z",null]""", Assert.Single(Elements(kept, "Data"),
+ data => (string?)data.Attribute("name") == "coordTimes").Value);
+ Assert.Empty(Elements(kept, "Track"));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/FitReaderTests.cs b/tests/Filee.Engines.Tests/FitReaderTests.cs
new file mode 100644
index 00000000..48412425
--- /dev/null
+++ b/tests/Filee.Engines.Tests/FitReaderTests.cs
@@ -0,0 +1,259 @@
+using System.Buffers.Binary;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Engines.Geo;
+
+namespace Filee.Engines.Tests;
+
+public class FitReaderTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static DateTime Time(uint value) => DateTime.UnixEpoch.AddSeconds(value + 631065600L);
+
+ private FitActivity Read(FitBuilder builder, int headerSize = 14, bool headerCrc = true) =>
+ FitFormat.Read(FitBuilder.Save(fx.NewFolder(), builder.Build(headerSize, headerCrc)), CancellationToken.None);
+
+ private void Refused(byte[] bytes, string key, string? detail = null)
+ {
+ var path = FitBuilder.Save(fx.NewFolder(), bytes);
+ var error = Assert.Throws<ConversionRefusedException>(() => FitFormat.Read(path, CancellationToken.None));
+ Assert.Equal(key, error.ErrorKey);
+ Assert.Equal(detail, error.Detail);
+ }
+
+ [Fact]
+ public void Garmin_header_crc_matches_published_vector()
+ {
+ Assert.Equal(0x8596, FitFormat.FitCrc(Convert.FromHexString("0E104308780609002E464954")));
+ }
+
+ [Fact]
+ public void Record_values_enhanced_precedence_big_endian_and_sessions_are_read_in_file_order()
+ {
+ var first = new[] { FitBuilder.U32(253, 0x1000003B), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000), FitBuilder.U16(2, 3000), FitBuilder.U8(3, 72),
+ FitBuilder.U8(4, 88), FitBuilder.U32(5, 12345), FitBuilder.U16(6, 4321), FitBuilder.U16(7, 210),
+ FitBuilder.U32(73, 5678), FitBuilder.U32(78, 4000) };
+ var next = first.Select(f => f.Number == 253 ? FitBuilder.U32(253, 0x10000040) : f).ToArray();
+ var activity = Read(new FitBuilder().FileId().Define(0, 20, fields: first).Message(0, first)
+ .Session(0x10000035, 1).Session(0x10000030, 2)
+ .Message(0, next));
+
+ Assert.Equal(2, activity.Records.Count);
+ var record = activity.Records[0];
+ Assert.Equal(Time(0x1000003B), record.Time);
+ Assert.Equal(45, record.Latitude);
+ Assert.Equal(90, record.Longitude);
+ Assert.Equal(300, record.Elevation); // enhanced 4000 / 5 - 500, not ordinary 3000 / 5 - 500
+ Assert.Equal(72, record.HeartRate);
+ Assert.Equal(88, record.Cadence);
+ Assert.Equal(210, record.Power);
+ Assert.Equal(5.678, record.Speed);
+ Assert.Equal(123.45, record.Distance);
+ Assert.Equal(Time(0x10000040), activity.Records[1].Time);
+ Assert.Equal([Time(0x10000035), Time(0x10000030)], activity.Sessions.Select(s => s.StartTime));
+ Assert.Equal(["running", "cycling"], activity.Sessions.Select(s => s.SportName));
+ Assert.Equal("200", FitFormat.SportName(200));
+ Assert.Equal("canoeing", FitFormat.SportName(88));
+
+ var big = new[] { FitBuilder.U32(253, 0x1000003B, big: true), FitBuilder.S32(0, 0x20000000, big: true),
+ FitBuilder.S32(1, 0x40000000, big: true), FitBuilder.U32(73, 5678, big: true) };
+ var bigActivity = Read(new FitBuilder().FileId().Define(0, 20, big: true, fields: big).Message(0, big));
+ Assert.Equal(record.Time, bigActivity.Records[0].Time);
+ Assert.Equal(record.Latitude, bigActivity.Records[0].Latitude);
+ Assert.Equal(record.Longitude, bigActivity.Records[0].Longitude);
+ Assert.Equal(record.Speed, bigActivity.Records[0].Speed);
+ }
+
+ [Fact]
+ public void Missing_invalid_and_out_of_range_values_do_not_remove_other_record_data()
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x1000003B), FitBuilder.S32(0, int.MaxValue),
+ FitBuilder.S32(1, 0x40000000), FitBuilder.U16(2, ushort.MaxValue),
+ FitBuilder.U8(3, byte.MaxValue), FitBuilder.U8(4, 80) };
+ var outside = fields.Select(f => f.Number == 0 ? FitBuilder.S32(0, 0x41000000) : f).ToArray();
+ var activity = Read(new FitBuilder().FileId().Define(0, 20, fields: fields).Message(0, fields).Message(0, outside));
+ Assert.Equal(2, activity.Records.Count);
+ Assert.All(activity.Records, record =>
+ {
+ Assert.Null(record.Latitude);
+ Assert.Null(record.Longitude);
+ Assert.Null(record.Elevation);
+ Assert.Null(record.HeartRate);
+ Assert.Equal(80, record.Cadence);
+ Assert.Equal(Time(0x1000003B), record.Time);
+ });
+ }
+
+ [Fact]
+ public void Compressed_timestamps_roll_over_and_consume_all_defined_bytes()
+ {
+ var full = new[] { FitBuilder.U32(253, 0x1000003B), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000) };
+ var position = new[] { FitBuilder.S32(0, 0x30000000), FitBuilder.S32(1, 0x40000000) };
+ var changed = new[] { FitBuilder.U32(253, 0x10000055), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000) };
+ var activity = Read(new FitBuilder().FileId()
+ .Define(0, 20, fields: full).Message(0, full)
+ .Define(1, 20, fields: position)
+ .Compressed(1, 0x1D, position).Compressed(1, 0x05, position)
+ .Message(0, full).Compressed(0, 0x06, changed)
+ .Compressed(1, 0x17, position));
+ Assert.Equal(new uint[] { 0x1000003B, 0x1000003D, 0x10000045, 0x1000003B, 0x10000055, 0x10000057 }
+ .Select(value => (DateTime?)Time(value)).ToArray(), activity.Records.Select(r => r.Time).ToArray());
+ Assert.Equal([45.0, 67.5, 67.5, 45.0, 45.0, 67.5], activity.Records.Select(r => r.Latitude));
+ }
+
+ [Fact]
+ public void Twelve_byte_zero_crc_and_developer_messages_leave_records_unchanged()
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x1000003B), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000) };
+ foreach (var (size, crc) in new[] { (12, false), (14, false), (14, true) })
+ {
+ var record = Read(new FitBuilder().FileId()
+ .Define(3, 207, fields: [FitBuilder.U8(0, 1)]).Message(3, [FitBuilder.U8(0, 1)])
+ .Define(3, 206, fields: [FitBuilder.U8(0, 1)]).Message(3, [FitBuilder.U8(0, 1)])
+ .Define(3, 132, fields: [FitBuilder.U8(3, 99)]).Message(3, [FitBuilder.U8(3, 99)])
+ .Define(0, 20, developer: [new(1, [9, 8])], fields: fields)
+ .Message(0, fields, new FitBuilder.DeveloperField(1, [9, 8])), size, crc).Records.Single();
+ Assert.Equal(Time(0x1000003B), record.Time);
+ Assert.Equal(45, record.Latitude);
+ Assert.Null(record.HeartRate);
+ }
+ }
+
+ [Fact]
+ public void Corruptions_are_refused_with_the_first_matching_key_and_detail()
+ {
+ var valid = new FitBuilder().FileId().Build();
+ var cases = new (byte[] Bytes, string Key, string? Detail)[]
+ {
+ ([], "error.fit_not_fit", null),
+ (Encoding.ASCII.GetBytes("SIMPLE = FIT"), "error.fit_not_fit", null),
+ (FitBuilder.FlipHeaderCrc(valid), "error.fit_damaged", "header CRC"),
+ (FitBuilder.CutShort(valid), "error.fit_damaged", "cut short"),
+ (valid[..12], "error.fit_damaged", "cut short"),
+ (FitBuilder.FlipFileCrc(valid), "error.fit_damaged", "CRC"),
+ (FitBuilder.ExtraBytes(valid), "error.fit_damaged", "extra bytes"),
+ (FitBuilder.Chained(valid), "error.fit_chained", null),
+ (FitBuilder.InvalidArchitecture(), "error.fit_damaged", "architecture"),
+ (FitBuilder.UndefinedLocal(), "error.fit_damaged", "undefined local message 3"),
+ (new FitBuilder().Build(), "error.fit_no_file_id", null),
+ (new FitBuilder().FileId(255).Build(), "error.fit_no_file_id", null),
+ (FitBuilder.RawData(0x40), "error.fit_damaged", "cut short"),
+ (FitBuilder.RawData(0x40, 0, 0, 20, 0, 1, 0, 4, 0x86, 0), "error.fit_damaged", "cut short"),
+ };
+ foreach (var (bytes, key, detail) in cases)
+ Refused(bytes, key, detail);
+ }
+
+ [Fact]
+ public void Huge_declared_data_size_is_refused_before_allocating_it()
+ {
+ var bytes = new FitBuilder().FileId().Build(headerCrc: false);
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), 0x7FFFFFFF);
+ var path = FitBuilder.Save(fx.NewFolder(), bytes);
+ // Warm the parser before measuring allocations in the deliberately short input.
+ _ = Read(new FitBuilder().FileId());
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var error = Assert.Throws<ConversionRefusedException>(() => FitFormat.Read(path, CancellationToken.None));
+ Assert.True(GC.GetAllocatedBytesForCurrentThread() - before < 1_000_000);
+ Assert.Equal("error.fit_damaged", error.ErrorKey);
+ Assert.Equal("cut short", error.Detail);
+ }
+
+ [Fact]
+ public void Configurable_file_and_record_limits_refuse_only_excess()
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x1000003B), new FitBuilder.FitField(90, 0x02, new byte[100]) };
+ var builder = new FitBuilder().FileId().Define(0, 20, fields: fields);
+ for (var i = 0; i < 11; i++)
+ builder.Message(0, fields);
+ var path = FitBuilder.Save(fx.NewFolder(), builder.Build());
+ Assert.Equal(11, FitFormat.Read(path, CancellationToken.None, maxBytes: 2000, maxRecords: 11).Records.Count);
+ var records = Assert.Throws<ConversionRefusedException>(() => FitFormat.Read(path, CancellationToken.None, maxRecords: 10));
+ Assert.Equal("error.fit_too_large", records.ErrorKey);
+ Assert.Equal("2000000 records", records.Detail);
+ var bytes = Assert.Throws<ConversionRefusedException>(() => FitFormat.Read(path, CancellationToken.None, maxBytes: 1000));
+ Assert.Equal("error.fit_too_large", bytes.ErrorKey);
+ Assert.Equal("64 MB", bytes.Detail);
+ }
+
+ [Theory]
+ [InlineData(6, "course")]
+ [InlineData(5, "workout")]
+ [InlineData(2, "settings")]
+ [InlineData(32, "monitoring_b")]
+ [InlineData(200, "type 200")]
+ public void Non_activity_file_types_are_refused_even_when_they_contain_records(byte type, string detail)
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x1000003B) };
+ var error = Assert.Throws<ConversionRefusedException>(() =>
+ Read(new FitBuilder().FileId(type).Define(0, 20, fields: fields).Message(0, fields)));
+ Assert.Equal("error.fit_not_activity", error.ErrorKey);
+ Assert.Equal(detail, error.Detail);
+ }
+
+ [Fact]
+ public void Fits_and_fixed_seed_random_inputs_only_produce_fit_refusals()
+ {
+ Refused(Encoding.ASCII.GetBytes("SIMPLE = T"), "error.fit_not_fit");
+ var random = new Random(451);
+ for (var i = 0; i < 15; i++)
+ {
+ var bytes = new byte[random.Next(0, 3001)];
+ random.NextBytes(bytes);
+ var error = Assert.Throws<ConversionRefusedException>(() =>
+ FitFormat.Read(FitBuilder.Save(fx.NewFolder(), bytes), CancellationToken.None));
+ Assert.StartsWith("error.fit_", error.ErrorKey);
+ }
+ for (var i = 0; i < 15; i++)
+ {
+ var bytes = new byte[Math.Max(14, random.Next(0, 3001))];
+ random.NextBytes(bytes);
+ bytes[0] = 14;
+ ".FIT"u8.CopyTo(bytes.AsSpan(8));
+ var error = Assert.Throws<ConversionRefusedException>(() =>
+ FitFormat.Read(FitBuilder.Save(fx.NewFolder(), bytes), CancellationToken.None));
+ Assert.StartsWith("error.fit_", error.ErrorKey);
+ }
+ }
+
+ [Fact]
+ public void Relative_timestamps_never_create_an_absolute_time_or_replace_its_base()
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x0FFFFFFF) };
+ var absolute = new[] { FitBuilder.U32(253, 0x1000003B) };
+ var empty = Array.Empty<FitBuilder.FitField>();
+ var activity = Read(new FitBuilder().FileId()
+ .Define(0, 20, fields: fields).Message(0, fields)
+ .Define(1, 20, fields: empty).Compressed(1, 0, empty).Compressed(1, 1, empty)
+ .Message(0, absolute).Message(0, fields).Compressed(1, 0x1D, empty));
+ Assert.Equal([null, null, null, Time(0x1000003B), null, Time(0x1000003D)],
+ activity.Records.Select(r => r.Time));
+ }
+
+ [Fact]
+ public void Csv_has_exact_header_converted_units_and_only_substantive_records()
+ {
+ var fields = new[] { FitBuilder.U32(253, 0x1000003B), FitBuilder.S32(0, 0x20000000),
+ FitBuilder.S32(1, 0x40000000), FitBuilder.U16(2, 3000), FitBuilder.U8(3, 72),
+ FitBuilder.U8(4, 88), FitBuilder.U16(7, 210), FitBuilder.U16(6, 4321),
+ FitBuilder.U32(5, 12345) };
+ var activity = Read(new FitBuilder().FileId().Define(0, 20, fields: fields).Message(0, fields));
+ activity.Records.Add(new FitRecord(null, null, null, 17, null, null, null, null, null));
+ activity.Records.Add(new FitRecord(null, null, null, null, null, null, null, null, null));
+ activity.Records.Add(new FitRecord(null, null, null, 12, 60, null, null, null, null));
+ var path = Path.Combine(fx.NewFolder(), "records.csv");
+ FitFormat.WriteCsv(activity, path);
+ var bytes = File.ReadAllBytes(path);
+ Assert.Equal([0xEF, 0xBB, 0xBF], bytes[..3]);
+ Assert.Equal("time,longitude,latitude,elevation,heart_rate,cadence,power,speed,distance\r\n" +
+ $"{Time(0x1000003B):yyyy-MM-ddTHH:mm:ssZ},90,45,100,72,88,210,4.321,123.45\r\n" +
+ ",,,12,60,,,,\r\n", Encoding.UTF8.GetString(bytes[3..]));
+ var noRows = Assert.Throws<ConversionRefusedException>(() =>
+ FitFormat.WriteCsv(new FitActivity(), Path.Combine(fx.NewFolder(), "empty.csv")));
+ Assert.Equal("error.fit_no_records", noRows.ErrorKey);
+ Assert.Null(noRows.Detail);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/GeoPointTimesTests.cs b/tests/Filee.Engines.Tests/GeoPointTimesTests.cs
new file mode 100644
index 00000000..787e8ab7
--- /dev/null
+++ b/tests/Filee.Engines.Tests/GeoPointTimesTests.cs
@@ -0,0 +1,199 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text.Json;
+using System.Xml.Linq;
+using Filee.Engines.Geo;
+
+namespace Filee.Engines.Tests;
+
+public class GeoPointTimesTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly DateTime First = new(2026, 10, 24, 1, 2, 3, DateTimeKind.Utc);
+ private static readonly DateTime Last = First.AddMinutes(2);
+ private static readonly Coord[] AllHeights = [new(10, 20, 100), new(11, 21, 200), new(12, 22, 300)];
+ private static readonly Coord[] PartialHeights = [AllHeights[0], new(11, 21), AllHeights[2]];
+
+ private static GeoDataset Dataset(IReadOnlyList<Coord> points, IReadOnlyList<DateTime?>? times, bool sparseHeights = true)
+ {
+ var dataset = new GeoDataset { Name = "ride", SparseHeights = sparseHeights };
+ dataset.Features.Add(new GeoFeature(new GeoLineString(points, times), [new("type", "running")]));
+ return dataset;
+ }
+
+ private static void SamePoints(GeoDataset dataset, IReadOnlyList<Coord> points)
+ {
+ var line = Assert.IsType<GeoLineString>(Assert.Single(dataset.Features).Geometry);
+ Assert.Equal(points.ToArray(), line.Points.ToArray());
+ }
+
+ [Fact]
+ public void Mapping_a_line_preserves_the_time_list()
+ {
+ DateTime?[] times = [First, null, Last];
+ var line = new GeoLineString(PartialHeights, times);
+ var mapped = Assert.IsType<GeoLineString>(line.Map(p => p with { X = p.X + 1 }));
+ Assert.Same(times, mapped.Times);
+ Assert.Equal([11.0, 12.0, 13.0], mapped.Points.Select(p => p.X).ToArray());
+ Assert.Null(new GeoLineString(PartialHeights).Times);
+ Assert.False(new GeoDataset().SparseHeights);
+ }
+
+ [Theory]
+ [InlineData("all", false)]
+ [InlineData("partial", false)]
+ [InlineData("none", false)]
+ [InlineData("all", true)]
+ [InlineData("partial", true)]
+ [InlineData("none", true)]
+ public void Writers_keep_times_and_sparse_heights_in_their_own_forms(string timeCase, bool partialHeight)
+ {
+ DateTime?[]? times = timeCase switch
+ {
+ "all" => [First, First.AddMinutes(1), Last],
+ "partial" => [First, null, Last],
+ _ => null,
+ };
+ var points = partialHeight ? PartialHeights : AllHeights;
+ var dataset = Dataset(points, times);
+ var dir = fx.NewFolder();
+ var gpx = Path.Combine(dir, "ride.gpx");
+ var kml = Path.Combine(dir, "ride.kml");
+ var kmz = Path.Combine(dir, "ride.kmz");
+ var geojson = Path.Combine(dir, "ride.geojson");
+ Assert.False(GpxFormat.Write(dataset, gpx, CancellationToken.None));
+ KmlFormat.Write(dataset, kml, zipped: false, CancellationToken.None);
+ KmlFormat.Write(dataset, kmz, zipped: true, CancellationToken.None);
+ GeoJsonFormat.Write(dataset, geojson, CancellationToken.None);
+
+ var trackPoints = XDocument.Load(gpx).Descendants().Where(e => e.Name.LocalName == "trkpt").ToArray();
+ Assert.Equal(points.Length, trackPoints.Length);
+ for (var i = 0; i < points.Length; i++)
+ {
+ Assert.Equal(points[i].HasZ ? points[i].Z.ToString(System.Globalization.CultureInfo.InvariantCulture) : null,
+ trackPoints[i].Elements().FirstOrDefault(e => e.Name.LocalName == "ele")?.Value);
+ Assert.Equal(times?[i]?.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"),
+ trackPoints[i].Elements().FirstOrDefault(e => e.Name.LocalName == "time")?.Value);
+ Assert.Equal(new[] { "ele", "time" }.Where((_, n) => n == 0 ? points[i].HasZ : times?[i] is not null),
+ trackPoints[i].Elements().Select(e => e.Name.LocalName));
+ }
+ SamePoints(GpxFormat.Read(gpx, CancellationToken.None), points);
+
+ using (var archive = ZipFile.OpenRead(kmz))
+ using (var zipped = archive.GetEntry("doc.kml")!.Open())
+ using (var copy = new MemoryStream())
+ {
+ zipped.CopyTo(copy);
+ Assert.Equal(File.ReadAllBytes(kml), copy.ToArray());
+ }
+ var xml = XDocument.Load(kml);
+ var isTrack = timeCase == "all" && !partialHeight;
+ Assert.Equal(isTrack ? 1 : 0, xml.Descendants().Count(e => e.Name.LocalName == "Track"));
+ var when = xml.Descendants().Where(e => e.Name.LocalName == "when").Select(e => e.Value).ToArray();
+ var coords = xml.Descendants().Where(e => e.Name.LocalName == "coord").Select(e => e.Value).ToArray();
+ if (isTrack)
+ {
+ Assert.Equal(times!.Select(t => t!.Value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'")), when);
+ Assert.Equal(["10 20 100", "11 21 200", "12 22 300"], coords);
+ }
+ else
+ {
+ Assert.Empty(when);
+ Assert.Empty(coords);
+ Assert.Equal(partialHeight ? "10,20,100 11,21 12,22,300" : "10,20,100 11,21,200 12,22,300",
+ xml.Descendants().Single(e => e.Name.LocalName == "coordinates").Value);
+ }
+ var coordTimes = xml.Descendants().SingleOrDefault(e => e.Name.LocalName == "Data"
+ && (string?)e.Attribute("name") == "coordTimes");
+ Assert.Equal(times is not null && !isTrack, coordTimes is not null);
+ if (coordTimes is not null)
+ Assert.Equal(JsonSerializer.Serialize(times!.Select(t => t?.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"))),
+ coordTimes.Descendants().Single(e => e.Name.LocalName == "value").Value);
+ SamePoints(KmlFormat.Read(kml, zipped: false, CancellationToken.None), points);
+ SamePoints(KmlFormat.Read(kmz, zipped: true, CancellationToken.None), points);
+
+ using var json = JsonDocument.Parse(File.ReadAllBytes(geojson));
+ var feature = json.RootElement.GetProperty("features")[0];
+ var properties = feature.GetProperty("properties");
+ string[] propertyNames = times is null ? ["type"] : ["type", "coordTimes"];
+ Assert.Equal(propertyNames, properties.EnumerateObject().Select(p => p.Name).ToArray());
+ if (times is not null)
+ {
+ var actualTimes = properties.GetProperty("coordTimes");
+ Assert.Equal(3, actualTimes.GetArrayLength());
+ for (var i = 0; i < times.Length; i++)
+ Assert.Equal(times[i]?.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"), actualTimes[i].ValueKind == JsonValueKind.Null
+ ? null : actualTimes[i].GetString());
+ }
+ var positions = feature.GetProperty("geometry").GetProperty("coordinates");
+ for (var i = 0; i < points.Length; i++)
+ Assert.Equal(points[i].HasZ ? 3 : 2, positions[i].GetArrayLength());
+ SamePoints(GeoJsonFormat.Read(geojson, CancellationToken.None), points);
+ }
+
+ [Fact]
+ public void Drop_heights_writes_2d_point_and_polyline_records()
+ {
+ var dir = fx.NewFolder();
+ var dataset = Dataset(PartialHeights, [First, null, Last]);
+ dataset.Features.Add(new GeoFeature(new GeoPoint(new Coord(14, 24, 40)), []));
+ foreach (var group in ShapefileFormat.Plan(dataset))
+ {
+ var path = Path.Combine(dir, group.Kind + ".shp");
+ ShapefileFormat.Write(group, path, CancellationToken.None, dropHeights: true);
+ var bytes = File.ReadAllBytes(path);
+ var expectedType = group.Kind == ShapeKind.Point ? 1 : 3;
+ Assert.Equal(expectedType, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(32)));
+ Assert.Equal(expectedType, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(108)));
+ var restored = ShapefileFormat.Read(path, CancellationToken.None);
+ var input = group.Records.Single().Geometry!.Coordinates().ToArray();
+ var output = restored.Features.Single().Geometry!.Coordinates().ToArray();
+ Assert.Equal(input.Select(p => p with { Z = double.NaN }).ToArray(), output);
+ }
+ }
+
+ [Fact]
+ public void Default_writer_behavior_keeps_zero_filled_heights_and_existing_coordTimes()
+ {
+ var dataset = Dataset(PartialHeights, null, sparseHeights: false);
+ dataset.Features[0].Properties.Add(new("coordTimes", """["old"]"""));
+ var dir = fx.NewFolder();
+ var kml = Path.Combine(dir, "old.kml");
+ var json = Path.Combine(dir, "old.geojson");
+ var shp = Path.Combine(dir, "old.shp");
+ KmlFormat.Write(dataset, kml, zipped: false, CancellationToken.None);
+ GeoJsonFormat.Write(dataset, json, CancellationToken.None);
+ ShapefileFormat.Write(ShapefileFormat.Plan(dataset).Single(), shp, CancellationToken.None);
+ Assert.Contains("11,21,0", File.ReadAllText(kml));
+ Assert.Contains("""[11,21,0]""", File.ReadAllText(json));
+ using var doc = JsonDocument.Parse(File.ReadAllBytes(json));
+ Assert.Equal("""["old"]""", doc.RootElement.GetProperty("features")[0]
+ .GetProperty("properties").GetProperty("coordTimes").GetString());
+ Assert.Equal(13, BinaryPrimitives.ReadInt32LittleEndian(File.ReadAllBytes(shp).AsSpan(32)));
+ var restored = Assert.IsType<GeoLineString>(ShapefileFormat.Read(shp, CancellationToken.None).Features.Single().Geometry);
+ Assert.Equal(0, restored.Points[1].Z);
+ }
+
+ [Fact]
+ public void Missing_heights_stay_2d_and_generated_times_replace_old_attribute()
+ {
+ var dataset = Dataset([new(10, 20), new(11, 21)], [First, null]);
+ dataset.Features[0].Properties.Add(new("coordTimes", """["old"]"""));
+ var dir = fx.NewFolder();
+ var kml = Path.Combine(dir, "plain.kml");
+ var json = Path.Combine(dir, "plain.geojson");
+ KmlFormat.Write(dataset, kml, zipped: false, CancellationToken.None);
+ GeoJsonFormat.Write(dataset, json, CancellationToken.None);
+ var xml = XDocument.Load(kml);
+ Assert.Equal("10,20 11,21", xml.Descendants().Single(e => e.Name.LocalName == "coordinates").Value);
+ Assert.Equal("""["2026-10-24T01:02:03Z",null]""", xml.Descendants()
+ .Single(e => e.Name.LocalName == "Data" && (string?)e.Attribute("name") == "coordTimes").Value);
+ using var doc = JsonDocument.Parse(File.ReadAllBytes(json));
+ var feature = doc.RootElement.GetProperty("features")[0];
+ Assert.Equal("""["2026-10-24T01:02:03Z",null]""",
+ feature.GetProperty("properties").GetProperty("coordTimes").GetRawText());
+ Assert.All(feature.GetProperty("geometry").GetProperty("coordinates").EnumerateArray(),
+ position => Assert.Equal(2, position.GetArrayLength()));
+ SamePoints(KmlFormat.Read(kml, zipped: false, CancellationToken.None),
+ [new Coord(10, 20), new Coord(11, 21)]);
+ }
+}