Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3323,7 +3323,7 @@ pub fn shapefile_for_dbf(path: &Path) -> Option<std::path::PathBuf> {

/// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole
/// and streamed reads. A missing sidecar keeps the usual lowercase path for the error.
pub(crate) fn dbf_sidecar(path: &Path) -> std::path::PathBuf {
pub fn dbf_sidecar(path: &Path) -> std::path::PathBuf {
["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"]
.iter()
.map(|e| path.with_extension(e))
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ info.commands
info.databaseTables database password?
info.diagnostics
info.fileColumns path delimiter? layer? crs?
info.fileLayers path crs?
info.fileLayers path crs? link?
info.infographic layer?
info.project nameFilter? includeFields?
job.new name description? assigned? viewExtent?
Expand Down
73 changes: 66 additions & 7 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ pub const MAX_LAYER_NAME: usize = 200;
pub fn commands() -> Vec<C> {
vec![
C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: bool, "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV x/longitude column", "y"?: "CSV y/latitude column", "wkt"?: "CSV WKT geometry column", "delimiter"?: ","|";"|"\\t"|"|"}"#),
.params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV x/longitude column", "y"?: "CSV y/latitude column", "wkt"?: "CSV WKT geometry column", "delimiter"?: ","|";"|"\\t"|"|"}"#),
C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(
r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#,
),
C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
.params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)"}"#),
.params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "link"?: "bool: for a file Add Data can link instead of copying (GeoPackage, GeoParquet, FlatGeobuf, Shapefile, .geojson; desktop), also say how it would take it, as link: linked (what it does without stream) and copy (whether it can be read whole); it opens each table, so only when asked"}"#),
C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params(
r#"{"path": "a delimited text file (CSV, TSV, TXT, DAT, or gzip-compressed text) or a spreadsheet", "delimiter"?: ","|";"|"\\t"|"|", "layer"?: "a spreadsheet's sheet (the first by default)", "crs"?: "EPSG:… (or WKT), as layer.addData: a projected system keeps the columns found by name"}"#,
),
Expand Down Expand Up @@ -2511,6 +2511,48 @@ fn streams_geojson(p: &Value, path: &str) -> bool {
.unwrap_or_else(|| std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > rustgis_data::source::geojson::IN_PLACE_ABOVE))
}

/// Whether Add Data reads a GeoPackage table, GeoParquet or FlatGeobuf file holding `count`
/// features in place, without `"stream"`: when it holds more than
/// [`STREAM_ABOVE`](rustgis_map::source::STREAM_ABOVE), or doesn't say how many.
fn streams_by_count(count: Option<u64>) -> bool {
count.is_none_or(|c| c > rustgis_map::source::STREAM_ABOVE)
}

/// What Add Data's question, copy a file into the project or link to it (#2350), starts from:
/// `{"linked", "copy"}`, or `None` for a file it doesn't ask about. Asked about: a `.geojson`
/// file, a Shapefile, a GeoPackage (one choice for all of `tables`), GeoParquet and FlatGeobuf.
/// Not asked: LiDAR (always linked), a `.json` (it may be a city model, decided by size as
/// before), files read whole, and those it can't open (`layer.addData` then says why).
/// `linked` is what `layer.addData` does without `"stream"`, by the same rules
/// ([`streams_geojson`], [`past_cap_shapefile`] and [`streams_shapefile`], [`streams_by_count`],
/// linked when any table would be). `copy` is whether it can be read whole: a GeoJSON file or a
/// Shapefile (and its `.dbf`) within [`rustgis_data::io::max_bytes`]; a source's whole read is
/// bounded where it is read.
#[cfg(not(target_arch = "wasm32"))]
fn link_choice(path: &str, tables: &[String]) -> Option<Value> {
let lower = path.to_ascii_lowercase();
let unset = json!({});
let fits = |p: &Path| std::fs::metadata(p).is_ok_and(|m| m.len() <= rustgis_data::io::max_bytes());
let (linked, copy) = if lower.ends_with(".geojson") {
(streams_geojson(&unset, path), fits(Path::new(path)))
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
} else if lower.ends_with(".shp") {
let shp = Path::new(path);
let linked = past_cap_shapefile(path, &unset).is_some() || streams_shapefile(&unset, path);
(linked, fits(shp) && fits(&rustgis_data::io::dbf_sidecar(shp)))
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
} else if rustgis_data::source::is_source_name(path) && !lower.ends_with(".las") && !lower.ends_with(".laz") {
let gpkg = lower.ends_with(".gpkg");
let mut linked = false;
for table in tables.iter().map(|t| gpkg.then_some(t.as_str())) {
let src = rustgis_data::source::open_path(Path::new(path), table).ok()?;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
linked |= streams_by_count(src.info().count);
}
(linked, true)
} else {
return None;
};
Some(json!({"linked": linked, "copy": copy}))
}

/// A large Shapefile or GeoJSON file, read in place, as Add Data opens it ahead (#2446).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) struct Opened {
Expand Down Expand Up @@ -2542,9 +2584,7 @@ impl Opened {
let stamp = file_stamp(path);
let source = open();
let whole = match &source {
Ok(src) if may_load && src.info().count.is_some_and(|c| c <= rustgis_map::source::STREAM_ABOVE) => {
Some(rustgis_data::source::materialize(src.as_ref()))
}
Ok(src) if may_load && !streams_by_count(src.info().count) => Some(rustgis_data::source::materialize(src.as_ref())),
_ => None,
};
Self { stamp, source, whole }
Expand Down Expand Up @@ -3071,8 +3111,27 @@ fn apply_styles(s: &mut Session, id: u32, styles: &[(String, rustgis_data::kml::
}

/// The layers a file holds, without adding them: a GeoPackage's feature tables, a GDAL dataset's
/// layers, or the one layer of other files. `layer.addData` takes a name with `"layer"`.
/// layers, or the one layer of other files. `layer.addData` takes a name with `"layer"`. A file
/// Add Data can link instead of copying says how it would take it, in `"link"`, when `"link": true`
/// asks ([`link_choice`]): it opens each of a GeoPackage's tables, which the other callers (List
/// Tables, Repair Data Source) don't need.
fn file_layers(s: &mut Session, p: &Value) -> CmdResult {
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let mut v = listed_layers(s, p)?;
#[cfg(not(target_arch = "wasm32"))]
if b(p, "link") == Some(true)
&& let Some(path) = ps(p, "path")
{
let tables: Vec<String> = v["layers"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
if let Some(link) = link_choice(path, &tables) {
v["link"] = link;
}
}
Ok(v)
}

/// [`file_layers`]' listing.
fn listed_layers(s: &mut Session, p: &Value) -> CmdResult {
let path = s_req(p, "path")?;
let path = &*gdb_path(path);
let err = |e: rustgis_data::DataError| format!("{path}: {e}");
Expand Down Expand Up @@ -3390,7 +3449,7 @@ fn add_source_read(
// of points; its colours come from a sample of it.
let lidar = info.format == "LiDAR";
let style = if lidar { lidar_renderer(src.as_ref(), s.map().layers.len() as u32) } else { None };
let stream = b(p, "stream").unwrap_or(lidar || info.count.is_none_or(|c| c > rustgis_map::source::STREAM_ABOVE));
let stream = b(p, "stream").unwrap_or(lidar || streams_by_count(info.count));
// A name given applies to a single table.
let name = match ps(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
Some(n) if ids.is_empty() => n.to_string(),
Expand Down
112 changes: 112 additions & 0 deletions crates/engine/tests/integration/link_choice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
//! Add Data asks whether to copy a file into the project or link to it (#2350): `info.fileLayers`
//! says, when asked (`"link": true`), for a file Add Data can link, which it would do without
//! being told, and whether it can copy it at all. What it says is what `layer.addData` does
//! without `"stream"`. Unasked, it says nothing more than before.

use crate::portable_projects::common::{Fixture, gpkg_file, session};
use rustgis_engine::Session;
use rustgis_engine::data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as V};
use serde_json::{Value, json};
use std::path::Path;

/// `n` points with a name each.
fn points(n: usize) -> Dataset {
let mut ds = Dataset::new("points", GeometryType::Point, vec![Field::new("name", FieldType::Text)]);
for i in 0..n {
let x = (i % 1000) as f64 * 0.01;
let y = (i / 1000) as f64 * 0.01;
ds.push(Some(Geometry::Point(Coord::new(x, y))), vec![V::Text(format!("p{i}"))]);
}
ds
}

fn listed(s: &mut Session, path: &Path) -> Value {
s.run("info.fileLayers", &json!({"path": path, "link": true})).unwrap()
}

/// Whether `layer.addData` without `"stream"` keeps the file linked (read in place).
fn added_linked(path: &Path) -> bool {
let mut s = session();
let id = s.run("layer.addData", &json!({"path": path})).unwrap()["layer"].as_u64().unwrap() as u32;
s.map().layer(id).unwrap().is_streamed()
}

#[test]
fn a_linkable_file_says_what_add_data_does_without_being_told() {
let f = Fixture::new("link-choice");
let small = points(10);
let large = points(rustgis_engine::map::source::STREAM_ABOVE as usize + 1);
let mut s = session();
for ext in ["geojson", "shp", "fgb", "parquet", "gpkg"] {
for (size, ds) in [("small", &small), ("large", &large)] {
let path = f.file(&format!("{size}/points.{ext}"));
rustgis_engine::data::io::write_path(ds, &path).unwrap();
if ext == "geojson" && size == "large" {
// A GeoJSON file is linked by its size: past it, with spaces after the document.
use std::io::Write;
let past = rustgis_engine::data::source::geojson::IN_PLACE_ABOVE + 1;
let len = std::fs::metadata(&path).unwrap().len();
let pad = vec![b' '; past.saturating_sub(len) as usize];
std::fs::OpenOptions::new().append(true).open(&path).unwrap().write_all(&pad).unwrap();
}
let v = listed(&mut s, &path);
let link = &v["link"];
assert_eq!(link["linked"], size == "large", "{ext} {size}: {v}");
assert_eq!(link["copy"], true, "{ext} {size}: {v}");
assert_eq!(added_linked(&path), size == "large", "{ext} {size}: layer.addData disagrees with {v}");
}
}
}

#[test]
fn other_files_are_not_asked_about() {
let f = Fixture::new("link-none");
let ds = points(3);
let mut s = session();
// A .json may be a city model and is decided by size as before; the others are always read
// whole, so the project holds them.
for ext in ["json", "csv", "kml", "gpx"] {
let path = f.file(&format!("points.{ext}"));
rustgis_engine::data::io::write_path(&ds, &path).unwrap();
let v = listed(&mut s, &path);
assert!(v.get("link").is_none(), "{ext}: {v}");
}
}

#[test]
fn a_file_too_large_to_read_whole_can_only_be_linked() {
let f = Fixture::new("link-only");
let ds = points(200);
let mut s = session();
for ext in ["geojson", "shp"] {
let path = f.file(&format!("points.{ext}"));
rustgis_engine::data::io::write_path(&ds, &path).unwrap();
let v = rustgis_engine::data::io::with_max_bytes(1024, || listed(&mut s, &path));
assert_eq!(v["link"]["copy"], false, "{ext}: {v}");
assert_eq!(listed(&mut s, &path)["link"]["copy"], true, "{ext}");
}
}

#[test]
fn a_shapefile_with_an_upper_case_table_can_be_copied() {
let f = Fixture::new("link-dbf");
let path = f.file("points.shp");
rustgis_engine::data::io::write_path(&points(3), &path).unwrap();
std::fs::rename(path.with_extension("dbf"), path.with_extension("DBF")).unwrap();
let mut s = session();
assert_eq!(listed(&mut s, &path)["link"], json!({"linked": false, "copy": true}));
}

#[test]
fn a_geopackage_of_several_tables_has_one_choice_for_them_all() {
let f = Fixture::new("link-gpkg");
let path = f.file("survey.gpkg");
gpkg_file(&path, &["roads", "wells"]);
let mut s = session();
let v = listed(&mut s, &path);
assert_eq!(v["count"], 2, "{v}");
assert_eq!(v["link"], json!({"linked": false, "copy": true}), "{v}");
// Unasked (List Tables, Repair Data Source): no tables opened, nothing more said.
let plain = s.run("info.fileLayers", &json!({"path": path})).unwrap();
assert!(plain.get("link").is_none(), "{plain}");
}
1 change: 1 addition & 0 deletions crates/engine/tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod define_projection;
mod geojson_crs;
mod geometry_calculator;
mod kml_duplicate_data;
mod link_choice;
mod measurement_units;
mod move_shared_vertex;
mod never_silent_reading;
Expand Down
Loading
Loading