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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Add geospatial vector conversion: Shapefile, GeoJSON, KML, KMZ, GPX, CSV
KAPPI1925d0c68dbbc44a
diff --git a/.gitattributes b/.gitattributesindex 6eda92c5..e4cd7dff 100644--- a/.gitattributes+++ b/.gitattributes@@ -20,3 +20,7 @@*.docx binary*.hwpx binary*.hwp binary+*.shp binary+*.shx binary+*.dbf binary+*.kmz binarydiff --git a/README.ko.md b/README.ko.mdindex 85fcd03f..b94adca6 100644--- a/README.ko.md+++ b/README.ko.md@@ -103,6 +103,7 @@| **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 || **데이터**: JSON, JSON Lines, YAML, TOML, XML · vCard | 서로 변환, CSV·XLSX(표 모양 데이터); vCard ↔ CSV || **3D 모델**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY; FBX는 읽기 | 서로 변환, PNG 미리보기 |+| **지리 정보(벡터)**: Shapefile, GeoJSON, KML, KMZ, GPX · 좌표가 있는 CSV | 서로 변환, CSV·XLSX·JSON; 투영 좌표계(UTM, 웹 메르카토르, 람베르트, 알버스)는 WGS 84 경위도로 변환 |표시가 없는 형식은 오피스·한컴오피스·LibreOffice 없이 바로 변환돼요.표시가 있는 형식은 추가 엔진이 필요하고, 필요할 때만 내려받아요: ¹ Ghostscript, ² LibreOffice, ³ Pandoc,diff --git a/README.md b/README.mdindex f80b3674..0b6b0c59 100644--- a/README.md+++ b/README.md@@ -103,6 +103,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other || **Data**: JSON, JSON Lines, YAML, TOML, XML · vCard | each other, CSV and XLSX (tables); vCard ↔ CSV || **3D models**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY; FBX read | each other, PNG preview |+| **Geospatial vectors**: Shapefile, GeoJSON, KML, KMZ, GPX · CSV with coordinates | each other and CSV / XLSX / JSON; 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,diff --git a/README.zh-CN.md b/README.zh-CN.mdindex b53d90fe..d3488041 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -102,6 +102,7 @@| **字体**:TTF、OTF、WOFF、WOFF2、EOT | 互相转换 || **数据**:JSON、JSON Lines、YAML、TOML、XML · vCard | 互相转换、CSV 和 XLSX(表格数据)、vCard ↔ CSV || **3D 模型**:GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY;FBX 仅读取 | 互相转换、PNG 预览 |+| **地理信息(矢量)**:Shapefile、GeoJSON、KML、KMZ、GPX · 带坐标的 CSV | 互相转换、CSV / XLSX / JSON;投影坐标系(UTM、Web 墨卡托、兰伯特、阿尔伯斯)会转换为 WGS 84 经纬度 |未标注的格式装好即用,无需 Office、韩文办公软件或 LibreOffice。标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpegdiff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 5ef91e29..829db2a0 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -26,6 +26,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) || rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** || Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 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 |@@ -713,6 +714,79 @@ binary 7.4 and 7.5, plain and compressed arrays, ASCII): a cube under a moved patemplated material and an embedded or neighbouring texture, Z-up files in metres, rotation orders, concave polygons andmaterials 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)++`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+geometry and its attributes in file order) and every writer takes it, so each pair is one step; through CSV the data+also reaches the spreadsheet and data engines (Shapefile → XLSX, GeoJSON → JSON, KML → HWPX, …).++- **Always WGS 84.** Whatever the source's coordinate system, results are longitude / latitude in degrees (and a height+ where there is one). A Shapefile in UTM, Web Mercator or Lambert becomes a GeoJSON that opens in the right place.+ Keeping the original system is not an option yet.+- **One file in, one set out.** A Shapefile is read from its `.shp`; the `.dbf` (attributes), `.prj` (coordinate system)+ and `.cpg` (text encoding) are found next to it in any letter case, the `.shx` is not needed. A Shapefile is written+ as `name.shp`, `.shx`, `.dbf`, `.prj` and `.cpg`; the engine returns all of them. The file names always match: when+ the `.shp` name is taken, the next free name is used for the whole set, and a leftover file of the same name (a lone+ `.dbf`) is never written over.+- **Same format again** (`shp → shp`, `geojson → geojson`) rewrites the file in WGS 84, which is how a projected+ Shapefile is reprojected, and splits mixed geometries (below).++What each format keeps:++| Format | Read | Written |+|---|---|---|+| GeoJSON | FeatureCollection, Feature or a bare geometry; UTF-8, UTF-16 or an old code page; comments and trailing commas; `id` (as the attribute `id`); the 2008 `crs` member for the systems below; attributes as text, numbers, true / false, null (lists and objects become their JSON text); Z | one feature per line, polygons in RFC 7946 winding (outer counter-clockwise), at most ten decimals |+| KML / KMZ | every Placemark wherever it sits (Document, Folders), `name`, `description`, `ExtendedData` (`Data`, `SimpleData`); Point, LineString, LinearRing, Polygon with holes, MultiGeometry (as Multi* when the parts are alike, else a collection), `gx:Track`, `gx:MultiTrack`; altitude; KMZ: `doc.kml`, else the first `.kml` inside | one Document with a Placemark per feature, `name` / `description` from the attributes of that name, all other attributes as `ExtendedData`, `MultiGeometry` for several parts; KMZ is a ZIP with `doc.kml` |+| 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 |++**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+Krüger's series), Mercator and Web Mercator, Lambert Conformal Conic (1 and 2 parallels), Albers;+metres, feet and US survey feet. They agree with PROJ to well under a millimetre: `GeoCrsTests` checks ten systems against reference+positions computed with pyproj. Anything else (Lambert azimuthal,+stereographic, oblique Mercator, WKT 2, geocentric, local) is **refused with its name** (`error.geo_unsupported_crs`)+rather than read as degrees. Coordinates outside the Earth with no usable system (`error.geo_unknown_crs`, a CSV or+GeoJSON in metres, a Shapefile without `.prj`) are refused too.++**Datums are not shifted.** WGS 84, NAD83, ETRS89, GDA, JGD, Korea 2000, CGCS2000, RGF93, SIRGAS and every other datum on+the GRS 80 / WGS 84 ellipsoid agree within a metre or two. A datum on another ellipsoid (Bessel, Airy, Clarke,+International: Tokyo / Korean 1985, DHDN, OSGB36, ED50, NAD27, …) is converted as if it were WGS 84, which can be+tens to hundreds of metres off, and the file carries the note `notice.geo_datum_assumed`.++**Shapefile writing.**++- A Shapefile holds one kind of geometry. Mixed data becomes `name_points`, `name_lines` and `name_polygons` (each a+ full set) with the note `notice.geo_shapefile_split`. A collection is split into its members, each a record with the+ attributes repeated; features without geometry go into the first file as null shapes.+- Polygons are written clockwise, holes counter-clockwise, rings closed; Multi* geometries are one record.+- `.dbf` columns: whole numbers as `N`, other numbers as `N` with the decimals they need (15 at most, 24 wide), true /+ false as `L`, everything else as text (`C`, up to 254 bytes; longer text is cut between characters,+ `notice.geo_text_cut`). A column that mixes numbers and text is text. Field names are cut to 10 bytes, made of letters,+ digits and underscores, and made unique (`population_2020`, `population_2021` → `population`, `populati_1`,+ `notice.geo_field_names`). More than 255 columns keep the first 255 (`notice.geo_columns_dropped`). Features without+ attributes get a record-number field `FID`, since a `.dbf` needs one.+- Reading takes the text encoding from the `.cpg`, else the language driver byte of the `.dbf`, else UTF-8 if the text is+ valid UTF-8, else Korean CP949, else Windows-1252. (Chinese GBK and Korean CP949 can't be told apart without a `.cpg`.)+- The files are limited to 2 GB (`error.geo_too_large`); whole files are read into memory, a few at a time.++**Safety.** XML (KML, GPX) is read without DTDs or external entities, so a file can't read other files or expand into+gigabytes, and a document is limited to 512 million characters (which also stops a KMZ that unpacks to far more than+it says). Counts and indexes in binary Shapefiles are checked against the record before anything is allocated, nesting+of JSON, WKT and WKT definitions is limited, and every failure is a reason the user can act on: a damaged file, a+system Filee can't convert, a CSV with no coordinates (`error.geo_*` in the language files). Nothing is written when a+conversion fails.++Tests: `GeoFormatTests`, `GeoShapefileTests`, `GeoCrsTests` and `GeoRobustnessTests` in `tests/Filee.Engines.Tests`. The+reference files in `tests/Filee.Engines.Tests/Geo` were written by GDAL (synthetic data), the Shapefile builder in+`GeoBuilders.cs` follows the ESRI specification for the cases GDAL won't write, and the written Shapefiles are parsed+in the tests from the specification, not read back with the engine. `GeoRobustnessTests` reads every reference file+truncated at every length and with random bytes changed.++Not here yet: raster data (GeoTIFF, bands), GeoPackage, zipped Shapefiles as input, datum shifts, more projections.+## HWPX reader`Hwp/Hwpx/HwpxReader*.cs` is the inverse of the writer: it reads an HWPX package into the same document model, sodiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex df3dd260..8c2eec2e 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -79,7 +79,22 @@"error.rhwp_timeout": "rhwp couldn't finish this long document in time","error.rhwp_timeout_calibre": "rhwp couldn't finish this long document in time. For an e-book, move Calibre above the HWPX writer in Settings → Engines, and Calibre makes the PDF much faster","error.conversion_failed": "The engine reported an error",+ "error.geo_empty": "The file has no features",+ "error.geo_unknown_crs": "The coordinates are not longitude and latitude, and the file doesn't name its coordinate system (next to a Shapefile, keep its .prj file)",+ "error.geo_unsupported_crs": "This coordinate system isn't supported yet",+ "error.geo_bad_coordinates": "The coordinates don't fit this coordinate system",+ "error.geo_csv_no_coordinates": "The CSV has no longitude/latitude columns and no WKT column",+ "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","notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",+ "notice.geo_datum_assumed": "The datum isn't WGS 84; positions were converted as if it were and can be off by up to hundreds of metres",+ "notice.geo_gpx_lossy": "GPX holds only points, routes and tracks with a few fields: other attributes were left out and polygons became tracks",+ "notice.geo_text_cut": "Some text was longer than a Shapefile field allows (254 bytes) and was cut",+ "notice.geo_columns_dropped": "A Shapefile holds 255 columns at most: the rest were left out",+ "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","engine.reason.not_installed": "Not installed","engine.reason.error": "Error while checking",@@ -105,6 +120,7 @@"engine.font.description": "Fonts: TTF, OTF, WOFF, WOFF2 and EOT into each other.","engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.","engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, FBX into any of them, and a PNG preview.",+ "engine.geo.description": "Geospatial vector data: GeoJSON, KML, KMZ, GPX, Shapefile and CSV (longitude/latitude or WKT) into each other.\nResults are WGS 84 longitude/latitude; projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted.","engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, ISO and more, and packs ZIP, 7Z or TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text.\nAlso documents to EPUB, EPUB to KEPUB for Kobo and PDF to CBZ.","engine.subtitle.description": "Subtitles: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD and SCC into each other, saved as UTF-8.\nKorean SMI and SRT files in CP949 / EUC-KR read correctly.",@@ -131,6 +147,7 @@"profile.fonts": "Fonts","profile.data": "Data","profile.models": "3D models",+ "profile.geo": "Geospatial","profile.mixed": "Mixed files","preset.half_size": "Half size",@@ -179,6 +196,7 @@"format.category.Subtitle": "Subtitle","format.category.Data": "Data","format.category.Model3D": "3D model",+ "format.category.Geo": "Geospatial","general.title": "General","general.language": "Language",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex a4a7658f..0f45f043 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -73,7 +73,22 @@"error.rhwp_timeout": "rhwp no pudo terminar este documento largo a tiempo","error.rhwp_timeout_calibre": "rhwp no pudo terminar este documento largo a tiempo. Para un libro electrónico, mueve Calibre por encima del escritor HWPX en Ajustes → Motores; Calibre genera el PDF mucho más rápido","error.conversion_failed": "El motor devolvió un error",+ "error.geo_empty": "El archivo no contiene ningún elemento",+ "error.geo_unknown_crs": "Las coordenadas no son longitud y latitud y el archivo no indica su sistema de coordenadas (junto a un Shapefile, conserva su archivo .prj)",+ "error.geo_unsupported_crs": "Este sistema de coordenadas aún no es compatible",+ "error.geo_bad_coordinates": "Las coordenadas no encajan en este sistema de coordenadas",+ "error.geo_csv_no_coordinates": "El CSV no tiene columnas de longitud/latitud ni una columna WKT",+ "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","notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",+ "notice.geo_datum_assumed": "El datum no es WGS 84; las posiciones se convirtieron como si lo fuera y pueden desviarse hasta cientos de metros",+ "notice.geo_gpx_lossy": "GPX solo guarda puntos, rutas y tracks con pocos campos: se omitieron los demás atributos y los polígonos pasaron a ser tracks",+ "notice.geo_text_cut": "Parte del texto superaba la longitud de campo de Shapefile (254 bytes) y se recortó",+ "notice.geo_columns_dropped": "Un Shapefile admite 255 columnas como máximo: se omitió el resto",+ "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","engine.reason.not_installed": "No instalado","engine.reason.error": "Error al comprobar","engine.reason.unsupported_platform": "No disponible en esta plataforma",@@ -98,6 +113,7 @@"engine.font.description": "Tipografías: TTF, OTF, WOFF, WOFF2 y EOT entre sí.","engine.cad.description": "Planos de AutoCAD: DWG ↔ DXF, y ambos a PDF, SVG y PNG.","engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, FBX a cualquiera de ellos, además de una vista previa en PNG.",+ "engine.geo.description": "Datos vectoriales geoespaciales: GeoJSON, KML, KMZ, GPX, Shapefile y CSV (longitud/latitud o WKT) entre sí.\nEl resultado es longitud/latitud WGS 84; los sistemas proyectados de Shapefile (UTM, Web Mercator, Lambert, Albers) se convierten.","engine.archive.description": "Extrae ZIP, 7Z, RAR, TAR, ISO y más, y empaqueta en ZIP, 7Z o TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 y cómics (CBZ, CBR) a PDF, EPUB, DOCX y texto.\nTambién documentos a EPUB, EPUB a KEPUB para Kobo y PDF a CBZ.","engine.subtitle.description": "Subtítulos: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD y SCC entre sí, guardados como UTF-8.\nLee correctamente archivos SMI y SRT coreanos en CP949 / EUC-KR.",@@ -123,6 +139,7 @@"profile.fonts": "Tipografías","profile.data": "Datos","profile.models": "Modelos 3D",+ "profile.geo": "Geoespacial","profile.mixed": "Archivos mixtos","preset.half_size": "Reducir 50 %","preset.grayscale": "Grises",@@ -169,6 +186,7 @@"format.category.Subtitle": "Subtítulo","format.category.Data": "Datos","format.category.Model3D": "Modelo 3D",+ "format.category.Geo": "Geoespacial","general.title": "General","general.language": "Idioma","general.language_auto": "Predeterminado del sistema",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex e70dfab9..a7de05af 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -79,7 +79,22 @@"error.rhwp_timeout": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요","error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요","error.conversion_failed": "엔진에서 오류가 발생했어요",+ "error.geo_empty": "파일에 지리 객체가 없어요",+ "error.geo_unknown_crs": "좌표가 경도·위도가 아닌데 좌표계 정보도 없어요 (Shapefile은 .prj 파일을 함께 두세요)",+ "error.geo_unsupported_crs": "아직 지원하지 않는 좌표계예요",+ "error.geo_bad_coordinates": "좌표가 이 좌표계의 범위를 벗어났어요",+ "error.geo_csv_no_coordinates": "CSV에서 경도·위도 열이나 WKT 열을 찾지 못했어요",+ "error.geo_csv_no_locations": "위치를 읽을 수 있는 행이 하나도 없어요",+ "error.geo_unsupported_shape": "지원하지 않는 도형 종류예요",+ "error.geo_too_large": "Shapefile의 한계인 2GB를 넘어요","notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",+ "notice.geo_datum_assumed": "측지계가 WGS 84가 아니라서 같은 것으로 보고 변환했어요. 위치가 수백 m까지 어긋날 수 있어요",+ "notice.geo_gpx_lossy": "GPX는 점·경로·트랙과 몇 가지 항목만 담아요. 다른 속성은 빠졌고 면은 트랙으로 바뀌었어요",+ "notice.geo_text_cut": "Shapefile 필드 길이(254바이트)보다 긴 글자는 잘렸어요",+ "notice.geo_columns_dropped": "Shapefile은 열을 255개까지만 담아서 나머지는 뺐어요",+ "notice.geo_rows_without_location": "위치를 읽을 수 없는 행은 도형 없이 저장했어요",+ "notice.geo_field_names": "Shapefile 필드 이름은 10자까지라서 일부를 줄였어요",+ "notice.geo_shapefile_split": "Shapefile은 한 종류의 도형만 담아서 점·선·면을 파일로 나눠 저장했어요","engine.reason.not_installed": "설치되지 않음","engine.reason.error": "확인 중 오류",@@ -105,6 +120,7 @@"engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.","engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.","engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고, FBX도 이 형식들로 바꾸고, PNG 미리보기도 만들어요.",+ "engine.geo.description": "지리 공간 벡터 데이터: GeoJSON, KML, KMZ, GPX, Shapefile, CSV(경도·위도 또는 WKT)를 서로 변환해요.\n결과는 WGS 84 경위도예요. Shapefile의 투영 좌표계(UTM, 웹 메르카토르, 람베르트, 알버스)는 변환해요.","engine.archive.description": "ZIP, 7Z, RAR, TAR, ISO 등을 풀고, ZIP·7Z·TAR.GZ로 묶어요(7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2, 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꿔요.\n문서는 EPUB으로, EPUB은 코보용 KEPUB으로, PDF는 CBZ로도 만들어요.","engine.subtitle.description": "SRT, ASS/SSA, WebVTT, SAMI(SMI), LRC, TTML, MicroDVD, SCC 자막을 서로 바꾸고 UTF-8로 저장해요.\nCP949/EUC-KR로 된 SMI·SRT 파일도 한글이 깨지지 않아요.",@@ -131,6 +147,7 @@"profile.fonts": "글꼴","profile.data": "데이터","profile.models": "3D 모델",+ "profile.geo": "지리 정보 (GIS)","profile.mixed": "혼합 파일","preset.half_size": "50% 축소",@@ -179,6 +196,7 @@"format.category.Subtitle": "자막","format.category.Data": "데이터","format.category.Model3D": "3D 모델",+ "format.category.Geo": "지리 정보","general.title": "일반","general.language": "언어",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 969fc55b..732d15c7 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -79,7 +79,22 @@"error.rhwp_timeout": "rhwp nie zdążył przetworzyć tego długiego dokumentu","error.rhwp_timeout_calibre": "rhwp nie zdążył przetworzyć tego długiego dokumentu. Dla e-booka przenieś Calibre nad HWPX writer w Ustawienia → Silniki, a Calibre zrobi PDF znacznie szybciej","error.conversion_failed": "Silnik zgłosił błąd",+ "error.geo_empty": "Plik nie zawiera żadnych obiektów",+ "error.geo_unknown_crs": "Współrzędne nie są długością i szerokością geograficzną, a plik nie podaje układu współrzędnych (przy Shapefile zachowaj obok plik .prj)",+ "error.geo_unsupported_crs": "Ten układ współrzędnych nie jest jeszcze obsługiwany",+ "error.geo_bad_coordinates": "Współrzędne nie mieszczą się w tym układzie współrzędnych",+ "error.geo_csv_no_coordinates": "W pliku CSV nie ma kolumn długości i szerokości geograficznej ani kolumny WKT",+ "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","notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",+ "notice.geo_datum_assumed": "Datum nie jest WGS 84; pozycje przeliczono tak, jakby było, więc mogą się różnić nawet o setki metrów",+ "notice.geo_gpx_lossy": "GPX przechowuje tylko punkty, trasy i ślady z kilkoma polami: pozostałe atrybuty pominięto, a poligony stały się śladami",+ "notice.geo_text_cut": "Część tekstu była dłuższa niż pole Shapefile (254 bajty) i została przycięta",+ "notice.geo_columns_dropped": "Shapefile ma najwyżej 255 kolumn: resztę pominięto",+ "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","engine.reason.not_installed": "Nie zainstalowano","engine.reason.error": "Błąd podczas sprawdzania",@@ -105,6 +120,7 @@"engine.font.description": "Czcionki: TTF, OTF, WOFF, WOFF2 i EOT między sobą.","engine.cad.description": "Rysunki AutoCAD: DWG ↔ DXF, oba także do PDF, SVG i PNG.","engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą, FBX do każdego z nich oraz podgląd PNG.",+ "engine.geo.description": "Wektorowe dane geoprzestrzenne: GeoJSON, KML, KMZ, GPX, Shapefile i CSV (długość/szerokość lub WKT) wzajemnie.\nWynik to długość i szerokość WGS 84; układy rzutowane w Shapefile (UTM, Web Mercator, Lambert, Albers) są przeliczane.","engine.archive.description": "Rozpakowuje ZIP, 7Z, RAR, TAR, ISO i inne, pakuje do ZIP, 7Z lub TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 i komiksy (CBZ, CBR) do PDF, EPUB, DOCX i tekstu.\nTakże dokumenty do EPUB, EPUB do KEPUB dla Kobo i PDF do CBZ.","engine.subtitle.description": "Napisy: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD i SCC między sobą, zapisywane w UTF-8.\nKoreańskie pliki SMI i SRT w CP949 / EUC-KR są odczytywane poprawnie.",@@ -131,6 +147,7 @@"profile.fonts": "Czcionki","profile.data": "Dane","profile.models": "Modele 3D",+ "profile.geo": "Geoprzestrzenne","profile.mixed": "Różne pliki","preset.half_size": "Połowa rozmiaru",@@ -179,6 +196,7 @@"format.category.Subtitle": "Napisy","format.category.Data": "Dane","format.category.Model3D": "Model 3D",+ "format.category.Geo": "Geoprzestrzenne","general.title": "Ogólne","general.language": "Język",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 19c10eb3..a9143e43 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -79,7 +79,22 @@"error.rhwp_timeout": "文档太长,rhwp 未能在时限内完成","error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多","error.conversion_failed": "转换引擎出错",+ "error.geo_empty": "文件中没有地理要素",+ "error.geo_unknown_crs": "坐标不是经纬度,文件也没有说明坐标系(Shapefile 请把 .prj 文件放在旁边)",+ "error.geo_unsupported_crs": "暂不支持此坐标系",+ "error.geo_bad_coordinates": "坐标超出了该坐标系的范围",+ "error.geo_csv_no_coordinates": "CSV 中没有经纬度列,也没有 WKT 列",+ "error.geo_csv_no_locations": "CSV 中没有一行能读出位置",+ "error.geo_unsupported_shape": "不支持此类形状",+ "error.geo_too_large": "将超过 Shapefile 2 GB 的上限","notice.pdf_not_smaller": "无法再缩小,已原样复制",+ "notice.geo_datum_assumed": "基准面不是 WGS 84,已按相同处理,位置可能偏差数百米",+ "notice.geo_gpx_lossy": "GPX 只能保存点、路线和轨迹及少数字段:其他属性已省略,面变成了轨迹",+ "notice.geo_text_cut": "部分文字超过 Shapefile 字段长度(254 字节),已被截断",+ "notice.geo_columns_dropped": "Shapefile 最多 255 列,多出的列已省略",+ "notice.geo_rows_without_location": "部分行无法读出位置,已不带形状保存",+ "notice.geo_field_names": "Shapefile 字段名最多 10 个字符,部分名称已缩短",+ "notice.geo_shapefile_split": "Shapefile 只能保存一种形状,因此点、线、面被分别存成了多个文件","engine.reason.not_installed": "未安装","engine.reason.error": "检查时出错",@@ -105,6 +120,7 @@"engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。","engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。","engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,FBX 可转换为其中任意格式,并可生成 PNG 预览。",+ "engine.geo.description": "地理空间矢量数据:GeoJSON、KML、KMZ、GPX、Shapefile 和 CSV(经纬度或 WKT)互相转换。\n结果为 WGS 84 经纬度;Shapefile 的投影坐标系(UTM、Web 墨卡托、兰伯特、阿尔伯斯)会被转换。","engine.archive.description": "解压 ZIP、7Z、RAR、TAR、ISO 等,并打包为 ZIP、7Z 或 TAR.GZ(7-Zip)。","engine.ebook.description": "EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本。\n也能把文档转为 EPUB、把 EPUB 转为 Kobo 用的 KEPUB、把 PDF 转为 CBZ。","engine.subtitle.description": "SRT、ASS/SSA、WebVTT、SAMI(SMI)、LRC、TTML、MicroDVD、SCC 字幕互转,保存为 UTF-8。\n也能正确读取 CP949/EUC-KR 编码的韩文字幕。",@@ -131,6 +147,7 @@"profile.fonts": "字体","profile.data": "数据","profile.models": "3D 模型",+ "profile.geo": "地理信息 (GIS)","profile.mixed": "混合文件","preset.half_size": "缩小 50%",@@ -179,6 +196,7 @@"format.category.Subtitle": "字幕","format.category.Data": "数据","format.category.Model3D": "3D 模型",+ "format.category.Geo": "地理信息","general.title": "常规","general.language": "语言",diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.csindex 38bfca6c..24cf8f16 100644--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs@@ -399,9 +399,9 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;public bool ShowMultiPageTiff => TargetId is "tiff";public bool ShowIco => TargetId == "ico";- /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font, subtitle, data, e-mail and 3D targets.</summary>+ /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font, subtitle, data, e-mail, 3D and geospatial targets.</summary>public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font- or FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D) && TargetId != "eml";+ or FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D or FormatCategory.Geo) && TargetId != "eml";public bool ShowPdfBuild => TargetId == "pdf";public bool ShowPdfSplit => TargetId == "pdf";diff --git a/src/Filee.Core/Formats/FileFormat.cs b/src/Filee.Core/Formats/FileFormat.csindex eca34e16..da3642ae 100644--- a/src/Filee.Core/Formats/FileFormat.cs+++ b/src/Filee.Core/Formats/FileFormat.cs@@ -22,6 +22,7 @@ public enum FormatCategorySubtitle,Data,Model3D,+ Geo,}/// <summary>diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex c4793b42..630406a1 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -299,6 +299,13 @@ public static class FormatRegistrynew("3mf", "3MF", FormatCategory.Model3D, ["3mf"]),new("ply", "PLY", FormatCategory.Model3D, ["ply"]),new("fbx", "FBX", FormatCategory.Model3D, ["fbx"], Writable: false),++ // Geospatial vector data (CSV with coordinates is a Data format and reaches these through the geo engine)+ new("geojson", "GeoJSON", FormatCategory.Geo, ["geojson"]),+ new("kml", "KML", FormatCategory.Geo, ["kml"]),+ new("kmz", "KMZ", FormatCategory.Geo, ["kmz"]),+ new("gpx", "GPX", FormatCategory.Geo, ["gpx"]),+ new("shp", "Shapefile", FormatCategory.Geo, ["shp"]),];private static readonly Dictionary<string, FileFormat> ById =diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 1ad105a2..b34fa67e 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -81,6 +81,7 @@ public static class BuiltInData.. DataPresets(),.. CodecAndSubtitlePresets(),.. ModelPresets(),+ .. GeoPresets(),.. TracePresets(),];@@ -179,6 +180,19 @@ public static class BuiltInDatanew() { Id = "to-gltf", Name = "glTF", TargetFormat = "gltf" },];+ /// <summary>+ /// Geospatial vector targets (added in settings schema 23, see SettingsMigrations). CSV, the sixth slice of the+ /// donut, is the spreadsheet preset. KMZ is a KML in a ZIP and is on no donut.+ /// </summary>+ public static List<Preset> GeoPresets() =>+ [+ new() { Id = "to-geojson", Name = "GeoJSON", TargetFormat = "geojson" },+ new() { Id = "to-shp", Name = "Shapefile", TargetFormat = "shp" },+ new() { Id = "to-kml", Name = "KML", TargetFormat = "kml" },+ new() { Id = "to-gpx", Name = "GPX", TargetFormat = "gpx" },+ new() { Id = "to-kmz", Name = "KMZ", TargetFormat = "kmz" },+ ];+/// <summary>/// Targets of the formats added in settings schema 6: images, vector, office, e-books, video, audio, archives,/// CAD and fonts (see SettingsMigrations).@@ -344,6 +358,7 @@ public static class BuiltInData.. WithSubtitleProfile(CatalogProfiles()),DataProfile(),ModelProfile(),+ GeoProfile(),new(){Id = "mixed", NameKey = "profile.mixed", IsFallback = true,@@ -470,6 +485,15 @@ public static class BuiltInDataPresetIds = ["to-glb", "to-stl", "to-obj", "to-3mf", "to-ply", "to-png"],};+ /// <summary>Geospatial vector data: Shapefile, GeoJSON, KML, KMZ, GPX (added in settings schema 23, after "models").</summary>+ public static ToolbarProfile GeoProfile() => new()+ {+ Id = "geo",+ NameKey = "profile.geo",+ Extensions = ExtensionsOf(FormatCategory.Geo),+ PresetIds = ["to-geojson", "to-shp", "to-kml", "to-csv", "to-gpx", "to-kmz"],+ };+/// <summary>Every file extension of the formats in <paramref name="category"/>.</summary>public static List<string> ExtensionsOf(FormatCategory category) =>FormatRegistry.Known.Where(f => f.Category == category)diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f1d77877..d7264a86 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -64,7 +64,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 22;+ public const int CurrentSchemaVersion = 23;public int SchemaVersion { get; set; } = CurrentSchemaVersion;@@ -107,7 +107,7 @@ public sealed class AppSettingspublic List<string> EnginePriority { get; set; } =["magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",- "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook",+ "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "geo", "archive", "ebook","subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice",];diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 72d44f90..125b7223 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -308,6 +308,17 @@ internal static class SettingsMigrationsInsertBefore(settings.EnginePriority, "model3d", settings.EnginePriority.Contains("archive") ? "archive" : "pandoc");}+ // v23: built-in "geo" engine (GeoJSON, KML, KMZ, GPX, Shapefile and CSV points), after the 3D models engine (else+ // before the archive engine, else before Pandoc).+ if (settings.SchemaVersion < 23 && !settings.EnginePriority.Contains("geo"))+ {+ var models = settings.EnginePriority.IndexOf("model3d");+ if (models >= 0)+ settings.EnginePriority.Insert(models + 1, "geo");+ else+ InsertBefore(settings.EnginePriority, "geo", settings.EnginePriority.Contains("archive") ? "archive" : "pandoc");+ }+// v18: built-in "pdf-slides" engine (PDF → PPTX, a picture of each page per slide), after "pdf-text".if (settings.SchemaVersion < 18 && !settings.EnginePriority.Contains("pdf-slides")){@@ -563,9 +574,43 @@ internal static class SettingsMigrations// takes it. Other extensions the user removed from a built-in donut stay removed.if (from < 22)changed |= LearnExtensions(profiles, out _, ["fbx"]);+ // v23: geospatial vector data (Shapefile, GeoJSON, KML, KMZ, GPX) gets presets and its own donut after "models"+ // (else after "data", else after "fonts"), with the extensions no donut of the user takes yet.+ if (from < 23)+ changed |= AddGeo(presets, profiles);return changed;}+ private static bool AddGeo(List<Preset> presets, List<ToolbarProfile> profiles)+ {+ var changed = false;+ foreach (var preset in BuiltInData.GeoPresets().Where(p => presets.All(existing => existing.Id != p.Id)))+ {+ presets.Add(preset);+ changed = true;+ }+ // Only the geospatial extensions: others a user removed from a built-in donut stay removed.+ changed |= LearnExtensions(profiles, out var claimed, BuiltInData.GeoProfile().Extensions);+ if (profiles.Any(p => p.Id == "geo"))+ return changed;++ var geo = BuiltInData.GeoProfile();+ // Only the extensions no donut of the user takes yet.+ geo.Extensions = geo.Extensions.Where(claimed.Add).ToList();+ if (geo.Extensions.Count == 0)+ return changed;+ var ids = presets.Select(p => p.Id).ToHashSet();+ geo.PresetIds = geo.PresetIds.Where(ids.Contains).ToList();+ var after = profiles.FindIndex(p => p.Id == "models");+ if (after < 0)+ after = profiles.FindIndex(p => p.Id == "data");+ if (after < 0)+ after = profiles.FindIndex(p => p.Id == "fonts");+ var insertAt = after >= 0 ? after + 1 : profiles.FindIndex(p => p.IsFallback);+ profiles.Insert(insertAt < 0 ? profiles.Count : insertAt, geo);+ return true;+ }+private static bool AddPdfSlides(List<Preset> presets, List<ToolbarProfile> profiles){var changed = false;diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 57659ee3..b9c0f010 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -7,6 +7,7 @@ using Filee.Engines.Data;using Filee.Engines.Ebooks;using Filee.Engines.Email;using Filee.Engines.Fonts;+using Filee.Engines.Geo;using Filee.Engines.Hwp;using Filee.Engines.Hwp.Hwpx;using Filee.Engines.Icns;@@ -61,6 +62,7 @@ public static class EngineRegistrynew FfmpegConverter(loggers?.CreateLogger<FfmpegConverter>()),new CadConverter(),new ModelConverter(),+ new GeoConverter(),new EbookConverter(),new PandocConverter(),new GhostscriptConverter(),diff --git a/src/Filee.Engines/Geo/DbfFormat.cs b/src/Filee.Engines/Geo/DbfFormat.csnew file mode 100644index 00000000..f219557a--- /dev/null+++ b/src/Filee.Engines/Geo/DbfFormat.cs@@ -0,0 +1,522 @@+// dBASE (.dbf), the attribute table of a Shapefile. Reading handles dBASE III / IV / FoxPro tables: text (C), numbers (N,+// F), true / false (L), dates (D), binary integers and doubles (I, B); memo fields read as empty. The text encoding comes+// from the .cpg file or the file's language driver byte; without either the text is UTF-8 if it is valid, else Korean+// CP949 (like the CSV reader), else Windows-1252. Records marked as deleted are returned as null.+// Writing makes a dBASE III table in UTF-8 (the .cpg says so): text columns up to 254 bytes, numbers as N with the+// decimals they need, booleans as L. Field names are cut to 10 bytes and made unique, as the format requires.++using System.Buffers.Binary;+using System.Globalization;+using System.Text;++namespace Filee.Engines.Geo;++internal sealed record DbfField(string Name, char Type, int Length, int Decimals);++internal sealed class DbfTable+{+ public List<DbfField> Fields { get; } = [];++ /// <summary>The values of each record in field order; null for a record marked as deleted.</summary>+ public List<object?[]?> Rows { get; } = [];+}++/// <summary>What the writer had to change to fit the format, so the file can carry a notice.</summary>+internal readonly record struct DbfLosses(bool NamesChanged, bool TextCut, bool ColumnsDropped);++internal static class DbfFormat+{+ private const int MaxTextBytes = 254;+ private const int MaxFields = 255;+ private const int MaxNumberWidth = 24;++ static DbfFormat() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);++ // ---- Reading ----++ /// <summary>Reads a table; <paramref name="cpg"/> is the text of the .cpg file, or null.</summary>+ public static DbfTable Read(string path, string? cpg, CancellationToken cancellationToken)+ {+ var bytes = File.ReadAllBytes(path);+ if (bytes.Length < 33)+ throw new InvalidDataException("The .dbf file is too short to be a dBASE table.");+ var recordCount = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(4));+ var headerLength = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8));+ var recordLength = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(10));+ if (headerLength < 33 || headerLength > bytes.Length || recordLength < 1)+ throw new InvalidDataException("The .dbf header is damaged.");++ var table = new DbfTable();+ var offsets = new List<int>();+ var position = 1;+ for (var at = 32; at + 32 <= headerLength && bytes[at] != 0x0D; at += 32)+ {+ if (table.Fields.Count >= 2046)+ throw new InvalidDataException("The .dbf has too many fields.");+ var nameEnd = Array.IndexOf(bytes, (byte)0, at, 11);+ var nameBytes = bytes.AsSpan(at, (nameEnd < 0 ? at + 11 : nameEnd) - at);+ var field = new DbfField(Latin1(nameBytes), (char)bytes[at + 11], bytes[at + 16], bytes[at + 17]);+ table.Fields.Add(field);+ offsets.Add(position);+ position += field.Length;+ }+ if (position > recordLength)+ throw new InvalidDataException("The .dbf field lengths do not fit the record length.");++ var encoding = Resolve(cpg, bytes[29]) ?? Detect(bytes, headerLength, recordLength, table.Fields, offsets, recordCount);+ // Field names were read as Latin-1 above; re-read them in the table's encoding (they are ASCII almost always).+ for (var i = 0; i < table.Fields.Count; i++)+ {+ var at = 32 + 32 * i;+ var nameEnd = Array.IndexOf(bytes, (byte)0, at, 11);+ var name = encoding.GetString(bytes, at, (nameEnd < 0 ? at + 11 : nameEnd) - at).Trim();+ table.Fields[i] = table.Fields[i] with { Name = name.Length == 0 ? $"FIELD{i + 1}" : name };+ }++ var available = (bytes.Length - headerLength) / recordLength;+ var count = (int)Math.Min(recordCount, (uint)available);+ for (var r = 0; r < count; r++)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var start = headerLength + r * recordLength;+ if (bytes[start] == (byte)'*')+ {+ table.Rows.Add(null);+ continue;+ }+ var values = new object?[table.Fields.Count];+ for (var f = 0; f < values.Length; f++)+ values[f] = Value(table.Fields[f], bytes.AsSpan(start + offsets[f], table.Fields[f].Length), encoding);+ table.Rows.Add(values);+ }+ return table;+ }++ private static string Latin1(ReadOnlySpan<byte> bytes) => Encoding.Latin1.GetString(bytes);++ private static object? Value(DbfField field, ReadOnlySpan<byte> cell, Encoding encoding)+ {+ switch (char.ToUpperInvariant(field.Type))+ {+ case 'C':+ {+ var end = cell.Length;+ while (end > 0 && cell[end - 1] is (byte)' ' or 0)+ end--;+ return end == 0 ? "" : encoding.GetString(cell[..end]);+ }+ case 'N' or 'F':+ {+ var text = Latin1(cell).Trim();+ if (text.Length == 0 || text[0] == '*')+ return null;+ if (field.Decimals == 0 && long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var whole))+ return whole;+ return double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var real) && double.IsFinite(real)+ ? real == Math.Floor(real) && Math.Abs(real) < 1e15 && field.Decimals == 0 ? (long)real : real+ : null;+ }+ case 'L':+ return (char)cell[0] switch+ {+ 'T' or 't' or 'Y' or 'y' => true,+ 'F' or 'f' or 'N' or 'n' => false,+ _ => null,+ };+ case 'D':+ {+ var text = Latin1(cell).Trim();+ return text.Length == 8 && DateTime.TryParseExact(text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)+ ? date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)+ : null;+ }+ case 'I' or '+' when cell.Length >= 4:+ return (long)BinaryPrimitives.ReadInt32LittleEndian(cell);+ case 'B' or 'O' when cell.Length >= 8:+ {+ var real = BitConverter.ToDouble(cell[..8]);+ return double.IsFinite(real) ? real : null;+ }+ default:+ // Memo, date-time and other types that point elsewhere or need extra files.+ return null;+ }+ }++ private static Encoding? Resolve(string? cpg, byte languageDriver)+ {+ if (!string.IsNullOrWhiteSpace(cpg))+ {+ var name = cpg.Trim().Trim('\0');+ try+ {+ if (name.Equals("UTF-8", StringComparison.OrdinalIgnoreCase) || name.Equals("UTF8", StringComparison.OrdinalIgnoreCase) || name == "65001")+ return new UTF8Encoding(false);+ if (int.TryParse(name, NumberStyles.None, CultureInfo.InvariantCulture, out var page))+ return Encoding.GetEncoding(page);+ if (name.StartsWith("ANSI ", StringComparison.OrdinalIgnoreCase) && int.TryParse(name.AsSpan(5), NumberStyles.None, CultureInfo.InvariantCulture, out page))+ return Encoding.GetEncoding(page);+ return Encoding.GetEncoding(name.Replace("LATIN1", "ISO-8859-1", StringComparison.OrdinalIgnoreCase));+ }+ catch (ArgumentException)+ {+ // An encoding name this system doesn't know: fall back to the language driver byte, then to detection.+ }+ }+ // The dBASE "language driver ID" in the header.+ var codePage = languageDriver switch+ {+ 0x01 => 437,+ 0x02 => 850,+ 0x03 or 0x57 or 0x58 or 0x59 => 1252,+ 0x08 => 865,+ 0x09 => 437,+ 0x0A => 850,+ 0x0B => 437,+ 0x0D => 437,+ 0x0E => 850,+ 0x0F => 437,+ 0x10 => 850,+ 0x11 => 437,+ 0x12 => 850,+ 0x13 => 932,+ 0x14 => 850,+ 0x15 => 437,+ 0x16 => 850,+ 0x17 => 865,+ 0x18 => 437,+ 0x19 => 437,+ 0x1A => 850,+ 0x1B => 437,+ 0x1C => 863,+ 0x1D => 850,+ 0x1F => 852,+ 0x22 => 852,+ 0x23 => 852,+ 0x24 => 860,+ 0x25 => 850,+ 0x26 => 866,+ 0x37 => 850,+ 0x40 => 852,+ 0x4D => 936,+ 0x4E => 949,+ 0x4F => 950,+ 0x50 => 874,+ 0x64 => 852,+ 0x65 => 866,+ 0x66 => 865,+ 0x67 => 861,+ 0x6A => 737,+ 0x6B => 857,+ 0x78 => 950,+ 0x79 => 949,+ 0x7A => 936,+ 0x7B => 932,+ 0x7C => 874,+ 0x7D => 1255,+ 0x7E => 1256,+ 0xC8 => 1250,+ 0xC9 => 1251,+ 0xCA => 1254,+ 0xCB => 1253,+ 0xCC => 1257,+ _ => 0,+ };+ if (codePage == 0)+ return null;+ try+ {+ return Encoding.GetEncoding(codePage);+ }+ catch (ArgumentException)+ {+ return null;+ }+ }++ /// <summary>UTF-8 when the text of the first records is valid UTF-8, else CP949 if valid, else Windows-1252.</summary>+ private static Encoding Detect(byte[] bytes, int headerLength, int recordLength, List<DbfField> fields, List<int> offsets, uint recordCount)+ {+ var sample = new List<byte>();+ var count = (int)Math.Min(recordCount, (uint)((bytes.Length - headerLength) / recordLength));+ for (var r = 0; r < count && sample.Count < 1 << 20; r++)+ {+ var start = headerLength + r * recordLength;+ for (var f = 0; f < fields.Count; f++)+ {+ if (char.ToUpperInvariant(fields[f].Type) == 'C')+ sample.AddRange(bytes.AsSpan(start + offsets[f], fields[f].Length).ToArray());+ }+ }+ var data = sample.ToArray();+ foreach (var encoding in new[] { Strict(new UTF8Encoding(false)), Strict(Encoding.GetEncoding(949)) })+ {+ try+ {+ encoding.GetString(data);+ return encoding.CodePage == 65001 ? new UTF8Encoding(false) : Encoding.GetEncoding(encoding.CodePage);+ }+ catch (DecoderFallbackException)+ {+ }+ }+ return Encoding.GetEncoding(1252);+ }++ private static Encoding Strict(Encoding encoding) =>+ Encoding.GetEncoding(encoding.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);++ // ---- Writing ----++ /// <summary>+ /// Writes the attributes of <paramref name="features"/> as a dBASE III table in UTF-8. A table needs at least one+ /// field, so features without attributes get a record number field "FID".+ /// </summary>+ public static DbfLosses Write(string path, IReadOnlyList<GeoFeature> features, CancellationToken cancellationToken)+ {+ var columns = new List<string>();+ var seen = new HashSet<string>(StringComparer.Ordinal);+ foreach (var feature in features)+ {+ foreach (var (key, _) in feature.Properties)+ {+ if (seen.Add(key))+ columns.Add(key);+ }+ }+ var columnsDropped = columns.Count > MaxFields;+ if (columnsDropped)+ columns = columns.GetRange(0, MaxFields);++ var rows = features.Select(f =>+ {+ var map = new Dictionary<string, object?>(StringComparer.Ordinal);+ foreach (var (key, value) in f.Properties)+ map.TryAdd(key, value);+ return map;+ }).ToList();++ var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ var namesChanged = false;+ var layouts = new List<Layout>();+ if (columns.Count == 0)+ {+ layouts.Add(new Layout("FID", 'N', 11, 0, "FID", Fid: true));+ used.Add("FID");+ }+ foreach (var column in columns)+ {+ var name = FieldName(column, used);+ namesChanged |= name != column;+ layouts.Add(Describe(name, column, rows));+ }++ var textCut = false;+ var recordLength = 1 + layouts.Sum(l => l.Length);+ var headerLength = 32 + 32 * layouts.Count + 1;+ if (recordLength > ushort.MaxValue || headerLength > ushort.MaxValue)+ throw new InvalidDataException("The attribute table is too wide for a dBASE file.");++ using var stream = new BufferedStream(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16), 1 << 16);+ var header = new byte[32];+ header[0] = 0x03;+ var today = DateTime.UtcNow;+ header[1] = (byte)(today.Year - 1900);+ header[2] = (byte)today.Month;+ header[3] = (byte)today.Day;+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4), (uint)rows.Count);+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(8), (ushort)headerLength);+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(10), (ushort)recordLength);+ stream.Write(header);+ foreach (var layout in layouts)+ {+ var descriptor = new byte[32];+ Encoding.UTF8.GetBytes(layout.Name, descriptor);+ descriptor[11] = (byte)layout.Type;+ descriptor[16] = (byte)layout.Length;+ descriptor[17] = (byte)layout.Decimals;+ stream.Write(descriptor);+ }+ stream.WriteByte(0x0D);++ var record = new byte[recordLength];+ for (var r = 0; r < rows.Count; r++)+ {+ cancellationToken.ThrowIfCancellationRequested();+ Array.Fill(record, (byte)' ');+ var at = 1;+ foreach (var layout in layouts)+ {+ var value = layout.Fid ? (long)r : rows[r].GetValueOrDefault(layout.Source);+ textCut |= Put(record.AsSpan(at, layout.Length), layout, value);+ at += layout.Length;+ }+ stream.Write(record);+ }+ stream.WriteByte(0x1A);+ return new DbfLosses(namesChanged, textCut, columnsDropped);+ }++ private sealed record Layout(string Name, char Type, int Length, int Decimals, string Source, bool Fid = false);++ private static Layout Describe(string name, string source, List<Dictionary<string, object?>> rows)+ {+ var strings = false;+ var bools = false;+ var longs = false;+ var doubles = false;+ var textBytes = 1;+ var longWidth = 1;+ var decimals = 0;+ foreach (var row in rows)+ {+ if (!row.TryGetValue(source, out var value) || value is null)+ continue;+ switch (value)+ {+ case bool:+ bools = true;+ break;+ case long whole:+ longs = true;+ longWidth = Math.Max(longWidth, whole.ToString(CultureInfo.InvariantCulture).Length);+ break;+ case double real when double.IsFinite(real):+ doubles = true;+ var text = GeoText.Number(real);+ var dot = text.IndexOf('.', StringComparison.Ordinal);+ decimals = Math.Max(decimals, dot < 0 ? 0 : text.Length - dot - 1);+ break;+ case double:+ break;+ default:+ strings = true;+ break;+ }+ if (strings)+ break;+ }+ if (!strings && !(bools && (longs || doubles)))+ {+ if (bools)+ return new Layout(name, 'L', 1, 0, source);+ if (doubles)+ {+ // Fixed decimals, as many as the values need (15 at most), in a width of 24 at most.+ decimals = Math.Min(decimals, 15);+ var width = 1;+ var fits = true;+ foreach (var row in rows)+ {+ if (!row.TryGetValue(source, out var value) || value is null)+ continue;+ var real = value is long whole ? whole : value is double d && double.IsFinite(d) ? d : double.NaN;+ if (double.IsNaN(real))+ continue;+ width = Math.Max(width, real.ToString("F" + decimals, CultureInfo.InvariantCulture).Length);+ }+ while (width > MaxNumberWidth && decimals > 0)+ {+ decimals--;+ width--;+ }+ fits = width <= MaxNumberWidth;+ if (fits)+ return new Layout(name, 'N', Math.Max(width, 1), decimals, source);+ strings = true;+ }+ else if (longs && longWidth <= 18)+ {+ return new Layout(name, 'N', longWidth, 0, source);+ }+ else if (!longs)+ {+ // Only empty values: a text column of one blank.+ return new Layout(name, 'C', 1, 0, source);+ }+ else+ {+ strings = true;+ }+ }+ foreach (var row in rows)+ {+ if (row.TryGetValue(source, out var value) && value is not null)+ textBytes = Math.Max(textBytes, Encoding.UTF8.GetByteCount(GeoText.ToText(value)));+ }+ return new Layout(name, 'C', Math.Min(textBytes, MaxTextBytes), 0, source);+ }++ /// <summary>Writes one value into its cell; returns true if text had to be cut to the field width.</summary>+ private static bool Put(Span<byte> cell, Layout layout, object? value)+ {+ switch (layout.Type)+ {+ case 'L':+ cell[0] = value switch { true => (byte)'T', false => (byte)'F', _ => (byte)'?' };+ return false;+ case 'N':+ {+ string? text = value switch+ {+ long whole => layout.Decimals == 0 ? whole.ToString(CultureInfo.InvariantCulture) : ((double)whole).ToString("F" + layout.Decimals, CultureInfo.InvariantCulture),+ double real when double.IsFinite(real) => real.ToString("F" + layout.Decimals, CultureInfo.InvariantCulture),+ _ => null,+ };+ if (text is null)+ return false;+ if (text.Length > cell.Length)+ text = text[..cell.Length];+ Encoding.ASCII.GetBytes(text, cell[(cell.Length - text.Length)..]);+ return false;+ }+ default:+ {+ var text = GeoText.ToText(value);+ var bytes = Encoding.UTF8.GetBytes(text);+ var length = bytes.Length;+ var cut = length > cell.Length;+ if (cut)+ {+ length = cell.Length;+ // Don't end in the middle of a character.+ while (length > 0 && (bytes[length] & 0xC0) == 0x80)+ length--;+ }+ bytes.AsSpan(0, length).CopyTo(cell);+ return cut;+ }+ }+ }++ /// <summary>A field name of at most ten bytes of letters, digits and underscores that is not used yet.</summary>+ private static string FieldName(string source, HashSet<string> used)+ {+ var builder = new StringBuilder();+ foreach (var rune in source.EnumerateRunes())+ builder.Append(Rune.IsLetterOrDigit(rune) || rune.Value == '_' ? rune.ToString() : "_");+ var name = builder.Length == 0 ? "FIELD" : builder.ToString();+ var candidate = Cut(name, 10);+ for (var n = 1; !used.Add(candidate); n++)+ {+ var suffix = "_" + n.ToString(CultureInfo.InvariantCulture);+ candidate = Cut(name, 10 - suffix.Length) + suffix;+ }+ return candidate;+ }++ /// <summary>The start of <paramref name="text"/> that fits in <paramref name="bytes"/> bytes of UTF-8.</summary>+ private static string Cut(string text, int bytes)+ {+ var result = new StringBuilder();+ var size = 0;+ foreach (var rune in text.EnumerateRunes())+ {+ size += rune.Utf8SequenceLength;+ if (size > bytes)+ break;+ result.Append(rune.ToString());+ }+ return result.ToString();+ }+}diff --git a/src/Filee.Engines/Geo/GeoConverter.cs b/src/Filee.Engines/Geo/GeoConverter.csnew file mode 100644index 00000000..8fab9957--- /dev/null+++ b/src/Filee.Engines/Geo/GeoConverter.cs@@ -0,0 +1,242 @@+// 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+// (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.++using Filee.Core.Conversion;+using Filee.Engines.Infrastructure;+using Microsoft.Extensions.Logging;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.Engines.Geo;++/// <summary>Converts GeoJSON, KML, KMZ, GPX, Shapefile and CSV points / WKT into each other.</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"];++ private readonly ILogger _logger = logger ?? NullLogger.Instance;++ public string Id => "geo";+ public string DisplayName => "Geospatial vector data (built-in)";++ /// <summary>Whole files are read into memory, so only a few run at once.</summary>+ public int MaxParallelism => Math.Clamp(Environment.ProcessorCount / 2, 1, 4);++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ .. from source in Formats from target in Formats where source != target select new ConversionEdge(source, target),+ // The same format again rewrites the file in WGS 84: a projected Shapefile or a GeoJSON with an old "crs" member+ // becomes longitude / latitude, and a Shapefile with mixed geometries is split by kind.+ new("shp", "shp"),+ new("geojson", "geojson"),+ .. Formats.Select(format => new ConversionEdge(format, "csv")),+ .. Formats.Select(format => new ConversionEdge("csv", format)),+ ];++ public EngineStatus GetStatus() => EngineStatus.Available("GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other 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);+ 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");+ progress?.Report(0.6);++ var outputs = new List<string>();+ try+ {+ Write(dataset, step, outputs, notices, cancellationToken);+ }+ catch+ {+ foreach (var output in outputs)+ TryDelete(output);+ throw;+ }+ notices.Report();+ progress?.Report(1);+ return outputs;+ }, cancellationToken);++ private static GeoDataset Read(ConversionStep step, CancellationToken cancellationToken) => step.From switch+ {+ "geojson" => GeoJsonFormat.Read(step.InputPath, cancellationToken),+ "kml" => KmlFormat.Read(step.InputPath, zipped: false, cancellationToken),+ "kmz" => KmlFormat.Read(step.InputPath, zipped: true, cancellationToken),+ "gpx" => GpxFormat.Read(step.InputPath, cancellationToken),+ "shp" => ShapefileFormat.Read(step.InputPath, cancellationToken),+ "csv" => GeoCsvFormat.Read(step.InputPath, cancellationToken),+ _ => throw new NotSupportedException($"{step.From} is not a geospatial format."),+ };++ /// <summary>+ /// Puts every position into longitude / latitude, and refuses data whose positions can't be: coordinates outside the+ /// Earth with no coordinate system to explain them are most likely a projected system the file doesn't name.+ /// </summary>+ internal static void ToWgs84(GeoDataset dataset, Notices notices)+ {+ var crs = dataset.Crs;+ if (crs.IsApproximate)+ notices.Add("notice.geo_datum_assumed");+ var features = dataset.Features;+ for (var i = 0; i < features.Count; i++)+ {+ if (features[i].Geometry is not { } geometry)+ continue;+ var converted = crs.IsIdentity ? geometry : geometry.Map(crs.ToLonLat);+ if (!InRange(converted))+ {+ throw dataset.CrsDeclared && !crs.IsGeographic+ ? new ConversionRefusedException("error.geo_bad_coordinates", crs.Name)+ : new ConversionRefusedException("error.geo_unknown_crs", dataset.CrsDeclared ? crs.Name : null);+ }+ if (!ReferenceEquals(converted, geometry))+ features[i] = new GeoFeature(converted, features[i].Properties);+ }+ dataset.Crs = GeoCrs.Wgs84;+ }++ private static bool InRange(GeoGeometry geometry)+ {+ foreach (var c in geometry.Coordinates())+ {+ if (!c.IsFinite || c.Y is < -90.000001 or > 90.000001 || c.X is < -360 or > 360)+ return false;+ }+ return true;+ }++ private static void Write(GeoDataset dataset, ConversionStep step, List<string> outputs, Notices notices, CancellationToken cancellationToken)+ {+ switch (step.To)+ {+ case "geojson" or "kml" or "kmz" or "gpx" or "csv":+ {+ if (step.Output.Allocate(step.To) is not { } path)+ return;+ outputs.Add(path);+ switch (step.To)+ {+ case "geojson":+ GeoJsonFormat.Write(dataset, path, cancellationToken);+ break;+ case "kml" or "kmz":+ KmlFormat.Write(dataset, path, zipped: step.To == "kmz", cancellationToken);+ break;+ case "gpx":+ if (GpxFormat.Write(dataset, path, cancellationToken))+ notices.Add("notice.geo_gpx_lossy");+ break;+ default:+ GeoCsvFormat.Write(dataset, path, cancellationToken);+ break;+ }+ break;+ }+ case "shp":+ WriteShapefiles(dataset, step, outputs, notices, cancellationToken);+ break;+ default:+ throw new NotSupportedException($"{step.To} is not a geospatial format.");+ }+ }++ /// <summary>One shapefile per kind of geometry; each is the .shp with its .shx, .dbf, .prj and .cpg.</summary>+ private static void WriteShapefiles(GeoDataset dataset, ConversionStep step, List<string> outputs, Notices notices, CancellationToken cancellationToken)+ {+ var groups = ShapefileFormat.Plan(dataset);+ if (groups.Count > 1)+ notices.Add("notice.geo_shapefile_split");+ foreach (var group in groups)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var suffix = groups.Count == 1 ? null : group.Kind switch+ {+ ShapeKind.Point => "_points",+ ShapeKind.Line => "_lines",+ _ => "_polygons",+ };+ if (AllocateShapefile(step.Output, suffix) is not { } shp)+ continue;+ string[] files = [shp, .. Siblings(shp)];+ outputs.AddRange(files);+ var losses = ShapefileFormat.Write(group, shp, cancellationToken);+ if (losses.TextCut)+ notices.Add("notice.geo_text_cut");+ if (losses.ColumnsDropped)+ notices.Add("notice.geo_columns_dropped");+ if (losses.NamesChanged)+ notices.Add("notice.geo_field_names");+ }+ }++ private static readonly string[] SiblingExtensions = ["shx", "dbf", "prj", "cpg"];++ private static string[] Siblings(string shp) => [.. SiblingExtensions.Select(e => Path.ChangeExtension(shp, e))];++ /// <summary>+ /// The path for a .shp whose sibling files (same name, other extensions) are all free. The allocator only knows the+ /// .shp, so when an old .dbf or .prj of the same name is lying around the next name is tried, rather than+ /// writing over files that don't belong to this shapefile. When the .shp itself is being overwritten (the user's+ /// choice), its siblings are overwritten with it.+ /// </summary>+ private static string? AllocateShapefile(IOutputAllocator output, string? suffix)+ {+ for (var attempt = 1; attempt <= 100; attempt++)+ {+ var path = output.Allocate("shp", attempt == 1 ? suffix : $"{suffix}_{attempt}");+ if (path is null)+ return null;+ if (File.Exists(path) || Siblings(path).All(sibling => !File.Exists(sibling)))+ return path;+ }+ throw new IOException("No free name for the shapefile.");+ }++ private static void TryDelete(string path)+ {+ try+ {+ File.Delete(path);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ /// <summary>+ /// The notes a conversion collects. A file carries one note, so the most important one is reported:+ /// the assumed datum can move data by hundreds of metres, the rest only say what a format could not hold.+ /// </summary>+ internal sealed class Notices(Action<string>? sink)+ {+ private static readonly string[] Priority =+ [+ "notice.geo_datum_assumed", "notice.geo_gpx_lossy", "notice.geo_text_cut", "notice.geo_columns_dropped",+ "notice.geo_rows_without_location", "notice.geo_field_names", "notice.geo_shapefile_split",+ ];++ private readonly HashSet<string> _keys = [];++ public void Add(string key) => _keys.Add(key);++ public IReadOnlyCollection<string> Keys => _keys;++ public void Report()+ {+ if (sink is null)+ return;+ var key = Priority.FirstOrDefault(_keys.Contains);+ if (key is not null)+ sink(key);+ }+ }+}diff --git a/src/Filee.Engines/Geo/GeoCrs.cs b/src/Filee.Engines/Geo/GeoCrs.csnew file mode 100644index 00000000..fcfcc6e2--- /dev/null+++ b/src/Filee.Engines/Geo/GeoCrs.cs@@ -0,0 +1,620 @@+// Coordinate reference systems, just enough to put every file into longitude / latitude: geographic systems (degrees)+// and the projections most projected data uses (UTM and other Transverse Mercator, Mercator and Web Mercator, Lambert+// Conformal Conic, Albers) read from a .prj file (ESRI or OGC WKT) or an EPSG code. A system outside that list is+// refused with its name rather than guessed, because coordinates in the wrong system land on the wrong place on Earth.+// Datums are not shifted: WGS 84, NAD83, ETRS89 and the other systems tied to ITRF agree within a metre or two, and+// anything else is converted as if it were WGS 84 and the file gets a notice (see IsApproximate).++using System.Globalization;+using System.Text;+using Filee.Core.Conversion;++namespace Filee.Engines.Geo;++/// <summary>A coordinate system that can turn its positions into longitude / latitude in degrees.</summary>+internal abstract class GeoCrs+{+ private const double Degrees = 180 / Math.PI;++ /// <summary>The system of GeoJSON, KML and GPX.</summary>+ public static GeoCrs Wgs84 { get; } = new GeographicCrs("WGS 84", 1, 0, approximate: false);++ /// <summary>Name for messages, e.g. "NAD83 / UTM zone 18N".</summary>+ public string Name { get; private set; } = "";++ /// <summary>True for degrees of longitude / latitude (no projection).</summary>+ public virtual bool IsGeographic => false;++ /// <summary>True if positions are already longitude / latitude in degrees from Greenwich, so nothing needs converting.</summary>+ public virtual bool IsIdentity => false;++ /// <summary>+ /// True if the datum is not one that agrees with WGS 84 within a few metres, so positions are converted as if it+ /// were (they can be off by up to hundreds of metres).+ /// </summary>+ public bool IsApproximate { get; private set; }++ /// <summary>The position in degrees of longitude (X) and latitude (Y); the height is kept.</summary>+ public abstract Coord ToLonLat(Coord position);++ /// <summary>Reads a .prj / WKT definition; <see cref="ConversionRefusedException"/> if it is unknown or unsupported.</summary>+ public static GeoCrs FromWkt(string wkt)+ {+ if (wkt.Length > 1 << 16)+ throw Unsupported("(definition too long)");+ WktNode root;+ try+ {+ root = WktNode.Parse(wkt);+ }+ catch (FormatException ex)+ {+ throw Unsupported(ex.Message);+ }+ // WKT2 (ISO 19162) uses other keywords for the same things; PROJ writes it into .prj files only rarely.+ if (root.Name is "GEOGCRS" or "GEODCRS" or "PROJCRS" or "PROJECTEDCRS" or "BOUNDCRS" or "COMPOUNDCRS")+ throw Unsupported(root.Text(0) ?? root.Name);+ return root.Name switch+ {+ "GEOGCS" => FromGeographic(root),+ "PROJCS" => FromProjected(root),+ "COMPD_CS" => root.Child("PROJCS") is { } projected ? FromProjected(projected)+ : root.Child("GEOGCS") is { } geographic ? FromGeographic(geographic)+ : throw Unsupported(root.Text(0) ?? "COMPD_CS"),+ "GEOCCS" or "LOCAL_CS" or "VERT_CS" => throw Unsupported(root.Text(0) ?? root.Name),+ _ => throw Unsupported(root.Name),+ };+ }++ /// <summary>The system of an EPSG code, or null if it is not one Filee knows.</summary>+ public static GeoCrs? FromEpsg(int code)+ {+ switch (code)+ {+ case 4326:+ return Wgs84;+ case 4269 or 4258 or 4283 or 7844 or 4490 or 6318 or 4167 or 4612 or 6668 or 4674 or 4171 or 9777:+ // NAD83, ETRS89, GDA94, GDA2020, CGCS2000, NAD83(NSRS2007), NZGD2000, JGD2000, JGD2011, SIRGAS 2000, RGF93, Korea 2000+ return new GeographicCrs($"EPSG:{code}", 1, 0, approximate: false);+ case 3857 or 900913 or 3785 or 102100 or 102113:+ return new MercatorCrs("WGS 84 / Pseudo-Mercator", Ellipsoid.Sphere(6378137), 0, 1, 0, 0);+ }+ if (code is >= 32601 and <= 32660)+ return Utm(code, code - 32600, south: false, Ellipsoid.Wgs84, "WGS 84");+ if (code is >= 32701 and <= 32760)+ return Utm(code, code - 32700, south: true, Ellipsoid.Wgs84, "WGS 84");+ if (code is >= 26901 and <= 26923)+ return Utm(code, code - 26900, south: false, Ellipsoid.Grs80, "NAD83");+ if (code is >= 25828 and <= 25838)+ return Utm(code, code - 25800, south: false, Ellipsoid.Grs80, "ETRS89");+ return null;+ }++ /// <summary>A GeoJSON 2008 <c>crs</c> name such as "EPSG:4326" or "urn:ogc:def:crs:OGC:1.3:CRS84", or null.</summary>+ public static GeoCrs? FromName(string name)+ {+ var text = name.Trim();+ if (text.Contains("CRS84", StringComparison.OrdinalIgnoreCase) || text.Contains("CRS:84", StringComparison.OrdinalIgnoreCase))+ return Wgs84;+ var digits = text.Length - 1;+ while (digits >= 0 && char.IsAsciiDigit(text[digits]))+ digits--;+ return digits < text.Length - 1 && text.Contains("EPSG", StringComparison.OrdinalIgnoreCase)+ && int.TryParse(text.AsSpan(digits + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var code)+ ? FromEpsg(code)+ : null;+ }++ internal static ConversionRefusedException Unsupported(string detail) => new("error.geo_unsupported_crs", detail);++ private static GeoCrs Utm(int code, int zone, bool south, Ellipsoid ellipsoid, string datum) =>+ new TransverseMercatorCrs($"{datum} / UTM zone {zone}{(south ? 'S' : 'N')} (EPSG:{code})", ellipsoid,+ latitudeOrigin: 0, centralMeridian: (zone * 6 - 183) / Degrees, scale: 0.9996,+ falseEasting: 500000, falseNorthing: south ? 10000000 : 0, unit: 1);++ private static GeoCrs FromGeographic(WktNode node)+ {+ var name = node.Text(0) ?? "geographic";+ var datum = node.Child("DATUM")?.Text(0) ?? name;+ var compatible = IsWgs84Compatible(datum, node.Child("DATUM")?.Child("SPHEROID"));+ var unit = node.Child("UNIT")?.Number(1) ?? Math.PI / 180;+ var meridian = node.Child("PRIMEM")?.Number(1) ?? 0;+ // Angles in radians (UNIT factor) → degrees. A prime meridian other than Greenwich is given in the same unit.+ var toDegrees = Math.Abs(unit * Degrees - 1) < 1e-9 ? 1 : unit * Degrees;+ return new GeographicCrs(name, toDegrees, meridian * toDegrees, approximate: !compatible);+ }++ private static GeoCrs FromProjected(WktNode node)+ {+ var name = node.Text(0) ?? "projected";+ var geographic = node.Child("GEOGCS") ?? throw Unsupported(name);+ var datum = geographic.Child("DATUM");+ var spheroid = datum?.Child("SPHEROID");+ if (spheroid is null || spheroid.Number(1) is not { } axis || axis <= 0)+ throw Unsupported($"{name} (no ellipsoid)");+ var ellipsoid = Ellipsoid.FromInverseFlattening(axis, spheroid.Number(2) ?? 0);+ var approximate = !IsWgs84Compatible(datum?.Text(0) ?? geographic.Text(0) ?? "", spheroid);+ var unit = node.Children("UNIT").LastOrDefault()?.Number(1) ?? 1;+ if (unit <= 0)+ throw Unsupported($"{name} (unit)");+ var projection = node.Child("PROJECTION")?.Text(0) ?? throw Unsupported(name);+ var parameters = node.Children("PARAMETER").Where(p => p.Text(0) is not null && p.Number(1) is not null)+ .GroupBy(p => Key(p.Text(0)!)).ToDictionary(g => g.Key, g => g.First().Number(1)!.Value);++ double Get(string key, double fallback = 0) => parameters.TryGetValue(key, out var value) ? value : fallback;+ double Angle(string key) => Get(key) / Degrees;+ var falseEasting = Get("falseeasting") * unit;+ var falseNorthing = Get("falsenorthing") * unit;+ var centre = Angle("centralmeridian");+ var origin = Angle("latitudeoforigin");++ GeoCrs result;+ switch (Key(projection))+ {+ case "transversemercator" or "gausskruger" or "gausskrugerzone" or "tmerc":+ result = new TransverseMercatorCrs(name, ellipsoid, origin, centre, Get("scalefactor", 1), falseEasting, falseNorthing, unit);+ break;+ case "mercatorauxiliarysphere" or "popularvisualisationpseudomercator"+ or "popularvisualizationpseudomercator":+ result = new MercatorCrs(name, Ellipsoid.Sphere(axis), centre, 1, falseEasting, falseNorthing, unit);+ break;+ case "mercator" or "mercator1sp" or "mercator2sp":+ {+ var sphere = name.Contains("Pseudo", StringComparison.OrdinalIgnoreCase) || name.Contains("Web_Mercator", StringComparison.OrdinalIgnoreCase)+ || name.Contains("Web Mercator", StringComparison.OrdinalIgnoreCase);+ var body = sphere ? Ellipsoid.Sphere(axis) : ellipsoid;+ var k0 = Get("scalefactor", 1);+ if (parameters.ContainsKey("standardparallel1"))+ k0 = MercatorScale(body, Angle("standardparallel1"));+ result = new MercatorCrs(name, body, centre, k0, falseEasting, falseNorthing, unit);+ break;+ }+ case "lambertconformalconic" or "lambertconformalconic2sp" or "lambertconformalconic1sp" or "lambertconformalconicbelgium":+ {+ var first = parameters.ContainsKey("standardparallel1") ? Angle("standardparallel1") : origin;+ var second = parameters.ContainsKey("standardparallel2") ? Angle("standardparallel2") : first;+ result = new LambertConformalCrs(name, ellipsoid, origin, centre, first, second, Get("scalefactor", 1), falseEasting, falseNorthing, unit);+ break;+ }+ case "albersconicequalarea" or "albers" or "albersequalareaconic":+ result = new AlbersCrs(name, ellipsoid, origin, centre, Angle("standardparallel1"), Angle("standardparallel2"), falseEasting, falseNorthing, unit);+ break;+ default:+ throw Unsupported($"{name} ({projection})");+ }+ if (!approximate)+ return result;+ result.IsApproximate = true;+ return result;+ }++ private static double MercatorScale(Ellipsoid ellipsoid, double parallel)+ {+ var sin = Math.Sin(parallel);+ return Math.Cos(parallel) / Math.Sqrt(1 - ellipsoid.E2 * sin * sin);+ }++ private static string Key(string name) => new([.. name.Where(char.IsAsciiLetterOrDigit).Select(char.ToLowerInvariant)]);++ /// <summary>Datums that agree with WGS 84 within about two metres (ITRF-based systems), by name.</summary>+ private static readonly string[] Compatible =+ [+ "WGS1984", "WGS84", "NORTHAMERICAN1983", "NAD83", "ETRS89", "ETRS1989", "EUROPEANTERRESTRIALREFERENCESYSTEM1989",+ "GRS1980", "KOREA2000", "CHINA2000", "CGCS2000", "CHINAGEODETICCOORDINATESYSTEM2000", "JGD2011", "JGD2000",+ "JAPANGEODETICDATUM", "GDA94", "GDA2020", "GEOCENTRICDATUMOFAUSTRALIA", "NZGD2000", "NEWZEALANDGEODETICDATUM2000",+ "SIRGAS2000", "SIRGAS", "RGF93", "RESEAUGEODESIQUEFRANCAIS1993", "ITRF", "HARN", "NSRS2007",+ ];++ /// <summary>+ /// True for a datum named in <see cref="Compatible"/>, or on the WGS 84 / GRS 80 ellipsoid: modern national datums+ /// (LKS94, RGF93, SWEREF99, ...) are all realisations of ITRF on GRS 80 and agree with WGS 84 within a metre or two.+ /// Older datums use other ellipsoids (Bessel, Airy, Clarke, International) and are shifted by tens to hundreds of metres.+ /// </summary>+ private static bool IsWgs84Compatible(string datum, WktNode? spheroid)+ {+ if (spheroid?.Number(1) is { } axis && spheroid.Number(2) is { } inverse && Math.Abs(axis - 6378137) < 0.01 && Math.Abs(inverse - 298.2572) < 0.001)+ return true;+ var key = Key(datum.StartsWith("D_", StringComparison.Ordinal) ? datum[2..] : datum).ToUpperInvariant();+ return key.Length > 0 && Compatible.Any(name => key.Contains(name, StringComparison.Ordinal));+ }++ // ---- Systems ----++ private sealed class GeographicCrs : GeoCrs+ {+ private readonly double _toDegrees;+ private readonly double _meridian;++ public GeographicCrs(string name, double toDegrees, double meridian, bool approximate)+ {+ Name = name;+ _toDegrees = toDegrees;+ _meridian = meridian;+ IsApproximate = approximate;+ }++ public override bool IsGeographic => true;++ public override bool IsIdentity => _toDegrees == 1 && _meridian == 0;++ public override Coord ToLonLat(Coord position) =>+ _toDegrees == 1 && _meridian == 0 ? position : new Coord(position.X * _toDegrees + _meridian, position.Y * _toDegrees, position.Z);+ }++ /// <summary>A projection given by the inverse formula that maps metres to radians (longitude, latitude).</summary>+ private abstract class ProjectedBase : GeoCrs+ {+ private readonly double _unit;++ protected ProjectedBase(string name, double unit)+ {+ Name = name;+ _unit = unit;+ }++ /// <summary>Longitude and latitude in radians of a position in metres.</summary>+ protected abstract (double Lon, double Lat) Inverse(double x, double y);++ public override Coord ToLonLat(Coord position)+ {+ var (lon, lat) = Inverse(position.X * _unit, position.Y * _unit);+ return new Coord(lon * Degrees, lat * Degrees, position.Z);+ }+ }++ private sealed class TransverseMercatorCrs : ProjectedBase+ {+ // Krüger's series in the third flattening n (Karney 2011), accurate to nanometres far from the central meridian.+ private readonly double _centre, _scale, _falseEasting, _falseNorthing, _radius, _originArc;+ private readonly double[] _beta = new double[7];+ private readonly double[] _delta = new double[7];++ public TransverseMercatorCrs(string name, Ellipsoid ellipsoid, double latitudeOrigin, double centralMeridian, double scale,+ double falseEasting, double falseNorthing, double unit) : base(name, unit)+ {+ _centre = centralMeridian;+ _scale = scale;+ _falseEasting = falseEasting;+ _falseNorthing = falseNorthing;+ var n = ellipsoid.Flattening / (2 - ellipsoid.Flattening);+ var n2 = n * n;+ var n3 = n2 * n;+ var n4 = n3 * n;+ var n5 = n4 * n;+ var n6 = n5 * n;+ _radius = ellipsoid.SemiMajor / (1 + n) * (1 + n2 / 4 + n4 / 64 + n6 / 256);+ _beta[1] = n / 2 - 2 * n2 / 3 + 37 * n3 / 96 - n4 / 360 - 81 * n5 / 512 + 96199 * n6 / 604800;+ _beta[2] = n2 / 48 + n3 / 15 - 437 * n4 / 1440 + 46 * n5 / 105 - 1118711 * n6 / 3870720;+ _beta[3] = 17 * n3 / 480 - 37 * n4 / 840 - 209 * n5 / 4480 + 5569 * n6 / 90720;+ _beta[4] = 4397 * n4 / 161280 - 11 * n5 / 504 - 830251 * n6 / 7257600;+ _beta[5] = 4583 * n5 / 161280 - 108847 * n6 / 3991680;+ _beta[6] = 20648693 * n6 / 638668800;+ _delta[1] = 2 * n - 2 * n2 / 3 - 2 * n3 + 116 * n4 / 45 + 26 * n5 / 45 - 2854 * n6 / 675;+ _delta[2] = 7 * n2 / 3 - 8 * n3 / 5 - 227 * n4 / 45 + 2704 * n5 / 315 + 2323 * n6 / 945;+ _delta[3] = 56 * n3 / 15 - 136 * n4 / 35 - 1262 * n5 / 105 + 73814 * n6 / 2835;+ _delta[4] = 4279 * n4 / 630 - 332 * n5 / 35 - 399572 * n6 / 14175;+ _delta[5] = 4174 * n5 / 315 - 144838 * n6 / 6237;+ _delta[6] = 601676 * n6 / 22275;+ _originArc = latitudeOrigin == 0 ? 0 : ellipsoid.MeridianArc(latitudeOrigin);+ }++ protected override (double Lon, double Lat) Inverse(double x, double y)+ {+ var xi = (y - _falseNorthing + _scale * _originArc) / (_scale * _radius);+ var eta = (x - _falseEasting) / (_scale * _radius);+ var xi2 = xi;+ var eta2 = eta;+ for (var j = 1; j <= 6; j++)+ {+ xi2 -= _beta[j] * Math.Sin(2 * j * xi) * Math.Cosh(2 * j * eta);+ eta2 -= _beta[j] * Math.Cos(2 * j * xi) * Math.Sinh(2 * j * eta);+ }+ var chi = Math.Asin(Math.Sin(xi2) / Math.Cosh(eta2));+ var lat = chi;+ for (var j = 1; j <= 6; j++)+ lat += _delta[j] * Math.Sin(2 * j * chi);+ return (_centre + Math.Atan2(Math.Sinh(eta2), Math.Cos(xi2)), lat);+ }+ }++ private sealed class MercatorCrs : ProjectedBase+ {+ private readonly Ellipsoid _ellipsoid;+ private readonly double _centre, _scale, _falseEasting, _falseNorthing;++ public MercatorCrs(string name, Ellipsoid ellipsoid, double centralMeridian, double scale, double falseEasting, double falseNorthing,+ double unit = 1) : base(name, unit)+ {+ _ellipsoid = ellipsoid;+ _centre = centralMeridian;+ _scale = scale;+ _falseEasting = falseEasting;+ _falseNorthing = falseNorthing;+ }++ protected override (double Lon, double Lat) Inverse(double x, double y)+ {+ var a = _ellipsoid.SemiMajor * _scale;+ var t = Math.Exp(-(y - _falseNorthing) / a);+ var lat = Math.PI / 2 - 2 * Math.Atan(t);+ var e = _ellipsoid.E;+ if (e > 0)+ {+ for (var i = 0; i < 12; i++)+ {+ var sin = e * Math.Sin(lat);+ var next = Math.PI / 2 - 2 * Math.Atan(t * Math.Pow((1 - sin) / (1 + sin), e / 2));+ var done = Math.Abs(next - lat) < 1e-14;+ lat = next;+ if (done)+ break;+ }+ }+ return (_centre + (x - _falseEasting) / a, lat);+ }+ }++ private sealed class LambertConformalCrs : ProjectedBase+ {+ private readonly Ellipsoid _ellipsoid;+ private readonly double _centre, _falseEasting, _falseNorthing, _n, _f, _rho0;++ public LambertConformalCrs(string name, Ellipsoid ellipsoid, double latitudeOrigin, double centralMeridian, double first, double second,+ double scale, double falseEasting, double falseNorthing, double unit) : base(name, unit)+ {+ _ellipsoid = ellipsoid;+ _centre = centralMeridian;+ _falseEasting = falseEasting;+ _falseNorthing = falseNorthing;+ var m1 = Math.Cos(first) / Math.Sqrt(1 - ellipsoid.E2 * Math.Pow(Math.Sin(first), 2));+ var t1 = T(first);+ if (Math.Abs(first - second) < 1e-12)+ {+ _n = Math.Sin(first);+ }+ else+ {+ var m2 = Math.Cos(second) / Math.Sqrt(1 - ellipsoid.E2 * Math.Pow(Math.Sin(second), 2));+ _n = (Math.Log(m1) - Math.Log(m2)) / (Math.Log(t1) - Math.Log(T(second)));+ }+ _f = ellipsoid.SemiMajor * scale * m1 / (_n * Math.Pow(t1, _n));+ _rho0 = _f * Math.Pow(T(latitudeOrigin), _n);+ }++ private double T(double lat)+ {+ var sin = _ellipsoid.E * Math.Sin(lat);+ return Math.Tan(Math.PI / 4 - lat / 2) / Math.Pow((1 - sin) / (1 + sin), _ellipsoid.E / 2);+ }++ protected override (double Lon, double Lat) Inverse(double x, double y)+ {+ var dx = x - _falseEasting;+ var dy = _rho0 - (y - _falseNorthing);+ var sign = Math.Sign(_n);+ var rho = sign * Math.Sqrt(dx * dx + dy * dy);+ var theta = Math.Atan2(sign * dx, sign * dy);+ var t = Math.Pow(rho / _f, 1 / _n);+ var lat = Math.PI / 2 - 2 * Math.Atan(t);+ var e = _ellipsoid.E;+ for (var i = 0; i < 12 && e > 0; i++)+ {+ var sin = e * Math.Sin(lat);+ var next = Math.PI / 2 - 2 * Math.Atan(t * Math.Pow((1 - sin) / (1 + sin), e / 2));+ var done = Math.Abs(next - lat) < 1e-14;+ lat = next;+ if (done)+ break;+ }+ return (_centre + theta / _n, lat);+ }+ }++ private sealed class AlbersCrs : ProjectedBase+ {+ private readonly Ellipsoid _ellipsoid;+ private readonly double _centre, _falseEasting, _falseNorthing, _n, _c, _rho0;++ public AlbersCrs(string name, Ellipsoid ellipsoid, double latitudeOrigin, double centralMeridian, double first, double second,+ double falseEasting, double falseNorthing, double unit) : base(name, unit)+ {+ _ellipsoid = ellipsoid;+ _centre = centralMeridian;+ _falseEasting = falseEasting;+ _falseNorthing = falseNorthing;+ var m1 = M(first);+ var q1 = Q(first);+ _n = Math.Abs(first - second) < 1e-12 ? Math.Sin(first) : (m1 * m1 - M(second) * M(second)) / (Q(second) - q1);+ _c = m1 * m1 + _n * q1;+ _rho0 = ellipsoid.SemiMajor * Math.Sqrt(Math.Max(0, _c - _n * Q(latitudeOrigin))) / _n;+ }++ private double M(double lat) => Math.Cos(lat) / Math.Sqrt(1 - _ellipsoid.E2 * Math.Pow(Math.Sin(lat), 2));++ private double Q(double lat)+ {+ var sin = Math.Sin(lat);+ var e = _ellipsoid.E;+ if (e < 1e-12)+ return 2 * sin;+ return (1 - _ellipsoid.E2) * (sin / (1 - _ellipsoid.E2 * sin * sin) - Math.Log((1 - e * sin) / (1 + e * sin)) / (2 * e));+ }++ protected override (double Lon, double Lat) Inverse(double x, double y)+ {+ var dx = x - _falseEasting;+ var dy = _rho0 - (y - _falseNorthing);+ var sign = Math.Sign(_n);+ var rho = Math.Sqrt(dx * dx + dy * dy);+ var theta = Math.Atan2(sign * dx, sign * dy);+ var a = _ellipsoid.SemiMajor;+ var q = (_c - rho * rho * _n * _n / (a * a)) / _n;+ var e = _ellipsoid.E;+ var lat = Math.Asin(Math.Clamp(q / 2, -1, 1));+ if (e > 1e-12)+ {+ var polar = Q(Math.PI / 2);+ if (Math.Abs(Math.Abs(q) - polar) < 1e-10)+ return (_centre + theta / _n, Math.Sign(q) * Math.PI / 2);+ for (var i = 0; i < 20; i++)+ {+ var sin = Math.Sin(lat);+ var w = 1 - _ellipsoid.E2 * sin * sin;+ var step = w * w / (2 * Math.Cos(lat))+ * (q / (1 - _ellipsoid.E2) - sin / w + Math.Log((1 - e * sin) / (1 + e * sin)) / (2 * e));+ lat += step;+ if (Math.Abs(step) < 1e-14)+ break;+ }+ }+ return (_centre + theta / _n, lat);+ }+ }++ // ---- Ellipsoid ----++ private sealed class Ellipsoid+ {+ public static readonly Ellipsoid Wgs84 = FromInverseFlattening(6378137, 298.257223563);+ public static readonly Ellipsoid Grs80 = FromInverseFlattening(6378137, 298.257222101);++ private Ellipsoid(double semiMajor, double flattening)+ {+ SemiMajor = semiMajor;+ Flattening = flattening;+ E2 = flattening * (2 - flattening);+ E = Math.Sqrt(E2);+ }++ public double SemiMajor { get; }+ public double Flattening { get; }+ public double E2 { get; }+ public double E { get; }++ public static Ellipsoid FromInverseFlattening(double semiMajor, double inverseFlattening) =>+ new(semiMajor, inverseFlattening > 1 ? 1 / inverseFlattening : 0);++ public static Ellipsoid Sphere(double radius) => new(radius, 0);++ /// <summary>The distance along the meridian from the equator to <paramref name="lat"/> (radians), in metres.</summary>+ public double MeridianArc(double lat)+ {+ var e4 = E2 * E2;+ var e6 = e4 * E2;+ return SemiMajor * ((1 - E2 / 4 - 3 * e4 / 64 - 5 * e6 / 256) * lat+ - (3 * E2 / 8 + 3 * e4 / 32 + 45 * e6 / 1024) * Math.Sin(2 * lat)+ + (15 * e4 / 256 + 45 * e6 / 1024) * Math.Sin(4 * lat)+ - 35 * e6 / 3072 * Math.Sin(6 * lat));+ }+ }+}++/// <summary>A node of a WKT definition: <c>NAME[arg, arg, NAME[...]]</c>; arguments are text, numbers or nodes.</summary>+internal sealed class WktNode(string name, List<object> items)+{+ private const int MaxDepth = 24;++ public string Name { get; } = name;+ public List<object> Items { get; } = items;++ /// <summary>The quoted text or word at <paramref name="index"/>, or null.</summary>+ public string? Text(int index) => index < Items.Count ? Items[index] as string : null;++ /// <summary>The number at <paramref name="index"/>, or null.</summary>+ public double? Number(int index) => index < Items.Count && Items[index] is double value ? value : null;++ public WktNode? Child(string name) => Children(name).FirstOrDefault();++ public IEnumerable<WktNode> Children(string name) =>+ Items.OfType<WktNode>().Where(n => n.Name.Equals(name, StringComparison.OrdinalIgnoreCase));++ /// <summary>Parses a definition; <see cref="FormatException"/> says what is wrong with it.</summary>+ public static WktNode Parse(string text)+ {+ var position = 0;+ var node = ReadNode(text, ref position, 0) ?? throw new FormatException("empty definition");+ return node;+ }++ private static WktNode? ReadNode(string text, ref int position, int depth)+ {+ if (depth > MaxDepth)+ throw new FormatException("definition nested too deeply");+ SkipSpace(text, ref position);+ var start = position;+ while (position < text.Length && (char.IsAsciiLetterOrDigit(text[position]) || text[position] == '_'))+ position++;+ if (position == start)+ return null;+ var name = text[start..position].ToUpperInvariant();+ SkipSpace(text, ref position);+ var items = new List<object>();+ if (position >= text.Length || text[position] is not ('[' or '('))+ return new WktNode(name, items);+ var close = text[position] == '[' ? ']' : ')';+ position++;+ while (true)+ {+ SkipSpace(text, ref position);+ if (position >= text.Length)+ throw new FormatException("missing closing bracket");+ var ch = text[position];+ if (ch == close)+ {+ position++;+ return new WktNode(name, items);+ }+ if (ch == ',')+ {+ position++;+ }+ else if (ch == '"')+ {+ var builder = new StringBuilder();+ position++;+ while (true)+ {+ if (position >= text.Length)+ throw new FormatException("missing closing quote");+ if (text[position] == '"')+ {+ if (position + 1 < text.Length && text[position + 1] == '"')+ {+ builder.Append('"');+ position += 2;+ continue;+ }+ position++;+ break;+ }+ builder.Append(text[position++]);+ }+ items.Add(builder.ToString());+ }+ else if (char.IsAsciiDigit(ch) || ch is '-' or '+' or '.')+ {+ var from = position;+ while (position < text.Length && (char.IsAsciiDigit(text[position]) || text[position] is '-' or '+' or '.' or 'e' or 'E'))+ position++;+ if (!double.TryParse(text.AsSpan(from, position - from), NumberStyles.Float, CultureInfo.InvariantCulture, out var number))+ throw new FormatException($"bad number '{text[from..position]}'");+ items.Add(number);+ }+ else if (ReadNode(text, ref position, depth + 1) is { } child)+ {+ // A word with no brackets, like the axis direction NORTH, is kept as text.+ items.Add(child.Items.Count == 0 ? child.Name : child);+ }+ else+ {+ throw new FormatException($"unexpected '{ch}'");+ }+ }+ }++ private static void SkipSpace(string text, ref int position)+ {+ while (position < text.Length && char.IsWhiteSpace(text[position]))+ position++;+ }+}diff --git a/src/Filee.Engines/Geo/GeoCsvFormat.cs b/src/Filee.Engines/Geo/GeoCsvFormat.csnew file mode 100644index 00000000..ce7327d0--- /dev/null+++ b/src/Filee.Engines/Geo/GeoCsvFormat.cs@@ -0,0 +1,185 @@+// Geospatial CSV in and out. Reading finds the location of each row in a WKT column (wkt, geom, geometry, the_geom,+// shape) or in a pair of longitude / latitude columns (lon, lng, long, longitude, x and lat, latitude, y; a decimal+// comma is accepted); the other columns become attributes, typed as numbers or true / false when they look like them.+// Rows with no usable location stay in the data without a geometry. Writing gives longitude and latitude columns (and+// elevation) when every geometry is a point, otherwise one WKT column; the attributes follow. CSV has no coordinate+// system, so it is always WGS 84.++using System.Globalization;+using Filee.Core.Conversion;+using Filee.Engines.Data;+using Filee.Engines.Office.Sheets;++namespace Filee.Engines.Geo;++internal static class GeoCsvFormat+{+ private static readonly string[] WktNames = ["wktgeo", "wkt", "geom", "geometry", "thegeom", "wktgeom", "wktgeometry", "geometrywkt", "shape", "geometria"];+ private static readonly string[] LonNames = ["longitude", "lon", "lng", "long", "lons", "longitud", "longitudine", "lond", "xcoord", "xcoordinate", "x", "easting", "lonx"];+ private static readonly string[] LatNames = ["latitude", "lat", "lats", "latitud", "latitudine", "latd", "ycoord", "ycoordinate", "y", "northing", "laty"];+ private static readonly string[] HeightNames = ["elevation", "elev", "altitude", "alt", "z", "height", "ele"];++ /// <summary>Reads a CSV with a location in each row; <see cref="ConversionRefusedException"/> if it has none.</summary>+ public static GeoDataset Read(string path, CancellationToken cancellationToken)+ {+ var rows = CsvData.ReadRows(path);+ if (rows.Count == 0)+ throw new ConversionRefusedException("error.geo_empty");+ var header = rows[0].Select(h => h.Trim().TrimStart('')).ToList();+ var keys = header.Select(Key).ToList();++ var wkt = Find(keys, WktNames);+ var lon = Find(keys, LonNames);+ var lat = Find(keys, LatNames);+ if (wkt < 0 && (lon < 0 || lat < 0))+ throw new ConversionRefusedException("error.geo_csv_no_coordinates", string.Join(", ", header.Take(8)));+ var height = wkt < 0 ? Find(keys, HeightNames) : -1;++ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path) };+ var names = UniqueNames(header);+ var used = wkt >= 0 ? new HashSet<int> { wkt } : new HashSet<int> { lon, lat };+ var located = 0;+ for (var r = 1; r < rows.Count; r++)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var row = rows[r];+ string Cell(int column) => column < row.Count ? row[column].Trim() : "";++ GeoGeometry? geometry = null;+ if (wkt >= 0)+ {+ var text = Cell(wkt);+ if (text.Length > 0)+ {+ try+ {+ geometry = WktFormat.Parse(text);+ }+ catch (FormatException ex)+ {+ throw new InvalidDataException($"Row {r + 1}: the {header[wkt]} column is not valid WKT ({ex.Message}).", ex);+ }+ }+ }+ else if (Number(Cell(lon)) is { } x && Number(Cell(lat)) is { } y)+ {+ var z = height >= 0 && Number(Cell(height)) is { } elevation ? elevation : double.NaN;+ geometry = new GeoPoint(new Coord(x, y, z));+ }+ if (geometry is not null)+ located++;+ var properties = new List<KeyValuePair<string, object?>>();+ for (var c = 0; c < header.Count; c++)+ {+ if (!used.Contains(c))+ properties.Add(new(names[c], GeoText.Typed(Cell(c))));+ }+ dataset.Features.Add(new GeoFeature(geometry, properties));+ }+ if (dataset.Features.Count == 0)+ throw new ConversionRefusedException("error.geo_empty");+ if (located == 0)+ throw new ConversionRefusedException("error.geo_csv_no_locations", wkt >= 0 ? header[wkt] : $"{header[lon]}, {header[lat]}");+ dataset.RowsWithoutLocation = located < dataset.Features.Count;+ return dataset;+ }++ private static int Find(List<string> keys, string[] candidates)+ {+ foreach (var candidate in candidates)+ {+ var index = keys.IndexOf(candidate);+ if (index >= 0)+ return index;+ }+ return -1;+ }++ private static string Key(string header) => new([.. header.Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant)]);++ /// <summary>Column names with blanks named "columnN" and repeats numbered, so every attribute has its own name.</summary>+ private static List<string> UniqueNames(List<string> header)+ {+ var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ var names = new List<string>();+ for (var i = 0; i < header.Count; i++)+ {+ var name = header[i].Length == 0 ? $"column{i + 1}" : header[i];+ var unique = name;+ for (var n = 2; !seen.Add(unique); n++)+ unique = $"{name}_{n}";+ names.Add(unique);+ }+ return names;+ }++ /// <summary>A coordinate: "12.5", "-3", or "12,5" with a decimal comma; null for blank or anything else.</summary>+ private static double? Number(string text)+ {+ if (text.Length == 0)+ return null;+ if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && double.IsFinite(value))+ return value;+ if (text.Count(c => c == ',') == 1 && !text.Contains('.', StringComparison.Ordinal)+ && double.TryParse(text.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value))+ return value;+ return null;+ }++ // ---- Writing ----++ /// <summary>Writes the dataset (in longitude / latitude) as CSV.</summary>+ public static void Write(GeoDataset dataset, string path, CancellationToken cancellationToken)+ {+ var columns = dataset.Columns();+ var geometries = dataset.Features.Select(f => f.Geometry).OfType<GeoGeometry>().ToList();+ // An attribute that already is a longitude or latitude column would be mistaken for the geometry when the CSV is+ // read again, so such a dataset gets its geometry as WKT.+ var ambiguous = columns.Any(c => LonNames.Contains(Key(c)) || LatNames.Contains(Key(c)));+ var points = !ambiguous && geometries.Count > 0 && geometries.All(g => g is GeoPoint);+ var withHeight = points && geometries.Any(g => g.HasZ);++ string[] geometryColumns = !points ? ["wkt"] : withHeight ? ["longitude", "latitude", "elevation"] : ["longitude", "latitude"];+ // An attribute that already has one of these names keeps it; the geometry column gets "_geo" after it.+ var taken = new HashSet<string>(columns, StringComparer.OrdinalIgnoreCase);+ var geometryNames = geometryColumns.Select(name =>+ {+ var unique = name;+ while (!taken.Add(unique))+ unique += "_geo";+ return unique;+ }).ToList();++ List<List<string>> rows = [[.. geometryNames, .. columns]];+ foreach (var feature in dataset.Features)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var row = new List<string>(geometryNames.Count + columns.Count);+ if (points)+ {+ if (feature.Geometry is GeoPoint point)+ {+ row.Add(GeoText.Degrees(point.Position.X));+ row.Add(GeoText.Degrees(point.Position.Y));+ if (withHeight)+ row.Add(point.Position.HasZ ? GeoText.Height(point.Position.Z) : "");+ }+ else+ {+ row.AddRange(Enumerable.Repeat("", geometryNames.Count));+ }+ }+ else+ {+ row.Add(feature.Geometry is { } geometry ? WktFormat.Write(geometry) : "");+ }+ var values = new Dictionary<string, object?>(StringComparer.Ordinal);+ foreach (var (key, value) in feature.Properties)+ values.TryAdd(key, value);+ foreach (var column in columns)+ row.Add(values.TryGetValue(column, out var value) ? GeoText.ToText(value) : "");+ rows.Add(row);+ }+ CsvFormat.WriteRows(rows, path);+ }+}diff --git a/src/Filee.Engines/Geo/GeoJsonFormat.cs b/src/Filee.Engines/Geo/GeoJsonFormat.csnew file mode 100644index 00000000..7294f5ac--- /dev/null+++ b/src/Filee.Engines/Geo/GeoJsonFormat.cs@@ -0,0 +1,340 @@+// GeoJSON (RFC 7946) in and out: FeatureCollection, Feature or a bare geometry on the way in; one feature per line on+// the way out, polygons in the RFC's orientation (outer ring counter-clockwise). Attributes that are objects or lists+// are kept as their JSON text. Positions beyond longitude / latitude / height are ignored. A "crs" member (GeoJSON+// 2008) is honoured for the systems GeoCrs knows; any other is refused rather than read as degrees.++using System.Buffers;+using System.Globalization;+using System.Text;+using System.Text.Encodings.Web;+using System.Text.Json;+using System.Text.Unicode;+using Filee.Engines.Hwp.Hwpx;++namespace Filee.Engines.Geo;++internal static class GeoJsonFormat+{+ /// <summary>Reads a GeoJSON file; <see cref="InvalidDataException"/> says what is wrong with it.</summary>+ public static GeoDataset Read(string path, CancellationToken cancellationToken)+ {+ var bytes = File.ReadAllBytes(path);+ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path) };+ try+ {+ using var document = Parse(bytes);+ var root = document.RootElement;+ if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String)+ throw new InvalidDataException("The file is JSON but not GeoJSON: the top level has no \"type\".");+ ReadCrs(root, dataset);+ switch (type.GetString())+ {+ case "FeatureCollection":+ if (!root.TryGetProperty("features", out var features) || features.ValueKind != JsonValueKind.Array)+ throw new InvalidDataException("The FeatureCollection has no \"features\" list.");+ var index = 0;+ foreach (var feature in features.EnumerateArray())+ {+ cancellationToken.ThrowIfCancellationRequested();+ dataset.Features.Add(ReadFeature(feature, index++));+ }+ break;+ case "Feature":+ dataset.Features.Add(ReadFeature(root, 0));+ break;+ default:+ dataset.Features.Add(new GeoFeature(ReadGeometry(root, "geometry"), []));+ break;+ }+ }+ catch (JsonException ex)+ {+ throw new InvalidDataException($"The file is not valid JSON ({ex.Message})", ex);+ }+ return dataset;+ }++ private static JsonDocument Parse(byte[] bytes)+ {+ var options = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = 128 };+ var skip = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;+ // UTF-8 is parsed as it is (the usual, and the cheap, case). UTF-16 and text in an old code page are decoded first;+ // the parser alone would accept invalid UTF-8 inside strings and fail later, in an unhelpful way.+ if (Utf8.IsValid(bytes.AsSpan(skip)))+ return JsonDocument.Parse(bytes.AsMemory(skip), options);+ return JsonDocument.Parse(HwpxConverter.DecodeText(bytes), options);+ }++ private static void ReadCrs(JsonElement root, GeoDataset dataset)+ {+ if (!root.TryGetProperty("crs", out var crs) || crs.ValueKind != JsonValueKind.Object)+ return;+ string? name = null;+ if (crs.TryGetProperty("properties", out var properties) && properties.ValueKind == JsonValueKind.Object+ && properties.TryGetProperty("name", out var nameElement) && nameElement.ValueKind == JsonValueKind.String)+ name = nameElement.GetString();+ if (name is null)+ return;+ dataset.Crs = GeoCrs.FromName(name) ?? throw GeoCrs.Unsupported(name);+ dataset.CrsDeclared = true;+ }++ private static GeoFeature ReadFeature(JsonElement feature, int index)+ {+ if (feature.ValueKind != JsonValueKind.Object)+ throw new InvalidDataException($"Feature {index + 1} is not an object.");+ var properties = new List<KeyValuePair<string, object?>>();+ var hasProperties = feature.TryGetProperty("properties", out var attributes) && attributes.ValueKind == JsonValueKind.Object;+ if (feature.TryGetProperty("id", out var id) && id.ValueKind is JsonValueKind.String or JsonValueKind.Number+ && !(hasProperties && attributes.TryGetProperty("id", out _)))+ properties.Add(new("id", Value(id)));+ if (hasProperties)+ {+ foreach (var property in attributes.EnumerateObject())+ properties.Add(new(property.Name, Value(property.Value)));+ }+ GeoGeometry? geometry = null;+ if (feature.TryGetProperty("geometry", out var geometryElement) && geometryElement.ValueKind == JsonValueKind.Object)+ geometry = ReadGeometry(geometryElement, $"feature {index + 1}");+ return new GeoFeature(geometry, properties);+ }++ private static object? Value(JsonElement element) => element.ValueKind switch+ {+ JsonValueKind.String => element.GetString(),+ JsonValueKind.Number => element.TryGetInt64(out var whole) ? whole : element.GetDouble(),+ JsonValueKind.True => true,+ JsonValueKind.False => false,+ JsonValueKind.Null or JsonValueKind.Undefined => null,+ _ => element.GetRawText(),+ };++ private static GeoGeometry? ReadGeometry(JsonElement element, string where)+ {+ if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty("type", out var typeElement) || typeElement.ValueKind != JsonValueKind.String)+ throw new InvalidDataException($"The geometry of {where} has no \"type\".");+ var type = typeElement.GetString();+ if (type == "GeometryCollection")+ {+ if (!element.TryGetProperty("geometries", out var members) || members.ValueKind != JsonValueKind.Array)+ throw new InvalidDataException($"The GeometryCollection of {where} has no \"geometries\" list.");+ var parts = members.EnumerateArray().Select(m => ReadGeometry(m, where)).OfType<GeoGeometry>().ToList();+ return parts.Count == 0 ? null : new GeoCollection(parts);+ }+ if (!element.TryGetProperty("coordinates", out var coordinates) || coordinates.ValueKind != JsonValueKind.Array)+ throw new InvalidDataException($"The {type} of {where} has no \"coordinates\".");+ switch (type)+ {+ case "Point":+ return coordinates.GetArrayLength() == 0 ? null : new GeoPoint(Position(coordinates, where));+ case "MultiPoint":+ {+ var points = Line(coordinates, where);+ return points.Count == 0 ? null : new GeoMultiPoint(points);+ }+ case "LineString":+ {+ var line = Line(coordinates, where);+ return line.Count < 2 ? null : new GeoLineString(line);+ }+ case "MultiLineString":+ {+ var lines = coordinates.EnumerateArray().Select(l => Line(l, where)).Where(l => l.Count >= 2).ToList();+ return lines.Count == 0 ? null : new GeoMultiLineString([.. lines.Select(l => (IReadOnlyList<Coord>)l)]);+ }+ case "Polygon":+ return Polygon(coordinates, where);+ case "MultiPolygon":+ {+ var polygons = coordinates.EnumerateArray().Select(p => Polygon(p, where)).OfType<GeoPolygon>().ToList();+ return polygons.Count == 0 ? null : new GeoMultiPolygon(polygons);+ }+ default:+ throw new InvalidDataException($"Unknown geometry type \"{type}\" in {where}.");+ }+ }++ private static GeoPolygon? Polygon(JsonElement rings, string where)+ {+ if (rings.ValueKind != JsonValueKind.Array)+ throw new InvalidDataException($"A polygon of {where} is not a list of rings.");+ var closed = rings.EnumerateArray().Select(r => GeoRings.Close(Line(r, where))).OfType<IReadOnlyList<Coord>>().ToList();+ return closed.Count == 0 ? null : new GeoPolygon(closed);+ }++ private static List<Coord> Line(JsonElement positions, string where)+ {+ if (positions.ValueKind != JsonValueKind.Array)+ throw new InvalidDataException($"A list of positions in {where} is not a list.");+ var line = new List<Coord>(positions.GetArrayLength());+ foreach (var position in positions.EnumerateArray())+ line.Add(Position(position, where));+ return line;+ }++ private static Coord Position(JsonElement position, string where)+ {+ if (position.ValueKind != JsonValueKind.Array || position.GetArrayLength() < 2)+ throw new InvalidDataException($"A position in {where} needs at least longitude and latitude.");+ double? x = null, y = null;+ var z = double.NaN;+ var i = 0;+ foreach (var number in position.EnumerateArray())+ {+ if (number.ValueKind != JsonValueKind.Number)+ throw new InvalidDataException($"A position in {where} holds something that is not a number.");+ switch (i++)+ {+ case 0: x = number.GetDouble(); break;+ case 1: y = number.GetDouble(); break;+ case 2: z = number.GetDouble(); break;+ }+ }+ return new Coord(x!.Value, y!.Value, z);+ }++ // ---- Writing ----++ /// <summary>Writes the dataset (in longitude / latitude) as a FeatureCollection, one feature per line.</summary>+ public static void Write(GeoDataset dataset, string path, CancellationToken cancellationToken)+ {+ using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);+ stream.Write("{\"type\":\"FeatureCollection\",\"features\":[\n"u8);+ var buffer = new ArrayBufferWriter<byte>(4096);+ using var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });+ for (var i = 0; i < dataset.Features.Count; i++)+ {+ cancellationToken.ThrowIfCancellationRequested();+ buffer.Clear();+ writer.Reset(buffer);+ WriteFeature(writer, dataset.Features[i]);+ writer.Flush();+ if (i > 0)+ stream.Write(",\n"u8);+ stream.Write(buffer.WrittenSpan);+ }+ stream.Write("\n]}\n"u8);+ }++ private static void WriteFeature(Utf8JsonWriter writer, GeoFeature feature)+ {+ writer.WriteStartObject();+ writer.WriteString("type", "Feature");+ writer.WriteStartObject("properties");+ var written = new HashSet<string>(StringComparer.Ordinal);+ foreach (var (key, value) in feature.Properties)+ {+ // 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);+ }+ writer.WriteEndObject();+ writer.WritePropertyName("geometry");+ if (feature.Geometry is { } geometry)+ WriteGeometry(writer, geometry);+ else+ writer.WriteNullValue();+ writer.WriteEndObject();+ }++ private static void WriteValue(Utf8JsonWriter writer, object? value)+ {+ switch (value)+ {+ case null:+ writer.WriteNullValue();+ break;+ case string text:+ writer.WriteStringValue(text);+ break;+ case bool flag:+ writer.WriteBooleanValue(flag);+ break;+ case long whole:+ writer.WriteNumberValue(whole);+ break;+ case double real when double.IsFinite(real):+ writer.WriteNumberValue(real);+ break;+ case double:+ writer.WriteNullValue();+ break;+ default:+ writer.WriteStringValue(GeoText.ToText(value));+ break;+ }+ }++ private static void WriteGeometry(Utf8JsonWriter writer, GeoGeometry geometry)+ {+ writer.WriteStartObject();+ writer.WriteString("type", geometry.TypeName);+ if (geometry is GeoCollection collection)+ {+ writer.WriteStartArray("geometries");+ foreach (var member in collection.Geometries)+ WriteGeometry(writer, member);+ writer.WriteEndArray();+ writer.WriteEndObject();+ return;+ }+ var hasZ = geometry.HasZ;+ writer.WritePropertyName("coordinates");+ switch (geometry)+ {+ case GeoPoint point:+ WritePosition(writer, point.Position, hasZ);+ break;+ case GeoMultiPoint multiPoint:+ WriteLine(writer, multiPoint.Points, hasZ);+ break;+ case GeoLineString line:+ WriteLine(writer, line.Points, hasZ);+ break;+ case GeoMultiLineString lines:+ writer.WriteStartArray();+ foreach (var part in lines.Lines)+ WriteLine(writer, part, hasZ);+ writer.WriteEndArray();+ break;+ case GeoPolygon polygon:+ WritePolygon(writer, polygon, hasZ);+ break;+ case GeoMultiPolygon polygons:+ writer.WriteStartArray();+ foreach (var part in polygons.Polygons)+ WritePolygon(writer, part, hasZ);+ writer.WriteEndArray();+ break;+ }+ writer.WriteEndObject();+ }++ private static void WritePolygon(Utf8JsonWriter writer, GeoPolygon polygon, bool hasZ)+ {+ writer.WriteStartArray();+ for (var i = 0; i < polygon.Rings.Count; i++)+ WriteLine(writer, GeoRings.Oriented(polygon.Rings[i], counterClockwise: i == 0), hasZ);+ writer.WriteEndArray();+ }++ private static void WriteLine(Utf8JsonWriter writer, IReadOnlyList<Coord> points, bool hasZ)+ {+ writer.WriteStartArray();+ foreach (var point in points)+ WritePosition(writer, point, hasZ);+ writer.WriteEndArray();+ }++ private static void WritePosition(Utf8JsonWriter writer, Coord position, bool hasZ)+ {+ writer.WriteStartArray();+ writer.WriteRawValue(GeoText.Degrees(position.X));+ writer.WriteRawValue(GeoText.Degrees(position.Y));+ if (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.csnew file mode 100644index 00000000..b1d42b0f--- /dev/null+++ b/src/Filee.Engines/Geo/GeoModel.cs@@ -0,0 +1,261 @@+// The in-memory model every geospatial vector format is read into and written from: features (a geometry and an+// ordered list of attributes) in longitude / latitude. Each reader produces it and each writer consumes it, so GeoJSON,+// KML, KMZ, GPX, Shapefile and CSV convert to each other through this one shape. See docs/ENGINES.md, "Geospatial".++using System.Globalization;++namespace Filee.Engines.Geo;++/// <summary>One position: X = longitude and Y = latitude in degrees once a file is read, <see cref="Z"/> the height or NaN.</summary>+internal readonly record struct Coord(double X, double Y, double Z = double.NaN)+{+ /// <summary>True if the position has a height.</summary>+ public bool HasZ => !double.IsNaN(Z);++ /// <summary>True if both X and Y are real numbers.</summary>+ public bool IsFinite => double.IsFinite(X) && double.IsFinite(Y);+}++/// <summary>A geometry: a point, line, polygon, a collection of them, or a collection of mixed kinds.</summary>+internal abstract class GeoGeometry+{+ /// <summary>The OGC name of the type, e.g. <c>"Polygon"</c>.</summary>+ public abstract string TypeName { get; }++ /// <summary>Every position of the geometry, in order.</summary>+ public abstract IEnumerable<Coord> Coordinates();++ /// <summary>The same geometry with <paramref name="map"/> applied to every position.</summary>+ public abstract GeoGeometry Map(Func<Coord, Coord> map);++ /// <summary>True if any position has a height.</summary>+ public bool HasZ => Coordinates().Any(c => c.HasZ);++ /// <summary>The simple parts of the geometry: itself unless it is a collection or a Multi* geometry.</summary>+ public virtual IEnumerable<GeoGeometry> Parts() => [this];++ internal static List<Coord> Map(IEnumerable<Coord> line, Func<Coord, Coord> map) => [.. line.Select(map)];+}++internal sealed class GeoPoint(Coord position) : GeoGeometry+{+ public Coord Position { get; } = position;+ public override string TypeName => "Point";+ public override IEnumerable<Coord> Coordinates() => [Position];+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoPoint(map(Position));+}++internal sealed class GeoMultiPoint(IReadOnlyList<Coord> points) : GeoGeometry+{+ public IReadOnlyList<Coord> Points { get; } = points;+ public override string TypeName => "MultiPoint";+ public override IEnumerable<Coord> Coordinates() => Points;+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoMultiPoint(Map(Points, map));+ public override IEnumerable<GeoGeometry> Parts() => Points.Select(p => new GeoPoint(p));+}++internal sealed class GeoLineString(IReadOnlyList<Coord> points) : GeoGeometry+{+ public IReadOnlyList<Coord> Points { get; } = points;+ public override string TypeName => "LineString";+ public override IEnumerable<Coord> Coordinates() => Points;+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoLineString(Map(Points, map));+}++internal sealed class GeoMultiLineString(IReadOnlyList<IReadOnlyList<Coord>> lines) : GeoGeometry+{+ public IReadOnlyList<IReadOnlyList<Coord>> Lines { get; } = lines;+ public override string TypeName => "MultiLineString";+ public override IEnumerable<Coord> Coordinates() => Lines.SelectMany(l => l);+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoMultiLineString([.. Lines.Select(l => (IReadOnlyList<Coord>)Map(l, map))]);+ public override IEnumerable<GeoGeometry> Parts() => Lines.Select(l => new GeoLineString(l));+}++/// <summary>A polygon: the first ring is the outer boundary, the others are holes. Rings are closed (first = last).</summary>+internal sealed class GeoPolygon(IReadOnlyList<IReadOnlyList<Coord>> rings) : GeoGeometry+{+ public IReadOnlyList<IReadOnlyList<Coord>> Rings { get; } = rings;+ public override string TypeName => "Polygon";+ public override IEnumerable<Coord> Coordinates() => Rings.SelectMany(r => r);+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoPolygon([.. Rings.Select(r => (IReadOnlyList<Coord>)Map(r, map))]);+}++internal sealed class GeoMultiPolygon(IReadOnlyList<GeoPolygon> polygons) : GeoGeometry+{+ public IReadOnlyList<GeoPolygon> Polygons { get; } = polygons;+ public override string TypeName => "MultiPolygon";+ public override IEnumerable<Coord> Coordinates() => Polygons.SelectMany(p => p.Coordinates());+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoMultiPolygon([.. Polygons.Select(p => (GeoPolygon)p.Map(map))]);+ public override IEnumerable<GeoGeometry> Parts() => Polygons;+}++/// <summary>Geometries of any kinds in one feature (GeoJSON GeometryCollection, KML MultiGeometry).</summary>+internal sealed class GeoCollection(IReadOnlyList<GeoGeometry> geometries) : GeoGeometry+{+ public IReadOnlyList<GeoGeometry> Geometries { get; } = geometries;+ public override string TypeName => "GeometryCollection";+ public override IEnumerable<Coord> Coordinates() => Geometries.SelectMany(g => g.Coordinates());+ public override GeoGeometry Map(Func<Coord, Coord> map) => new GeoCollection([.. Geometries.Select(g => g.Map(map))]);+ public override IEnumerable<GeoGeometry> Parts() => Geometries.SelectMany(g => g.Parts());+}++/// <summary>+/// One feature: a geometry (null when the record has no location) and its attributes in file order. A value is a+/// <see cref="string"/>, <see cref="long"/>, <see cref="double"/>, <see cref="bool"/> or null.+/// </summary>+internal sealed class GeoFeature(GeoGeometry? geometry, List<KeyValuePair<string, object?>> properties)+{+ public GeoGeometry? Geometry { get; } = geometry;+ public List<KeyValuePair<string, object?>> Properties { get; } = properties;++ /// <summary>The value of the first attribute called <paramref name="names"/> (compared without case), or null.</summary>+ public object? Find(params string[] names)+ {+ foreach (var name in names)+ {+ foreach (var (key, value) in Properties)+ {+ if (key.Equals(name, StringComparison.OrdinalIgnoreCase))+ return value;+ }+ }+ return null;+ }++ /// <summary>Like <see cref="Find"/>, as text; null for a missing or empty value.</summary>+ public string? FindText(params string[] names) =>+ Find(names) is { } value && GeoText.ToText(value) is { Length: > 0 } text ? text : null;+}++/// <summary>Everything read from one file.</summary>+internal sealed class GeoDataset+{+ /// <summary>A name for the data, e.g. the file name; KML and GPX use it as the document name.</summary>+ public string Name { get; set; } = "";++ public List<GeoFeature> Features { get; } = [];++ /// <summary>The coordinate system the positions are in until <see cref="GeoConverter"/> converts them to WGS 84.</summary>+ public GeoCrs Crs { get; set; } = GeoCrs.Wgs84;++ /// <summary>True if the file said which system it uses (a .prj, a GeoJSON crs member); KML and GPX are always WGS 84.</summary>+ public bool CrsDeclared { get; set; }++ /// <summary>True if some rows of a CSV had no usable location and so have no geometry.</summary>+ public bool RowsWithoutLocation { get; set; }++ /// <summary>The attribute names of all features, in the order they first appear.</summary>+ public List<string> Columns()+ {+ var seen = new HashSet<string>(StringComparer.Ordinal);+ var columns = new List<string>();+ foreach (var feature in Features)+ {+ foreach (var (key, _) in feature.Properties)+ {+ if (seen.Add(key))+ columns.Add(key);+ }+ }+ return columns;+ }+}++/// <summary>Text forms of coordinates and attribute values shared by the writers.</summary>+internal static class GeoText+{+ /// <summary>A coordinate with up to ten decimals (about 0.01 mm of longitude / latitude), no exponent.</summary>+ public static string Degrees(double value) => Trim(value.ToString("0.##########", CultureInfo.InvariantCulture));++ /// <summary>A height with up to six decimals.</summary>+ public static string Height(double value) => Trim(value.ToString("0.######", CultureInfo.InvariantCulture));++ /// <summary>The shortest text that reads back as the same number, never with an exponent a spreadsheet would trip on.</summary>+ public static string Number(double value)+ {+ var text = value.ToString("R", CultureInfo.InvariantCulture);+ return Trim(text.Contains('E', StringComparison.Ordinal) ? value.ToString("0.####################", CultureInfo.InvariantCulture) : text);+ }++ /// <summary>An attribute value as text: numbers as <see cref="Number"/>, booleans as true / false, null as empty.</summary>+ public static string ToText(object? value) => value switch+ {+ null => "",+ string text => text,+ bool flag => flag ? "true" : "false",+ long whole => whole.ToString(CultureInfo.InvariantCulture),+ double real => Number(real),+ _ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? "",+ };++ /// <summary>Text from a file as the most specific attribute value: whole number, number, true / false, else the text.</summary>+ public static object? Typed(string text)+ {+ if (text.Length is 0 or > 24)+ return text.Length == 0 ? null : text;+ // "007" and "+1" are identifiers or phone numbers, not numbers.+ var digits = text[0] == '-' ? text[1..] : text;+ if (digits.Length == 0 || digits.Length > 1 && digits[0] == '0' && digits[1] != '.')+ return text;+ if (long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var whole))+ return whole;+ if ((char.IsAsciiDigit(digits[0]) || digits[0] == '.') && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var real) && double.IsFinite(real))+ return real;+ return text switch+ {+ "true" or "True" or "TRUE" => true,+ "false" or "False" or "FALSE" => false,+ _ => text,+ };+ }++ private static string Trim(string text) => text is "-0" ? "0" : text;+}++/// <summary>Ring helpers: closing, orientation and containment.</summary>+internal static class GeoRings+{+ /// <summary>+ /// The ring closed (first position repeated at the end), or null if it has fewer than three distinct positions+ /// and so encloses nothing.+ /// </summary>+ public static IReadOnlyList<Coord>? Close(IReadOnlyList<Coord> ring)+ {+ if (ring.Count < 3)+ return null;+ var closed = ring.Count > 0 && Same(ring[0], ring[^1]);+ var points = closed ? ring : [.. ring, ring[0]];+ return points.Count < 4 ? null : points;+ }++ /// <summary>Twice the area with a sign: positive when the ring runs counter-clockwise (X right, Y up).</summary>+ public static double SignedArea(IReadOnlyList<Coord> ring)+ {+ var sum = 0.0;+ for (var i = 0; i + 1 < ring.Count; i++)+ sum += ring[i].X * ring[i + 1].Y - ring[i + 1].X * ring[i].Y;+ return sum;+ }++ /// <summary>The ring in the direction asked for (reversed when it runs the other way).</summary>+ public static IReadOnlyList<Coord> Oriented(IReadOnlyList<Coord> ring, bool counterClockwise)+ {+ var area = SignedArea(ring);+ return area == 0 || area > 0 == counterClockwise ? ring : [.. ring.Reverse()];+ }++ /// <summary>True if <paramref name="point"/> lies inside <paramref name="ring"/> (even-odd rule).</summary>+ public static bool Contains(IReadOnlyList<Coord> ring, Coord point)+ {+ var inside = false;+ for (int i = 0, j = ring.Count - 1; i < ring.Count; j = i++)+ {+ if (ring[i].Y > point.Y != ring[j].Y > point.Y+ && point.X < (ring[j].X - ring[i].X) * (point.Y - ring[i].Y) / (ring[j].Y - ring[i].Y) + ring[i].X)+ inside = !inside;+ }+ return inside;+ }++ private static bool Same(Coord a, Coord b) => a.X == b.X && a.Y == b.Y;+}diff --git a/src/Filee.Engines/Geo/GpxFormat.cs b/src/Filee.Engines/Geo/GpxFormat.csnew file mode 100644index 00000000..d60d9289--- /dev/null+++ b/src/Filee.Engines/Geo/GpxFormat.cs@@ -0,0 +1,206 @@+// GPX 1.0 / 1.1 in and out. Reading turns every waypoint into a Point, every route into a LineString and every track+// 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.++using System.Globalization;+using System.Xml;+using System.Xml.Linq;++namespace Filee.Engines.Geo;++internal static class GpxFormat+{+ private static readonly XNamespace Gpx = "http://www.topografix.com/GPX/1/1";++ /// <summary>The attributes GPX can hold, in the order of its schema; "elevation" and "time" are written per point.</summary>+ private static readonly string[] Fields = ["name", "cmt", "desc", "src", "sym", "number", "type"];++ public static GeoDataset Read(string path, CancellationToken cancellationToken)+ {+ XDocument document;+ using (var stream = File.OpenRead(path))+ document = GeoXml.Load(stream);+ var root = document.Root;+ if (root is null || !root.Name.LocalName.Equals("gpx", StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException("The file is XML but not GPX: the root element is not <gpx>.");++ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path) };+ foreach (var element in root.Elements())+ {+ cancellationToken.ThrowIfCancellationRequested();+ switch (element.Name.LocalName)+ {+ case "wpt":+ {+ var properties = Properties(element, "waypoint");+ var point = Position(element);+ dataset.Features.Add(new GeoFeature(new GeoPoint(point), properties));+ break;+ }+ case "rte":+ {+ var line = element.Elements().Where(e => e.Name.LocalName == "rtept").Select(Position).ToList();+ dataset.Features.Add(new GeoFeature(line.Count < 2 ? null : new GeoLineString(line), Properties(element, "route")));+ break;+ }+ case "trk":+ {+ var segments = element.Elements().Where(e => e.Name.LocalName == "trkseg")+ .Select(s => s.Elements().Where(e => e.Name.LocalName == "trkpt").Select(Position).ToList())+ .Where(l => l.Count >= 2).Select(l => (IReadOnlyList<Coord>)l).ToList();+ GeoGeometry? geometry = segments.Count switch+ {+ 0 => null,+ 1 => new GeoLineString(segments[0]),+ _ => new GeoMultiLineString(segments),+ };+ dataset.Features.Add(new GeoFeature(geometry, Properties(element, "track")));+ break;+ }+ }+ }+ return dataset;+ }++ private static List<KeyValuePair<string, object?>> Properties(XElement element, string kind)+ {+ var properties = new List<KeyValuePair<string, object?>> { new("gpx_type", kind) };+ foreach (var name in new[] { "name", "cmt", "desc", "src", "sym", "number", "type", "time" })+ {+ var value = element.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value.Trim();+ if (!string.IsNullOrEmpty(value))+ properties.Add(new(name, name == "number" ? GeoText.Typed(value) : value));+ }+ return properties;+ }++ private static Coord Position(XElement point)+ {+ if (!GeoXml.TryNumber((string?)point.Attribute("lon") ?? "", out var lon) || !GeoXml.TryNumber((string?)point.Attribute("lat") ?? "", out var lat))+ throw new InvalidDataException($"A GPX <{point.Name.LocalName}> has no valid lat and lon.");+ if (lat is < -90 or > 90 || lon is < -180 or > 360)+ throw new InvalidDataException($"A GPX <{point.Name.LocalName}> is outside the Earth (lat {lat}, lon {lon}).");+ var elevation = point.Elements().FirstOrDefault(e => e.Name.LocalName == "ele")?.Value;+ return new Coord(lon, lat, elevation is not null && GeoXml.TryNumber(elevation.Trim(), out var z) ? z : double.NaN);+ }++ // ---- Writing ----++ /// <summary>Writes a GPX 1.1 file; returns true if some attributes or polygon areas could not be kept.</summary>+ public static bool Write(GeoDataset dataset, string path, CancellationToken cancellationToken)+ {+ var lossy = false;+ var settings = new XmlWriterSettings { Indent = true, IndentChars = " ", Encoding = new System.Text.UTF8Encoding(false), CheckCharacters = false };+ using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);+ using var writer = XmlWriter.Create(stream, settings);+ writer.WriteStartDocument();+ writer.WriteStartElement("gpx", Gpx.NamespaceName);+ writer.WriteAttributeString("version", "1.1");+ writer.WriteAttributeString("creator", "Filee");+ foreach (var feature in dataset.Features)+ {+ cancellationToken.ThrowIfCancellationRequested();+ if (feature.Geometry is not { } geometry)+ continue;+ var kept = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "gpx_type", "time" };+ foreach (var field in Fields)+ kept.Add(field);+ lossy |= feature.Properties.Any(p => !kept.Contains(p.Key) && GeoText.ToText(p.Value).Length > 0);+ 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 outlines = false;+ foreach (var part in geometry.Parts())+ {+ switch (part)+ {+ case GeoPoint point:+ WritePoint(writer, "wpt", point.Position, feature, withFields: true);+ break;+ case GeoLineString line:+ lines.Add(line.Points);+ break;+ case GeoPolygon polygon:+ lossy = outlines = true;+ lines.AddRange(polygon.Rings);+ break;+ }+ }+ if (lines.Count > 0)+ WriteLines(writer, lines, feature, asRoute && !outlines);+ }+ writer.WriteEndElement();+ writer.WriteEndDocument();+ return lossy;+ }++ private static void WriteLines(XmlWriter writer, IReadOnlyList<IReadOnlyList<Coord>> lines, GeoFeature feature, bool route)+ {+ if (route)+ {+ // A route is one line; extra parts become routes of their own.+ foreach (var line in lines)+ {+ writer.WriteStartElement("rte");+ WriteFields(writer, feature, trackFields: true);+ foreach (var point in line)+ WritePoint(writer, "rtept", point, feature, withFields: false);+ writer.WriteEndElement();+ }+ return;+ }+ writer.WriteStartElement("trk");+ WriteFields(writer, feature, trackFields: true);+ foreach (var line in lines)+ {+ writer.WriteStartElement("trkseg");+ foreach (var point in line)+ WritePoint(writer, "trkpt", point, feature, withFields: false);+ writer.WriteEndElement();+ }+ writer.WriteEndElement();+ }++ private static void WritePoint(XmlWriter writer, string element, Coord point, GeoFeature feature, bool withFields)+ {+ 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 (withFields)+ {+ if (Time(feature.FindText("time")) is { } time)+ writer.WriteElementString("time", time);+ WriteFields(writer, feature, trackFields: false);+ }+ writer.WriteEndElement();+ }++ /// <summary>The GPX fields in schema order; "number" belongs to routes and tracks only.</summary>+ private static void WriteFields(XmlWriter writer, GeoFeature feature, bool trackFields)+ {+ foreach (var field in Fields)+ {+ if (field == "number" && !trackFields)+ continue;+ if (field is "sym" && trackFields)+ continue;+ var text = feature.FindText(field);+ if (text is null)+ continue;+ if (field == "number" && !uint.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out _))+ continue;+ writer.WriteElementString(field, GeoXml.Clean(text));+ }+ }++ /// <summary>An xsd:dateTime from a time attribute in any common ISO form, or null if it isn't one.</summary>+ private static string? Time(string? text) =>+ text is not null && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time)+ ? time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)+ : null;+}diff --git a/src/Filee.Engines/Geo/KmlFormat.cs b/src/Filee.Engines/Geo/KmlFormat.csnew file mode 100644index 00000000..7d19002a--- /dev/null+++ b/src/Filee.Engines/Geo/KmlFormat.cs@@ -0,0 +1,357 @@+// KML and KMZ in and out. Reading takes every Placemark wherever it sits (Document, Folder, nested folders) with its+// 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.++using System.IO.Compression;+using System.Xml;+using System.Xml.Linq;++namespace Filee.Engines.Geo;++internal static class KmlFormat+{+ private static readonly XNamespace Kml = "http://www.opengis.net/kml/2.2";++ /// <summary>Reads a .kml or a .kmz file.</summary>+ public static GeoDataset Read(string path, bool zipped, CancellationToken cancellationToken)+ {+ XDocument document;+ if (zipped)+ {+ ZipArchive archive;+ try+ {+ archive = ZipFile.OpenRead(path);+ }+ catch (InvalidDataException ex)+ {+ throw new InvalidDataException($"The file is not a valid KMZ archive ({ex.Message})", ex);+ }+ using (archive)+ {+ var entry = archive.Entries.FirstOrDefault(e => e.FullName.Equals("doc.kml", StringComparison.OrdinalIgnoreCase))+ ?? archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".kml", StringComparison.OrdinalIgnoreCase))+ ?? throw new InvalidDataException("The KMZ has no .kml file inside.");+ using var stream = entry.Open();+ document = GeoXml.Load(stream);+ }+ }+ else+ {+ using var stream = File.OpenRead(path);+ document = GeoXml.Load(stream);+ }++ var root = document.Root;+ if (root is null || !root.Name.LocalName.Equals("kml", StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException("The file is XML but not KML: the root element is not <kml>.");++ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path) };+ foreach (var placemark in root.Descendants().Where(e => e.Name.LocalName == "Placemark"))+ {+ cancellationToken.ThrowIfCancellationRequested();+ dataset.Features.Add(ReadPlacemark(placemark));+ }+ return dataset;+ }++ private static GeoFeature ReadPlacemark(XElement placemark)+ {+ var properties = new List<KeyValuePair<string, object?>>();+ if (Text(placemark, "name") is { Length: > 0 } name)+ properties.Add(new("name", name));+ if (Text(placemark, "description") is { Length: > 0 } description)+ properties.Add(new("description", description));+ var names = new HashSet<string>(properties.Select(p => p.Key), StringComparer.OrdinalIgnoreCase);+ foreach (var data in placemark.Descendants().Where(e => e.Name.LocalName is "Data" or "SimpleData"))+ {+ var key = (string?)data.Attribute("name");+ if (string.IsNullOrEmpty(key))+ continue;+ var value = data.Name.LocalName == "Data" ? Text(data, "value") ?? data.Value : data.Value;+ if (names.Add(key))+ properties.Add(new(key, GeoText.Typed(value.Trim())));+ }+ var geometries = placemark.Elements().Select(ReadGeometry).OfType<GeoGeometry>().ToList();+ GeoGeometry? geometry = geometries.Count switch+ {+ 0 => null,+ 1 => geometries[0],+ _ => new GeoCollection(geometries),+ };+ return new GeoFeature(geometry, properties);+ }++ private static GeoGeometry? ReadGeometry(XElement element)+ {+ switch (element.Name.LocalName)+ {+ case "Point":+ {+ var points = Coordinates(element);+ return points.Count == 0 ? null : new GeoPoint(points[0]);+ }+ case "LineString" or "LinearRing":+ {+ var line = Coordinates(element);+ return line.Count < 2 ? null : new GeoLineString(line);+ }+ case "Track" or "MultiTrack":+ {+ // gx:Track lists <gx:coord>lon lat alt</gx:coord>; a MultiTrack holds several.+ var lines = element.Name.LocalName == "Track" ? [element] : element.Elements().Where(e => e.Name.LocalName == "Track").ToList();+ var parsed = lines.Select(TrackCoordinates).Where(l => l.Count >= 2).Select(l => (IReadOnlyList<Coord>)l).ToList();+ return parsed.Count switch+ {+ 0 => null,+ 1 => new GeoLineString(parsed[0]),+ _ => new GeoMultiLineString(parsed),+ };+ }+ case "Polygon":+ {+ var rings = new List<IReadOnlyList<Coord>>();+ foreach (var boundary in element.Elements().Where(e => e.Name.LocalName is "outerBoundaryIs" or "innerBoundaryIs")+ .OrderBy(e => e.Name.LocalName == "outerBoundaryIs" ? 0 : 1))+ {+ var ring = boundary.Descendants().FirstOrDefault(e => e.Name.LocalName == "LinearRing");+ if (ring is not null && GeoRings.Close(Coordinates(ring)) is { } closed)+ rings.Add(closed);+ }+ return rings.Count == 0 ? null : new GeoPolygon(rings);+ }+ case "MultiGeometry":+ {+ var parts = element.Elements().Select(ReadGeometry).OfType<GeoGeometry>().ToList();+ return parts.Count switch+ {+ 0 => null,+ 1 => parts[0],+ _ when parts.All(p => p is GeoPoint) => new GeoMultiPoint([.. parts.Cast<GeoPoint>().Select(p => p.Position)]),+ _ when parts.All(p => p is GeoLineString) => new GeoMultiLineString([.. parts.Cast<GeoLineString>().Select(p => p.Points)]),+ _ when parts.All(p => p is GeoPolygon) => new GeoMultiPolygon([.. parts.Cast<GeoPolygon>()]),+ _ => new GeoCollection(parts),+ };+ }+ default:+ return null;+ }+ }++ /// <summary>The positions of the <coordinates> child: "lon,lat[,alt]" tuples separated by white space.</summary>+ private static List<Coord> Coordinates(XElement element)+ {+ var coordinates = element.Elements().FirstOrDefault(e => e.Name.LocalName == "coordinates");+ var line = new List<Coord>();+ if (coordinates is null)+ return line;+ // Some writers put spaces after the commas ("1, 2, 3"): glue those back before splitting on white space.+ var text = System.Text.RegularExpressions.Regex.Replace(coordinates.Value, @"\s*,\s*", ",");+ foreach (var tuple in text.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries))+ {+ var parts = tuple.Split(',');+ if (parts.Length < 2 || !GeoXml.TryNumber(parts[0], out var x) || !GeoXml.TryNumber(parts[1], out var y))+ throw new InvalidDataException($"A KML position is not \"longitude,latitude\": \"{Shorten(tuple)}\".");+ var z = parts.Length > 2 && GeoXml.TryNumber(parts[2], out var height) ? height : double.NaN;+ line.Add(new Coord(x, y, z));+ }+ return line;+ }++ private static List<Coord> TrackCoordinates(XElement track)+ {+ var line = new List<Coord>();+ foreach (var coord in track.Elements().Where(e => e.Name.LocalName == "coord"))+ {+ var parts = coord.Value.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);+ if (parts.Length < 2 || !GeoXml.TryNumber(parts[0], out var x) || !GeoXml.TryNumber(parts[1], out var y))+ throw new InvalidDataException($"A KML track position is not \"longitude latitude\": \"{Shorten(coord.Value)}\".");+ line.Add(new Coord(x, y, parts.Length > 2 && GeoXml.TryNumber(parts[2], out var height) ? height : double.NaN));+ }+ return line;+ }++ private static string? Text(XElement parent, string name) =>+ parent.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value.Trim();++ private static string Shorten(string text) => text.Length <= 40 ? text : text[..40] + "…";++ // ---- Writing ----++ /// <summary>Writes a .kml, or a .kmz (a ZIP holding doc.kml) when <paramref name="zipped"/>.</summary>+ public static void Write(GeoDataset dataset, string path, bool zipped, CancellationToken cancellationToken)+ {+ if (!zipped)+ {+ using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);+ WriteDocument(dataset, stream, cancellationToken);+ return;+ }+ using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);+ using var archive = new ZipArchive(file, ZipArchiveMode.Create);+ var entry = archive.CreateEntry("doc.kml", CompressionLevel.Optimal);+ using var entryStream = entry.Open();+ WriteDocument(dataset, entryStream, cancellationToken);+ }++ private static void WriteDocument(GeoDataset dataset, Stream stream, CancellationToken cancellationToken)+ {+ var settings = new XmlWriterSettings+ {+ Indent = true,+ IndentChars = " ",+ Encoding = new System.Text.UTF8Encoding(false),+ CheckCharacters = false,+ };+ using var writer = XmlWriter.Create(stream, settings);+ writer.WriteStartDocument();+ writer.WriteStartElement("kml", Kml.NamespaceName);+ writer.WriteStartElement("Document");+ writer.WriteElementString("name", GeoXml.Clean(dataset.Name));+ foreach (var feature in dataset.Features)+ {+ cancellationToken.ThrowIfCancellationRequested();+ WritePlacemark(writer, feature);+ }+ writer.WriteEndElement();+ writer.WriteEndElement();+ writer.WriteEndDocument();+ }++ private static void WritePlacemark(XmlWriter writer, GeoFeature feature)+ {+ writer.WriteStartElement("Placemark");+ 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)+ {+ writer.WriteStartElement("ExtendedData");+ var used = new HashSet<string>(StringComparer.Ordinal);+ foreach (var (key, value) in extra)+ {+ if (!used.Add(key))+ continue;+ writer.WriteStartElement("Data");+ writer.WriteAttributeString("name", GeoXml.Clean(key));+ writer.WriteElementString("value", GeoXml.Clean(GeoText.ToText(value)));+ writer.WriteEndElement();+ }+ writer.WriteEndElement();+ }+ if (feature.Geometry is { } geometry)+ WriteGeometry(writer, geometry);+ writer.WriteEndElement();+ }++ /// <summary>True for the attributes already written as the Placemark's name and description.</summary>+ private static bool IsNameOrDescription(string key, string? name, string? description, GeoFeature feature)+ {+ if (name is not null && key.Equals(FirstKey(feature, "name", "title", "label"), StringComparison.OrdinalIgnoreCase))+ return true;+ return description is not null && key.Equals(FirstKey(feature, "description", "desc", "comment"), StringComparison.OrdinalIgnoreCase);+ }++ private static string? FirstKey(GeoFeature feature, params string[] names)+ {+ foreach (var wanted in names)+ {+ var found = feature.Properties.FirstOrDefault(p => p.Key.Equals(wanted, StringComparison.OrdinalIgnoreCase) && GeoText.ToText(p.Value).Length > 0);+ if (found.Key is not null)+ return found.Key;+ }+ return null;+ }++ private static void WriteGeometry(XmlWriter writer, GeoGeometry geometry)+ {+ switch (geometry)+ {+ case GeoPoint point:+ writer.WriteStartElement("Point");+ WriteCoordinates(writer, [point.Position]);+ writer.WriteEndElement();+ break;+ case GeoLineString line:+ writer.WriteStartElement("LineString");+ WriteCoordinates(writer, line.Points);+ writer.WriteEndElement();+ break;+ case GeoPolygon polygon:+ WritePolygon(writer, polygon);+ break;+ default:+ // Several parts of one feature: MultiGeometry holds the simple geometries.+ writer.WriteStartElement("MultiGeometry");+ foreach (var part in geometry.Parts())+ WriteGeometry(writer, part);+ writer.WriteEndElement();+ break;+ }+ }++ private static void WritePolygon(XmlWriter writer, GeoPolygon polygon)+ {+ 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));+ writer.WriteEndElement();+ writer.WriteEndElement();+ }+ writer.WriteEndElement();+ }++ private static void WriteCoordinates(XmlWriter writer, IReadOnlyList<Coord> points)+ {+ 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)}")));+ writer.WriteEndElement();+ }+}++/// <summary>XML helpers shared by the KML and GPX formats.</summary>+internal static class GeoXml+{+ /// <summary>Parses XML without DTDs or external entities, so a hostile file can't read files or expand into gigabytes.</summary>+ public static XDocument Load(Stream stream)+ {+ var settings = new XmlReaderSettings+ {+ DtdProcessing = DtdProcessing.Prohibit,+ XmlResolver = null,+ MaxCharactersFromEntities = 0,+ CheckCharacters = false,+ // Also the limit for a KMZ: the .kml inside is unpacked while it is read, so a ZIP bomb stops here.+ MaxCharactersInDocument = 1L << 29,+ };+ try+ {+ using var reader = XmlReader.Create(stream, settings);+ return XDocument.Load(reader, LoadOptions.None);+ }+ catch (XmlException ex)+ {+ throw new InvalidDataException($"The file is not valid XML ({ex.Message})", ex);+ }+ }++ public static bool TryNumber(string text, out double value) =>+ double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value) && double.IsFinite(value);++ /// <summary>Text without the control characters XML 1.0 can't hold (they would make the file unreadable).</summary>+ public static string Clean(string text) =>+ text.Any(c => c < ' ' && c is not ('\t' or '\n' or '\r') || c is '' or '')+ ? new string([.. text.Where(c => !(c < ' ' && c is not ('\t' or '\n' or '\r') || c is '' or ''))])+ : text;+}diff --git a/src/Filee.Engines/Geo/ShapefileFormat.cs b/src/Filee.Engines/Geo/ShapefileFormat.csnew file mode 100644index 00000000..72ec6ca2--- /dev/null+++ b/src/Filee.Engines/Geo/ShapefileFormat.cs@@ -0,0 +1,503 @@+// ESRI Shapefile in and out, in managed code. A shapefile is several files with the same name: .shp (shapes), .shx+// (index), .dbf (attributes), .prj (coordinate system) and .cpg (text encoding of the .dbf). Reading takes the .shp and+// finds the others next to it (the .shx is not needed). Point, MultiPoint, PolyLine and Polygon shapes are read with their+// Z, MultiPatch is refused. Polygon rings are sorted into polygons and holes by their direction (outer rings clockwise),+// with holes assigned to the ring that contains them. Writing makes one shapefile per kind of geometry (a shapefile holds+// only one), in WGS 84 with a .prj, polygons clockwise as the format requires.++using System.Buffers.Binary;+using System.Text;+using Filee.Core.Conversion;++namespace Filee.Engines.Geo;++/// <summary>The kinds of shape a shapefile can hold; a file holds one.</summary>+internal enum ShapeKind+{+ Point,+ Line,+ Polygon,+}++/// <summary>The records that go into one shapefile.</summary>+internal sealed class ShapefileGroup(ShapeKind kind, List<GeoFeature> records)+{+ public ShapeKind Kind { get; } = kind;++ /// <summary>One record each; a record's geometry is null for a feature without location.</summary>+ public List<GeoFeature> Records { get; } = records;+}++internal static class ShapefileFormat+{+ /// <summary>ESRI's definition of WGS 84, written to the .prj of every shapefile Filee makes.</summary>+ internal const string Wgs84Prj =+ "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]";++ private const int HeaderLength = 100;+ private const double NoData = -1e39;++ // ---- Reading ----++ /// <summary>Finds a file next to <paramref name="shpPath"/> with the same name and another extension (any letter case).</summary>+ internal static string? Sidecar(string shpPath, string extension)+ {+ var full = Path.GetFullPath(shpPath);+ var directory = Path.GetDirectoryName(full)!;+ var name = Path.GetFileNameWithoutExtension(full);+ var exact = Path.Combine(directory, name + "." + extension);+ if (File.Exists(exact))+ return exact;+ // On a case-sensitive file system the sidecar may be "NAME.DBF" or "Name.Dbf".+ foreach (var candidate in Directory.EnumerateFiles(directory, name + ".*"))+ {+ if (Path.GetFileNameWithoutExtension(candidate).Equals(name, StringComparison.OrdinalIgnoreCase)+ && Path.GetExtension(candidate).TrimStart('.').Equals(extension, StringComparison.OrdinalIgnoreCase))+ return candidate;+ }+ return null;+ }++ /// <summary>Reads the shapes of <paramref name="path"/> and their attributes and coordinate system.</summary>+ public static GeoDataset Read(string path, CancellationToken cancellationToken)+ {+ var bytes = File.ReadAllBytes(path);+ if (bytes.Length < HeaderLength || BinaryPrimitives.ReadInt32BigEndian(bytes) != 9994)+ throw new InvalidDataException("The .shp file does not start with a shapefile header.");+ var headerType = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(32));+ if (headerType == 31)+ throw new ConversionRefusedException("error.geo_unsupported_shape", "MultiPatch");+ if (headerType is not (0 or 1 or 3 or 5 or 8 or 11 or 13 or 15 or 18 or 21 or 23 or 25 or 28))+ throw new InvalidDataException($"The .shp has an unknown shape type ({headerType}).");++ var declared = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(24)) * 2L;+ // Some writers leave the length wrong; what is really in the file decides.+ var end = declared is >= HeaderLength && declared <= bytes.Length ? (int)declared : bytes.Length;++ var dataset = new GeoDataset { Name = Path.GetFileNameWithoutExtension(path) };+ var geometries = new List<GeoGeometry?>();+ var position = HeaderLength;+ while (position + 8 <= end)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var contentLength = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position + 4)) * 2L;+ position += 8;+ if (contentLength < 4 || position + contentLength > end)+ throw new InvalidDataException($"The .shp is cut off or damaged at shape {geometries.Count + 1}.");+ geometries.Add(ReadShape(bytes.AsSpan(position, (int)contentLength), geometries.Count + 1));+ position += (int)contentLength;+ }++ DbfTable? table = null;+ if (Sidecar(path, "dbf") is { } dbfPath)+ {+ var cpgPath = Sidecar(path, "cpg");+ table = DbfFormat.Read(dbfPath, cpgPath is null ? null : File.ReadAllText(cpgPath), cancellationToken);+ if (table.Rows.Count < geometries.Count)+ throw new InvalidDataException($"The .dbf has {table.Rows.Count} rows but the .shp has {geometries.Count} shapes.");+ }+ for (var i = 0; i < geometries.Count; i++)+ {+ var properties = new List<KeyValuePair<string, object?>>();+ if (table is not null)+ {+ if (table.Rows[i] is not { } row)+ continue; // marked as deleted in the .dbf+ for (var f = 0; f < table.Fields.Count; f++)+ properties.Add(new(table.Fields[f].Name, row[f]));+ }+ dataset.Features.Add(new GeoFeature(geometries[i], properties));+ }++ if (Sidecar(path, "prj") is { } prjPath)+ {+ dataset.Crs = GeoCrs.FromWkt(File.ReadAllText(prjPath));+ dataset.CrsDeclared = true;+ }+ return dataset;+ }++ private static GeoGeometry? ReadShape(ReadOnlySpan<byte> c, int number)+ {+ var type = BinaryPrimitives.ReadInt32LittleEndian(c);+ switch (type)+ {+ case 0:+ return null;+ case 1 or 11 or 21:+ {+ Need(c, 20, number);+ var x = Double(c, 4);+ var y = Double(c, 12);+ if (!double.IsFinite(x) || !double.IsFinite(y))+ return null; // an empty point is written as NaN+ var z = type == 11 && c.Length >= 28 ? Height(Double(c, 20)) : double.NaN;+ return new GeoPoint(new Coord(x, y, z));+ }+ case 8 or 18 or 28:+ {+ Need(c, 40, number);+ var count = BinaryPrimitives.ReadInt32LittleEndian(c[36..]);+ if (count < 0 || 40L + 16L * count > c.Length)+ throw new InvalidDataException($"Shape {number}: the point count does not fit the record.");+ var zAt = 40 + 16 * count + 16;+ var hasZ = type == 18 && zAt + 8L * count <= c.Length;+ var points = new List<Coord>(count);+ for (var i = 0; i < count; i++)+ points.Add(new Coord(Double(c, 40 + 16 * i), Double(c, 48 + 16 * i), hasZ ? Height(Double(c, zAt + 8 * i)) : double.NaN));+ points.RemoveAll(p => !p.IsFinite);+ return points.Count == 0 ? null : points.Count == 1 ? new GeoPoint(points[0]) : new GeoMultiPoint(points);+ }+ case 3 or 13 or 23 or 5 or 15 or 25:+ return ReadParts(c, type, number);+ default:+ if (type == 31)+ throw new ConversionRefusedException("error.geo_unsupported_shape", "MultiPatch");+ throw new InvalidDataException($"Shape {number} has an unknown shape type ({type}).");+ }+ }++ private static GeoGeometry? ReadParts(ReadOnlySpan<byte> c, int type, int number)+ {+ Need(c, 44, number);+ var parts = BinaryPrimitives.ReadInt32LittleEndian(c[36..]);+ var count = BinaryPrimitives.ReadInt32LittleEndian(c[40..]);+ var pointsAt = 44L + 4L * parts;+ if (parts < 0 || count < 0 || pointsAt + 16L * count > c.Length)+ throw new InvalidDataException($"Shape {number}: the part and point counts do not fit the record.");+ var zAt = (int)pointsAt + 16 * count + 16;+ var hasZ = type is 13 or 15 && zAt + 8L * count <= c.Length;++ var starts = new int[parts + 1];+ for (var p = 0; p < parts; p++)+ {+ starts[p] = BinaryPrimitives.ReadInt32LittleEndian(c[(44 + 4 * p)..]);+ if (starts[p] < 0 || starts[p] > count || p > 0 && starts[p] < starts[p - 1])+ throw new InvalidDataException($"Shape {number}: the part {p + 1} starts outside the points.");+ }+ starts[parts] = count;++ var lines = new List<List<Coord>>(parts);+ for (var p = 0; p < parts; p++)+ {+ var line = new List<Coord>(starts[p + 1] - starts[p]);+ for (var i = starts[p]; i < starts[p + 1]; i++)+ {+ var at = (int)pointsAt + 16 * i;+ var point = new Coord(Double(c, at), Double(c, at + 8), hasZ ? Height(Double(c, zAt + 8 * i)) : double.NaN);+ if (point.IsFinite)+ line.Add(point);+ }+ lines.Add(line);+ }++ if (type is 3 or 13 or 23)+ {+ var kept = lines.Where(l => l.Count >= 2).Select(l => (IReadOnlyList<Coord>)l).ToList();+ return kept.Count switch+ {+ 0 => null,+ 1 => new GeoLineString(kept[0]),+ _ => new GeoMultiLineString(kept),+ };+ }+ return Polygons(lines);+ }++ /// <summary>Sorts rings into polygons with holes: outer rings run clockwise, holes counter-clockwise.</summary>+ private static GeoGeometry? Polygons(List<List<Coord>> lines)+ {+ var rings = lines.Select(l => GeoRings.Close(l)).OfType<IReadOnlyList<Coord>>().Where(r => GeoRings.SignedArea(r) != 0).ToList();+ if (rings.Count == 0)+ return null;+ var outers = rings.Where(r => GeoRings.SignedArea(r) < 0).ToList();+ var holes = rings.Where(r => GeoRings.SignedArea(r) > 0).ToList();+ if (outers.Count == 0)+ {+ // Every ring runs counter-clockwise: the writer used the other convention, so they are all outer rings.+ outers = holes;+ holes = [];+ }+ var assigned = outers.Select(o => new List<IReadOnlyList<Coord>> { o }).ToList();+ var bounds = outers.Select(Bounds).ToList();+ foreach (var hole in holes)+ {+ var probe = hole[0];+ var best = -1;+ var bestArea = double.MaxValue;+ for (var i = 0; i < outers.Count; i++)+ {+ if (probe.X < bounds[i].MinX || probe.X > bounds[i].MaxX || probe.Y < bounds[i].MinY || probe.Y > bounds[i].MaxY)+ continue;+ var area = Math.Abs(GeoRings.SignedArea(outers[i]));+ if (area < bestArea && GeoRings.Contains(outers[i], probe))+ {+ best = i;+ bestArea = area;+ }+ }+ if (best >= 0)+ assigned[best].Add(hole);+ else+ assigned.Add([hole]); // a hole outside every outer ring is a ring of its own+ }+ var polygons = assigned.Select(rs => new GeoPolygon(rs)).ToList();+ return polygons.Count == 1 ? polygons[0] : new GeoMultiPolygon(polygons);+ }++ private static (double MinX, double MinY, double MaxX, double MaxY) Bounds(IReadOnlyList<Coord> ring) =>+ (ring.Min(p => p.X), ring.Min(p => p.Y), ring.Max(p => p.X), ring.Max(p => p.Y));++ private static double Double(ReadOnlySpan<byte> c, int at) => BinaryPrimitives.ReadDoubleLittleEndian(c[at..]);++ /// <summary>Heights below -1e38 mean "no data".</summary>+ private static double Height(double z) => double.IsFinite(z) && z > -1e38 ? z : double.NaN;++ private static void Need(ReadOnlySpan<byte> c, int length, int number)+ {+ if (c.Length < length)+ throw new InvalidDataException($"Shape {number} is shorter than its type needs.");+ }++ // ---- Writing ----++ /// <summary>+ /// Sorts the features into the shapefiles to write: one per kind of geometry present. Collections are split into+ /// their members (each a record with the same attributes); features without geometry go to the first file.+ /// </summary>+ public static List<ShapefileGroup> Plan(GeoDataset dataset)+ {+ ShapeKind[] kinds = [ShapeKind.Point, ShapeKind.Line, ShapeKind.Polygon];+ var buckets = kinds.ToDictionary(kind => kind, _ => new List<GeoFeature>());+ var withoutGeometry = new List<GeoFeature>();+ foreach (var feature in dataset.Features)+ {+ if (feature.Geometry is null)+ {+ withoutGeometry.Add(feature);+ continue;+ }+ foreach (var part in Flatten(feature.Geometry))+ buckets[KindOf(part)].Add(new GeoFeature(part, feature.Properties));+ }+ var groups = kinds.Where(kind => buckets[kind].Count > 0).Select(kind => new ShapefileGroup(kind, buckets[kind])).ToList();+ if (groups.Count == 0)+ groups.Add(new ShapefileGroup(ShapeKind.Point, []));+ groups[0].Records.AddRange(withoutGeometry);+ return groups;+ }++ private static IEnumerable<GeoGeometry> Flatten(GeoGeometry geometry) =>+ geometry is GeoCollection collection ? collection.Geometries.SelectMany(Flatten) : [geometry];++ private static ShapeKind KindOf(GeoGeometry geometry) => geometry switch+ {+ GeoPoint or GeoMultiPoint => ShapeKind.Point,+ GeoLineString or GeoMultiLineString => ShapeKind.Line,+ _ => ShapeKind.Polygon,+ };++ /// <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)+ {+ var shapes = group.Records;+ var hasZ = 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+ {+ ShapeKind.Point => multiPoint ? (hasZ ? 18 : 8) : (hasZ ? 11 : 1),+ ShapeKind.Line => hasZ ? 13 : 3,+ _ => hasZ ? 15 : 5,+ };++ var bounds = new Extent();+ long length = HeaderLength;+ var index = new List<(int Offset, int Length)>(shapes.Count);+ using (var shp = new FileStream(shpPath, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))+ {+ shp.Write(new byte[HeaderLength]);+ var recordNumber = 0;+ Span<byte> head = stackalloc byte[8];+ foreach (var record in shapes)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var content = Encode(record.Geometry, shapeType, bounds);+ length += 8 + content.Length;+ if (length > int.MaxValue)+ throw new ConversionRefusedException("error.geo_too_large");+ BinaryPrimitives.WriteInt32BigEndian(head, ++recordNumber);+ BinaryPrimitives.WriteInt32BigEndian(head[4..], content.Length / 2);+ shp.Write(head);+ shp.Write(content);+ index.Add(((int)(length - 8 - content.Length) / 2, content.Length / 2));+ }+ shp.Position = 0;+ shp.Write(Header(shapeType, (int)(length / 2), bounds));+ }++ using (var shx = new FileStream(Path.ChangeExtension(shpPath, "shx"), FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))+ {+ shx.Write(Header(shapeType, (HeaderLength + 8 * index.Count) / 2, bounds));+ Span<byte> entry = stackalloc byte[8];+ foreach (var (offset, words) in index)+ {+ BinaryPrimitives.WriteInt32BigEndian(entry, offset);+ BinaryPrimitives.WriteInt32BigEndian(entry[4..], words);+ shx.Write(entry);+ }+ }++ var losses = DbfFormat.Write(Path.ChangeExtension(shpPath, "dbf"), shapes, cancellationToken);+ File.WriteAllText(Path.ChangeExtension(shpPath, "prj"), Wgs84Prj, new UTF8Encoding(false));+ File.WriteAllText(Path.ChangeExtension(shpPath, "cpg"), "UTF-8", new UTF8Encoding(false));+ return losses;+ }++ private sealed class Extent+ {+ public double MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue;+ public double MinZ = double.MaxValue, MaxZ = double.MinValue;++ public bool IsEmpty => MinX > MaxX;++ public void Add(Coord c)+ {+ MinX = Math.Min(MinX, c.X);+ MaxX = Math.Max(MaxX, c.X);+ MinY = Math.Min(MinY, c.Y);+ MaxY = Math.Max(MaxY, c.Y);+ var z = c.HasZ ? c.Z : 0;+ MinZ = Math.Min(MinZ, z);+ MaxZ = Math.Max(MaxZ, z);+ }+ }++ private static byte[] Header(int shapeType, int lengthInWords, Extent bounds)+ {+ var header = new byte[HeaderLength];+ BinaryPrimitives.WriteInt32BigEndian(header, 9994);+ BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(24), lengthInWords);+ BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(28), 1000);+ BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(32), shapeType);+ double[] values = bounds.IsEmpty+ ? [0, 0, 0, 0, 0, 0, 0, 0]+ : [bounds.MinX, bounds.MinY, bounds.MaxX, bounds.MaxY, bounds.MinZ, bounds.MaxZ, 0, 0];+ for (var i = 0; i < 8; i++)+ BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(36 + 8 * i), values[i]);+ return header;+ }++ /// <summary>The content of one record: its shape type, then the shape.</summary>+ private static byte[] Encode(GeoGeometry? geometry, int fileType, Extent bounds)+ {+ var z = fileType is 11 or 13 or 15 or 18;+ if (geometry is null)+ return BitConverter.GetBytes(0);++ switch (geometry)+ {+ case GeoPoint { Position: var p }:+ return EncodePoints(fileType, [p], bounds, z);+ case GeoMultiPoint { Points: var points }:+ return EncodePoints(fileType, points, bounds, z);+ case GeoLineString line:+ return EncodeParts(fileType, [line.Points], bounds, z);+ case GeoMultiLineString lines:+ return EncodeParts(fileType, lines.Lines, bounds, z);+ case GeoPolygon polygon:+ return EncodeParts(fileType, Rings([polygon]), bounds, z);+ case GeoMultiPolygon polygons:+ return EncodeParts(fileType, Rings(polygons.Polygons), bounds, z);+ default:+ throw new InvalidDataException($"A {geometry.TypeName} can't be written to a shapefile record.");+ }+ }++ /// <summary>Outer rings clockwise, holes counter-clockwise.</summary>+ private static List<IReadOnlyList<Coord>> Rings(IReadOnlyList<GeoPolygon> polygons)+ {+ var rings = new List<IReadOnlyList<Coord>>();+ foreach (var polygon in polygons)+ {+ for (var i = 0; i < polygon.Rings.Count; i++)+ rings.Add(GeoRings.Oriented(polygon.Rings[i], counterClockwise: i != 0));+ }+ return rings;+ }++ private static byte[] EncodePoints(int fileType, IReadOnlyList<Coord> points, Extent bounds, bool z)+ {+ foreach (var point in points)+ bounds.Add(point);+ if (fileType is 1 or 11)+ {+ var size = fileType == 1 ? 20 : 36;+ var content = new byte[size];+ BinaryPrimitives.WriteInt32LittleEndian(content, fileType);+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(4), points[0].X);+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(12), points[0].Y);+ if (fileType == 11)+ {+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(20), points[0].HasZ ? points[0].Z : 0);+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(28), NoData);+ }+ return content;+ }+ var multi = new byte[40 + 16 * points.Count + (z ? 16 + 8 * points.Count : 0)];+ BinaryPrimitives.WriteInt32LittleEndian(multi, fileType);+ WriteBox(multi, points);+ BinaryPrimitives.WriteInt32LittleEndian(multi.AsSpan(36), points.Count);+ for (var i = 0; i < points.Count; i++)+ {+ BinaryPrimitives.WriteDoubleLittleEndian(multi.AsSpan(40 + 16 * i), points[i].X);+ BinaryPrimitives.WriteDoubleLittleEndian(multi.AsSpan(48 + 16 * i), points[i].Y);+ }+ if (z)+ WriteHeights(multi, 40 + 16 * points.Count, points);+ return multi;+ }++ private static byte[] EncodeParts(int fileType, IReadOnlyList<IReadOnlyList<Coord>> parts, Extent bounds, bool z)+ {+ var all = parts.SelectMany(p => p).ToList();+ foreach (var point in all)+ bounds.Add(point);+ var content = new byte[44 + 4 * parts.Count + 16 * all.Count + (z ? 16 + 8 * all.Count : 0)];+ BinaryPrimitives.WriteInt32LittleEndian(content, fileType);+ WriteBox(content, all);+ BinaryPrimitives.WriteInt32LittleEndian(content.AsSpan(36), parts.Count);+ BinaryPrimitives.WriteInt32LittleEndian(content.AsSpan(40), all.Count);+ var start = 0;+ for (var p = 0; p < parts.Count; p++)+ {+ BinaryPrimitives.WriteInt32LittleEndian(content.AsSpan(44 + 4 * p), start);+ start += parts[p].Count;+ }+ var pointsAt = 44 + 4 * parts.Count;+ for (var i = 0; i < all.Count; i++)+ {+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(pointsAt + 16 * i), all[i].X);+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(pointsAt + 16 * i + 8), all[i].Y);+ }+ if (z)+ WriteHeights(content, pointsAt + 16 * all.Count, all);+ return content;+ }++ private static void WriteBox(byte[] content, IReadOnlyList<Coord> points)+ {+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(4), points.Min(p => p.X));+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(12), points.Min(p => p.Y));+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(20), points.Max(p => p.X));+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(28), points.Max(p => p.Y));+ }++ private static void WriteHeights(byte[] content, int at, IReadOnlyList<Coord> points)+ {+ var heights = points.Select(p => p.HasZ ? p.Z : 0).ToList();+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(at), heights.Min());+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(at + 8), heights.Max());+ for (var i = 0; i < heights.Count; i++)+ BinaryPrimitives.WriteDoubleLittleEndian(content.AsSpan(at + 16 + 8 * i), heights[i]);+ }+}diff --git a/src/Filee.Engines/Geo/WktFormat.cs b/src/Filee.Engines/Geo/WktFormat.csnew file mode 100644index 00000000..13ca89b2--- /dev/null+++ b/src/Filee.Engines/Geo/WktFormat.cs@@ -0,0 +1,367 @@+// Well-known text (WKT / EWKT) for geometries: POINT, LINESTRING, POLYGON, their MULTI* forms and GEOMETRYCOLLECTION,+// with Z (or M, which is dropped) and EMPTY. Used for the geometry column of a CSV. An "SRID=4326;" prefix is accepted+// and ignored (the CSV reader treats coordinates as longitude / latitude).++using System.Globalization;+using System.Text;++namespace Filee.Engines.Geo;++internal static class WktFormat+{+ private const int MaxDepth = 16;++ /// <summary>Parses WKT; <see cref="FormatException"/> says what is wrong. An empty geometry gives null.</summary>+ public static GeoGeometry? Parse(string text)+ {+ var parser = new Parser(text);+ var geometry = parser.ReadGeometry(0);+ parser.ExpectEnd();+ return geometry;+ }++ // ---- Writing ----++ public static string Write(GeoGeometry geometry)+ {+ var builder = new StringBuilder();+ Write(builder, geometry);+ return builder.ToString();+ }++ private static void Write(StringBuilder builder, GeoGeometry geometry)+ {+ var z = geometry.HasZ;+ builder.Append(geometry.TypeName.ToUpperInvariant()).Append(z ? " Z " : " ");+ switch (geometry)+ {+ case GeoPoint point:+ builder.Append('(');+ Position(builder, point.Position, z);+ builder.Append(')');+ break;+ case GeoMultiPoint points:+ builder.Append('(');+ Join(builder, points.Points, c => { builder.Append('('); Position(builder, c, z); builder.Append(')'); });+ builder.Append(')');+ break;+ case GeoLineString line:+ Line(builder, line.Points, z);+ break;+ case GeoMultiLineString lines:+ builder.Append('(');+ Join(builder, lines.Lines, l => Line(builder, l, z));+ builder.Append(')');+ break;+ case GeoPolygon polygon:+ Polygon(builder, polygon, z);+ break;+ case GeoMultiPolygon polygons:+ builder.Append('(');+ Join(builder, polygons.Polygons, p => Polygon(builder, p, z));+ builder.Append(')');+ break;+ case GeoCollection collection:+ builder.Length -= z ? 3 : 1; // "GEOMETRYCOLLECTION" has no Z of its own: members carry it+ builder.Append(" (");+ Join(builder, collection.Geometries, g => Write(builder, g));+ builder.Append(')');+ break;+ }+ }++ private static void Polygon(StringBuilder builder, GeoPolygon polygon, bool z)+ {+ builder.Append('(');+ var index = 0;+ Join(builder, polygon.Rings, ring => Line(builder, GeoRings.Oriented(ring, counterClockwise: index++ == 0), z));+ builder.Append(')');+ }++ private static void Line(StringBuilder builder, IReadOnlyList<Coord> points, bool z)+ {+ builder.Append('(');+ Join(builder, points, c => Position(builder, c, z));+ builder.Append(')');+ }++ private static void Position(StringBuilder builder, Coord c, bool z)+ {+ builder.Append(GeoText.Degrees(c.X)).Append(' ').Append(GeoText.Degrees(c.Y));+ if (z)+ builder.Append(' ').Append(GeoText.Height(c.HasZ ? c.Z : 0));+ }++ private static void Join<T>(StringBuilder builder, IEnumerable<T> items, Action<T> write)+ {+ var first = true;+ foreach (var item in items)+ {+ if (!first)+ builder.Append(", ");+ first = false;+ write(item);+ }+ }++ // ---- Parsing ----++ private sealed class Parser(string text)+ {+ private int _position;++ public GeoGeometry? ReadGeometry(int depth)+ {+ if (depth > MaxDepth)+ throw new FormatException("geometry nested too deeply");+ SkipSpace();+ // EWKT: "SRID=4326;POINT(...)".+ if (text.AsSpan(_position).StartsWith("SRID=", StringComparison.OrdinalIgnoreCase))+ {+ var semicolon = text.IndexOf(';', _position);+ if (semicolon < 0)+ throw new FormatException("SRID prefix without ';'");+ _position = semicolon + 1;+ SkipSpace();+ }+ var word = ReadWord();+ if (word.Length == 0)+ throw new FormatException($"expected a geometry type at position {_position}");+ var kind = word.ToUpperInvariant();+ // "POINTZ", "POINT Z", "POINT ZM", "POINT M".+ var hasZ = false;+ var hasM = false;+ foreach (var suffix in new[] { "ZM", "Z", "M" })+ {+ if (kind.Length > suffix.Length && kind.EndsWith(suffix, StringComparison.Ordinal) && kind[..^suffix.Length] is "POINT" or "LINESTRING" or "POLYGON"+ or "MULTIPOINT" or "MULTILINESTRING" or "MULTIPOLYGON" or "GEOMETRYCOLLECTION")+ {+ hasZ = suffix.Contains('Z', StringComparison.Ordinal);+ hasM = suffix.Contains('M', StringComparison.Ordinal);+ kind = kind[..^suffix.Length];+ break;+ }+ }+ SkipSpace();+ var flag = PeekWord();+ if (flag is "Z" or "ZM" or "M" or "z" or "zm" or "m")+ {+ ReadWord();+ hasZ = flag.Contains('Z', StringComparison.OrdinalIgnoreCase);+ hasM = flag.Contains('M', StringComparison.OrdinalIgnoreCase);+ SkipSpace();+ }+ var dimension = new Dimension(hasZ, hasM);+ if (PeekWord().Equals("EMPTY", StringComparison.OrdinalIgnoreCase))+ {+ ReadWord();+ return null;+ }+ switch (kind)+ {+ case "POINT":+ Open();+ var point = ReadPosition(dimension);+ Close();+ return new GeoPoint(point);+ case "LINESTRING":+ {+ var line = ReadLine(dimension);+ return line.Count < 2 ? throw new FormatException("a LINESTRING needs two positions") : new GeoLineString(line);+ }+ case "POLYGON":+ return ReadPolygon(dimension);+ case "MULTIPOINT":+ {+ Open();+ var points = new List<Coord>();+ do+ {+ SkipSpace();+ if (Peek() == '(')+ {+ Open();+ points.Add(ReadPosition(dimension));+ Close();+ }+ else if (PeekWord().Equals("EMPTY", StringComparison.OrdinalIgnoreCase))+ {+ ReadWord();+ }+ else+ {+ points.Add(ReadPosition(dimension));+ }+ }+ while (Comma());+ Close();+ return points.Count == 0 ? null : new GeoMultiPoint(points);+ }+ case "MULTILINESTRING":+ {+ Open();+ var lines = new List<IReadOnlyList<Coord>>();+ do+ {+ if (TryEmpty())+ continue;+ var line = ReadLine(dimension);+ if (line.Count >= 2)+ lines.Add(line);+ }+ while (Comma());+ Close();+ return lines.Count == 0 ? null : new GeoMultiLineString(lines);+ }+ case "MULTIPOLYGON":+ {+ Open();+ var polygons = new List<GeoPolygon>();+ do+ {+ if (TryEmpty())+ continue;+ if (ReadPolygon(dimension) is { } polygon)+ polygons.Add(polygon);+ }+ while (Comma());+ Close();+ return polygons.Count == 0 ? null : new GeoMultiPolygon(polygons);+ }+ case "GEOMETRYCOLLECTION":+ {+ Open();+ var parts = new List<GeoGeometry>();+ do+ {+ if (ReadGeometry(depth + 1) is { } part)+ parts.Add(part);+ }+ while (Comma());+ Close();+ return parts.Count == 0 ? null : new GeoCollection(parts);+ }+ default:+ throw new FormatException($"unknown geometry type \"{word}\"");+ }+ }++ public void ExpectEnd()+ {+ SkipSpace();+ if (_position < text.Length)+ throw new FormatException($"unexpected text at position {_position}");+ }++ private GeoPolygon? ReadPolygon(Dimension dimension)+ {+ Open();+ var rings = new List<IReadOnlyList<Coord>>();+ do+ {+ if (TryEmpty())+ continue;+ if (GeoRings.Close(ReadLine(dimension)) is { } ring)+ rings.Add(ring);+ }+ while (Comma());+ Close();+ return rings.Count == 0 ? null : new GeoPolygon(rings);+ }++ private List<Coord> ReadLine(Dimension dimension)+ {+ Open();+ var line = new List<Coord>();+ do+ {+ line.Add(ReadPosition(dimension));+ }+ while (Comma());+ Close();+ return line;+ }++ private Coord ReadPosition(Dimension dimension)+ {+ var numbers = new List<double>(4);+ while (true)+ {+ SkipSpace();+ var start = _position;+ while (_position < text.Length && (char.IsAsciiDigit(text[_position]) || text[_position] is '-' or '+' or '.' or 'e' or 'E'))+ _position++;+ if (_position == start)+ break;+ if (!double.TryParse(text.AsSpan(start, _position - start), NumberStyles.Float, CultureInfo.InvariantCulture, out var number) || !double.IsFinite(number))+ throw new FormatException($"bad number at position {start}");+ numbers.Add(number);+ }+ if (numbers.Count < 2)+ throw new FormatException($"a position needs two numbers (position {_position})");+ // X Y [Z] [M]: with M only (POINT M) the third number is the measure; without a flag three numbers mean Z.+ var z = numbers.Count >= 3 && (dimension.Z || !dimension.M) ? numbers[2] : double.NaN;+ return new Coord(numbers[0], numbers[1], z);+ }++ private bool TryEmpty()+ {+ SkipSpace();+ if (!PeekWord().Equals("EMPTY", StringComparison.OrdinalIgnoreCase))+ return false;+ ReadWord();+ return true;+ }++ private void Open()+ {+ SkipSpace();+ if (Peek() != '(')+ throw new FormatException($"expected '(' at position {_position}");+ _position++;+ }++ private void Close()+ {+ SkipSpace();+ if (Peek() != ')')+ throw new FormatException($"expected ')' at position {_position}");+ _position++;+ }++ private bool Comma()+ {+ SkipSpace();+ if (Peek() != ',')+ return false;+ _position++;+ return true;+ }++ private char Peek() => _position < text.Length ? text[_position] : '\0';++ private void SkipSpace()+ {+ while (_position < text.Length && char.IsWhiteSpace(text[_position]))+ _position++;+ }++ private string ReadWord()+ {+ var start = _position;+ while (_position < text.Length && char.IsAsciiLetter(text[_position]))+ _position++;+ return text[start.._position];+ }++ private string PeekWord()+ {+ var saved = _position;+ var word = ReadWord();+ _position = saved;+ return word;+ }+ }++ private readonly record struct Dimension(bool Z, bool M);+}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex ee9ed7db..eac8f84b 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -1218,6 +1218,22 @@ public class RenderTestsAssert.Equal("Subtitle", vm.Target.Detail);}+ /// <summary>The geospatial donut in the toolbar editor: GeoJSON, Shapefile, KML, CSV, GPX and KMZ for geo files.</summary>+ [AvaloniaTheory]+ [InlineData("en")]+ [InlineData("ko")]+ public void Toolbar_geospatial_donut_renders(string language)+ {+ WithProfiles(language, false, 1240, _ => { }, (window, vm) =>+ {+ vm.SelectedProfile = vm.Profiles.Single(p => p.Profile.Id == "geo");+ Pump();+ Assert.Equal(["to-geojson", "to-shp", "to-kml", "to-csv", "to-gpx", "to-kmz"], vm.SelectedProfile.Profile.PresetIds);+ Assert.Contains("shp", vm.ExtensionTags!.Tags.Select(t => t.Text.TrimStart('.')));+ Save(window, $"toolbar-geospatial-{language}.png");+ });+ }+/// <summary>Shows the toolbar page (tall, so the profile card is visible) with temporarily changed profiles.</summary>private static void WithProfiles(string language, bool dark, double height, Action<List<ToolbarProfile>> change, Action<Window, ToolbarPageViewModel> act){diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 42c55c56..d786bfe5 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -208,7 +208,7 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "geo", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}@@ -260,7 +260,7 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "pdf-slides", "email", "data", "vector", "icns", "font", "cad", "model3d", "geo", "archive", "ebook", "subtitle", "wic", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);var ids = store.Profiles.Select(p => p.Id).ToList();Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));@@ -275,8 +275,8 @@ public class UserDataStoreTests{// As written by 1.0.x with schema 5: no catalog presets, donuts or extensions.var presets = BuiltInData.CreatePresets()- .Where(p => BuiltInData.CatalogPresets().Concat(BuiltInData.CodecAndSubtitlePresets()).Concat(BuiltInData.ModelPresets()).All(c => c.Id != p.Id)).ToList();- var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("subtitles").Append("models").ToHashSet();+ .Where(p => BuiltInData.CatalogPresets().Concat(BuiltInData.CodecAndSubtitlePresets()).Concat(BuiltInData.ModelPresets()).Concat(BuiltInData.GeoPresets()).All(c => c.Id != p.Id)).ToList();+ var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("subtitles").Append("models").Append("geo").ToHashSet();var profiles = BuiltInData.CreateProfiles().Where(p => !catalogIds.Contains(p.Id)).ToList();profiles.Single(p => p.Id == "images").Extensions = ["png", "jpg"];profiles.Single(p => p.Id == "pdf").PresetIds.Remove("to-docx");@@ -290,7 +290,8 @@ public class UserDataStoreTestsAssert.Equal(ids.IndexOf("text") + 1, ids.IndexOf("ebooks"));Assert.Equal(ids.IndexOf("fonts") + 1, ids.IndexOf("data")); // schema 14Assert.Equal(ids.IndexOf("data") + 1, ids.IndexOf("models")); // schema 15- Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("models"));+ Assert.Equal(ids.IndexOf("models") + 1, ids.IndexOf("geo")); // schema 21+ Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("geo"));Assert.Equal(ids.IndexOf("audio") + 1, ids.IndexOf("subtitles"));Assert.Contains("cr2", profiles.Single(p => p.Id == "images").Extensions);Assert.DoesNotContain("mp3", profiles.Single(p => p.Id == "audio").Extensions);@@ -433,8 +434,9 @@ public class UserDataStoreTestsstore.Load();// ... and, from schema 15, the 3D model engine before Pandoc (no CAD or archive engine in this list), from- // schema 18 the PDF slides engine there too (no PDF text engine), from schema 21 the WIC engine (no FFmpeg).- Assert.Equal(["magick", "email", "data", "vector", "model3d", "pdf-slides", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ // schema 18 the PDF slides engine there too (no PDF text engine), from schema 21 the WIC engine (no FFmpeg),+ // from schema 23 the geospatial engine after the 3D models engine.+ Assert.Equal(["magick", "email", "data", "vector", "model3d", "geo", "pdf-slides", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);}[Fact]@@ -528,15 +530,17 @@ public class UserDataStoreTests{// As written with schema 14: no 3D formats.var modelIds = BuiltInData.ModelPresets().Select(p => p.Id).ToHashSet();- var presets = BuiltInData.CreatePresets().Where(p => !modelIds.Contains(p.Id)).ToList();- var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "models").ToList();+ var geoIds = BuiltInData.GeoPresets().Select(p => p.Id).ToHashSet();+ var presets = BuiltInData.CreatePresets().Where(p => !modelIds.Contains(p.Id) && !geoIds.Contains(p.Id)).ToList();+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id is not ("models" or "geo")).ToList();Assert.True(SettingsMigrations.ApplyToLibrary(14, presets, profiles));Assert.Equal(["to-glb", "to-stl", "to-obj", "to-3mf", "to-ply", "to-gltf"], presets.Where(p => modelIds.Contains(p.Id)).Select(p => p.Id));var ids = profiles.Select(p => p.Id).ToList();Assert.Equal(ids.IndexOf("data") + 1, ids.IndexOf("models"));- Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("models"));+ Assert.Equal(ids.IndexOf("models") + 1, ids.IndexOf("geo")); // and, from schema 21, the geospatial donut+ Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("geo"));var models = profiles.Single(p => p.Id == "models");Assert.Equal(["glb", "gltf", "stl", "obj", "3mf", "ply", "fbx"], models.Extensions);Assert.Equal(BuiltInData.ModelProfile().PresetIds, models.PresetIds);@@ -547,7 +551,7 @@ public class UserDataStoreTestspublic void The_3d_donut_leaves_out_extensions_a_profile_of_the_user_takes(){var presets = BuiltInData.CreatePresets();- var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "models").ToList();+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id is not ("models" or "geo")).ToList();profiles.Insert(0, new ToolbarProfile { Id = "printing", Name = "Printing", Extensions = ["stl", "3mf"] });Assert.True(SettingsMigrations.ApplyToLibrary(14, presets, profiles));@@ -577,6 +581,94 @@ public class UserDataStoreTestsAssert.DoesNotContain("fbx", profiles.Single(p => p.Id == "models").Extensions);}+ [Fact]+ public void Version_22_libraries_get_geospatial_presets_and_their_donut_after_models()+ {+ // As written with schema 22: no geospatial formats.+ var geoIds = BuiltInData.GeoPresets().Select(p => p.Id).ToHashSet();+ var presets = BuiltInData.CreatePresets().Where(p => !geoIds.Contains(p.Id)).ToList();+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "geo").ToList();++ Assert.True(SettingsMigrations.ApplyToLibrary(22, presets, profiles));++ Assert.Equal(["to-geojson", "to-shp", "to-kml", "to-gpx", "to-kmz"], presets.Where(p => geoIds.Contains(p.Id)).Select(p => p.Id));+ Assert.Equal(["geojson", "shp", "kml", "gpx"], presets.Where(p => geoIds.Contains(p.Id)).Select(p => p.TargetFormat).Take(4));+ var ids = profiles.Select(p => p.Id).ToList();+ 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(BuiltInData.GeoProfile().PresetIds, geo.PresetIds);+ Assert.All(geo.PresetIds, id => Assert.Contains(presets, p => p.Id == id));+ Assert.False(SettingsMigrations.ApplyToLibrary(22, presets, profiles)); // once only+ }++ [Fact]+ public void The_geospatial_donut_leaves_out_extensions_a_profile_of_the_user_takes_and_is_skipped_when_all_are_taken()+ {+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "geo").ToList();+ profiles.Insert(0, new ToolbarProfile { Id = "earth", Name = "Earth", Extensions = ["kml", "kmz"] });++ Assert.True(SettingsMigrations.ApplyToLibrary(22, presets, profiles));+ Assert.Equal(["geojson", "gpx", "shp"], 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"] });+ var geoIds = BuiltInData.GeoPresets().Select(p => p.Id).ToHashSet();+ var withoutPresets = BuiltInData.CreatePresets().Where(p => !geoIds.Contains(p.Id)).ToList();++ Assert.True(SettingsMigrations.ApplyToLibrary(22, withoutPresets, taken)); // the presets are still added+ Assert.DoesNotContain(taken, p => p.Id == "geo");+ Assert.Contains(withoutPresets, p => p.Id == "to-shp");+ }++ [Fact]+ public void A_geospatial_donut_of_the_user_is_not_replaced()+ {+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var mine = profiles.Single(p => p.Id == "geo");+ mine.PresetIds = ["to-kml"];+ mine.Extensions = ["kml"];++ SettingsMigrations.ApplyToLibrary(22, presets, profiles);++ 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);+ }++ [Fact]+ public void Version_22_settings_get_the_geo_engine_after_the_3d_models_engine()+ {+ using var dir = new TempDir();+ File.WriteAllText(Path.Combine(dir.Path, "settings.json"),+ """{ "schemaVersion": 22, "enginePriority": ["magick", "cad", "model3d", "archive", "pandoc", "libreoffice"] }""");++ var store = new UserDataStore(dir.Path);+ store.Load();++ Assert.Equal(["magick", "cad", "model3d", "geo", "archive", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);+ }++ [Fact]+ public void A_new_library_has_the_geospatial_donut_with_presets_that_exist()+ {+ using var dir = new TempDir();+ var store = new UserDataStore(dir.Path);+ store.Load();++ var ids = store.Profiles.Select(p => p.Id).ToList();+ Assert.Equal(ids.IndexOf("models") + 1, ids.IndexOf("geo"));+ var geo = store.Profiles.Single(p => p.Id == "geo");+ Assert.All(geo.PresetIds, id => Assert.NotNull(store.FindPreset(id)));+ Assert.Equal("shp", store.FindPreset("to-shp")!.TargetFormat);+ Assert.Equal("csv", store.FindPreset("to-csv")!.TargetFormat);+ }+[Fact]public void Version_15_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf(){@@ -695,7 +787,7 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "pdfium", "docx-writer", "pdf-text", "pdf-slides", "email", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "pdfium", "docx-writer", "pdf-text", "pdf-slides", "email", "geo", "wic", "pandoc", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}@@ -710,7 +802,7 @@ public class UserDataStoreTestsstore.Load();// Not near the top: the HWPX writer stays among the ranks that win ties (see EbookTests).- Assert.Equal(["magick", "pdfium", "hwpx-writer", "subtitle", "wic", "ffmpeg", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "pdfium", "hwpx-writer", "subtitle", "wic", "ffmpeg", "geo", "pandoc", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}@@ -865,7 +957,7 @@ public class UserDataStoreTests// Schema-5 data where the user already limited a mixed-files donut to MP3 and JPG: those checks must not// count as "taken" when the catalog donuts and extensions are added.var presets = BuiltInData.CreatePresets().Where(p => BuiltInData.CatalogPresets().All(c => c.Id != p.Id)).ToList();- var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("models").ToHashSet();+ var catalogIds = BuiltInData.CatalogProfiles().Select(p => p.Id).Append("models").Append("geo").ToHashSet();var profiles = BuiltInData.CreateProfiles().Where(p => !catalogIds.Contains(p.Id)).ToList();profiles.Single(p => p.Id == "images").Extensions = ["png"];profiles.Add(new ToolbarProfile { Id = "music-mix", Name = "Music mix", IsFallback = true, Extensions = ["mp3", "jpg"] });diff --git a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csprojindex 17919d0a..f2305ad0 100644--- a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj+++ b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj@@ -23,5 +23,7 @@<ItemGroup><!-- Small OFL test fonts for FontTests (see Fonts/OFL.txt and Fonts/make-test-fonts.py). --><None Update="Fonts\*.ttf;Fonts\*.otf;Fonts\*.woff2" CopyToOutputDirectory="PreserveNewest" />+ <!-- Small reference files written by GDAL for the geospatial tests (synthetic data). -->+ <None Update="Geo\*" CopyToOutputDirectory="PreserveNewest" /></ItemGroup></Project>diff --git a/tests/Filee.Engines.Tests/Geo/gdal_linesz.cpg b/tests/Filee.Engines.Tests/Geo/gdal_linesz.cpgnew file mode 100644index 00000000..cd89cb97--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_linesz.cpg@@ -0,0 +1 @@+ISO-8859-1\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_linesz.dbf b/tests/Filee.Engines.Tests/Geo/gdal_linesz.dbfnew file mode 100644index 00000000..c105a622Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_linesz.dbf differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_linesz.prj b/tests/Filee.Engines.Tests/Geo/gdal_linesz.prjnew file mode 100644index 00000000..f45cbadf--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_linesz.prj@@ -0,0 +1 @@+GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_linesz.shp b/tests/Filee.Engines.Tests/Geo/gdal_linesz.shpnew file mode 100644index 00000000..6d5c614eBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_linesz.shp differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_linesz.shx b/tests/Filee.Engines.Tests/Geo/gdal_linesz.shxnew file mode 100644index 00000000..729d7467Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_linesz.shx differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.cpg b/tests/Filee.Engines.Tests/Geo/gdal_points.cpgnew file mode 100644index 00000000..3ad133c0--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_points.cpg@@ -0,0 +1 @@+UTF-8\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.dbf b/tests/Filee.Engines.Tests/Geo/gdal_points.dbfnew file mode 100644index 00000000..9a2a00a2Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_points.dbf differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.geojson b/tests/Filee.Engines.Tests/Geo/gdal_points.geojsonnew file mode 100644index 00000000..f9cebad5--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_points.geojson@@ -0,0 +1,9 @@+{+"type": "FeatureCollection",+"name": "gdal_points",+"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },+"features": [+{ "type": "Feature", "properties": { "name": "A", "n": 1 }, "geometry": { "type": "Point", "coordinates": [ 10.5, 20.25 ] } },+{ "type": "Feature", "properties": { "name": "B", "n": 2 }, "geometry": { "type": "Point", "coordinates": [ -5.0, 40.0 ] } }+]+}diff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.kml b/tests/Filee.Engines.Tests/Geo/gdal_points.kmlnew file mode 100644index 00000000..c9f4f492--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_points.kml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8" ?>+<kml xmlns="http://www.opengis.net/kml/2.2">+<Document id="root_doc">+<Folder><name>gdal_points</name>+ <Placemark>+ <name>A</name>+ <description>first</description>+ <Point><coordinates>10.5,20.25</coordinates></Point>+ </Placemark>+ <Placemark>+ <name>B</name>+ <description>second</description>+ <Point><coordinates>-5,40</coordinates></Point>+ </Placemark>+</Folder>+</Document></kml>diff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.prj b/tests/Filee.Engines.Tests/Geo/gdal_points.prjnew file mode 100644index 00000000..f45cbadf--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_points.prj@@ -0,0 +1 @@+GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.shp b/tests/Filee.Engines.Tests/Geo/gdal_points.shpnew file mode 100644index 00000000..69b51d4bBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_points.shp differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.shx b/tests/Filee.Engines.Tests/Geo/gdal_points.shxnew file mode 100644index 00000000..421c04dbBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_points.shx differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_polygons.cpg b/tests/Filee.Engines.Tests/Geo/gdal_polygons.cpgnew file mode 100644index 00000000..3ad133c0--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_polygons.cpg@@ -0,0 +1 @@+UTF-8\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_polygons.dbf b/tests/Filee.Engines.Tests/Geo/gdal_polygons.dbfnew file mode 100644index 00000000..34c04573Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_polygons.dbf differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_polygons.prj b/tests/Filee.Engines.Tests/Geo/gdal_polygons.prjnew file mode 100644index 00000000..f45cbadf--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_polygons.prj@@ -0,0 +1 @@+GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_polygons.shp b/tests/Filee.Engines.Tests/Geo/gdal_polygons.shpnew file mode 100644index 00000000..d188a17eBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_polygons.shp differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_polygons.shx b/tests/Filee.Engines.Tests/Geo/gdal_polygons.shxnew file mode 100644index 00000000..1f1803ffBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_polygons.shx differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_utm33.cpg b/tests/Filee.Engines.Tests/Geo/gdal_utm33.cpgnew file mode 100644index 00000000..cd89cb97--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_utm33.cpg@@ -0,0 +1 @@+ISO-8859-1\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_utm33.dbf b/tests/Filee.Engines.Tests/Geo/gdal_utm33.dbfnew file mode 100644index 00000000..eaf8e4d4Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_utm33.dbf differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_utm33.prj b/tests/Filee.Engines.Tests/Geo/gdal_utm33.prjnew file mode 100644index 00000000..12f46005--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_utm33.prj@@ -0,0 +1 @@+PROJCS["WGS_1984_UTM_Zone_33N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",15.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]\ No newline at end of filediff --git a/tests/Filee.Engines.Tests/Geo/gdal_utm33.shp b/tests/Filee.Engines.Tests/Geo/gdal_utm33.shpnew file mode 100644index 00000000..e8c78104Binary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_utm33.shp differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_utm33.shx b/tests/Filee.Engines.Tests/Geo/gdal_utm33.shxnew file mode 100644index 00000000..6e9dcdfbBinary files /dev/null and b/tests/Filee.Engines.Tests/Geo/gdal_utm33.shx differdiff --git a/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpx b/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpxnew file mode 100644index 00000000..ce28adf1--- /dev/null+++ b/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpx@@ -0,0 +1,14 @@+<?xml version="1.0"?>+<gpx version="1.1" creator="GDAL 3.9.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">+<metadata>+<bounds minlat="20.250000000000000" minlon="-5.000000000000000" maxlat="40.000000000000000" maxlon="10.500000000000000"/>+</metadata>+<wpt lat="20.25" lon="10.5">+ <ele>12.5</ele>+ <name>A</name>+</wpt>+<wpt lat="40.0" lon="-5.0">+ <ele>0.0</ele>+ <name>B</name>+</wpt>+</gpx>diff --git a/tests/Filee.Engines.Tests/GeoBuilders.cs b/tests/Filee.Engines.Tests/GeoBuilders.csnew file mode 100644index 00000000..cc60fbc7--- /dev/null+++ b/tests/Filee.Engines.Tests/GeoBuilders.cs@@ -0,0 +1,220 @@+// Helpers for the geospatial tests: reference files made by GDAL (tests/Filee.Engines.Tests/Geo), and a small shapefile+// and dBASE writer built straight from the ESRI specification, independent of the engine, for the cases GDAL won't+// write on purpose (a wrong .prj, a truncated record, MultiPatch, deleted rows, other encodings).++using System.Buffers.Binary;+using System.Text;+using System.Text.Json;+using Filee.Core.Conversion;+using Filee.Core.Presets;++namespace Filee.Engines.Tests;++internal static class GeoFixtures+{+ public static string Folder => Path.Combine(AppContext.BaseDirectory, "Geo");++ /// <summary>Copies every file of the reference set <paramref name="name"/> into a fresh folder; returns the path of its <paramref name="extension"/> file.</summary>+ public static string Copy(EngineFixture fx, string name, string extension)+ {+ var folder = fx.NewFolder();+ foreach (var file in Directory.EnumerateFiles(Folder, name + ".*"))+ File.Copy(file, Path.Combine(folder, Path.GetFileName(file)));+ return Path.Combine(folder, name + "." + extension);+ }++ /// <summary>Converts <paramref name="input"/> to <paramref name="target"/> as the app would.</summary>+ public static async Task<ConversionJob> ConvertAsync(this EngineFixture fx, string input, string target, Action<Preset>? tweak = null)+ {+ var preset = new Preset { TargetFormat = target };+ tweak?.Invoke(preset);+ return await fx.ConvertAsync([input], preset);+ }++ /// <summary>Converts and expects success; returns the files written.</summary>+ public static async Task<List<string>> ConvertOkAsync(this EngineFixture fx, string input, string target, Action<Preset>? tweak = null)+ {+ var job = await fx.ConvertAsync(input, target, tweak);+ Assert.True(job.State == JobState.Completed, Describe(job));+ return [.. job.Outputs];+ }++ /// <summary>Converts and expects the file to fail; returns its error key and detail.</summary>+ public static async Task<(string Key, string Detail)> ConvertFailsAsync(this EngineFixture fx, string input, string target)+ {+ var job = await fx.ConvertAsync(input, target);+ Assert.Equal(JobState.Failed, job.State);+ var file = job.Files.Single();+ Assert.Empty(file.Outputs);+ return (file.ErrorKey ?? "", file.ErrorDetail ?? "");+ }++ public static string Describe(ConversionJob job) => string.Join("; ", job.Files.Select(f => $"{f.State} {f.ErrorKey} {f.ErrorDetail}"));++ public static JsonDocument ReadJson(string path) => JsonDocument.Parse(File.ReadAllBytes(path));++ public static string WriteText(EngineFixture fx, string name, string text)+ {+ var path = Path.Combine(fx.NewFolder(), name);+ File.WriteAllText(path, text, new UTF8Encoding(false));+ return path;+ }++ /// <summary>The coordinates [x, y(, z)] of a GeoJSON point geometry.</summary>+ public static double[] Position(JsonElement geometry) =>+ [.. geometry.GetProperty("coordinates").EnumerateArray().Select(n => n.GetDouble())];+}++/// <summary>A shapefile written from the specification: header, records, index and attribute table.</summary>+internal sealed class ShapefileBuilder(int shapeType)+{+ private readonly List<byte[]> _records = [];++ public int ShapeType { get; set; } = shapeType;++ public ShapefileBuilder Null() => Add(Le(0));++ public ShapefileBuilder Point(double x, double y) => Add([.. Le(1), .. Dbl(x), .. Dbl(y)]);++ public ShapefileBuilder PointZ(double x, double y, double z) => Add([.. Le(11), .. Dbl(x), .. Dbl(y), .. Dbl(z), .. Dbl(-1e39)]);++ public ShapefileBuilder MultiPoint(params (double X, double Y)[] points) =>+ Add([.. Le(8), .. Box(points), .. Le(points.Length), .. points.SelectMany(p => Dbl(p.X).Concat(Dbl(p.Y)))]);++ /// <summary>A PolyLine (type 3) or Polygon (type 5) record from its parts; the caller sets the ring direction.</summary>+ public ShapefileBuilder Parts(int type, params (double X, double Y)[][] parts)+ {+ var all = parts.SelectMany(p => p).ToArray();+ var starts = new int[parts.Length];+ for (var i = 1; i < parts.Length; i++)+ starts[i] = starts[i - 1] + parts[i - 1].Length;+ return Add([.. Le(type), .. Box(all), .. Le(parts.Length), .. Le(all.Length), .. starts.SelectMany(Le),+ .. all.SelectMany(p => Dbl(p.X).Concat(Dbl(p.Y)))]);+ }++ /// <summary>A record exactly as given (to build damaged files).</summary>+ public ShapefileBuilder Raw(byte[] content) => Add(content);++ private ShapefileBuilder Add(byte[] content)+ {+ _records.Add(content);+ return this;+ }++ /// <summary>Writes name.shp and name.shx; the .prj when <paramref name="prj"/> is given; the .dbf when <paramref name="dbf"/> is.</summary>+ public string Save(string folder, string name, string? prj = null, DbfBuilder? dbf = null)+ {+ var shpPath = Path.Combine(folder, name + ".shp");+ var shp = new List<byte>();+ var shx = new List<byte>();+ foreach (var (content, index) in _records.Select((c, i) => (c, i)))+ {+ shx.AddRange(Be((100 + shp.Count) / 2));+ shx.AddRange(Be(content.Length / 2));+ shp.AddRange(Be(index + 1));+ shp.AddRange(Be(content.Length / 2));+ shp.AddRange(content);+ }+ File.WriteAllBytes(shpPath, [.. Header(100 + shp.Count), .. shp]);+ File.WriteAllBytes(Path.Combine(folder, name + ".shx"), [.. Header(100 + shx.Count), .. shx]);+ if (prj is not null)+ File.WriteAllText(Path.Combine(folder, name + ".prj"), prj);+ dbf?.Save(Path.Combine(folder, name + ".dbf"));+ return shpPath;+ }++ private byte[] Header(int bytes)+ {+ var header = new byte[100];+ BinaryPrimitives.WriteInt32BigEndian(header, 9994);+ BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(24), bytes / 2);+ BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(28), 1000);+ BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(32), ShapeType);+ return header;+ }++ private static byte[] Box(IEnumerable<(double X, double Y)> points)+ {+ var list = points.ToList();+ return [.. Dbl(list.Min(p => p.X)), .. Dbl(list.Min(p => p.Y)), .. Dbl(list.Max(p => p.X)), .. Dbl(list.Max(p => p.Y))];+ }++ public static byte[] Le(int value) => BitConverter.GetBytes(value);++ public static byte[] Be(int value)+ {+ var bytes = new byte[4];+ BinaryPrimitives.WriteInt32BigEndian(bytes, value);+ return bytes;+ }++ public static byte[] Dbl(double value) => BitConverter.GetBytes(value);+}++/// <summary>A dBASE III table from fields and the exact text of each cell.</summary>+internal sealed class DbfBuilder+{+ private readonly List<(string Name, char Type, int Length, int Decimals)> _fields = [];+ private readonly List<(bool Deleted, string[] Cells)> _rows = [];++ public byte LanguageDriver { get; set; }+ public Encoding Encoding { get; set; } = new UTF8Encoding(false);++ public DbfBuilder Field(string name, char type, int length, int decimals = 0)+ {+ _fields.Add((name, type, length, decimals));+ return this;+ }++ public DbfBuilder Row(params string[] cells) => Row(false, cells);++ public DbfBuilder Row(bool deleted, params string[] cells)+ {+ _rows.Add((deleted, cells));+ return this;+ }++ public void Save(string path)+ {+ var recordLength = 1 + _fields.Sum(f => f.Length);+ var headerLength = 32 + 32 * _fields.Count + 1;+ var bytes = new List<byte>();+ var header = new byte[32];+ header[0] = 3;+ header[1] = 124;+ header[2] = 1;+ header[3] = 1;+ BitConverter.GetBytes(_rows.Count).CopyTo(header, 4);+ BitConverter.GetBytes((ushort)headerLength).CopyTo(header, 8);+ BitConverter.GetBytes((ushort)recordLength).CopyTo(header, 10);+ header[29] = LanguageDriver;+ bytes.AddRange(header);+ foreach (var (name, type, length, decimals) in _fields)+ {+ var descriptor = new byte[32];+ Encoding.ASCII.GetBytes(name).CopyTo(descriptor, 0);+ descriptor[11] = (byte)type;+ descriptor[16] = (byte)length;+ descriptor[17] = (byte)decimals;+ bytes.AddRange(descriptor);+ }+ bytes.Add(0x0D);+ foreach (var (deleted, cells) in _rows)+ {+ bytes.Add(deleted ? (byte)'*' : (byte)' ');+ for (var f = 0; f < _fields.Count; f++)+ {+ var cell = new byte[_fields[f].Length];+ Array.Fill(cell, (byte)' ');+ var text = Encoding.GetBytes(f < cells.Length ? cells[f] : "");+ if (_fields[f].Type is 'N' or 'F')+ text.CopyTo(cell, Math.Max(0, cell.Length - text.Length));+ else+ text.AsSpan(0, Math.Min(text.Length, cell.Length)).CopyTo(cell);+ bytes.AddRange(cell);+ }+ }+ bytes.Add(0x1A);+ File.WriteAllBytes(path, [.. bytes]);+ }+}diff --git a/tests/Filee.Engines.Tests/GeoCrsTests.cs b/tests/Filee.Engines.Tests/GeoCrsTests.csnew file mode 100644index 00000000..d6766200--- /dev/null+++ b/tests/Filee.Engines.Tests/GeoCrsTests.cs@@ -0,0 +1,284 @@+// Coordinate systems of the geospatial engine against PROJ: the .prj definitions GDAL writes (ESRI WKT) and EPSG codes+// must put a projected position within a millimetre of where PROJ says it is; systems Filee can't convert are refused+// with their name; the datum rules; and the WKT / WKT-geometry parsers' errors. The reference positions below come+// from pyproj 3.x (PROJ) for the longitude / latitude next to them.++using Filee.Core.Conversion;+using Filee.Engines.Geo;++namespace Filee.Engines.Tests;++public class GeoCrsTests+{+ internal sealed record Case(int Code, string Wkt, double X, double Y, double Lon, double Lat);++ /// <summary>Systems whose datum PROJ shifts and Filee doesn't: the position is only right to a few hundred metres.</summary>+ private static readonly int[] ShiftedByProj = [27700];++ internal static readonly Case[] Cases =+ [+ // Vienna, UTM 33N+ new(32633, """PROJCS["WGS_1984_UTM_Zone_33N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",15.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""", 602065.2074110014, 5340353.594303575, 16.3738, 48.2082),+ // Cape Town, UTM 33S (false northing)+ new(32733, """PROJCS["WGS_1984_UTM_Zone_33S",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",10000000.0],PARAMETER["Central_Meridian",15.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""", 816557.7955966464, 6240887.995569803, 18.4241, -33.9249),+ // Tokyo, Web Mercator+ new(3857, """PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator_Auxiliary_Sphere"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",0.0],PARAMETER["Auxiliary_Sphere_Type",0.0],UNIT["Meter",1.0]]""", 15550408.912046732, 4257980.732184108, 139.6917, 35.6895),+ // Paris, Lambert-93 (Lambert Conformal Conic, two parallels)+ new(2154, """PROJCS["RGF_1993_Lambert_93",GEOGCS["GCS_RGF_1993",DATUM["D_RGF_1993",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",700000.0],PARAMETER["False_Northing",6600000.0],PARAMETER["Central_Meridian",3.0],PARAMETER["Standard_Parallel_1",49.0],PARAMETER["Standard_Parallel_2",44.0],PARAMETER["Latitude_Of_Origin",46.5],UNIT["Meter",1.0]]""", 652469.0227091359, 6862035.259420077, 2.3522, 48.8566),+ // Chicago, Albers CONUS+ new(5070, """PROJCS["NAD_1983_Contiguous_USA_Albers",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Albers"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-96.0],PARAMETER["Standard_Parallel_1",29.5],PARAMETER["Standard_Parallel_2",45.5],PARAMETER["Latitude_Of_Origin",23.0],UNIT["Meter",1.0]]""", 688894.5442286755, 2127632.7534185336, -87.6298, 41.8781),+ // New York, Long Island state plane in US survey feet+ new(2263, """PROJCS["NAD_1983_StatePlane_New_York_Long_Island_FIPS_3104_Feet",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",984250.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-74.0],PARAMETER["Standard_Parallel_1",41.0333333333333],PARAMETER["Standard_Parallel_2",40.6666666666667],PARAMETER["Latitude_Of_Origin",40.1666666666667],UNIT["US survey foot",0.304800609601219]]""", 988212.237182985, 211939.27856831398, -73.9857, 40.7484),+ // Sydney, World Mercator (ellipsoidal)+ new(3395, """PROJCS["WGS_1984_World_Mercator",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",0.0],UNIT["Meter",1.0]]""", 16832542.27920734, -3987387.019596725, 151.2093, -33.8688),+ // Vilnius, LKS94 (Transverse Mercator, scale 0.9998)+ new(3346, """PROJCS["LKS_1994_Lithuania_TM",GEOGCS["GCS_LKS_1994",DATUM["D_Lithuania_1994",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",24.0],PARAMETER["Scale_Factor",0.9998],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""", 582510.367297761, 6061948.683017084, 25.2797, 54.6872),+ // Zurich, ETRS89 UTM 32N+ new(25832, """PROJCS["ETRS_1989_UTM_Zone_32N",GEOGCS["GCS_ETRS_1989",DATUM["D_ETRS_1989",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",9.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""", 465403.2844656688, 5247150.839302885, 8.5417, 47.3769),+ // London, British National Grid (Airy; PROJ applies a datum shift Filee doesn't)+ new(27700, """PROJCS["British_National_Grid",GEOGCS["GCS_OSGB_1936",DATUM["D_OSGB_1936",SPHEROID["Airy_1830",6377563.396,299.3249646]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",400000.0],PARAMETER["False_Northing",-100000.0],PARAMETER["Central_Meridian",-2.0],PARAMETER["Scale_Factor",0.9996012717],PARAMETER["Latitude_Of_Origin",49.0],UNIT["Meter",1.0]]""", 530043.1949814068, 180358.20862000342, -0.1276, 51.5072),+ // Montpelier, Vermont state plane (Transverse Mercator, latitude of origin 42.5, scale 0.999964)+ new(32145, """PROJCS["NAD_1983_StatePlane_Vermont_FIPS_4400",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-72.5],PARAMETER["Scale_Factor",0.999964286],PARAMETER["Latitude_Of_Origin",42.5],UNIT["Meter",1.0]]""", 493787.50490179786, 195543.33416470452, -72.5778, 44.2601),+ // Singapore, SVY21 (Transverse Mercator, latitude of origin 1.3667)+ new(3414, """PROJCS["SVY21_Singapore_TM",GEOGCS["GCS_SVY21",DATUM["D_SVY21",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",28001.642],PARAMETER["False_Northing",38744.572],PARAMETER["Central_Meridian",103.833333333333],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",1.36666666666667],UNIT["Meter",1.0]]""", 26495.534871029464, 37133.86847645403, 103.8198, 1.3521),+ // Mercator with a standard parallel at 41 degrees south+ new(3994, """PROJCS["WGS_1984_Mercator_41",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",100.0],PARAMETER["Standard_Parallel_1",-41.0],UNIT["Meter",1.0]]""", -6730814.809125746, -6320521.100279815, 20.0, -60.0),+ // Alice Springs area, Australian Albers (southern hemisphere)+ new(3577, """PROJCS["GDA_1994_Australia_Albers",GEOGCS["GCS_GDA_1994",DATUM["D_GDA_1994",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Albers"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",132.0],PARAMETER["Standard_Parallel_1",-18.0],PARAMETER["Standard_Parallel_2",-36.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""", 176715.9535210848, -2734549.475872395, 133.7751, -25.2744),+ // Melbourne, Vicgrid (Lambert Conformal Conic in the south)+ new(3111, """PROJCS["GDA_1994_VICGRID94",GEOGCS["GCS_GDA_1994",DATUM["D_GDA_1994",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",2500000.0],PARAMETER["False_Northing",2500000.0],PARAMETER["Central_Meridian",145.0],PARAMETER["Standard_Parallel_1",-36.0],PARAMETER["Standard_Parallel_2",-38.0],PARAMETER["Latitude_Of_Origin",-37.0],UNIT["Meter",1.0]]""", 2496750.963165419, 2409712.430055314, 144.9631, -37.8136),+ ];++ public static TheoryData<int> Codes => [.. Cases.Select(c => c.Code)];++ private static double Metres(double lon1, double lat1, double lon2, double lat2)+ {+ // Haversine on the WGS 84 mean radius: good to a few metres, and the tolerances below are far larger or far smaller.+ const double r = 6371008.8;+ var dLat = (lat2 - lat1) * Math.PI / 180;+ var dLon = (lon2 - lon1) * Math.PI / 180;+ var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)+ + Math.Cos(lat1 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);+ return 2 * r * Math.Asin(Math.Sqrt(a));+ }++ [Theory]+ [MemberData(nameof(Codes))]+ public void Prj_definition_converts_a_position_like_PROJ(int code)+ {+ var c = Cases.Single(x => x.Code == code);+ var crs = GeoCrs.FromWkt(c.Wkt);+ var position = crs.ToLonLat(new Coord(c.X, c.Y));+ if (ShiftedByProj.Contains(code))+ {+ Assert.True(crs.IsApproximate, "a datum Filee doesn't shift is reported");+ Assert.InRange(Metres(position.X, position.Y, c.Lon, c.Lat), 0, 300);+ return;+ }+ Assert.False(crs.IsApproximate);+ // 1e-8 degrees is about a millimetre; the formulas agree with PROJ far closer than that.+ Assert.Equal(c.Lon, position.X, 8);+ Assert.Equal(c.Lat, position.Y, 8);+ }++ [Theory]+ [InlineData(32633)]+ [InlineData(32733)]+ [InlineData(3857)]+ [InlineData(25832)]+ public void Epsg_code_converts_a_position_like_PROJ(int code)+ {+ var c = Cases.Single(x => x.Code == code);+ var crs = GeoCrs.FromEpsg(code)!;+ var position = crs.ToLonLat(new Coord(c.X, c.Y));+ Assert.Equal(c.Lon, position.X, 8);+ Assert.Equal(c.Lat, position.Y, 8);+ }++ [Fact]+ public void Height_is_kept_and_a_missing_height_stays_missing()+ {+ var crs = GeoCrs.FromEpsg(32633)!;+ Assert.Equal(123.5, crs.ToLonLat(new Coord(602065.2074110014, 5340353.594303575, 123.5)).Z);+ Assert.False(crs.ToLonLat(new Coord(602065.2074110014, 5340353.594303575)).HasZ);+ }++ [Theory]+ [InlineData("urn:ogc:def:crs:OGC:1.3:CRS84", true)]+ [InlineData("EPSG:4326", true)]+ [InlineData("urn:ogc:def:crs:EPSG::4326", true)]+ [InlineData("urn:ogc:def:crs:EPSG::3857", true)]+ [InlineData("EPSG:32633", true)]+ [InlineData("EPSG:3035", false)]+ [InlineData("EPSG:", false)]+ [InlineData("something else", false)]+ public void Crs_names_of_GeoJSON_are_understood_or_not(string name, bool known) =>+ Assert.Equal(known, GeoCrs.FromName(name) is not null);++ [Fact]+ public void Geographic_system_in_grads_with_the_Paris_meridian_is_converted_to_degrees_from_Greenwich()+ {+ var crs = GeoCrs.FromWkt("""GEOGCS["NTF (Paris)",DATUM["Nouvelle_Triangulation_Francaise",SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936269]],PRIMEM["Paris",2.5969213],UNIT["grad",0.01570796326794897]]""");+ var position = crs.ToLonLat(new Coord(0, 50));+ Assert.Equal(2.5969213 * 0.9, position.X, 9);+ Assert.Equal(45, position.Y, 9);+ Assert.True(crs.IsApproximate);+ }++ [Theory]+ [InlineData("""GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", false)]+ [InlineData("""GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", false)]+ [InlineData("""GEOGCS["GCS_Korea_2000",DATUM["D_Korea_2000",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", false)]+ [InlineData("""GEOGCS["GCS_Korean_Datum_1985",DATUM["D_Korean_Datum_1985",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", true)]+ [InlineData("""GEOGCS["GCS_European_1950",DATUM["D_European_1950",SPHEROID["International_1924",6378388.0,297.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", true)]+ [InlineData("""GEOGCS["GCS_North_American_1927",DATUM["D_North_American_1927",SPHEROID["Clarke_1866",6378206.4,294.9786982]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", true)]+ public void A_datum_that_is_not_WGS84_compatible_is_marked_approximate(string wkt, bool approximate)+ {+ var crs = GeoCrs.FromWkt(wkt);+ Assert.True(crs.IsGeographic);+ Assert.Equal(approximate, crs.IsApproximate);+ }++ [Theory]+ // Lambert azimuthal equal-area (Europe), polar stereographic, oblique stereographic: projections Filee doesn't have.+ [InlineData("""PROJCS["ETRS89_LAEA_Europe",GEOGCS["GCS_ETRS_1989",DATUM["D_ETRS_1989",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["False_Easting",4321000.0],PARAMETER["False_Northing",3210000.0],PARAMETER["Central_Meridian",10.0],PARAMETER["Latitude_Of_Origin",52.0],UNIT["Meter",1.0]]""", "Lambert_Azimuthal_Equal_Area")]+ [InlineData("""PROJCS["WGS_1984_UPS_North",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Stereographic"],PARAMETER["False_Easting",2000000.0],UNIT["Meter",1.0]]""", "Stereographic")]+ // WKT2 and geocentric / local / vertical systems.+ [InlineData("""PROJCRS["WGS 84 / UTM zone 33N",BASEGEOGCRS["WGS 84"],CONVERSION["UTM zone 33N"]]""", "WGS 84 / UTM zone 33N")]+ [InlineData("""GEOCCS["WGS 84 (geocentric)",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["metre",1]]""", "WGS 84 (geocentric)")]+ [InlineData("""LOCAL_CS["Site grid",UNIT["metre",1]]""", "Site grid")]+ [InlineData("""PROJCS["No ellipsoid",GEOGCS["x",DATUM["d"]],PROJECTION["Transverse_Mercator"]]""", "No ellipsoid")]+ [InlineData("""PROJCS["No projection",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]]]]""", "No projection")]+ [InlineData("not a definition at all", "NOT")]+ [InlineData("GEOGCS[\"unclosed\"", "missing closing bracket")]+ [InlineData("GEOGCS[\"unterminated string]", "missing closing quote")]+ [InlineData("", "empty definition")]+ public void A_system_Filee_cannot_convert_is_refused_with_its_name(string wkt, string expectedInDetail)+ {+ var error = Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt(wkt));+ Assert.Equal("error.geo_unsupported_crs", error.ErrorKey);+ Assert.Contains(expectedInDetail, error.Detail, StringComparison.OrdinalIgnoreCase);+ }++ [Fact]+ public void A_definition_nested_far_too_deep_is_refused_instead_of_overflowing_the_stack()+ {+ var wkt = string.Concat(Enumerable.Repeat("A[", 5000)) + string.Concat(Enumerable.Repeat("]", 5000));+ var error = Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt(wkt));+ Assert.Contains("nested", error.Detail, StringComparison.Ordinal);+ }++ [Fact]+ public void A_huge_definition_is_refused()+ {+ var error = Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt("GEOGCS[\"" + new string('x', 100_000) + "\"]"));+ Assert.Equal("error.geo_unsupported_crs", error.ErrorKey);+ }++ [Fact]+ public void Text_in_a_definition_can_hold_doubled_quotes_and_unusual_spacing()+ {+ var crs = GeoCrs.FromWkt(" GEOGCS [ \"My \"\"quoted\"\" system\" , DATUM [ \"D_WGS_1984\" , SPHEROID [ \"WGS_1984\" , 6378137.0 , 298.257223563 ] ] , UNIT [ \"Degree\" , 0.0174532925199433 ] ] ");+ Assert.Equal("My \"quoted\" system", crs.Name);+ Assert.True(crs.IsIdentity);+ }++ [Fact]+ public void Random_text_never_throws_anything_but_a_refusal()+ {+ var random = new Random(7);+ const string alphabet = "GEOCSPROJ[]\",.0123456789-+eE _ABCDHMNTU()";+ for (var i = 0; i < 3000; i++)+ {+ var text = new string([.. Enumerable.Range(0, random.Next(0, 120)).Select(_ => alphabet[random.Next(alphabet.Length)])]);+ try+ {+ GeoCrs.FromWkt(text);+ }+ catch (ConversionRefusedException)+ {+ }+ }+ }+}++public class GeoWktTests+{+ private static string RoundTrip(string wkt) => WktFormat.Write(WktFormat.Parse(wkt)!);++ [Theory]+ [InlineData("POINT (1 2)", "POINT (1 2)")]+ [InlineData("point(1.5 -2.25)", "POINT (1.5 -2.25)")]+ [InlineData("POINT Z (1 2 3)", "POINT Z (1 2 3)")]+ [InlineData("POINTZ(1 2 3)", "POINT Z (1 2 3)")]+ [InlineData("POINT ZM (1 2 3 4)", "POINT Z (1 2 3)")]+ [InlineData("POINT M (1 2 9)", "POINT (1 2)")]+ [InlineData("SRID=4326;POINT (1 2)", "POINT (1 2)")]+ [InlineData("LINESTRING (0 0, 1 1, 2 0)", "LINESTRING (0 0, 1 1, 2 0)")]+ [InlineData("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 1 2, 2 2, 2 1, 1 1))", "POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 1 2, 2 2, 2 1, 1 1))")]+ [InlineData("POLYGON ((0 0, 0 4, 4 4, 4 0, 0 0))", "POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))")] // a clockwise outer ring is written counter-clockwise+ [InlineData("POLYGON ((0 0, 4 0, 4 4, 0 4))", "POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))")] // an open ring is closed+ [InlineData("MULTIPOINT ((1 2), (3 4))", "MULTIPOINT ((1 2), (3 4))")]+ [InlineData("MULTIPOINT (1 2, 3 4)", "MULTIPOINT ((1 2), (3 4))")]+ [InlineData("MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))", "MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))")]+ [InlineData("MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 5, 6 5, 6 6, 5 6, 5 5)))", "MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 5, 6 5, 6 6, 5 6, 5 5)))")]+ [InlineData("GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (0 0, 1 1))", "GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (0 0, 1 1))")]+ public void Wkt_is_read_and_written_in_a_canonical_form(string wkt, string? expected)+ {+ if (expected is null)+ {+ Assert.Throws<FormatException>(() => WktFormat.Parse(wkt));+ return;+ }+ Assert.Equal(expected, RoundTrip(wkt));+ }++ [Theory]+ [InlineData("POINT EMPTY")]+ [InlineData("LINESTRING EMPTY")]+ [InlineData("POLYGON EMPTY")]+ [InlineData("MULTIPOLYGON EMPTY")]+ [InlineData("GEOMETRYCOLLECTION EMPTY")]+ [InlineData("MULTIPOINT (EMPTY)")]+ public void Empty_geometry_gives_null(string wkt) => Assert.Null(WktFormat.Parse(wkt));++ [Theory]+ [InlineData("")]+ [InlineData("POINT")]+ [InlineData("POINT (1)")]+ [InlineData("POINT (a b)")]+ [InlineData("POINT (1 2")]+ [InlineData("POINT (1 2) trailing")]+ [InlineData("TRIANGLE ((0 0, 1 0, 0 1, 0 0))")]+ [InlineData("LINESTRING (0 0)")]+ [InlineData("SRID=4326 POINT (1 2)")]+ [InlineData("POINT (1e999 2)")]+ [InlineData("POINT (NaN 2)")]+ public void Malformed_wkt_is_a_format_error(string wkt) => Assert.Throws<FormatException>(() => WktFormat.Parse(wkt));++ [Fact]+ public void Collections_nested_too_deep_are_refused_instead_of_overflowing_the_stack()+ {+ var wkt = string.Concat(Enumerable.Repeat("GEOMETRYCOLLECTION (", 10_000)) + "POINT (1 2)" + new string(')', 10_000);+ Assert.Throws<FormatException>(() => WktFormat.Parse(wkt));+ }++ [Fact]+ public void Random_text_never_throws_anything_but_a_format_error()+ {+ var random = new Random(11);+ const string pieces = "POINT LINESTRING POLYGON MULTI GEOMETRYCOLLECTION Z M EMPTY ( ) , 0 1 2 3.5 -4 1e3 SRID=4326; ";+ var words = pieces.Split(' ');+ for (var i = 0; i < 5000; i++)+ {+ var text = string.Join(' ', Enumerable.Range(0, random.Next(0, 14)).Select(_ => words[random.Next(words.Length)]));+ try+ {+ WktFormat.Parse(text);+ }+ catch (FormatException)+ {+ }+ }+ }+}diff --git a/tests/Filee.Engines.Tests/GeoFormatTests.cs b/tests/Filee.Engines.Tests/GeoFormatTests.csnew file mode 100644index 00000000..d0bbff03--- /dev/null+++ b/tests/Filee.Engines.Tests/GeoFormatTests.cs@@ -0,0 +1,697 @@+// GeoJSON, KML, KMZ, GPX and CSV through the geospatial engine: reference files written by GDAL, hand-written files with+// the shapes real files take (folders, ExtendedData, MultiGeometry, tracks, decimal commas, WKT columns), every format+// into every other, the notes a conversion leaves, and the errors for files that can't be converted.++using System.IO.Compression;+using System.Text;+using System.Text.Json;+using System.Xml.Linq;+using Filee.Core.Conversion;++namespace Filee.Engines.Tests;++public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ static GeoFormatTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);++ private static JsonElement Features(JsonDocument doc) => doc.RootElement.GetProperty("features");++ private static double SignedArea(JsonElement ring)+ {+ var points = ring.EnumerateArray().Select(p => (X: p[0].GetDouble(), Y: p[1].GetDouble())).ToList();+ var sum = 0.0;+ for (var i = 0; i + 1 < points.Count; i++)+ sum += points[i].X * points[i + 1].Y - points[i + 1].X * points[i].Y;+ return sum;+ }++ private async Task<JsonDocument> ToGeoJsonAsync(string input)+ {+ var output = (await fx.ConvertOkAsync(input, "geojson")).Single();+ return GeoFixtures.ReadJson(output);+ }++ // ---- GDAL reference files ----++ [Fact]+ public async Task Gdal_shapefile_points_keep_geometry_text_numbers_booleans_and_dates()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_points", "shp"));+ var features = Features(doc);+ Assert.Equal("FeatureCollection", doc.RootElement.GetProperty("type").GetString());+ Assert.Equal(3, features.GetArrayLength());++ var first = features[0];+ Assert.Equal([126.978, 37.5665], GeoFixtures.Position(first.GetProperty("geometry")));+ var properties = first.GetProperty("properties");+ Assert.Equal("서울 City Hall", properties.GetProperty("name").GetString());+ Assert.Equal(1, properties.GetProperty("n").GetInt64());+ Assert.Equal(1.5, properties.GetProperty("v").GetDouble());+ Assert.True(properties.GetProperty("ok").GetBoolean());+ Assert.Equal("2024-02-29", properties.GetProperty("day").GetString());++ var second = features[1].GetProperty("properties");+ Assert.Equal("Café Eiffel – Paris", second.GetProperty("name").GetString());+ Assert.Equal(-20, second.GetProperty("n").GetInt64());+ Assert.Equal(0.001, second.GetProperty("v").GetDouble());+ Assert.False(second.GetProperty("ok").GetBoolean());++ var third = features[2].GetProperty("properties");+ Assert.Equal("北京 / London", third.GetProperty("name").GetString());+ Assert.Equal(-12345.6789, third.GetProperty("v").GetDouble());+ Assert.Equal(JsonValueKind.Null, third.GetProperty("day").ValueKind);+ }++ [Fact]+ public async Task Gdal_shapefile_polygons_get_their_holes_and_parts_in_geojson_winding()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_polygons", "shp"));+ var features = Features(doc);++ var withHole = features[0].GetProperty("geometry");+ Assert.Equal("Polygon", withHole.GetProperty("type").GetString());+ var rings = withHole.GetProperty("coordinates");+ Assert.Equal(2, rings.GetArrayLength());+ Assert.True(SignedArea(rings[0]) > 0, "RFC 7946: the outer ring runs counter-clockwise");+ Assert.True(SignedArea(rings[1]) < 0, "RFC 7946: holes run clockwise");+ Assert.Equal(100 - 4, SignedArea(rings[0]) / 2 + SignedArea(rings[1]) / 2);++ var twoParts = features[1].GetProperty("geometry");+ Assert.Equal("MultiPolygon", twoParts.GetProperty("type").GetString());+ Assert.Equal(2, twoParts.GetProperty("coordinates").GetArrayLength());+ Assert.Equal("two parts", features[1].GetProperty("properties").GetProperty("label").GetString());+ }++ [Fact]+ public async Task Gdal_utm_shapefile_is_converted_to_longitude_latitude_using_its_prj()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_utm33", "shp"));+ var expected = new[] { ("Vienna", 16.3738, 48.2082), ("Prague", 14.4378, 50.0755), ("Berlin", 13.4050, 52.5200) };+ var features = Features(doc);+ for (var i = 0; i < expected.Length; i++)+ {+ var position = GeoFixtures.Position(features[i].GetProperty("geometry"));+ Assert.Equal(expected[i].Item1, features[i].GetProperty("properties").GetProperty("name").GetString());+ Assert.Equal(expected[i].Item2, position[0], 8);+ Assert.Equal(expected[i].Item3, position[1], 8);+ }+ }++ [Fact]+ public async Task Gdal_3d_lines_keep_their_heights_in_every_format()+ {+ var shp = GeoFixtures.Copy(fx, "gdal_linesz", "shp");+ using (var doc = await ToGeoJsonAsync(shp))+ {+ var line = Features(doc)[0].GetProperty("geometry");+ Assert.Equal("LineString", line.GetProperty("type").GetString());+ Assert.Equal([[0.0, 0.0, 10.0], [1.0, 1.0, 20.5], [2.0, 0.0, 30.0]],+ line.GetProperty("coordinates").EnumerateArray().Select(p => p.EnumerateArray().Select(n => n.GetDouble()).ToArray()).ToArray());+ }+ var kml = (await fx.ConvertOkAsync(shp, "kml")).Single();+ Assert.Contains("0,0,10 1,1,20.5 2,0,30", File.ReadAllText(kml));+ var gpx = (await fx.ConvertOkAsync(shp, "gpx")).Single();+ Assert.Equal(["10", "20.5", "30"], XDocument.Load(gpx).Descendants().Where(e => e.Name.LocalName == "ele").Select(e => e.Value).ToArray());+ var csv = (await fx.ConvertOkAsync(shp, "csv")).Single();+ Assert.Contains("LINESTRING Z (0 0 10, 1 1 20.5, 2 0 30)", File.ReadAllText(csv));+ }++ [Fact]+ public async Task Gdal_kml_name_and_description_become_attributes()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_points", "kml"));+ var features = Features(doc);+ Assert.Equal(2, features.GetArrayLength());+ Assert.Equal([10.5, 20.25], GeoFixtures.Position(features[0].GetProperty("geometry")));+ Assert.Equal("A", features[0].GetProperty("properties").GetProperty("name").GetString());+ Assert.Equal("second", features[1].GetProperty("properties").GetProperty("description").GetString());+ }++ [Fact]+ public async Task Gdal_gpx_waypoint_elevation_becomes_the_height()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_waypoints", "gpx"));+ var features = Features(doc);+ Assert.Equal(2, features.GetArrayLength());+ Assert.Equal([10.5, 20.25, 12.5], GeoFixtures.Position(features[0].GetProperty("geometry")));+ Assert.Equal("waypoint", features[0].GetProperty("properties").GetProperty("gpx_type").GetString());+ Assert.Equal("B", features[1].GetProperty("properties").GetProperty("name").GetString());+ }++ [Fact]+ public async Task Gdal_geojson_converts_to_the_same_geojson_rewritten_one_feature_per_line()+ {+ var output = (await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_points", "geojson"), "geojson")).Single();+ var lines = File.ReadAllLines(output);+ Assert.Equal(4, lines.Length); // the opening, one line for each of the two features, the closing+ Assert.StartsWith("""{"type":"Feature",""", lines[1]);+ using var doc = GeoFixtures.ReadJson(output);+ Assert.Equal(2, Features(doc).GetArrayLength());+ }++ // ---- Every format into every other ----++ [Fact]+ public async Task Every_format_converts_into_every_other_and_back_to_the_same_places_and_names()+ {+ var formats = new[] { "kml", "kmz", "gpx", "shp", "csv", "geojson" };+ var source = GeoFixtures.Copy(fx, "gdal_points", "geojson");+ var made = new Dictionary<string, string> { ["geojson"] = source };+ foreach (var format in formats.Where(f => f != "geojson"))+ made[format] = (await fx.ConvertOkAsync(source, format)).First(path => path.EndsWith("." + format, StringComparison.Ordinal));++ foreach (var from in formats)+ {+ foreach (var to in formats.Where(t => t != from))+ {+ var step = (await fx.ConvertOkAsync(made[from], to)).First(path => path.EndsWith("." + to, StringComparison.Ordinal));+ var final = to == "geojson" ? step : (await fx.ConvertOkAsync(step, "geojson")).Single();+ using var doc = GeoFixtures.ReadJson(final);+ var features = Features(doc);+ Assert.True(features.GetArrayLength() == 2, $"{from} -> {to}: {features.GetArrayLength()} features");+ Assert.Equal([10.5, 20.25], GeoFixtures.Position(features[0].GetProperty("geometry"))[..2]);+ Assert.Equal([-5.0, 40.0], GeoFixtures.Position(features[1].GetProperty("geometry"))[..2]);+ Assert.True(features[0].GetProperty("properties").GetProperty("name").GetString() == "A", $"{from} -> {to} keeps the name");+ }+ }+ }++ [Fact]+ public async Task A_shapefile_reaches_json_xlsx_and_text_formats_through_csv()+ {+ var shp = GeoFixtures.Copy(fx, "gdal_points", "shp");+ foreach (var target in new[] { "xlsx", "json", "yaml" })+ {+ var output = (await fx.ConvertOkAsync(shp, target)).Single();+ Assert.True(new FileInfo(output).Length > 100, target);+ }+ using var rows = GeoFixtures.ReadJson((await fx.ConvertOkAsync(shp, "json")).Single());+ Assert.Equal(126.978, rows.RootElement[0].GetProperty("longitude").GetDouble());+ Assert.Equal("서울 City Hall", rows.RootElement[0].GetProperty("name").GetString());+ Assert.Equal(3, rows.RootElement.GetArrayLength());+ }++ // ---- GeoJSON ----++ [Fact]+ public async Task GeoJson_input_forms_are_all_accepted()+ {+ var featureCollection = """{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[1,2]},"properties":{"a":1}}]}""";+ var feature = """{"type":"Feature","geometry":{"type":"Point","coordinates":[1,2]},"properties":{"a":1}}""";+ var bare = """{"type":"Point","coordinates":[1,2]}""";+ foreach (var text in new[] { featureCollection, feature, bare, "\uFEFF" + feature, "// comment\n" + feature + "\n", feature.Replace("}}", "},}") })+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "input.geojson", text));+ Assert.Equal(1, Features(doc).GetArrayLength());+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(Features(doc)[0].GetProperty("geometry")));+ }+ }++ [Fact]+ public async Task GeoJson_in_utf16_either_way_round_and_in_an_old_code_page_is_read()+ {+ const string text = """{"type":"Feature","geometry":{"type":"Point","coordinates":[1,2]},"properties":{"n":"유니코드 서울"}}""";+ foreach (var encoding in new Encoding[] { Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.GetEncoding(949) })+ {+ var path = Path.Combine(fx.NewFolder(), "text.geojson");+ File.WriteAllText(path, text, encoding);+ using var doc = await ToGeoJsonAsync(path);+ Assert.Equal("유니코드 서울", Features(doc)[0].GetProperty("properties").GetProperty("n").GetString());+ }+ }++ [Fact]+ public async Task GeoJson_attributes_keep_their_types_and_nested_values_become_json_text()+ {+ var text = """{"type":"FeatureCollection","features":[{"type":"Feature","id":"abc-1","properties":{"s":"x","i":42,"big":12345678901234567890,"f":1.25,"b":true,"nil":null,"list":[1,2],"obj":{"k":"v"}},"geometry":{"type":"Point","coordinates":[3,4]}}]}""";+ var output = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "types.geojson", text), "geojson")).Single();+ using var doc = GeoFixtures.ReadJson(output);+ var p = Features(doc)[0].GetProperty("properties");+ Assert.Equal("abc-1", p.GetProperty("id").GetString());+ Assert.Equal(42, p.GetProperty("i").GetInt64());+ Assert.Equal(1.25, p.GetProperty("f").GetDouble());+ Assert.True(p.GetProperty("b").GetBoolean());+ Assert.Equal(JsonValueKind.Null, p.GetProperty("nil").ValueKind);+ Assert.Equal("[1,2]", p.GetProperty("list").GetString());+ Assert.Equal("{\"k\":\"v\"}", p.GetProperty("obj").GetString());+ Assert.True(p.GetProperty("big").GetDouble() > 1.2e19);+ }++ [Fact]+ public async Task GeoJson_feature_without_geometry_or_with_empty_coordinates_stays_as_a_feature()+ {+ var text = """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":null},{"type":"Feature","properties":{"n":2}},{"type":"Feature","properties":{"n":3},"geometry":{"type":"Point","coordinates":[]}},{"type":"Feature","properties":{"n":4},"geometry":{"type":"LineString","coordinates":[[1,1]]}}]}""";+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "nogeom.geojson", text));+ Assert.Equal(4, Features(doc).GetArrayLength());+ Assert.All(Features(doc).EnumerateArray(), f => Assert.Equal(JsonValueKind.Null, f.GetProperty("geometry").ValueKind));+ }++ [Fact]+ public async Task GeoJson_polygon_rings_are_closed_and_wound_by_the_rfc_on_output()+ {+ // Clockwise outer ring, not closed, with a counter-clockwise hole: both are put right.+ var text = """{"type":"Polygon","coordinates":[[[0,0],[0,4],[4,4],[4,0]],[[1,1],[2,1],[2,2],[1,2],[1,1]]]}""";+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "ring.geojson", text));+ var rings = Features(doc)[0].GetProperty("geometry").GetProperty("coordinates");+ Assert.Equal(5, rings[0].GetArrayLength());+ Assert.True(SignedArea(rings[0]) > 0);+ Assert.True(SignedArea(rings[1]) < 0);+ }++ [Fact]+ public async Task GeoJson_crs_member_is_honoured_for_known_systems_and_refused_for_others()+ {+ var web = """{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::3857"}},"features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1113194.9079327357,1118889.9748579597]}}]}""";+ using (var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "web.geojson", web)))+ {+ var position = GeoFixtures.Position(Features(doc)[0].GetProperty("geometry"));+ Assert.Equal(10, position[0], 8);+ Assert.Equal(10, position[1], 8);+ }+ var laea = web.Replace("EPSG::3857", "EPSG::3035");+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "laea.geojson", laea), "kml");+ Assert.Equal("error.geo_unsupported_crs", key);+ Assert.Contains("EPSG::3035", detail);+ }++ [Fact]+ public async Task GeoJson_with_projected_coordinates_and_no_crs_is_refused_instead_of_placed_on_the_wrong_spot()+ {+ var text = """{"type":"Point","coordinates":[602065.2,5340353.6]}""";+ var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "utm.geojson", text), "kml");+ Assert.Equal("error.geo_unknown_crs", key);+ }++ [Fact]+ public async Task GeoJson_text_with_unicode_and_control_characters_is_written_safely_to_every_text_format()+ {+ var text = "{\"type\":\"Feature\",\"properties\":{\"name\":\"a\\u0001b <&> \\\"q\\\" 한국어\\n2nd\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[1,2]}}";+ var path = GeoFixtures.WriteText(fx, "ctl.geojson", text);+ var kml = (await fx.ConvertOkAsync(path, "kml")).Single();+ var name = XDocument.Load(kml).Descendants().First(e => e.Name.LocalName == "name" && e.Parent?.Name.LocalName == "Placemark").Value;+ Assert.Equal("ab <&> \"q\" 한국어\n2nd", name);+ var gpx = (await fx.ConvertOkAsync(path, "gpx")).Single();+ Assert.Equal("ab <&> \"q\" 한국어\n2nd", XDocument.Load(gpx).Descendants().First(e => e.Name.LocalName == "name").Value);+ var csv = File.ReadAllText((await fx.ConvertOkAsync(path, "csv")).Single());+ Assert.Contains("\"a\u0001b <&> \"\"q\"\" 한국어\n2nd\"", csv);+ }++ // ---- KML / KMZ ----++ internal const string KmlSample = """+ <?xml version="1.0" encoding="UTF-8"?>+ <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">+ <Document>+ <name>Sample</name>+ <Style id="s"><IconStyle><scale>2</scale></IconStyle></Style>+ <Folder>+ <name>Outer</name>+ <Folder>+ <Placemark>+ <name>Point with data</name>+ <description><![CDATA[<b>bold</b> text]]></description>+ <ExtendedData>+ <Data name="population"><value>1234</value></Data>+ <Data name="code"><value>007</value></Data>+ <SchemaData schemaUrl="#x"><SimpleData name="area">12.5</SimpleData></SchemaData>+ </ExtendedData>+ <Point><coordinates>10.5, 20.25, 99</coordinates></Point>+ </Placemark>+ </Folder>+ <Placemark><name>Line</name><LineString><coordinates>+ 0,0+ 1,1,5+ 2,0+ </coordinates></LineString></Placemark>+ <Placemark><name>Polygon</name><Polygon>+ <outerBoundaryIs><LinearRing><coordinates>0,0 4,0 4,4 0,4 0,0</coordinates></LinearRing></outerBoundaryIs>+ <innerBoundaryIs><LinearRing><coordinates>1,1 1,2 2,2 2,1 1,1</coordinates></LinearRing></innerBoundaryIs>+ </Polygon></Placemark>+ <Placemark><name>Several points</name><MultiGeometry><Point><coordinates>1,1</coordinates></Point><Point><coordinates>2,2</coordinates></Point></MultiGeometry></Placemark>+ <Placemark><name>Mixed</name><MultiGeometry><Point><coordinates>1,1</coordinates></Point><LineString><coordinates>0,0 3,3</coordinates></LineString></MultiGeometry></Placemark>+ <Placemark><name>Track</name><gx:Track><gx:coord>5 6 7</gx:coord><gx:coord>6 7 8</gx:coord></gx:Track></Placemark>+ <Placemark><name>No shape</name></Placemark>+ </Folder>+ <GroundOverlay><name>Not a feature</name></GroundOverlay>+ </Document>+ </kml>+ """;++ [Fact]+ public async Task Kml_placemarks_are_read_from_nested_folders_with_all_geometry_kinds_and_data()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "sample.kml", KmlSample));+ var features = Features(doc);+ Assert.Equal(7, features.GetArrayLength());++ var point = features[0];+ var p = point.GetProperty("properties");+ Assert.Equal("Point with data", p.GetProperty("name").GetString());+ Assert.Equal("<b>bold</b> text", p.GetProperty("description").GetString());+ Assert.Equal(1234, p.GetProperty("population").GetInt64());+ Assert.Equal("007", p.GetProperty("code").GetString());+ Assert.Equal(12.5, p.GetProperty("area").GetDouble());+ Assert.Equal([10.5, 20.25, 99.0], GeoFixtures.Position(point.GetProperty("geometry")));++ Assert.Equal("LineString", features[1].GetProperty("geometry").GetProperty("type").GetString());+ Assert.Equal(3, features[1].GetProperty("geometry").GetProperty("coordinates").GetArrayLength());+ var polygon = features[2].GetProperty("geometry");+ Assert.Equal(2, polygon.GetProperty("coordinates").GetArrayLength());+ Assert.Equal("MultiPoint", features[3].GetProperty("geometry").GetProperty("type").GetString());+ Assert.Equal("GeometryCollection", features[4].GetProperty("geometry").GetProperty("type").GetString());+ var track = features[5].GetProperty("geometry");+ Assert.Equal("LineString", track.GetProperty("type").GetString());+ Assert.Equal(7, track.GetProperty("coordinates")[0][2].GetDouble());+ Assert.Equal(JsonValueKind.Null, features[6].GetProperty("geometry").ValueKind);+ }++ [Fact]+ public async Task Kml_of_an_older_namespace_without_a_namespace_and_with_odd_coordinates_is_read()+ {+ foreach (var kml in new[]+ {+ """<kml xmlns="http://earth.google.com/kml/2.1"><Placemark><Point><coordinates>1,2</coordinates></Point></Placemark></kml>""",+ """<kml><Placemark><Point><coordinates>1,2</coordinates></Point></Placemark></kml>""",+ """<kml xmlns="http://www.opengis.net/kml/2.2"><Placemark><Point><coordinates> 1 , 2 </coordinates></Point></Placemark></kml>""",+ })+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "old.kml", kml));+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(Features(doc)[0].GetProperty("geometry")));+ }+ }++ [Fact]+ public async Task Kmz_is_written_as_a_zip_with_doc_kml_and_read_back_whatever_the_kml_is_called()+ {+ var geojson = GeoFixtures.Copy(fx, "gdal_points", "geojson");+ var kmz = (await fx.ConvertOkAsync(geojson, "kmz")).Single();+ using (var zip = ZipFile.OpenRead(kmz))+ Assert.Equal(["doc.kml"], zip.Entries.Select(e => e.FullName).ToArray());++ // A KMZ made elsewhere: other files first, the KML under another name.+ var odd = Path.Combine(fx.NewFolder(), "odd.kmz");+ using (var zip = ZipFile.Open(odd, ZipArchiveMode.Create))+ {+ using (var w = new StreamWriter(zip.CreateEntry("images/icon.png").Open()))+ w.Write("not really a picture");+ using var kml = new StreamWriter(zip.CreateEntry("files/places.kml").Open());+ kml.Write(KmlSample);+ }+ using var doc = await ToGeoJsonAsync(odd);+ Assert.Equal(7, Features(doc).GetArrayLength());+ }++ [Fact]+ public async Task Kml_output_has_one_placemark_per_feature_with_extended_data_and_valid_xml()+ {+ var kml = (await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_points", "shp"), "kml")).Single();+ var document = XDocument.Load(kml);+ XNamespace ns = "http://www.opengis.net/kml/2.2";+ var placemarks = document.Descendants(ns + "Placemark").ToList();+ Assert.Equal(3, placemarks.Count);+ Assert.Equal("서울 City Hall", placemarks[0].Element(ns + "name")!.Value);+ var data = placemarks[0].Element(ns + "ExtendedData")!.Elements(ns + "Data").ToDictionary(d => (string)d.Attribute("name")!, d => d.Element(ns + "value")!.Value);+ Assert.Equal("1", data["n"]);+ Assert.Equal("true", data["ok"]);+ Assert.Equal("126.978,37.5665", placemarks[0].Descendants(ns + "coordinates").Single().Value);+ Assert.DoesNotContain("name", data.Keys);+ }++ [Theory]+ [InlineData("not xml at all")]+ [InlineData("<kml><Placemark>")]+ [InlineData("<html><body/></html>")]+ public async Task Kml_that_is_broken_or_not_kml_fails_with_a_reason(string text)+ {+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bad.kml", text), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.NotEmpty(detail);+ }++ [Fact]+ public async Task Kml_with_a_position_that_is_not_a_number_names_the_text()+ {+ var kml = """<kml><Placemark><Point><coordinates>abc,2</coordinates></Point></Placemark></kml>""";+ var (_, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "nan.kml", kml), "geojson");+ Assert.Contains("abc,2", detail);+ }++ [Fact]+ public async Task A_kmz_that_is_not_a_zip_or_has_no_kml_fails_with_a_reason()+ {+ var (_, notZip) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "fake.kmz", "this is not a zip"), "geojson");+ Assert.Contains("KMZ", notZip);+ var empty = Path.Combine(fx.NewFolder(), "empty.kmz");+ using (var zip = ZipFile.Open(empty, ZipArchiveMode.Create))+ zip.CreateEntry("readme.txt");+ var (_, noKml) = await fx.ConvertFailsAsync(empty, "geojson");+ Assert.Contains("no .kml", noKml);+ }++ // ---- GPX ----++ internal const string GpxSample = """+ <?xml version="1.0"?>+ <gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">+ <metadata><name>file</name></metadata>+ <wpt lat="47.5" lon="8.25"><ele>412.5</ele><time>2024-05-01T10:00:00Z</time><name>Summit</name><cmt>comment</cmt><desc>Nice view</desc><sym>Flag</sym><type>peak</type></wpt>+ <rte><name>Route 1</name><rtept lat="1" lon="2"/><rtept lat="3" lon="4"/></rte>+ <trk><name>Track 1</name><number>3</number>+ <trkseg><trkpt lat="10" lon="20"><ele>5</ele></trkpt><trkpt lat="11" lon="21"/></trkseg>+ <trkseg><trkpt lat="12" lon="22"/><trkpt lat="13" lon="23"/></trkseg>+ </trk>+ <trk><name>Empty track</name></trk>+ </gpx>+ """;++ [Fact]+ public async Task Gpx_waypoints_routes_and_tracks_become_features()+ {+ using var doc = await ToGeoJsonAsync(GeoFixtures.WriteText(fx, "sample.gpx", GpxSample));+ var features = Features(doc);+ Assert.Equal(4, features.GetArrayLength());+ var wpt = features[0].GetProperty("properties");+ Assert.Equal("Summit", wpt.GetProperty("name").GetString());+ Assert.Equal("peak", wpt.GetProperty("type").GetString());+ Assert.Equal("Flag", wpt.GetProperty("sym").GetString());+ Assert.Equal("2024-05-01T10:00:00Z", wpt.GetProperty("time").GetString());+ Assert.Equal([8.25, 47.5, 412.5], GeoFixtures.Position(features[0].GetProperty("geometry")));+ Assert.Equal("route", features[1].GetProperty("properties").GetProperty("gpx_type").GetString());+ Assert.Equal("LineString", features[1].GetProperty("geometry").GetProperty("type").GetString());+ Assert.Equal(3, features[2].GetProperty("properties").GetProperty("number").GetInt64());+ Assert.Equal("MultiLineString", features[2].GetProperty("geometry").GetProperty("type").GetString());+ Assert.Equal(JsonValueKind.Null, features[3].GetProperty("geometry").ValueKind);+ }++ [Fact]+ public async Task Gpx_output_keeps_waypoint_fields_tracks_and_routes_in_schema_order()+ {+ var geojson = await ToGeoJsonPathAsync(GeoFixtures.WriteText(fx, "sample.gpx", GpxSample));+ var document = XDocument.Load((await fx.ConvertOkAsync(geojson, "gpx")).Single());+ XNamespace ns = "http://www.topografix.com/GPX/1/1";+ Assert.Equal("1.1", (string)document.Root!.Attribute("version")!);+ var wpt = document.Root.Element(ns + "wpt")!;+ Assert.Equal(["ele", "time", "name", "cmt", "desc", "sym", "type"], wpt.Elements().Select(e => e.Name.LocalName).ToArray());+ Assert.Equal("2024-05-01T10:00:00Z", wpt.Element(ns + "time")!.Value);+ Assert.Single(document.Root.Elements(ns + "rte"));+ var track = document.Root.Elements(ns + "trk").Single();+ Assert.Equal(2, track.Elements(ns + "trkseg").Count());+ Assert.Equal(["name", "number"], track.Elements().Take(2).Select(e => e.Name.LocalName).ToArray());+ }++ private async Task<string> ToGeoJsonPathAsync(string input) => (await fx.ConvertOkAsync(input, "geojson")).Single();++ [Fact]+ public async Task Gpx_output_says_when_polygons_and_other_attributes_could_not_be_kept()+ {+ var job = await fx.ConvertAsync(GeoFixtures.Copy(fx, "gdal_polygons", "shp"), "gpx");+ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal("notice.geo_gpx_lossy", job.Files.Single().NoticeKey);+ var tracks = XDocument.Load(job.Outputs.Single()).Descendants().Where(e => e.Name.LocalName == "trk").ToList();+ Assert.Equal(2, tracks.Count); // one track per feature, its rings as segments+ Assert.Equal(2, tracks[0].Elements().Count(e => e.Name.LocalName == "trkseg"));+ Assert.Equal(2, tracks[1].Elements().Count(e => e.Name.LocalName == "trkseg"));+ }++ [Theory]+ [InlineData("""<gpx><wpt lat="91" lon="0"/></gpx>""")]+ [InlineData("""<gpx><wpt lat="0" lon="500"/></gpx>""")]+ [InlineData("""<gpx><wpt lon="0"/></gpx>""")]+ [InlineData("""<gpx><wpt lat="north" lon="0"/></gpx>""")]+ [InlineData("""<notgpx/>""")]+ [InlineData("<gpx><wpt lat=\"1\" lon=\"2\">")]+ public async Task Gpx_with_invalid_positions_or_structure_fails_with_a_reason(string text)+ {+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bad.gpx", text), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.NotEmpty(detail);+ }++ // ---- CSV ----++ private async Task<(JsonDocument Doc, string? Notice)> CsvToGeoJsonAsync(string csv, string name = "points.csv")+ {+ var job = await fx.ConvertAsync(GeoFixtures.WriteText(fx, name, csv), "geojson");+ Assert.True(job.State == JobState.Completed, GeoFixtures.Describe(job));+ return (GeoFixtures.ReadJson(job.Outputs.Single()), job.Files.Single().NoticeKey);+ }++ [Theory]+ [InlineData("name,lat,lon\nA,48.8566,2.3522\n")]+ [InlineData("Name,Latitude,Longitude\nA,48.8566,2.3522\n")]+ [InlineData("name,LAT,LNG\nA,48.8566,2.3522\n")]+ [InlineData("name,y,x\nA,48.8566,2.3522\n")]+ [InlineData("name;lat;lon\nA;48,8566;2,3522\n")]+ [InlineData("name\tlatitude\tlongitude\nA\t48.8566\t2.3522\n")]+ [InlineData("\uFEFFname,\"lat\",\"long\"\r\n\"A\",\"48.8566\",\"2.3522\"\r\n")]+ public async Task Csv_longitude_and_latitude_columns_are_found_by_name_whatever_the_order_delimiter_or_decimal_mark(string csv)+ {+ var (doc, notice) = await CsvToGeoJsonAsync(csv);+ using (doc)+ {+ var feature = Features(doc)[0];+ Assert.Equal([2.3522, 48.8566], GeoFixtures.Position(feature.GetProperty("geometry")));+ // The coordinate columns are the geometry, not attributes: "name" is the only attribute (its header's case is kept).+ var attribute = Assert.Single(feature.GetProperty("properties").EnumerateObject());+ Assert.Equal("name", attribute.Name, ignoreCase: true);+ Assert.Equal("A", attribute.Value.GetString());+ Assert.Null(notice);+ }+ }++ [Fact]+ public async Task Csv_attribute_values_are_typed_and_identifiers_with_leading_zeros_stay_text()+ {+ var (doc, _) = await CsvToGeoJsonAsync("id,code,height,flag,note,lon,lat,elevation\n1,007,12.5,true,\"a,b\",1,2,300\n");+ using (doc)+ {+ var p = Features(doc)[0].GetProperty("properties");+ Assert.Equal(1, p.GetProperty("id").GetInt64());+ Assert.Equal("007", p.GetProperty("code").GetString());+ Assert.Equal(12.5, p.GetProperty("height").GetDouble());+ Assert.True(p.GetProperty("flag").GetBoolean());+ Assert.Equal("a,b", p.GetProperty("note").GetString());+ Assert.Equal([1.0, 2.0, 300.0], GeoFixtures.Position(Features(doc)[0].GetProperty("geometry")));+ }+ }++ [Fact]+ public async Task Csv_wkt_column_gives_any_geometry()+ {+ var csv = "id,WKT\n1,\"POINT (1 2)\"\n2,\"LINESTRING (0 0, 1 1)\"\n3,\"POLYGON ((0 0, 4 0, 4 4, 0 0))\"\n4,\"SRID=4326;MULTIPOINT ((1 1), (2 2))\"\n5,\n";+ var (doc, notice) = await CsvToGeoJsonAsync(csv);+ using (doc)+ {+ var types = Features(doc).EnumerateArray().Select(f => f.GetProperty("geometry") is { ValueKind: JsonValueKind.Object } g ? g.GetProperty("type").GetString() : null).ToArray();+ Assert.Equal(new string?[] { "Point", "LineString", "Polygon", "MultiPoint", null }, types);+ Assert.Equal("notice.geo_rows_without_location", notice);+ }+ }++ [Fact]+ public async Task Csv_rows_without_a_usable_location_are_kept_without_a_shape_and_noted()+ {+ var (doc, notice) = await CsvToGeoJsonAsync("n,lat,lon\n1,10,20\n2,,\n3,abc,30\n4,5,6\n");+ using (doc)+ {+ Assert.Equal(4, Features(doc).GetArrayLength());+ Assert.Equal(JsonValueKind.Null, Features(doc)[1].GetProperty("geometry").ValueKind);+ Assert.Equal(JsonValueKind.Null, Features(doc)[2].GetProperty("geometry").ValueKind);+ Assert.Equal("notice.geo_rows_without_location", notice);+ }+ }++ [Theory]+ [InlineData("name,value\nA,1\n", "error.geo_csv_no_coordinates")]+ [InlineData("name,lat\nA,1\n", "error.geo_csv_no_coordinates")]+ [InlineData("lat,lon\n,\n,\n", "error.geo_empty")] // rows with nothing in them don't count as rows+ [InlineData("lat,lon\nnorth,east\n", "error.geo_csv_no_locations")]+ [InlineData("lat,lon\n", "error.geo_empty")]+ [InlineData("easting,northing\n602065.2,5340353.6\n", "error.geo_unknown_crs")]+ [InlineData("x,y\n602065.2,5340353.6\n", "error.geo_unknown_crs")]+ [InlineData("lat,lon\n95,10\n", "error.geo_unknown_crs")]+ public async Task Csv_that_cannot_give_locations_is_refused_with_the_reason(string csv, string expectedKey)+ {+ var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bad.csv", csv), "geojson");+ Assert.Equal(expectedKey, key);+ }++ [Fact]+ public async Task Csv_with_an_invalid_wkt_cell_names_the_row()+ {+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "badwkt.csv", "id,wkt\n1,POINT (1 2)\n2,POINT (oops)\n"), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.Contains("Row 3", detail);+ }++ [Fact]+ public async Task Csv_output_is_longitude_latitude_columns_for_points_and_wkt_otherwise()+ {+ var points = File.ReadAllText((await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_points", "geojson"), "csv")).Single()).TrimStart('\uFEFF');+ Assert.StartsWith("longitude,latitude,name,n\r\n10.5,20.25,A,1\r\n-5,40,B,2\r\n", points);++ var polygons = File.ReadAllText((await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_polygons", "shp"), "csv")).Single()).TrimStart('\uFEFF');+ Assert.StartsWith("wkt,id,label\r\n", polygons);+ Assert.Contains("\"POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (2 2, 2 4, 4 4, 4 2, 2 2))\",1,with hole", polygons);+ }++ [Fact]+ public async Task Csv_output_uses_wkt_when_an_attribute_is_already_called_longitude_so_it_reads_back_unchanged()+ {+ var text = """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"LONGITUDE":111.0,"LATITUDE":222.0,"n":1},"geometry":{"type":"Point","coordinates":[1,2]}}]}""";+ var csv = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "attrs.geojson", text), "csv")).Single();+ Assert.StartsWith("wkt,LONGITUDE,LATITUDE,n", File.ReadAllText(csv).TrimStart('\uFEFF'));+ using var doc = await ToGeoJsonAsync(csv);+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(Features(doc)[0].GetProperty("geometry")));+ Assert.Equal(111, Features(doc)[0].GetProperty("properties").GetProperty("LONGITUDE").GetInt64());+ }++ [Fact]+ public async Task Csv_output_quotes_commas_quotes_and_line_breaks()+ {+ var text = "{\"type\":\"Feature\",\"properties\":{\"t\":\"a,b \\\"c\\\"\\nd\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[1,2]}}";+ var csv = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "quote.geojson", text), "csv")).Single();+ using var doc = await ToGeoJsonAsync(csv);+ Assert.Equal("a,b \"c\"\nd", Features(doc)[0].GetProperty("properties").GetProperty("t").GetString());+ }++ // ---- Empty and degenerate input ----++ [Theory]+ [InlineData("""{"type":"FeatureCollection","features":[]}""", "geojson")]+ [InlineData("""<kml><Document/></kml>""", "kml")]+ [InlineData("""<gpx/>""", "gpx")]+ public async Task A_file_with_no_features_is_refused_with_a_clear_reason(string text, string extension)+ {+ var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "empty." + extension, text), extension == "geojson" ? "kml" : "geojson");+ Assert.Equal("error.geo_empty", key);+ }++ [Theory]+ [InlineData(" ")]+ [InlineData("[1,2,3]")]+ [InlineData("""{"a":1}""")]+ [InlineData("""{"type":"FeatureCollection"}""")]+ [InlineData("""{"type":"Banana","coordinates":[1,2]}""")]+ [InlineData("""{"type":"Point"}""")]+ [InlineData("""{"type":"Point","coordinates":"x"}""")]+ [InlineData("""{"type":"Point","coordinates":[1]}""")]+ [InlineData("""{"type":"Point","coordinates":["a","b"]}""")]+ [InlineData("""{"type":"Polygon","coordinates":[1]}""")]+ [InlineData("""{"type":"FeatureCollection","features":[1]}""")]+ [InlineData("{\"type\":\"Point\",\"coordinates\":[1,2")]+ public async Task GeoJson_that_is_not_geojson_fails_with_a_reason(string text)+ {+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bad.geojson", text), "kml");+ Assert.Equal("error.conversion_failed", key);+ Assert.NotEmpty(detail);+ }++ [Fact]+ public async Task GeoJson_nested_far_too_deep_fails_instead_of_overflowing_the_stack()+ {+ var text = string.Concat(Enumerable.Repeat("[", 100_000)) + string.Concat(Enumerable.Repeat("]", 100_000));+ var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "deep.geojson", text), "kml");+ Assert.Equal("error.conversion_failed", key);+ }+}diff --git a/tests/Filee.Engines.Tests/GeoRobustnessTests.cs b/tests/Filee.Engines.Tests/GeoRobustnessTests.csnew file mode 100644index 00000000..a8153fac--- /dev/null+++ b/tests/Filee.Engines.Tests/GeoRobustnessTests.cs@@ -0,0 +1,295 @@+// What happens to files that are damaged, hostile or odd: every reference file truncated at every length and with+// random bytes changed must be read or refused with a reason (never crash, hang or allocate wildly), XML that tries to+// read files or expand entities is refused, names with brackets and Korean text work, several files in one job get+// their own consistent names, and a cancelled conversion stops.++using System.Diagnostics;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Geo;++namespace Filee.Engines.Tests;++public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private const string CsvSample = "id,name,lat,lon\n1,\"A, b\",48.85,2.35\n2,C,,\n3,D,51.5,-0.12\n";++ /// <summary>Reads <paramref name="path"/> with the reader of its format; only a refusal or a reason is allowed to come out.</summary>+ private static void ReadOrRefuse(string path)+ {+ try+ {+ var extension = Path.GetExtension(path).TrimStart('.').ToLowerInvariant();+ _ = extension switch+ {+ "geojson" => GeoJsonFormat.Read(path, CancellationToken.None),+ "kml" => KmlFormat.Read(path, zipped: false, CancellationToken.None),+ "kmz" => KmlFormat.Read(path, zipped: true, CancellationToken.None),+ "gpx" => GpxFormat.Read(path, CancellationToken.None),+ "shp" => ShapefileFormat.Read(path, CancellationToken.None),+ "csv" => GeoCsvFormat.Read(path, CancellationToken.None),+ _ => throw new NotSupportedException(extension),+ };+ }+ catch (Exception ex) when (ex is InvalidDataException or ConversionRefusedException)+ {+ }+ }++ private static string CopyFolder(string from, string to)+ {+ Directory.CreateDirectory(to);+ foreach (var file in Directory.EnumerateFiles(from))+ File.Copy(file, Path.Combine(to, Path.GetFileName(file)), overwrite: true);+ return to;+ }++ /// <summary>Truncates and corrupts the file <paramref name="target"/> of a copied reference set and reads <paramref name="main"/> each time.</summary>+ private void Fuzz(string set, string main, string target, int seed, int mutations = 120)+ {+ var original = Path.Combine(GeoFixtures.Folder, set + "." + target);+ var bytes = File.ReadAllBytes(original);+ var folder = CopyFolder(GeoFixtures.Folder, fx.NewFolder());+ var mainPath = Path.Combine(folder, set + "." + main);+ var targetPath = Path.Combine(folder, set + "." + target);++ var lengths = bytes.Length <= 400 ? Enumerable.Range(0, bytes.Length) : Enumerable.Range(0, 400).Select(i => i * bytes.Length / 400);+ foreach (var length in lengths)+ {+ File.WriteAllBytes(targetPath, bytes[..length]);+ ReadOrRefuse(mainPath);+ }+ var random = new Random(seed);+ for (var i = 0; i < mutations; i++)+ {+ var copy = (byte[])bytes.Clone();+ for (var change = random.Next(1, 5); change > 0; change--)+ copy[random.Next(copy.Length)] = (byte)random.Next(256);+ File.WriteAllBytes(targetPath, copy);+ ReadOrRefuse(mainPath);+ }+ }++ [Theory]+ [InlineData("gdal_points", "shp", "shp")]+ [InlineData("gdal_points", "shp", "dbf")]+ [InlineData("gdal_points", "shp", "prj")]+ [InlineData("gdal_points", "shp", "cpg")]+ [InlineData("gdal_polygons", "shp", "shp")]+ [InlineData("gdal_polygons", "shp", "dbf")]+ [InlineData("gdal_linesz", "shp", "shp")]+ [InlineData("gdal_utm33", "shp", "shp")]+ [InlineData("gdal_utm33", "shp", "prj")]+ [InlineData("gdal_points", "geojson", "geojson")]+ [InlineData("gdal_points", "kml", "kml")]+ [InlineData("gdal_waypoints", "gpx", "gpx")]+ public void Damaged_reference_files_are_read_or_refused_never_a_crash(string set, string main, string target)+ {+ var watch = Stopwatch.StartNew();+ Fuzz(set, main, target, seed: set.Length * 31 + target.Length);+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(60), $"took {watch.Elapsed}");+ }++ [Theory]+ [InlineData("kml")]+ [InlineData("gpx")]+ [InlineData("csv")]+ [InlineData("kmz")]+ public void Damaged_hand_written_files_are_read_or_refused_never_a_crash(string format)+ {+ var folder = fx.NewFolder();+ byte[] original;+ if (format == "kmz")+ {+ var path = Path.Combine(folder, "o.kmz");+ using (var zip = System.IO.Compression.ZipFile.Open(path, System.IO.Compression.ZipArchiveMode.Create))+ using (var writer = new StreamWriter(zip.CreateEntry("doc.kml").Open()))+ writer.Write(GeoFormatTests.KmlSample);+ original = File.ReadAllBytes(path);+ }+ else+ {+ original = Encoding.UTF8.GetBytes(format switch { "kml" => GeoFormatTests.KmlSample, "gpx" => GeoFormatTests.GpxSample, _ => CsvSample });+ }+ var target = Path.Combine(folder, "damaged." + format);+ for (var length = 0; length < original.Length; length += Math.Max(1, original.Length / 250))+ {+ File.WriteAllBytes(target, original[..length]);+ ReadOrRefuse(target);+ }+ var random = new Random(3);+ for (var i = 0; i < 200; i++)+ {+ var copy = (byte[])original.Clone();+ for (var change = random.Next(1, 6); change > 0; change--)+ copy[random.Next(copy.Length)] = (byte)random.Next(256);+ File.WriteAllBytes(target, copy);+ ReadOrRefuse(target);+ }+ }++ [Fact]+ public void Random_bytes_in_every_format_are_refused()+ {+ var random = new Random(9);+ var folder = fx.NewFolder();+ foreach (var extension in new[] { "shp", "geojson", "kml", "kmz", "gpx", "csv" })+ {+ for (var i = 0; i < 40; i++)+ {+ var bytes = new byte[random.Next(0, 3000)];+ random.NextBytes(bytes);+ var path = Path.Combine(folder, "random." + extension);+ File.WriteAllBytes(path, bytes);+ ReadOrRefuse(path);+ }+ }+ }++ // ---- Hostile XML ----++ [Fact]+ public async Task Xml_that_asks_to_read_a_local_file_is_refused_and_nothing_of_the_file_reaches_the_output()+ {+ var secret = Path.Combine(fx.NewFolder(), "secret.txt");+ File.WriteAllText(secret, "TOP-SECRET-VALUE");+ var uri = new Uri(secret).AbsoluteUri;+ var kml = $"""<?xml version="1.0"?><!DOCTYPE kml [<!ENTITY leak SYSTEM "{uri}">]><kml><Placemark><name>&leak;</name><Point><coordinates>1,2</coordinates></Point></Placemark></kml>""";+ var gpx = $"""<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY leak SYSTEM "{uri}">]><gpx><wpt lat="1" lon="2"><name>&leak;</name></wpt></gpx>""";+ foreach (var (name, text) in new[] { ("evil.kml", kml), ("evil.gpx", gpx) })+ {+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, name, text), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.DoesNotContain("TOP-SECRET-VALUE", detail);+ }+ }++ [Fact]+ public async Task An_entity_bomb_is_refused_quickly()+ {+ var builder = new StringBuilder("""<?xml version="1.0"?><!DOCTYPE kml [<!ENTITY a0 "lol">""");+ for (var i = 1; i < 10; i++)+ builder.Append($"<!ENTITY a{i} \"{string.Concat(Enumerable.Repeat($"&a{i - 1};", 10))}\">");+ builder.Append("]><kml><Placemark><name>&a9;</name><Point><coordinates>1,2</coordinates></Point></Placemark></kml>");+ var watch = Stopwatch.StartNew();+ var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bomb.kml", builder.ToString()), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(5), $"took {watch.Elapsed}");+ }++ // ---- Names, parallel files, cancellation ----++ [Fact]+ public async Task File_names_with_brackets_spaces_and_korean_text_find_their_sidecars_and_make_matching_outputs()+ {+ var folder = fx.NewFolder();+ foreach (var file in Directory.EnumerateFiles(GeoFixtures.Folder, "gdal_points.*").Where(f => !f.EndsWith(".geojson") && !f.EndsWith(".kml")))+ File.Copy(file, Path.Combine(folder, "서울 [data] (1)" + Path.GetExtension(file)));+ var files = await fx.ConvertOkAsync(Path.Combine(folder, "서울 [data] (1).shp"), "shp");+ Assert.Equal(5, files.Count);+ Assert.All(files, f => Assert.StartsWith("서울 [data] (1) (2).", Path.GetFileName(f)));+ var geojson = (await fx.ConvertOkAsync(files.First(f => f.EndsWith(".shp")), "geojson")).Single();+ using var doc = GeoFixtures.ReadJson(geojson);+ Assert.Equal("서울 City Hall", doc.RootElement.GetProperty("features")[0].GetProperty("properties").GetProperty("name").GetString());+ }++ [Fact]+ public async Task Files_of_one_job_that_would_get_the_same_output_name_get_separate_consistent_sets()+ {+ var folder = fx.NewFolder();+ const string point = """{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[1,2]}}""";+ var a = Path.Combine(folder, "same.geojson");+ File.WriteAllText(a, point);+ var b = Path.Combine(folder, "same.kml");+ File.WriteAllText(b, "<kml><Placemark><Point><coordinates>3,4</coordinates></Point></Placemark></kml>");+ var c = Path.Combine(folder, "same.gpx");+ File.WriteAllText(c, """<gpx><wpt lat="6" lon="5"/></gpx>""");+ var job = await fx.ConvertAsync([a, b, c], new Preset { TargetFormat = "shp" });+ Assert.True(job.State == JobState.Completed, GeoFixtures.Describe(job));+ var outputs = job.Outputs.ToList();+ Assert.Equal(15, outputs.Count);+ Assert.Equal(15, outputs.Distinct().Count());+ var sets = outputs.GroupBy(o => Path.GetFileNameWithoutExtension(o)).ToList();+ Assert.Equal(3, sets.Count);+ Assert.All(sets, g => Assert.Equal(["cpg", "dbf", "prj", "shp", "shx"], g.Select(f => Path.GetExtension(f)[1..]).Order().ToArray()));+ }++ [Fact]+ public async Task Many_files_convert_in_parallel_without_mixing_up_their_outputs()+ {+ var folder = fx.NewFolder();+ var sources = new List<string>();+ for (var i = 0; i < 24; i++)+ {+ var path = Path.Combine(folder, $"file{i:00}.geojson");+ File.WriteAllText(path, PointJson(i, i, i));+ sources.Add(path);+ }+ var job = await fx.ConvertAsync(sources, new Preset { TargetFormat = "kml" });+ Assert.True(job.State == JobState.Completed, GeoFixtures.Describe(job));+ foreach (var file in job.Files)+ {+ var index = int.Parse(Path.GetFileNameWithoutExtension(file.SourcePath)[4..]);+ Assert.Contains($"{index},{index}", File.ReadAllText(file.Outputs.Single()));+ }+ }++ [Fact]+ public async Task A_conversion_that_is_cancelled_stops_and_leaves_nothing_behind()+ {+ var converter = new GeoConverter();+ var folder = fx.NewFolder();+ var input = Path.Combine(folder, "big.geojson");+ var features = string.Join(',', Enumerable.Range(0, 20000).Select(i => PointJson(i, i % 180, i % 90)));+ File.WriteAllText(input, $$"""{"type":"FeatureCollection","features":[{{features}}]}""");+ using var cts = new CancellationTokenSource();+ cts.Cancel();+ var output = new FixedAllocator(folder);+ var step = new ConversionStep(input, "geojson", "shp", new Preset(), output, folder);+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => converter.ConvertAsync(step, null, cts.Token));+ Assert.Equal(["big.geojson"], Directory.GetFiles(folder).Select(f => Path.GetFileName(f)!).ToArray());+ }++ [Fact]+ public async Task Cancelling_while_the_file_is_written_removes_the_partial_files()+ {+ var converter = new GeoConverter();+ var folder = fx.NewFolder();+ var input = Path.Combine(folder, "big.geojson");+ var features = string.Join(',', Enumerable.Range(0, 60000).Select(PolygonJson));+ File.WriteAllText(input, $$"""{"type":"FeatureCollection","features":[{{features}}]}""");+ using var cts = new CancellationTokenSource();+ var output = new FixedAllocator(folder, onAllocate: () => cts.CancelAfter(1));+ var step = new ConversionStep(input, "geojson", "shp", new Preset(), output, folder);+ try+ {+ await converter.ConvertAsync(step, null, cts.Token);+ }+ catch (OperationCanceledException)+ {+ Assert.Equal(["big.geojson"], Directory.GetFiles(folder).Select(f => Path.GetFileName(f)!).ToArray());+ }+ // (If the machine was fast enough to finish within a millisecond, nothing was cancelled and there is nothing to check.)+ }++ private static string PointJson(int i, int x, int y) =>+ "{\"type\":\"Feature\",\"properties\":{\"i\":" + i + "},\"geometry\":{\"type\":\"Point\",\"coordinates\":[" + x + "," + y + "]}}";++ private static string PolygonJson(int i)+ {+ var width = i % 90 + 1;+ var height = i % 45 + 1;+ return "{\"type\":\"Feature\",\"properties\":{\"i\":" + i + ",\"t\":\"text " + i + "\"},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[0,0],["+ + width + ",0],[" + width + "," + height + "],[0,0]]]}}";+ }++ private sealed class FixedAllocator(string folder, Action? onAllocate = null) : IOutputAllocator+ {+ public string? Allocate(string extension, string? suffix = null)+ {+ onAllocate?.Invoke();+ return Path.Combine(folder, "out" + suffix + "." + extension);+ }+ }+}diff --git a/tests/Filee.Engines.Tests/GeoShapefileTests.cs b/tests/Filee.Engines.Tests/GeoShapefileTests.csnew file mode 100644index 00000000..35fb6285--- /dev/null+++ b/tests/Filee.Engines.Tests/GeoShapefileTests.cs@@ -0,0 +1,787 @@+// Shapefile in and out. Reading: polygons and holes in every arrangement real files have, shape types, dBASE types and+// encodings, deleted rows, the .prj rules and damaged files. Writing: the files are parsed here from the ESRI+// specification rather than read back with the engine, so the header, index, attribute table and ring directions are+// checked independently; field names and text that don't fit; files split by geometry kind; and name collisions.++using System.Buffers.Binary;+using System.Globalization;+using System.Text;+using System.Text.Json;+using Filee.Core.Conversion;+using Filee.Core.Presets;++namespace Filee.Engines.Tests;++public class GeoShapefileTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ static GeoShapefileTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);++ private const string Wgs84Prj = """GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""";++ // Shapefile rings: outer clockwise, holes counter-clockwise.+ private static (double X, double Y)[] Outer(double min, double max) => [(min, min), (min, max), (max, max), (max, min), (min, min)];++ private static (double X, double Y)[] Hole(double min, double max) => [(min, min), (max, min), (max, max), (min, max), (min, min)];++ private string NewShapefile(ShapefileBuilder builder, string? prj = Wgs84Prj, DbfBuilder? dbf = null)+ {+ var folder = fx.NewFolder();+ return builder.Save(folder, "data", prj, dbf);+ }++ private async Task<JsonDocument> GeoJsonAsync(string shp)+ {+ var output = (await fx.ConvertOkAsync(shp, "geojson")).Single();+ return GeoFixtures.ReadJson(output);+ }++ private static JsonElement Geometry(JsonDocument doc, int index = 0) => doc.RootElement.GetProperty("features")[index].GetProperty("geometry");++ private static string Type(JsonElement geometry) => geometry.ValueKind == JsonValueKind.Null ? "null" : geometry.GetProperty("type").GetString()!;++ private static int Rings(JsonElement polygon) => polygon.GetProperty("coordinates").GetArrayLength();++ // ---- Reading polygons ----++ [Fact]+ public async Task A_hole_counter_clockwise_inside_an_outer_ring_clockwise_is_one_polygon()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, Outer(0, 10), Hole(2, 4))));+ Assert.Equal("Polygon", Type(Geometry(doc)));+ Assert.Equal(2, Rings(Geometry(doc)));+ }++ [Fact]+ public async Task Holes_are_given_to_the_outer_ring_that_contains_them_whatever_the_order_of_the_parts()+ {+ var a = Outer(0, 10);+ var b = Outer(20, 30);+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, a, b, Hole(22, 24), Hole(2, 4), Hole(6, 8))));+ var geometry = Geometry(doc);+ Assert.Equal("MultiPolygon", Type(geometry));+ var polygons = geometry.GetProperty("coordinates").EnumerateArray().ToList();+ Assert.Equal(2, polygons.Count);+ Assert.Equal(3, polygons[0].GetArrayLength()); // outer 0..10 with two holes+ Assert.Equal(2, polygons[1].GetArrayLength()); // outer 20..30 with one+ }++ [Fact]+ public async Task An_island_inside_a_hole_is_a_polygon_of_its_own()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, Outer(0, 80), Hole(10, 70), Outer(30, 50))));+ var polygons = Geometry(doc).GetProperty("coordinates").EnumerateArray().ToList();+ Assert.Equal(2, polygons.Count);+ Assert.Equal(2, polygons[0].GetArrayLength());+ Assert.Equal(1, polygons[1].GetArrayLength());+ }++ [Fact]+ public async Task A_hole_outside_every_outer_ring_is_kept_as_a_ring_of_its_own()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, Outer(0, 10), Hole(50, 60))));+ Assert.Equal("MultiPolygon", Type(Geometry(doc)));+ Assert.Equal(2, Geometry(doc).GetProperty("coordinates").GetArrayLength());+ }++ [Fact]+ public async Task When_every_ring_runs_counter_clockwise_they_are_all_outer_rings()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, Hole(0, 10), Hole(20, 30))));+ Assert.Equal("MultiPolygon", Type(Geometry(doc)));+ Assert.Equal(2, Geometry(doc).GetProperty("coordinates").GetArrayLength());+ }++ [Fact]+ public async Task Open_degenerate_and_zero_area_rings_are_repaired_or_dropped()+ {+ var open = new (double X, double Y)[] { (0, 0), (0, 10), (10, 10), (10, 0) };+ var twoPoints = new (double X, double Y)[] { (50, 50), (60, 60) };+ var flat = new (double X, double Y)[] { (70, 70), (80, 70), (90, 70), (70, 70) };+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, open, twoPoints, flat)));+ Assert.Equal("Polygon", Type(Geometry(doc)));+ Assert.Equal(1, Rings(Geometry(doc)));+ Assert.Equal(5, Geometry(doc).GetProperty("coordinates")[0].GetArrayLength());+ }++ [Fact]+ public async Task A_polygon_with_only_degenerate_rings_has_no_geometry()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(5).Parts(5, [(1, 1), (2, 2)])));+ Assert.Equal("null", Type(Geometry(doc)));+ }++ // ---- Reading other shape types ----++ [Fact]+ public async Task Points_multipoints_lines_and_null_shapes_are_read()+ {+ using (var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(8).MultiPoint((1, 2), (3, 4)).MultiPoint((5, 6)))))+ {+ Assert.Equal("MultiPoint", Type(Geometry(doc, 0)));+ Assert.Equal("Point", Type(Geometry(doc, 1)));+ }+ using (var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(3).Parts(3, [(0, 0), (1, 1)], [(5, 5), (6, 6), (7, 5)], [(9, 9)]).Null())))+ {+ Assert.Equal("MultiLineString", Type(Geometry(doc, 0)));+ Assert.Equal(2, Geometry(doc, 0).GetProperty("coordinates").GetArrayLength()); // the one-point part is dropped+ Assert.Equal("null", Type(Geometry(doc, 1)));+ }+ }++ [Fact]+ public async Task PointZ_height_is_kept_and_no_data_is_not_a_height()+ {+ var folder = fx.NewFolder();+ var withZ = new ShapefileBuilder(11).PointZ(1, 2, 345.5).Save(folder, "z", Wgs84Prj);+ using var doc = await GeoJsonAsync(withZ);+ Assert.Equal([1.0, 2.0, 345.5], GeoFixtures.Position(Geometry(doc)));++ var noData = new ShapefileBuilder(11).PointZ(1, 2, -1e39).Save(fx.NewFolder(), "nz", Wgs84Prj);+ using var doc2 = await GeoJsonAsync(noData);+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(Geometry(doc2)));+ }++ [Fact]+ public async Task An_empty_point_written_as_NaN_has_no_geometry()+ {+ var nan = ShapefileBuilder.Le(1).Concat(ShapefileBuilder.Dbl(double.NaN)).Concat(ShapefileBuilder.Dbl(double.NaN)).ToArray();+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Raw(nan)));+ Assert.Equal("null", Type(Geometry(doc)));+ }++ // ---- The attribute table ----++ [Fact]+ public async Task Dbf_field_types_are_read_as_text_numbers_booleans_and_dates()+ {+ var dbf = new DbfBuilder()+ .Field("NAME", 'C', 10).Field("N0", 'N', 5).Field("N3", 'N', 10, 3).Field("F2", 'F', 8, 2)+ .Field("FLAG", 'L', 1).Field("DAY", 'D', 8).Field("MEMO", 'M', 10).Field("NEG", 'N', 6, 1)+ .Row("abc", " 42", " 1.500", " 3.14", "T", "20240229", "0000000001", " -2.5")+ .Row("", "", "", "", "?", "20241399", "", "*****")+ .Row("ünï", "12.0", "0", " -0.5", "n", " ", "", " 0.0");+ var builder = new ShapefileBuilder(1).Point(1, 1).Point(2, 2).Point(3, 3);+ using var doc = await GeoJsonAsync(NewShapefile(builder, dbf: dbf));+ var rows = doc.RootElement.GetProperty("features").EnumerateArray().Select(f => f.GetProperty("properties")).ToList();++ Assert.Equal("abc", rows[0].GetProperty("NAME").GetString());+ Assert.Equal(42, rows[0].GetProperty("N0").GetInt64());+ Assert.Equal(1.5, rows[0].GetProperty("N3").GetDouble());+ Assert.Equal(3.14, rows[0].GetProperty("F2").GetDouble());+ Assert.True(rows[0].GetProperty("FLAG").GetBoolean());+ Assert.Equal("2024-02-29", rows[0].GetProperty("DAY").GetString());+ Assert.Equal(JsonValueKind.Null, rows[0].GetProperty("MEMO").ValueKind);+ Assert.Equal(-2.5, rows[0].GetProperty("NEG").GetDouble());++ Assert.Equal("", rows[1].GetProperty("NAME").GetString());+ Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("N0").ValueKind);+ Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("N3").ValueKind);+ Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("FLAG").ValueKind);+ Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("DAY").ValueKind);+ Assert.Equal(JsonValueKind.Null, rows[1].GetProperty("NEG").ValueKind);++ Assert.Equal(12, rows[2].GetProperty("N0").GetInt64());+ Assert.False(rows[2].GetProperty("FLAG").GetBoolean());+ Assert.Equal(-0.5, rows[2].GetProperty("F2").GetDouble());+ }++ [Fact]+ public async Task Rows_marked_as_deleted_in_the_dbf_are_left_out()+ {+ var dbf = new DbfBuilder().Field("ID", 'N', 3).Row("1").Row(true, "2").Row("3");+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2).Point(3, 3), dbf: dbf));+ var ids = doc.RootElement.GetProperty("features").EnumerateArray().Select(f => f.GetProperty("properties").GetProperty("ID").GetInt64()).ToArray();+ Assert.Equal([1L, 3L], ids);+ }++ [Fact]+ public async Task A_shapefile_without_a_dbf_converts_with_no_attributes()+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Point(1, 1)));+ Assert.Empty(doc.RootElement.GetProperty("features")[0].GetProperty("properties").EnumerateObject());+ }++ [Fact]+ public async Task A_dbf_with_more_rows_than_shapes_is_used_and_one_with_fewer_is_refused()+ {+ var more = new DbfBuilder().Field("ID", 'N', 3).Row("1").Row("2").Row("3");+ using (var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2), dbf: more)))+ Assert.Equal(2, doc.RootElement.GetProperty("features").GetArrayLength());++ var fewer = new DbfBuilder().Field("ID", 'N', 3).Row("1");+ var (key, detail) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2), dbf: fewer), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.Contains("1 rows but the .shp has 2", detail);+ }++ [Theory]+ // text, code page of the bytes, language driver byte, .cpg text (null = no .cpg file)+ [InlineData("서울특별시 종로구", 949, (byte)0x4E, null)]+ [InlineData("서울특별시 종로구", 949, (byte)0, "949")]+ [InlineData("서울특별시 종로구", 949, (byte)0, "CP949")]+ [InlineData("서울특별시 종로구", 949, (byte)0, null)] // told by nothing: not UTF-8, valid CP949+ [InlineData("서울 Ünïcödé 北京", 65001, (byte)0, "UTF-8")]+ [InlineData("서울 Ünïcödé 北京", 65001, (byte)0, null)] // told by nothing: valid UTF-8+ [InlineData("Müller – Café", 1252, (byte)0x57, null)]+ [InlineData("Müller – Café", 1252, (byte)0x03, null)]+ [InlineData("Müller – Café", 1252, (byte)0, "1252")]+ [InlineData("Müller", 1252, (byte)0, "ISO-8859-1")]+ [InlineData("Müller", 1252, (byte)0, "LATIN1")]+ [InlineData("Müller", 1252, (byte)0, null)] // told by nothing: neither UTF-8 nor CP949+ [InlineData("北京市朝阳区", 936, (byte)0x4D, null)]+ [InlineData("北京市朝阳区", 936, (byte)0, "GBK")]+ [InlineData("日本語テキスト", 932, (byte)0x13, null)]+ [InlineData("Привет мир", 1251, (byte)0xC9, null)]+ [InlineData("Привет мир", 1251, (byte)0, "windows-1251")]+ public async Task Text_is_decoded_with_the_cpg_the_language_driver_or_by_detection(string text, int codePage, byte driver, string? cpg)+ {+ var encoding = Encoding.GetEncoding(codePage);+ if (codePage == 1252)+ text = text.Replace("–", "-", StringComparison.Ordinal); // not every character exists in every code page+ var dbf = new DbfBuilder { Encoding = encoding, LanguageDriver = driver }.Field("NAME", 'C', 40).Row(text);+ var folder = fx.NewFolder();+ var shp = new ShapefileBuilder(1).Point(1, 1).Save(folder, "enc", Wgs84Prj, dbf);+ if (cpg is not null)+ File.WriteAllText(Path.Combine(folder, "enc.cpg"), cpg);+ using var doc = await GeoJsonAsync(shp);+ Assert.Equal(text, doc.RootElement.GetProperty("features")[0].GetProperty("properties").GetProperty("NAME").GetString());+ }++ [Fact]+ public async Task Sidecar_files_are_found_whatever_the_letter_case()+ {+ var folder = fx.NewFolder();+ new ShapefileBuilder(1).Point(1, 2).Save(folder, "mixed", Wgs84Prj, new DbfBuilder().Field("ID", 'N', 3).Row("7"));+ File.Move(Path.Combine(folder, "mixed.dbf"), Path.Combine(folder, "mixed.DBF"));+ File.Move(Path.Combine(folder, "mixed.prj"), Path.Combine(folder, "mixed.Prj"));+ using var doc = await GeoJsonAsync(Path.Combine(folder, "mixed.shp"));+ Assert.Equal(7, doc.RootElement.GetProperty("features")[0].GetProperty("properties").GetProperty("ID").GetInt64());+ }++ // ---- Coordinate systems ----++ [Fact]+ public async Task Prj_with_a_projection_converts_the_positions_and_a_bom_or_newline_does_not_matter()+ {+ // Vienna in UTM 33N.+ const string utm = """PROJCS["WGS_1984_UTM_Zone_33N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",15.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""";+ foreach (var prj in new[] { utm, "" + utm + "\r\n", utm + "\n\n" })+ {+ using var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Point(602065.2074110014, 5340353.594303575), prj));+ var position = GeoFixtures.Position(Geometry(doc));+ Assert.Equal(16.3738, position[0], 8);+ Assert.Equal(48.2082, position[1], 8);+ }+ }++ [Fact]+ public async Task No_prj_is_fine_for_degrees_and_refused_for_anything_else()+ {+ using (var doc = await GeoJsonAsync(NewShapefile(new ShapefileBuilder(1).Point(16.37, 48.2), prj: null)))+ Assert.Equal([16.37, 48.2], GeoFixtures.Position(Geometry(doc)));+ var (key, _) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(1).Point(602065.2, 5340353.6), prj: null), "geojson");+ Assert.Equal("error.geo_unknown_crs", key);+ }++ [Fact]+ public async Task A_projection_filee_cannot_convert_is_refused_naming_it()+ {+ const string laea = """PROJCS["ETRS89_LAEA_Europe",GEOGCS["GCS_ETRS_1989",DATUM["D_ETRS_1989",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["False_Easting",4321000.0],PARAMETER["False_Northing",3210000.0],PARAMETER["Central_Meridian",10.0],PARAMETER["Latitude_Of_Origin",52.0],UNIT["Meter",1.0]]""";+ var (key, detail) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(1).Point(4321000, 3210000), laea), "geojson");+ Assert.Equal("error.geo_unsupported_crs", key);+ Assert.Contains("ETRS89_LAEA_Europe", detail);+ var (garbage, _) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(1).Point(1, 1), "hello"), "geojson");+ Assert.Equal("error.geo_unsupported_crs", garbage);+ }++ [Fact]+ public async Task A_position_far_outside_where_the_projection_works_is_refused_instead_of_placed_somewhere()+ {+ const string utm = """PROJCS["WGS_1984_UTM_Zone_33N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",15.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""";+ var (key, _) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(1).Point(5e9, 5e9), utm), "geojson");+ Assert.Equal("error.geo_bad_coordinates", key);+ }++ [Fact]+ public async Task A_datum_that_is_not_shifted_leaves_a_note_on_the_file()+ {+ const string dhdn = """PROJCS["DHDN_3_Degree_Gauss_Zone_3",GEOGCS["GCS_Deutsches_Hauptdreiecksnetz",DATUM["D_Deutsches_Hauptdreiecksnetz",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",3500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",9.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]""";+ var job = await fx.ConvertAsync(NewShapefile(new ShapefileBuilder(1).Point(3500000, 5400000), dhdn), "geojson");+ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal("notice.geo_datum_assumed", job.Files.Single().NoticeKey);+ }++ // ---- Damaged and unsupported files ----++ [Fact]+ public async Task MultiPatch_is_refused_by_name()+ {+ var folder = fx.NewFolder();+ var shp = new ShapefileBuilder(31).Raw(ShapefileBuilder.Le(31).Concat(new byte[60]).ToArray()).Save(folder, "patch", Wgs84Prj);+ var (key, detail) = await fx.ConvertFailsAsync(shp, "geojson");+ Assert.Equal("error.geo_unsupported_shape", key);+ Assert.Contains("MultiPatch", detail);+ }++ [Fact]+ public async Task Damaged_shp_files_fail_with_a_reason_for_the_user()+ {+ var good = NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2));+ var bytes = File.ReadAllBytes(good);++ (string Name, byte[] Data, string Expect)[] cases =+ [+ ("short1", bytes[..1], "shapefile header"),+ ("short", bytes[..60], "shapefile header"),+ ("magic", [.. bytes.Select((b, i) => i == 3 ? (byte)0 : b)], "shapefile header"),+ ("cut", bytes[..^7], "cut off"),+ ("type", [.. bytes.Select((b, i) => i == 32 ? (byte)99 : b)], "unknown shape type"),+ ];+ foreach (var (name, data, expect) in cases)+ {+ var path = Path.Combine(fx.NewFolder(), name + ".shp");+ File.WriteAllBytes(path, data);+ var (key, detail) = await fx.ConvertFailsAsync(path, "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.Contains(expect, detail);+ }+ }++ [Fact]+ public async Task Counts_and_part_indexes_that_do_not_fit_the_record_are_refused_without_allocating()+ {+ var record = new List<byte>();+ record.AddRange(ShapefileBuilder.Le(5));+ record.AddRange(new byte[32]);+ record.AddRange(ShapefileBuilder.Le(int.MaxValue)); // parts+ record.AddRange(ShapefileBuilder.Le(int.MaxValue)); // points+ var (key, detail) = await fx.ConvertFailsAsync(NewShapefile(new ShapefileBuilder(5).Raw([.. record])), "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.Contains("do not fit", detail);++ var badPart = new ShapefileBuilder(5).Parts(5, Outer(0, 10));+ var shp = NewShapefile(badPart);+ var bytes = File.ReadAllBytes(shp);+ BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(100 + 8 + 44), 99); // the first part starts after the last point+ File.WriteAllBytes(shp, bytes);+ var (_, partDetail) = await fx.ConvertFailsAsync(shp, "geojson");+ Assert.Contains("starts outside", partDetail);+ }++ [Fact]+ public async Task A_wrong_length_in_the_header_does_not_hide_the_shapes_or_make_the_file_fail()+ {+ var shp = NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2));+ var bytes = File.ReadAllBytes(shp);+ BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(24), 1_000_000); // claims far more than the file holds+ File.WriteAllBytes(shp, bytes);+ using (var doc = await GeoJsonAsync(shp))+ Assert.Equal(2, doc.RootElement.GetProperty("features").GetArrayLength());++ // Trailing bytes after the declared length (some tools pad the file) are ignored.+ var padded = NewShapefile(new ShapefileBuilder(1).Point(1, 1));+ File.WriteAllBytes(padded, [.. File.ReadAllBytes(padded), .. new byte[5]]);+ using var doc2 = await GeoJsonAsync(padded);+ Assert.Equal(1, doc2.RootElement.GetProperty("features").GetArrayLength());+ }++ [Fact]+ public async Task A_damaged_dbf_fails_with_a_reason()+ {+ var dbf = new DbfBuilder().Field("ID", 'N', 3).Row("1");+ var shp = NewShapefile(new ShapefileBuilder(1).Point(1, 1), dbf: dbf);+ var dbfPath = Path.ChangeExtension(shp, "dbf");+ var good = File.ReadAllBytes(dbfPath);++ (string Name, byte[] Data, string Expect)[] cases =+ [+ ("tiny", good[..10], "too short"),+ ("header", [.. good.Select((b, i) => i is 8 or 9 ? (byte)0 : b)], "damaged"),+ ("fields", [.. good.Select((b, i) => i == 10 ? (byte)1 : b)], "do not fit"),+ ];+ foreach (var (name, data, expect) in cases)+ {+ File.WriteAllBytes(dbfPath, data);+ var (key, detail) = await fx.ConvertFailsAsync(shp, "geojson");+ Assert.Equal("error.conversion_failed", key);+ Assert.Contains(expect, detail);+ }+ }++ [Fact]+ public async Task A_dbf_that_ends_early_gives_the_rows_that_are_there_and_then_a_mismatch_error()+ {+ var dbf = new DbfBuilder().Field("ID", 'N', 3).Row("1").Row("2").Row("3");+ var shp = NewShapefile(new ShapefileBuilder(1).Point(1, 1).Point(2, 2).Point(3, 3), dbf: dbf);+ var path = Path.ChangeExtension(shp, "dbf");+ File.WriteAllBytes(path, File.ReadAllBytes(path)[..^5]); // cuts the end marker and most of the last row+ var (_, detail) = await fx.ConvertFailsAsync(shp, "geojson");+ Assert.Contains("2 rows but the .shp has 3", detail);+ }++ // ---- Writing: the files are parsed here from the specification ----++ private sealed record ShpFile(int FileLengthBytes, int Type, List<byte[]> Records, int[] BoxBytes);++ private static ShpFile ParseShp(string path)+ {+ var bytes = File.ReadAllBytes(path);+ Assert.Equal(9994, BinaryPrimitives.ReadInt32BigEndian(bytes));+ Assert.Equal(1000, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(28)));+ var length = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(24)) * 2;+ Assert.Equal(bytes.Length, length);+ var records = new List<byte[]>();+ var position = 100;+ while (position < bytes.Length)+ {+ Assert.Equal(records.Count + 1, BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position)));+ var content = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position + 4)) * 2;+ records.Add(bytes[(position + 8)..(position + 8 + content)]);+ position += 8 + content;+ }+ Assert.Equal(bytes.Length, position);+ return new ShpFile(length, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(32)), records, []);+ }++ private static void CheckShx(string shxPath, string shpPath)+ {+ var shx = File.ReadAllBytes(shxPath);+ var shp = File.ReadAllBytes(shpPath);+ Assert.Equal(9994, BinaryPrimitives.ReadInt32BigEndian(shx));+ Assert.Equal(shx.Length, BinaryPrimitives.ReadInt32BigEndian(shx.AsSpan(24)) * 2);+ Assert.Equal(shp.AsSpan(32, 4).ToArray(), shx.AsSpan(32, 4).ToArray());+ Assert.Equal(shp.AsSpan(36, 64).ToArray(), shx.AsSpan(36, 64).ToArray()); // same bounding box+ var count = (shx.Length - 100) / 8;+ var position = 100;+ for (var i = 0; i < count; i++)+ {+ var offset = BinaryPrimitives.ReadInt32BigEndian(shx.AsSpan(100 + 8 * i)) * 2;+ var words = BinaryPrimitives.ReadInt32BigEndian(shx.AsSpan(104 + 8 * i));+ Assert.Equal(position, offset);+ Assert.Equal(words, BinaryPrimitives.ReadInt32BigEndian(shp.AsSpan(offset + 4)));+ position += 8 + words * 2;+ }+ }++ private sealed record DbfInfo(int Rows, int RecordLength, List<(string Name, char Type, int Length, int Decimals)> Fields, byte[] Bytes);++ private static DbfInfo ParseDbf(string path)+ {+ var bytes = File.ReadAllBytes(path);+ Assert.Equal(3, bytes[0]);+ var rows = (int)BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(4));+ var headerLength = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8));+ var recordLength = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(10));+ var fields = new List<(string, char, int, int)>();+ var at = 32;+ while (bytes[at] != 0x0D)+ {+ var name = Encoding.UTF8.GetString(bytes, at, 11).TrimEnd('\0');+ fields.Add((name, (char)bytes[at + 11], bytes[at + 16], bytes[at + 17]));+ at += 32;+ }+ Assert.Equal(headerLength, at + 1);+ Assert.Equal(1 + fields.Sum(f => f.Item3), recordLength);+ Assert.Equal(headerLength + rows * recordLength + 1, bytes.Length);+ Assert.Equal(0x1A, bytes[^1]);+ return new DbfInfo(rows, recordLength, fields, bytes);+ }++ private static string Cell(DbfInfo dbf, int row, int field)+ {+ var start = (int)BinaryPrimitives.ReadUInt16LittleEndian(dbf.Bytes.AsSpan(8)) + row * dbf.RecordLength + 1 + dbf.Fields.Take(field).Sum(f => f.Length);+ return Encoding.UTF8.GetString(dbf.Bytes, start, dbf.Fields[field].Length);+ }++ private async Task<(string Shp, List<string> Files)> ToShapefileAsync(string json, string name = "in.geojson", Action<Preset>? tweak = null)+ {+ var files = await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, name, json), "shp", tweak);+ return (files.First(f => f.EndsWith(".shp", StringComparison.Ordinal)), files);+ }++ private static string FeatureCollection(params string[] features) => """{"type":"FeatureCollection","features":[""" + string.Join(',', features) + "]}";++ private static string Feature(string geometry, string properties = "{}") => $$"""{"type":"Feature","properties":{{properties}},"geometry":{{geometry}}}""";++ [Fact]+ public async Task Points_make_a_complete_set_of_five_consistent_files()+ {+ var (shp, files) = await ToShapefileAsync(FeatureCollection(+ Feature("""{"type":"Point","coordinates":[10.5,20.25]}""", """{"name":"A","n":1}"""),+ Feature("""{"type":"Point","coordinates":[-5,40]}""", """{"name":"B","n":2}""")));+ Assert.Equal(["cpg", "dbf", "prj", "shp", "shx"], files.Select(f => Path.GetExtension(f)[1..]).Order().ToArray());+ Assert.Single(files.Select(f => Path.GetFileNameWithoutExtension(f)).Distinct());++ var parsed = ParseShp(shp);+ Assert.Equal(1, parsed.Type);+ Assert.Equal(2, parsed.Records.Count);+ Assert.All(parsed.Records, r => Assert.Equal(20, r.Length));+ Assert.Equal(10.5, BitConverter.ToDouble(parsed.Records[0], 4));+ Assert.Equal(20.25, BitConverter.ToDouble(parsed.Records[0], 12));+ var bytes = File.ReadAllBytes(shp);+ Assert.Equal(-5, BitConverter.ToDouble(bytes, 36)); // xmin+ Assert.Equal(20.25, BitConverter.ToDouble(bytes, 44)); // ymin+ Assert.Equal(10.5, BitConverter.ToDouble(bytes, 52)); // xmax+ Assert.Equal(40, BitConverter.ToDouble(bytes, 60)); // ymax+ CheckShx(Path.ChangeExtension(shp, "shx"), shp);++ var dbf = ParseDbf(Path.ChangeExtension(shp, "dbf"));+ Assert.Equal(2, dbf.Rows);+ Assert.Equal([("name", 'C', 1, 0), ("n", 'N', 1, 0)], dbf.Fields.ToArray());+ Assert.Equal("B", Cell(dbf, 1, 0));+ Assert.Equal("UTF-8", File.ReadAllText(Path.ChangeExtension(shp, "cpg")));+ Assert.StartsWith("GEOGCS[\"GCS_WGS_1984\"", File.ReadAllText(Path.ChangeExtension(shp, "prj")));+ }++ [Fact]+ public async Task Polygons_are_written_clockwise_with_holes_counter_clockwise_and_closed_rings()+ {+ const string polygon = """{"type":"Polygon","coordinates":[[[0,0],[4,0],[4,4],[0,4],[0,0]],[[1,1],[1,2],[2,2],[2,1],[1,1]]]}""";+ var (shp, _) = await ToShapefileAsync(FeatureCollection(Feature(polygon)));+ var parsed = ParseShp(shp);+ Assert.Equal(5, parsed.Type);+ var record = parsed.Records.Single();+ Assert.Equal(2, BitConverter.ToInt32(record, 36));+ Assert.Equal(10, BitConverter.ToInt32(record, 40));+ Assert.Equal([0, 5], new[] { BitConverter.ToInt32(record, 44), BitConverter.ToInt32(record, 48) });+ double Area(int from, int to)+ {+ var sum = 0.0;+ for (var i = from; i < to - 1; i++)+ {+ var (x1, y1) = (BitConverter.ToDouble(record, 52 + 16 * i), BitConverter.ToDouble(record, 60 + 16 * i));+ var (x2, y2) = (BitConverter.ToDouble(record, 52 + 16 * (i + 1)), BitConverter.ToDouble(record, 60 + 16 * (i + 1)));+ sum += x1 * y2 - x2 * y1;+ }+ return sum / 2;+ }+ Assert.Equal(-16, Area(0, 5));+ Assert.Equal(1, Area(5, 10));+ CheckShx(Path.ChangeExtension(shp, "shx"), shp);+ }++ [Fact]+ public async Task Height_makes_the_z_shape_types_and_a_missing_height_is_zero()+ {+ var (points, _) = await ToShapefileAsync(FeatureCollection(+ Feature("""{"type":"Point","coordinates":[1,2,30]}"""), Feature("""{"type":"Point","coordinates":[3,4]}""")), "z1.geojson");+ var parsed = ParseShp(points);+ Assert.Equal(11, parsed.Type);+ Assert.Equal(30, BitConverter.ToDouble(parsed.Records[0], 20));+ Assert.Equal(0, BitConverter.ToDouble(parsed.Records[1], 20));+ Assert.All(parsed.Records, r => Assert.Equal(36, r.Length));++ var (lines, _) = await ToShapefileAsync(FeatureCollection(Feature("""{"type":"LineString","coordinates":[[0,0,5],[1,1,6]]}""")), "z2.geojson");+ Assert.Equal(13, ParseShp(lines).Type);+ var (polygons, _) = await ToShapefileAsync(FeatureCollection(Feature("""{"type":"Polygon","coordinates":[[[0,0,1],[1,0,1],[1,1,1],[0,0,1]]]}""")), "z3.geojson");+ Assert.Equal(15, ParseShp(polygons).Type);+ CheckShx(Path.ChangeExtension(lines, "shx"), lines);+ }++ [Fact]+ public async Task Multipoints_make_a_multipoint_file_and_single_points_a_point_file()+ {+ var (multi, _) = await ToShapefileAsync(FeatureCollection(Feature("""{"type":"MultiPoint","coordinates":[[1,1],[2,2],[3,3]]}""")), "m.geojson");+ Assert.Equal(8, ParseShp(multi).Type);+ var (single, _) = await ToShapefileAsync(FeatureCollection(Feature("""{"type":"MultiPoint","coordinates":[[1,1]]}""")), "s.geojson");+ Assert.Equal(1, ParseShp(single).Type);+ }++ [Fact]+ public async Task Mixed_geometry_is_split_into_one_shapefile_per_kind_with_the_note()+ {+ var json = FeatureCollection(+ Feature("""{"type":"Point","coordinates":[1,1]}""", """{"a":1}"""),+ Feature("""{"type":"LineString","coordinates":[[0,0],[1,1]]}""", """{"a":2}"""),+ Feature("""{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}""", """{"a":3}"""),+ Feature("""{"type":"GeometryCollection","geometries":[{"type":"Point","coordinates":[5,5]},{"type":"LineString","coordinates":[[2,2],[3,3]]}]}""", """{"a":4}"""),+ Feature("null", """{"a":5}"""));+ var job = await fx.ConvertAsync(GeoFixtures.WriteText(fx, "mixed.geojson", json), "shp");+ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal("notice.geo_shapefile_split", job.Files.Single().NoticeKey);+ var shapes = job.Outputs.Where(f => f.EndsWith(".shp", StringComparison.Ordinal)).OrderBy(f => f).ToList();+ Assert.Equal(["mixed_lines.shp", "mixed_points.shp", "mixed_polygons.shp"], shapes.Select(f => Path.GetFileName(f)!).ToArray());+ Assert.Equal(15, job.Outputs.Count());++ var lines = ParseShp(shapes[0]);+ Assert.Equal(3, lines.Type);+ Assert.Equal(2, lines.Records.Count); // the line and the line inside the collection+ var points = ParseShp(shapes[1]);+ Assert.Equal(1, points.Type);+ Assert.Equal(3, points.Records.Count); // the point, the point in the collection, and the feature without geometry (in the first file)+ Assert.Equal(0, BitConverter.ToInt32(points.Records[2], 0));+ Assert.Equal(5, ParseShp(shapes[2]).Type);+ foreach (var shp in shapes)+ CheckShx(Path.ChangeExtension(shp, "shx"), shp);+ // The attributes of a collection are repeated for each of its members.+ var dbf = ParseDbf(Path.ChangeExtension(shapes[0], "dbf"));+ Assert.Equal(["2", "4"], Enumerable.Range(0, dbf.Rows).Select(r => Cell(dbf, r, 0).Trim()).ToArray());+ }++ [Fact]+ public async Task Features_without_any_geometry_make_a_point_shapefile_of_null_shapes()+ {+ var (shp, _) = await ToShapefileAsync(FeatureCollection(Feature("null", """{"a":1}"""), Feature("null", """{"a":2}""")));+ var parsed = ParseShp(shp);+ Assert.Equal(2, parsed.Records.Count);+ Assert.All(parsed.Records, r => Assert.Equal(0, BitConverter.ToInt32(r, 0)));+ Assert.Equal(2, ParseDbf(Path.ChangeExtension(shp, "dbf")).Rows);+ }++ [Fact]+ public async Task Attribute_columns_get_the_dbf_type_that_holds_their_values()+ {+ var rows = new[]+ {+ """{"i":-12,"f":1.5,"b":true,"s":"text","mixed":1,"nums":2,"allnull":null,"big":123456789012,"tiny":0.0000001}""",+ """{"i":7,"f":-0.125,"b":false,"s":"länger","mixed":"x","nums":3.25,"allnull":null,"big":5,"tiny":2}""",+ """{"i":null,"f":null,"b":null,"s":null,"mixed":null,"nums":null,"allnull":null,"big":null,"tiny":null}""",+ };+ var (shp, _) = await ToShapefileAsync(FeatureCollection(rows.Select(r => Feature("""{"type":"Point","coordinates":[1,1]}""", r)).ToArray()));+ var dbf = ParseDbf(Path.ChangeExtension(shp, "dbf"));+ var fields = dbf.Fields.ToDictionary(f => f.Name);+ Assert.Equal(('N', 3, 0), (fields["i"].Type, fields["i"].Length, fields["i"].Decimals));+ Assert.Equal('N', fields["f"].Type);+ Assert.Equal(3, fields["f"].Decimals);+ Assert.Equal('L', fields["b"].Type);+ Assert.Equal(('C', 7), (fields["s"].Type, fields["s"].Length)); // "länger" is 7 bytes+ Assert.Equal('C', fields["mixed"].Type);+ Assert.Equal(('N', 2), (fields["nums"].Type, fields["nums"].Decimals));+ Assert.Equal(('C', 1), (fields["allnull"].Type, fields["allnull"].Length));+ Assert.Equal(('N', 12, 0), (fields["big"].Type, fields["big"].Length, fields["big"].Decimals));+ Assert.Equal(('N', 7), (fields["tiny"].Type, fields["tiny"].Decimals));++ var names = dbf.Fields.Select(f => f.Name).ToList();+ Assert.Equal("-12", Cell(dbf, 0, names.IndexOf("i")).Trim());+ Assert.Equal("-0.125", Cell(dbf, 1, names.IndexOf("f")).Trim());+ Assert.Equal("T", Cell(dbf, 0, names.IndexOf("b")));+ Assert.Equal("F", Cell(dbf, 1, names.IndexOf("b")));+ Assert.Equal("?", Cell(dbf, 2, names.IndexOf("b")));+ Assert.Equal("", Cell(dbf, 2, names.IndexOf("i")).Trim());+ Assert.Equal("länger", Cell(dbf, 1, names.IndexOf("s")).TrimEnd());+ Assert.Equal("0.0000001", Cell(dbf, 0, names.IndexOf("tiny")).Trim());+ }++ [Fact]+ public async Task Field_names_are_cut_to_ten_bytes_made_unique_and_cleaned_with_a_note()+ {+ var props = """{"population_2020":1,"population_2021":2,"population_2022":3,"my col!":4,"도시이름도시이름도시":5,"short":6,"Short":7,"":8}""";+ var job = await fx.ConvertAsync(GeoFixtures.WriteText(fx, "names.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""", props))), "shp");+ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal("notice.geo_field_names", job.Files.Single().NoticeKey);+ var dbf = ParseDbf(Path.ChangeExtension(job.Outputs.First(f => f.EndsWith(".shp", StringComparison.Ordinal)), "dbf"));+ var names = dbf.Fields.Select(f => f.Name).ToArray();+ Assert.Equal(["population", "populati_1", "populati_2", "my_col_", "도시이", "short", "Short_1", "FIELD"], names);+ Assert.All(names, n => Assert.True(Encoding.UTF8.GetByteCount(n) <= 10, n));+ }++ [Fact]+ public async Task Text_longer_than_254_bytes_is_cut_between_characters_with_a_note()+ {+ var korean = new string('한', 100); // 300 bytes+ var job = await fx.ConvertAsync(GeoFixtures.WriteText(fx, "long.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""", $$"""{"t":"{{korean}}","e":"{{new string('x', 300)}}"}"""))), "shp");+ Assert.Equal("notice.geo_text_cut", job.Files.Single().NoticeKey);+ var shp = job.Outputs.First(f => f.EndsWith(".shp", StringComparison.Ordinal));+ var dbf = ParseDbf(Path.ChangeExtension(shp, "dbf"));+ Assert.Equal(254, dbf.Fields[0].Length);+ Assert.Equal(254, dbf.Fields[1].Length);+ Assert.Equal(new string('한', 84), Cell(dbf, 0, 0).TrimEnd()); // 84 characters = 252 bytes; none broken+ Assert.Equal(new string('x', 254), Cell(dbf, 0, 1));+ // GDAL's view of the same bytes is in the cross-check run; here the engine reads its own output back.+ using var doc = await GeoJsonAsync(shp);+ Assert.Equal(new string('한', 84), doc.RootElement.GetProperty("features")[0].GetProperty("properties").GetProperty("t").GetString());+ }++ [Fact]+ public async Task More_than_255_columns_keep_the_first_255_with_a_note()+ {+ var props = "{" + string.Join(',', Enumerable.Range(1, 300).Select(i => $"\"c{i}\":{i}")) + "}";+ var job = await fx.ConvertAsync(GeoFixtures.WriteText(fx, "wide.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""", props))), "shp");+ Assert.Equal("notice.geo_columns_dropped", job.Files.Single().NoticeKey);+ var dbf = ParseDbf(Path.ChangeExtension(job.Outputs.First(f => f.EndsWith(".shp", StringComparison.Ordinal)), "dbf"));+ Assert.Equal(255, dbf.Fields.Count);+ Assert.Equal("c255", dbf.Fields[^1].Name);+ }++ [Fact]+ public async Task Features_without_attributes_get_an_FID_column_because_a_dbf_needs_a_field()+ {+ var (shp, _) = await ToShapefileAsync(FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}"""), Feature("""{"type":"Point","coordinates":[2,2]}""")));+ var dbf = ParseDbf(Path.ChangeExtension(shp, "dbf"));+ Assert.Equal("FID", dbf.Fields.Single().Name);+ Assert.Equal(["0", "1"], Enumerable.Range(0, 2).Select(r => Cell(dbf, r, 0).Trim()).ToArray());+ }++ [Fact]+ public async Task Many_random_positions_survive_a_round_trip_at_full_precision()+ {+ var random = new Random(5);+ var points = Enumerable.Range(0, 5000).Select(_ => (X: random.NextDouble() * 360 - 180, Y: random.NextDouble() * 180 - 90)).ToList();+ var json = FeatureCollection([.. points.Select((p, i) => Feature($$"""{"type":"Point","coordinates":[{{p.X.ToString("R", CultureInfo.InvariantCulture)}},{{p.Y.ToString("R", CultureInfo.InvariantCulture)}}]}""", $$"""{"i":{{i}}}"""))]);+ var (shp, _) = await ToShapefileAsync(json, "random.geojson");+ using var doc = await GeoJsonAsync(shp);+ var features = doc.RootElement.GetProperty("features");+ Assert.Equal(points.Count, features.GetArrayLength());+ for (var i = 0; i < points.Count; i++)+ {+ var position = GeoFixtures.Position(features[i].GetProperty("geometry"));+ Assert.True(Math.Abs(position[0] - points[i].X) < 1e-9 && Math.Abs(position[1] - points[i].Y) < 1e-9, $"point {i}");+ Assert.Equal(i, features[i].GetProperty("properties").GetProperty("i").GetInt64());+ }+ }++ // ---- File names ----++ private static Action<Preset> WithConflict(ConflictPolicy policy) => preset => preset.Output.Conflict = policy;++ [Fact]+ public async Task Converting_twice_keeps_the_first_shapefile_and_names_the_second_set_consistently()+ {+ var input = GeoFixtures.WriteText(fx, "twice.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""", """{"a":1}""")));+ var first = await fx.ConvertOkAsync(input, "shp");+ var second = await fx.ConvertOkAsync(input, "shp");+ Assert.Equal(["twice.cpg", "twice.dbf", "twice.prj", "twice.shp", "twice.shx"], first.Select(f => Path.GetFileName(f)!).Order().ToArray());+ Assert.Equal(["twice (2).cpg", "twice (2).dbf", "twice (2).prj", "twice (2).shp", "twice (2).shx"], second.Select(f => Path.GetFileName(f)!).Order().ToArray());+ CheckShx(Path.ChangeExtension(second.First(f => f.EndsWith(".shp", StringComparison.Ordinal)), "shx"), second.First(f => f.EndsWith(".shp", StringComparison.Ordinal)));+ }++ [Fact]+ public async Task A_leftover_sibling_file_is_never_overwritten_the_next_free_name_is_used()+ {+ var input = GeoFixtures.WriteText(fx, "orphan.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""")));+ var folder = Path.GetDirectoryName(input)!;+ File.WriteAllText(Path.Combine(folder, "orphan.dbf"), "someone else's file");+ var files = await fx.ConvertOkAsync(input, "shp");+ Assert.Equal("someone else's file", File.ReadAllText(Path.Combine(folder, "orphan.dbf")));+ Assert.All(files, f => Assert.StartsWith("orphan_2.", Path.GetFileName(f)));+ }++ [Fact]+ public async Task The_overwrite_policy_replaces_the_whole_set_and_skip_leaves_it_alone()+ {+ var input = GeoFixtures.WriteText(fx, "policy.geojson", FeatureCollection(Feature("""{"type":"Point","coordinates":[1,1]}""", """{"a":1}""")));+ var first = await fx.ConvertOkAsync(input, "shp");+ var shp = first.First(f => f.EndsWith(".shp", StringComparison.Ordinal));+ File.WriteAllText(input, FeatureCollection(Feature("""{"type":"Point","coordinates":[2,2]}""", """{"a":1}"""), Feature("""{"type":"Point","coordinates":[3,3]}""", """{"a":2}""")));++ var skipped = await fx.ConvertAsync(input, "shp", WithConflict(ConflictPolicy.Skip));+ Assert.Equal(FileState.Skipped, skipped.Files.Single().State);+ Assert.Single(ParseShp(shp).Records);++ var replaced = await fx.ConvertOkAsync(input, "shp", WithConflict(ConflictPolicy.Overwrite));+ Assert.Equal(first.Order().ToArray(), replaced.Order().ToArray());+ Assert.Equal(2, ParseShp(shp).Records.Count);+ Assert.Equal(2, ParseDbf(Path.ChangeExtension(shp, "dbf")).Rows);+ CheckShx(Path.ChangeExtension(shp, "shx"), shp);+ }++ [Fact]+ public async Task A_failed_conversion_leaves_no_partial_files_behind()+ {+ var folder = fx.NewFolder();+ var input = Path.Combine(folder, "broken.geojson");+ File.WriteAllText(input, """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1]}}]}""");+ var (_, _) = await fx.ConvertFailsAsync(input, "shp");+ Assert.Equal(["broken.geojson"], Directory.GetFiles(folder).Select(f => Path.GetFileName(f)!).ToArray());+ }+}