-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathtauri-io.ts
More file actions
1273 lines (1155 loc) · 36.2 KB
/
Copy pathtauri-io.ts
File metadata and controls
1273 lines (1155 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { parseProject, type GeoLibreProject } from "@geolibre/core";
import { invoke } from "@tauri-apps/api/core";
import { open, save } from "@tauri-apps/plugin-dialog";
import {
readFile,
readTextFile,
readTextFileLines,
writeFile,
writeTextFile,
} from "@tauri-apps/plugin-fs";
import { unzip } from "fflate";
import type { FeatureCollection } from "geojson";
import shp from "shpjs";
import { parseDelimitedTextFields } from "./delimited-text";
import type { DuckDbVectorFile } from "./duckdb-vector-loader";
import type { DuckDbVectorLoadOptions } from "./duckdb-vector-guard";
import { parseGpxLayer } from "./gpx";
import { isTauri } from "./is-tauri";
import { parseKmlText } from "./kml";
// Re-exported so existing `import { isTauri } from "./tauri-io"` consumers keep
// working; the implementation lives in the lightweight ./is-tauri module.
export { isTauri };
function browserSafeFileName(path: string): string {
return path.split(/[/\\]/).pop() || "project.geolibre.json";
}
export interface FileDialogFilter {
name: string;
extensions: string[];
}
interface PickLocalPathOptions {
accept?: string;
directory?: boolean;
filters?: FileDialogFilter[];
}
interface PickSavePathOptions {
browserTypes?: BrowserFilePickerType[];
defaultName: string;
filters?: FileDialogFilter[];
}
interface LocalDataFileOptions {
filters: FileDialogFilter[];
accept: string;
readBinary?: boolean;
readText?: boolean;
}
interface BrowserFilePickerType {
description: string;
accept: Record<string, string[]>;
}
interface BrowserOpenFileHandle {
name: string;
getFile: () => Promise<File>;
}
interface BrowserWritableFileStream {
write: (data: string | Blob) => Promise<void>;
close: () => Promise<void>;
}
interface BrowserSaveFileHandle {
name: string;
createWritable: () => Promise<BrowserWritableFileStream>;
}
interface BrowserFilePickerWindow extends Window {
showOpenFilePicker?: (options: {
multiple?: boolean;
types?: BrowserFilePickerType[];
excludeAcceptAllOption?: boolean;
}) => Promise<BrowserOpenFileHandle[]>;
showSaveFilePicker?: (options: {
suggestedName?: string;
types?: BrowserFilePickerType[];
excludeAcceptAllOption?: boolean;
}) => Promise<BrowserSaveFileHandle>;
}
const GEOLIBRE_PROJECT_FILE_TYPES: BrowserFilePickerType[] = [
{
description: "GeoLibre Project",
accept: {
"application/json": [".geolibre", ".json"],
},
},
];
interface SaveTextFileOptions {
defaultName: string;
filters: FileDialogFilter[];
browserTypes: BrowserFilePickerType[];
mimeType: string;
}
interface SaveBinaryFileOptions extends SaveTextFileOptions {}
const SHAPEFILE_SIDECAR_EXTENSIONS = ["dbf", "shx", "prj", "cpg"];
export interface LoadedVectorLayer {
data: FeatureCollection;
name?: string;
path: string;
}
// Auxiliary files that accompany Shapefiles (spatial indexes, metadata, etc.)
// but are never standalone vector layers. Skipping them keeps a single such
// file from aborting an otherwise valid drag-and-drop import.
const NON_VECTOR_SIDECAR_EXTENSIONS = [
...SHAPEFILE_SIDECAR_EXTENSIONS,
"sbn",
"sbx",
"qix",
"qpj",
"aih",
"ain",
"atx",
"fbn",
"fbx",
"ixs",
"mxs",
];
/** GeoTIFF/COG extensions handled by the map drag and drop raster path. */
const RASTER_DROP_EXTENSIONS = ["tif", "tiff"];
/** Whether a filename looks like a raster the map can load (GeoTIFF/COG). */
export function isRasterFileName(name: string): boolean {
return RASTER_DROP_EXTENSIONS.includes(fileExtension(name));
}
function isAbortError(error: unknown): boolean {
return error instanceof DOMException && error.name === "AbortError";
}
export function isHttpUrl(path: string): boolean {
try {
const url = new URL(path);
return url.protocol === "http:" || url.protocol === "https:";
} catch {
return false;
}
}
function fileExtension(path: string): string {
const name = browserSafeFileName(path).toLowerCase();
if (name.endsWith(".geoparquet")) return "geoparquet";
return name.split(".").pop() ?? "";
}
function pathWithoutExtension(path: string): string {
return path.replace(/\.[^.\\/]+$/, "");
}
function isGeoLibreProjectFile(path: string): boolean {
const name = browserSafeFileName(path).toLowerCase();
return name.endsWith(".geolibre") || name.endsWith(".geolibre.json");
}
function isVectorFileName(path: string): boolean {
if (isGeoLibreProjectFile(path)) return false;
if (browserSafeFileName(path).toLowerCase().endsWith(".shp.xml"))
return false;
// Rasters are handled by the raster drop path, not the DuckDB vector loader.
if (isRasterFileName(path)) return false;
return !NON_VECTOR_SIDECAR_EXTENSIONS.includes(fileExtension(path));
}
function assertFeatureCollection(value: unknown): FeatureCollection {
if (
value &&
typeof value === "object" &&
(value as { type?: unknown }).type === "FeatureCollection" &&
Array.isArray((value as { features?: unknown }).features)
) {
return value as FeatureCollection;
}
throw new Error(
"The selected file did not produce a GeoJSON FeatureCollection.",
);
}
// DuckDB-wasm (pthreads build) can hand back a Uint8Array backed by a
// SharedArrayBuffer, which `Blob`'s BlobPart type rejects. Copy into a plain
// ArrayBuffer so the binary save path type-checks and stays portable.
function toArrayBuffer(data: Uint8Array): ArrayBuffer {
const buffer = new ArrayBuffer(data.byteLength);
new Uint8Array(buffer).set(data);
return buffer;
}
function mergeFeatureCollections(
collections: FeatureCollection[],
): FeatureCollection {
return {
type: "FeatureCollection",
features: collections.flatMap((collection) => collection.features),
};
}
function normalizeShapefileResult(value: unknown): FeatureCollection {
if (Array.isArray(value)) {
return mergeFeatureCollections(value.map(assertFeatureCollection));
}
return assertFeatureCollection(value);
}
async function parseGeoJsonText(text: string): Promise<FeatureCollection> {
return assertFeatureCollection(JSON.parse(text));
}
function parseGpxText(text: string): FeatureCollection {
const result = parseGpxLayer(text);
return mergeFeatureCollections([
result.waypoints,
result.tracks,
result.routes,
]);
}
function parseGpxTextLayers(text: string, path: string): LoadedVectorLayer[] {
const result = parseGpxLayer(text);
const baseName = pathWithoutExtension(browserSafeFileName(path)) || "GPX";
return [
{ data: result.waypoints, label: "Waypoints" },
{ data: result.tracks, label: "Tracks" },
{ data: result.routes, label: "Routes" },
]
.filter((layer) => layer.data.features.length > 0)
.map((layer) => ({
data: layer.data,
name: `${baseName} ${layer.label}`,
path,
}));
}
async function parseShapefileZip(
data: ArrayBuffer | Uint8Array,
): Promise<FeatureCollection> {
return normalizeShapefileResult(await shp(data));
}
function unzipArchive(
data: ArrayBuffer | Uint8Array,
): Promise<Record<string, Uint8Array>> {
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
return new Promise<Record<string, Uint8Array>>((resolve, reject) => {
unzip(bytes, (error, entries) => {
if (error) {
reject(error);
return;
}
resolve(entries);
});
});
}
function toDuckDbVectorData(data: Uint8Array): Uint8Array<ArrayBuffer> {
return new Uint8Array(data);
}
async function readKmzKmlFiles(
data: ArrayBuffer | Uint8Array,
): Promise<DuckDbVectorFile[]> {
const entries = await unzipArchive(data);
const kmlEntries = Object.entries(entries)
.filter(([entryName]) => entryName.toLowerCase().endsWith(".kml"))
.sort(([leftName], [rightName]) => {
if (browserSafeFileName(leftName).toLowerCase() === "doc.kml") return -1;
if (browserSafeFileName(rightName).toLowerCase() === "doc.kml") return 1;
return leftName.localeCompare(rightName);
});
if (!kmlEntries.length) {
throw new Error("The KMZ archive did not contain a KML file.");
}
return kmlEntries.map(([entryName, data], index) => {
const entryBaseName =
browserSafeFileName(entryName) || `document-${index + 1}.kml`;
return {
name:
kmlEntries.length === 1
? entryBaseName
: `${index + 1}-${entryBaseName}`,
extension: "kml",
data: toDuckDbVectorData(data),
};
});
}
async function parseKmz(
data: ArrayBuffer | Uint8Array,
options?: DuckDbVectorLoadOptions,
): Promise<FeatureCollection> {
const kmlFiles = await readKmzKmlFiles(data);
// Load each KML independently so declining one large KML inside a multi-KML
// archive drops just that layer instead of failing the whole KMZ (Promise.all
// is fail-fast). Real load errors still reject and abort the archive.
let cancellation: unknown;
const settled = await Promise.all(
kmlFiles.map((file) =>
loadKmlFile(file, options).then(
(collection): FeatureCollection | null => collection,
(error): null => {
if (!isVectorLoadCancelled(error)) throw error;
cancellation = error;
return null;
},
),
),
);
const collections = settled.filter(
(collection): collection is FeatureCollection => collection !== null,
);
// Every KML was declined: propagate the cancellation so the caller skips the
// whole archive rather than adding an empty layer.
if (collections.length === 0 && cancellation) throw cancellation;
return mergeFeatureCollections(collections);
}
async function loadDuckDbVector(
file: DuckDbVectorFile,
options?: DuckDbVectorLoadOptions,
) {
const { loadDuckDbVectorFile } = await import("./duckdb-vector-loader");
return loadDuckDbVectorFile(file, options);
}
/**
* Load one KML entry, preferring the styled in-house reader so embedded
* symbology survives, and falling back to DuckDB/GDAL for KML the reader does
* not cover (so geometry still loads, without the styling). Cancellation from
* the DuckDB fallback is allowed to propagate.
*/
async function loadKmlFile(
file: DuckDbVectorFile,
options?: DuckDbVectorLoadOptions,
): Promise<FeatureCollection> {
try {
return parseKmlText(new TextDecoder("utf-8").decode(file.data));
} catch {
return loadDuckDbVector(file, options);
}
}
/**
* Whether an error is the {@link VectorLoadCancelledError} thrown when the user
* declines a large-file load. Matched by `name` rather than `instanceof` so the
* heavy `duckdb-vector-loader` module (and its DuckDB-WASM imports) stays a
* lazy dynamic import instead of being pulled into this module's chunk.
*/
function isVectorLoadCancelled(error: unknown): boolean {
return (
error instanceof Error && error.name === "VectorLoadCancelledError"
);
}
async function fileToDuckDbVectorFile(file: File): Promise<DuckDbVectorFile> {
return {
name: file.name,
extension: fileExtension(file.name),
data: new Uint8Array(await file.arrayBuffer()),
};
}
async function loadBrowserVectorFile(
file: File,
siblingFiles: DuckDbVectorFile[] = [],
options?: DuckDbVectorLoadOptions,
): Promise<LoadedVectorLayer> {
const extension = fileExtension(file.name);
if (extension === "geojson" || extension === "json") {
try {
return {
data: await parseGeoJsonText(await file.text()),
path: file.name,
};
} catch {
// Some GDAL-backed vector formats use .json but are not GeoJSON
// FeatureCollections. Let DuckDB Spatial try them before failing.
}
}
if (extension === "zip") {
try {
return {
data: await parseShapefileZip(await file.arrayBuffer()),
path: file.name,
};
} catch {
// DuckDB Spatial may be able to read zipped vector data that shpjs cannot.
}
}
if (extension === "kmz") {
return {
data: await parseKmz(await file.arrayBuffer(), options),
path: file.name,
};
}
if (extension === "kml") {
try {
return {
data: parseKmlText(await file.text()),
path: file.name,
};
} catch {
// The styled reader does not cover this KML; let DuckDB Spatial try it.
}
}
if (extension === "gpx") {
return {
data: parseGpxText(await file.text()),
path: file.name,
};
}
return {
data: await loadDuckDbVector(
{
name: file.name,
extension,
data: new Uint8Array(await file.arrayBuffer()),
siblingFiles,
},
options,
),
path: file.name,
};
}
async function openVectorFileBrowser(
options?: DuckDbVectorLoadOptions,
): Promise<{
data: FeatureCollection;
path: string;
} | null> {
return new Promise((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
input.onchange = async () => {
try {
const file = input.files?.[0];
if (!file) {
resolve(null);
return;
}
resolve(await loadBrowserVectorFile(file, [], options));
} catch (error) {
reject(error);
}
};
input.click();
});
}
async function openVectorFileTauri(
options?: DuckDbVectorLoadOptions,
): Promise<{
data: FeatureCollection;
path: string;
} | null> {
const selected = await open({
multiple: false,
});
if (!selected || typeof selected !== "string") return null;
return loadTauriVectorFile(selected, options);
}
async function loadTauriVectorFile(
path: string,
options?: DuckDbVectorLoadOptions,
): Promise<{
data: FeatureCollection;
path: string;
}> {
const extension = fileExtension(path);
if (extension === "geojson" || extension === "json") {
try {
return {
data: await parseGeoJsonText(await readTextFile(path)),
path,
};
} catch {
// Some GDAL-backed vector formats use .json but are not GeoJSON
// FeatureCollections. Let DuckDB Spatial try them before failing.
}
}
if (extension === "zip") {
try {
return {
data: await parseShapefileZip(await readFile(path)),
path,
};
} catch {
// DuckDB Spatial may be able to read zipped vector data that shpjs cannot.
}
}
if (extension === "kmz") {
try {
return {
data: await parseKmz(await readFile(path), options),
path,
};
} catch (error) {
if (isVectorLoadCancelled(error)) throw error;
const detail = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Could not read this KMZ file. ${detail}`);
}
}
if (extension === "kml") {
try {
return {
data: parseKmlText(await readTextFile(path)),
path,
};
} catch {
// The styled reader does not cover this KML; let DuckDB Spatial try it.
}
}
if (extension === "gpx") {
try {
return {
data: parseGpxText(await readTextFile(path)),
path,
};
} catch (error) {
const detail = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Could not read this GPX file. ${detail}`);
}
}
try {
const siblingFiles =
extension === "shp" ? await readShapefileSiblings(path) : [];
return {
data: await loadDuckDbVector(
{
name: browserSafeFileName(path),
extension,
data: await readFile(path),
siblingFiles,
},
options,
),
path,
};
} catch (error) {
if (isVectorLoadCancelled(error)) throw error;
const detail = error instanceof Error ? error.message : "Unknown error";
throw new Error(
`Could not convert this vector file with DuckDB-WASM. ${detail}`,
);
}
}
async function readShapefileSiblings(
path: string,
): Promise<DuckDbVectorFile[]> {
const basePath = pathWithoutExtension(path);
const siblings = await Promise.all(
SHAPEFILE_SIDECAR_EXTENSIONS.map(async (extension) => {
const siblingPath = `${basePath}.${extension}`;
try {
return {
name: browserSafeFileName(siblingPath),
extension,
data: await readFile(siblingPath),
};
} catch {
return null;
}
}),
);
return siblings.filter(
(sibling): sibling is DuckDbVectorFile => sibling !== null,
);
}
async function openProjectFileBrowser(): Promise<{
project: GeoLibreProject;
path: string;
} | null> {
const pickerWindow = window as BrowserFilePickerWindow;
if (pickerWindow.showOpenFilePicker) {
try {
const [handle] = await pickerWindow.showOpenFilePicker({
multiple: false,
types: GEOLIBRE_PROJECT_FILE_TYPES,
excludeAcceptAllOption: false,
});
if (!handle) return null;
const file = await handle.getFile();
return {
project: parseProject(await file.text()),
path: handle.name || file.name,
};
} catch (error) {
if (isAbortError(error)) return null;
console.warn("Browser project file picker failed", error);
}
}
const result = await openLocalDataFileWithFallback({
filters: [{ name: "GeoLibre Project", extensions: ["geolibre", "json"] }],
accept: ".geolibre,.json,.geolibre.json",
readText: true,
});
if (!result?.text) return null;
return {
project: parseProject(result.text),
path: result.path,
};
}
/**
* Whether saving a project in the current environment would silently fall back
* to an anchor download under a fixed name — i.e. a browser (not Tauri) that
* lacks the File System Access save picker (`window.showSaveFilePicker`).
* Chromium browsers expose the picker and let the user name the file; Firefox
* and Safari do not, so callers prompt for a file name themselves before saving.
*
* @returns True only in a browser without the save picker; false under Tauri
* (which uses the native save dialog) or when the picker is available.
*/
export function browserSaveFallsBackToDownload(): boolean {
if (isTauri()) return false;
if (typeof window === "undefined") return false;
return (
typeof (window as BrowserFilePickerWindow).showSaveFilePicker !== "function"
);
}
async function saveProjectFileBrowser(
content: string,
defaultName?: string,
): Promise<string | null> {
const fileName = browserSafeFileName(defaultName ?? "project.geolibre.json");
const pickerWindow = window as BrowserFilePickerWindow;
if (pickerWindow.showSaveFilePicker) {
try {
const handle = await pickerWindow.showSaveFilePicker({
suggestedName: fileName,
types: GEOLIBRE_PROJECT_FILE_TYPES,
excludeAcceptAllOption: false,
});
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
return handle.name || fileName;
} catch (error) {
if (isAbortError(error)) return null;
console.warn("Browser project save picker failed", error);
}
}
const blob = new Blob([content], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
return fileName;
}
async function saveTextFileBrowser(
content: string,
options: SaveTextFileOptions,
): Promise<string | null> {
const fileName = browserSafeFileName(options.defaultName);
const pickerWindow = window as BrowserFilePickerWindow;
if (pickerWindow.showSaveFilePicker) {
try {
const handle = await pickerWindow.showSaveFilePicker({
suggestedName: fileName,
types: options.browserTypes,
excludeAcceptAllOption: false,
});
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
return handle.name || fileName;
} catch (error) {
if (isAbortError(error)) return null;
console.warn("Browser file save picker failed", error);
}
}
const blob = new Blob([content], { type: options.mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
return fileName;
}
async function saveBinaryFileBrowser(
content: Uint8Array,
options: SaveBinaryFileOptions,
): Promise<string | null> {
const fileName = browserSafeFileName(options.defaultName);
const pickerWindow = window as BrowserFilePickerWindow;
const blob = new Blob([toArrayBuffer(content)], { type: options.mimeType });
if (pickerWindow.showSaveFilePicker) {
try {
const handle = await pickerWindow.showSaveFilePicker({
suggestedName: fileName,
types: options.browserTypes,
excludeAcceptAllOption: false,
});
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
return handle.name || fileName;
} catch (error) {
if (isAbortError(error)) return null;
console.warn("Browser binary file save picker failed", error);
}
}
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
return fileName;
}
export async function openLocalDataFileWithFallback(
options: LocalDataFileOptions,
): Promise<{
data?: ArrayBuffer;
path: string;
text?: string;
} | null> {
if (isTauri()) {
const selected = await open({
multiple: false,
filters: options.filters,
});
if (!selected || typeof selected !== "string") return null;
const data = options.readBinary
? toArrayBuffer(await readFile(selected))
: undefined;
const text = options.readText ? await readTextFile(selected) : undefined;
return { data, path: selected, text };
}
return new Promise((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
input.accept = options.accept;
input.onchange = async () => {
try {
const file = input.files?.[0];
if (!file) {
resolve(null);
return;
}
const data = options.readBinary ? await file.arrayBuffer() : undefined;
const text = options.readText ? await file.text() : undefined;
resolve({ data, path: file.name, text });
} catch (error) {
reject(error);
}
};
input.click();
});
}
export async function pickLocalPathWithFallback(
options: PickLocalPathOptions = {},
): Promise<string | null> {
if (isTauri()) {
const selected = await open({
directory: options.directory ?? false,
filters: options.filters,
multiple: false,
});
return typeof selected === "string" ? selected : null;
}
// Browsers cannot expose absolute filesystem paths, and Whitebox parameters
// require a real path. Return null so callers surface the desktop-only
// message rather than passing a non-resolvable bare file name.
return null;
}
export async function pickSavePathWithFallback(
options: PickSavePathOptions,
): Promise<string | null> {
if (isTauri()) {
return save({
defaultPath: options.defaultName,
filters: options.filters,
});
}
const pickerWindow = window as BrowserFilePickerWindow;
if (pickerWindow.showSaveFilePicker) {
try {
await pickerWindow.showSaveFilePicker({
suggestedName: options.defaultName,
types: options.browserTypes,
excludeAcceptAllOption: false,
});
} catch (error) {
if (isAbortError(error)) return null;
console.warn("Browser save path picker failed", error);
}
}
// The browser only exposes a leaf file name, never a real filesystem path,
// so return null (matching pickLocalPathWithFallback) rather than handing a
// non-resolvable name to a Whitebox path parameter.
return null;
}
export async function openGeoJsonFile(): Promise<{
data: FeatureCollection;
path: string;
} | null> {
if (!isTauri()) {
console.warn("File dialog requires Tauri runtime");
return null;
}
const selected = await open({
multiple: false,
filters: [{ name: "GeoJSON", extensions: ["geojson", "json"] }],
});
if (!selected || typeof selected !== "string") return null;
const text = await readTextFile(selected);
const data = await parseGeoJsonText(text);
return { data, path: selected };
}
export async function openProjectFile(): Promise<{
project: GeoLibreProject;
path: string;
} | null> {
if (!isTauri()) {
return openProjectFileBrowser();
}
const selected = await open({
multiple: false,
filters: [{ name: "GeoLibre Project", extensions: ["geolibre", "json"] }],
});
if (!selected || typeof selected !== "string") return null;
const text = await readTextFile(selected);
const project = parseProject(text);
return { project, path: selected };
}
/**
* Thrown when a recent project is permanently gone (HTTP 404/410 or a local
* file that no longer exists), signalling the caller that the entry can be
* safely forgotten. Transient failures throw a plain `Error` instead so the
* entry is preserved for a retry.
*/
export class RecentProjectGoneError extends Error {
constructor(message: string) {
super(message);
this.name = "RecentProjectGoneError";
}
}
// Refuse to buffer absurdly large responses into memory (25 MB).
const MAX_PROJECT_URL_BYTES = 25 * 1024 * 1024;
function isFileMissingError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
// Match filesystem "missing file" signals only. Avoid broad substrings like
// "not found" / "cannot find" that also appear in transient IPC errors
// (e.g. "Command not found", Windows os error 3 for a disconnected drive).
return /no such file|os error 2|\benoent\b|cannot find the file|file not found|does not exist/i.test(
message,
);
}
export async function openRecentProjectFile(
path: string,
signal?: AbortSignal,
): Promise<{
project: GeoLibreProject;
path: string;
}> {
if (isHttpUrl(path)) {
const response = await fetch(path, {
headers: { Accept: "application/json, text/plain;q=0.9, */*;q=0.8" },
signal,
});
if (!response.ok) {
const message = `Could not load project URL: HTTP ${response.status} ${response.statusText}`;
if (response.status === 404 || response.status === 410) {
throw new RecentProjectGoneError(message);
}
throw new Error(message);
}
// Only a present Content-Length lets us guard up front. `Number(null)` is
// 0, which would silently pass for chunked/CDN responses that omit it.
const contentLength = response.headers.get("content-length");
if (
contentLength !== null &&
Number(contentLength) > MAX_PROJECT_URL_BYTES
) {
throw new Error("Project file is too large to load (over 25 MB).");
}
const contentType = response.headers.get("content-type") ?? "";
if (/\bhtml\b/i.test(contentType)) {
throw new Error(
`Unexpected content type "${contentType}" - the URL does not appear to be a project file.`,
);
}
return { project: parseProject(await response.text()), path };
}
if (!isTauri()) {
throw new Error(
"Recent local projects can only be reopened in GeoLibre Desktop.",
);
}
let text: string;
try {
text = await invoke<string>("read_project_file", { path });
} catch (error) {
if (isFileMissingError(error)) {
throw new RecentProjectGoneError(
`Project file no longer exists: ${path}`,
);
}
throw error;
}
return { project: parseProject(text), path };
}
export async function saveProjectFile(
content: string,
defaultName?: string,
): Promise<string | null> {
if (!isTauri()) {
return saveProjectFileBrowser(content, defaultName);
}
const path = await save({
filters: [{ name: "GeoLibre Project", extensions: ["geolibre", "json"] }],
defaultPath: defaultName ?? "project.geolibre.json",
});
if (!path) return null;
await writeTextFile(path, content);
return path;
}
/**
* Save a project directly to an already-known local path without prompting.
* Falls back to the save dialog when not running in Tauri (the browser never
* has a writable filesystem path) or when the path is an HTTP(S) URL.
*/
export async function saveProjectFileToPath(
content: string,
path: string,
): Promise<string | null> {
if (!isTauri() || isHttpUrl(path)) {
return saveProjectFile(content, path);