Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
36 changes: 26 additions & 10 deletions crates/geolibre/src/langpack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ fn english_to_pack(pack: &Pack, tools: &[ToolSpec]) -> HashMap<String, String> {
let Some(text) = pack.tools.get(spec.id.trim_start_matches(crate::PREFIX)) else { continue };
put(spec.name, text.name.as_deref());
put(spec.summary, text.description.as_deref());
for p in spec.params {
// RustGIS's own output name field isn't the manifest's `output` file the pack describes.
for p in spec.params.iter().filter(|p| !crate::is_output_name(p)) {
let Some((label, help)) = text.params.get(p.name) else { continue };
put(p.label, label.as_deref());
put(p.help, help.as_deref());
Expand Down Expand Up @@ -567,7 +568,10 @@ mod tests {
"toolMeta": {"whitebox": {"contours_from_raster": {
"name": "Curvas de nível a partir de raster",
"description": "Cria polilinhas de curvas de nível.",
"params": {"interval": {"label": "Intervalo", "description": "Equidistância."}}
"params": {
"interval": {"label": "Intervalo", "description": "Equidistância."},
"output": {"label": "Saída", "description": "Arquivo vetorial de saída."}
}
}}},
"whitebox": {
"categories": {"vector": "Vetor", "remoteSensingSar": "Sensoriamento remoto - SAR"},
Expand All @@ -579,14 +583,24 @@ mod tests {
.to_string()
}

static PARAMS: [ParamSpec; 1] = [ParamSpec {
name: "interval",
label: "Interval",
kind: ParamKind::Number,
required: false,
default: "",
help: "Contour interval value.",
}];
static PARAMS: [ParamSpec; 2] = [
ParamSpec {
name: "interval",
label: "Interval",
kind: ParamKind::Number,
required: false,
default: "",
help: "Contour interval value.",
},
ParamSpec {
name: crate::OUTPUT,
label: crate::OUTPUT_LABEL,
kind: ParamKind::Text,
required: false,
default: "",
help: crate::OUTPUT_HELP,
},
];

fn no_run(_: &dyn rustgis_analysis::Inputs, _: &Value) -> Result<rustgis_analysis::ToolResult, String> {
Err("not run".into())
Expand Down Expand Up @@ -632,6 +646,8 @@ mod tests {
assert_eq!(map.get("Remote Sensing").map(String::as_str), Some("Sensoriamento remoto"));
assert!(!map.contains_key("SAR"), "the same as the English, or missing: left out");
assert!(!map.contains_key("SAR Info"), "a tool the pack doesn't name stays in English");
// RustGIS's output name field isn't the output file the pack describes (#2224).
assert!(!map.contains_key(crate::OUTPUT_LABEL) && !map.contains_key(crate::OUTPUT_HELP), "{map:?}");
}

#[test]
Expand Down
97 changes: 92 additions & 5 deletions crates/geolibre/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ struct Meta {
schema: &'static [ParamSpec],
category: String,
params: Vec<MetaParam>,
/// The form has the [`OUTPUT`] field naming the layers the outputs come back as.
names_outputs: bool,
}

/// The parameter that names a tool's new layers, under the key the built-in tools use (#2224).
pub const OUTPUT: &str = "output";
/// The [`OUTPUT`] field's label, as on the built-in tools.
const OUTPUT_LABEL: &str = "Output Name";
/// The [`OUTPUT`] field's help: the same text on every tool, so it can be translated.
const OUTPUT_HELP: &str = "Name of the new layer. Empty: the tool's name. With several outputs, each adds its own name to it. A name already in use gets a number.";
/// The longest layer name [`OUTPUT`] keeps (the engine's longest name).
const MAX_OUTPUT_NAME: usize = 200;

/// `p` is the [`OUTPUT`] field RustGIS adds, not one of the manifest's parameters.
pub fn is_output_name(p: &ParamSpec) -> bool {
p.name == OUTPUT && p.label == OUTPUT_LABEL && p.kind == ParamKind::Text
}

static META: Mutex<Option<HashMap<String, Meta>>> = Mutex::new(None);
Expand Down Expand Up @@ -252,7 +268,8 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> {
let optional = !p.get("required").and_then(Value::as_bool).unwrap_or(false);
let default = defaults.and_then(|d| d.get(pname)).filter(|v| optional && !v.is_null()).cloned();
meta.push(MetaParam { name: pname.to_string(), role, data, default });
// Outputs are written to a scratch folder and come back as layers: no form field.
// Outputs are written to a scratch folder and come back as layers: no field of their own
// (the one [`OUTPUT`] field below names the layers).
if role == Role::Output {
continue;
}
Expand Down Expand Up @@ -306,6 +323,19 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> {
help: leak(help),
});
}
// One optional field names the new layers. A tool with an option or input of its own called
// `output` keeps it, and its outputs keep the tool's name.
let names_outputs = meta.iter().any(|p| p.role == Role::Output) && !params.iter().any(|p| p.name == OUTPUT);
if names_outputs {
params.push(ParamSpec {
name: OUTPUT,
label: OUTPUT_LABEL,
kind: ParamKind::Text,
required: false,
default: "",
help: OUTPUT_HELP,
});
}
let spec = ToolSpec {
id: leak(format!("{PREFIX}{id}")),
name: leak(name),
Expand All @@ -315,7 +345,7 @@ fn spec_of(m: &Value) -> Option<(ToolSpec, Meta)> {
run: rustgis_analysis::external_placeholder,
};
let schema = spec.params;
Some((spec, Meta { schema, category, params: meta }))
Some((spec, Meta { schema, category, params: meta, names_outputs }))
}

/// `g` with every point converted by `f`, or `None` when a point can't be (rather than
Expand Down Expand Up @@ -626,6 +656,9 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu
};

let n_outputs = meta.params.iter().filter(|p| p.role == Role::Output).count();
let given = if meta.names_outputs { output_name(spec, params, &mut job.notes)? } else { None };
let base = given.as_deref().unwrap_or(spec.name);
let (mut renamed, mut shortened) = (Vec::new(), false);
for p in &meta.params {
match p.role {
Role::Input => {
Expand All @@ -638,9 +671,21 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu
Role::Output => {
let file = format!("{}.{}", safe(&p.name), output_ext(p, meta));
job.args.push((p.name.clone(), Arg::Files(vec![FileRef::Work(file.clone())])));
let name =
if n_outputs > 1 { format!("{} {}", spec.name, label_of(&p.name).to_lowercase()) } else { spec.name.to_string() };
job.outputs.push((file, name));
// Each output's own name after the one given, kept whole within the limit.
let suffix = if n_outputs > 1 { format!(" {}", label_of(&p.name).to_lowercase()) } else { String::new() };
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let room = MAX_OUTPUT_NAME.saturating_sub(suffix.chars().count());
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
shortened |= given.is_some() && base.chars().count() > room;
let name: String = base.chars().take(room).chain(suffix.chars()).collect();
// A name a layer, a table or an earlier output of this run has gets a number, so two
// runs don't give two layers of one name. Said when it was the name given.
let taken = |n: &str| {
inputs.dataset(n).is_some() || inputs.raster(n).is_some() || job.outputs.iter().any(|(_, o)| o.eq_ignore_ascii_case(n))
};
let free = numbered(base, &suffix, taken);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
if given.is_some() && free != name {
renamed.push(format!("'{name}' is now '{free}'"));
}
job.outputs.push((file, free));
}
Role::Option => {
let Some(v) = value_of(&p.name).map(|v| option_value(v, p.data)) else { continue };
Expand All @@ -655,9 +700,51 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu
}
}
}
// One notice per kind, with a count.
if !renamed.is_empty() {
job.notes.push(format!("{}: {} output name(s) in use already, so numbered: {}", spec.name, renamed.len(), renamed.join(", ")));
}
if shortened {
job.notes.push(format!("{}: the output name is cut to fit each output's own name within {MAX_OUTPUT_NAME} characters", spec.name));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
Ok(job)
}

/// The layer name given in [`OUTPUT`], trimmed, or `None` for the tool's own name. Cut to
/// [`MAX_OUTPUT_NAME`] characters, which is said.
fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec<String>) -> Result<Option<String>, String> {
let name = match params.get(OUTPUT) {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(s)) => s.trim(),
Some(_) => return Err(format!("{}: '{OUTPUT}' is the new layer's name and must be text", spec.name)),
};
if name.is_empty() {
return Ok(None);
}
let n = name.chars().count();
if n > MAX_OUTPUT_NAME {
notes.push(format!("{}: the output name is cut from {n} to {MAX_OUTPUT_NAME} characters", spec.name));
}
Ok(Some(name.chars().take(MAX_OUTPUT_NAME).collect()))
}

/// `base` with `suffix` (one output's own name) after it, or, while `taken` claims that, the
/// first with ` 2`, ` 3`… after the suffix that it doesn't. Each fits [`MAX_OUTPUT_NAME`]
/// characters by cutting `base`, never the suffix or the number.
fn numbered(base: &str, suffix: &str, taken: impl Fn(&str) -> bool) -> String {
let fit = |tail: &str| -> String {
let room = MAX_OUTPUT_NAME.saturating_sub(tail.chars().count());
base.chars().take(room).chain(tail.chars()).collect()
};
let mut name = fit(suffix);
let mut k = 1u64;
while taken(&name) {
k += 1;
name = fit(&format!("{suffix} {k}"));
}
name
}

/// Coordinates that can't be longitude/latitude (a tool kept the working coordinate system).
fn looks_projected(ds: &Dataset) -> bool {
let e = ds.extent();
Expand Down
120 changes: 118 additions & 2 deletions crates/geolibre/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ impl Inputs for Fixture {
}
}

/// The fixture, plus layers of these names that hold nothing a tool reads.
struct TakenNames<'a>(&'a Fixture, &'a [&'a str]);

impl Inputs for TakenNames<'_> {
fn dataset(&self, layer: &str) -> Option<&Dataset> {
self.0.dataset(layer).or_else(|| self.1.contains(&layer).then_some(&self.0.points))
}
fn selection(&self, _: &str) -> &[usize] {
&[]
}
fn raster(&self, layer: &str) -> Option<RasterInput<'_>> {
self.0.raster(layer)
}
}

/// The fixture, or `None` (the test is skipped) when no runner is installed: set
/// `RUSTGIS_GEOLIBRE` to a `geolibre` executable, or put one on PATH, to run these.
fn setup() -> Option<Fixture> {
Expand Down Expand Up @@ -95,7 +110,9 @@ fn manifests_become_tool_forms() {
// Grouped by the runner's taxonomy; a runner from before it, by the coarse category.
assert!(matches!(slope.toolbox, "GeoLibre › Terrain › Derivatives" | "GeoLibre › Raster"), "{}", slope.toolbox);
assert_eq!(slope.params.first().map(|p| p.kind), Some(ParamKind::RasterLayer));
assert!(slope.params.iter().all(|p| p.name != "output"), "outputs are not form fields");
// Outputs have no field of their own: one optional field names the new layer (#2224).
let outputs: Vec<&ParamSpec> = slope.params.iter().filter(|p| p.name == OUTPUT).collect();
assert!(matches!(outputs[..], [p] if is_output_name(p) && !p.required && p.default.is_empty()), "{outputs:?}");
let units = slope.params.iter().find(|p| p.name == "units").unwrap();
assert!(matches!(units.kind, ParamKind::Choice(c) if c.contains(&"percent")));
// Defaults are JSON text (as for the built-in tools): the form and the runner parse it.
Expand Down Expand Up @@ -128,11 +145,110 @@ fn inputs_of_several_layers_are_layer_lists() {
("inputs", ParamKind::RasterLayers),
("vectors", ParamKind::VectorLayers),
("files", ParamKind::Text),
("dem", ParamKind::RasterLayer)
("dem", ParamKind::RasterLayer),
("output", ParamKind::Text)
]
);
}

/// The layers a run adds are named by `output`, as for the built-in tools, else by the tool;
/// a name in use gets a number (#2224).
#[test]
fn outputs_are_named_by_the_output_field() {
let f = Fixture::new();
let one = json!({
"id": "contours", "display_name": "Contours From Raster", "category": "Raster", "summary": "",
"params": [
{"name": "input", "io_role": "input", "data_kind": "raster", "required": true, "schema": {"kind": "input"}},
{"name": "output", "io_role": "output", "data_kind": "vector", "required": false, "schema": {"kind": "output"}}
]
});
let (spec, meta) = spec_of(&one).unwrap();
let field = spec.params.iter().find(|p| p.name == OUTPUT).unwrap();
assert!(is_output_name(field) && field.label == "Output Name", "{field:?}");
let job = |params: Value| {
let params = rustgis_analysis::resolve_params(&spec, &params)?;
prepare_with(&spec, &meta, &f, &params)
};
let named = |params: Value| job(params).map(|j| j.outputs.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>());
// Empty (the form's start), blank or left out: the tool's name, as before.
for p in [json!({"input": "dem"}), json!({"input": "dem", "output": ""}), json!({"input": "dem", "output": " "})] {
assert_eq!(named(p.clone()).unwrap(), ["Contours From Raster"], "{p}");
}
let given = job(json!({"input": "dem", "output": " Contours 10 m "})).unwrap();
assert_eq!(given.outputs, [("output.geojson".to_string(), "Contours 10 m".to_string())]);
// The file the runner writes doesn't change: the name is only the layer's.
assert_eq!(given.argv("/work"), ["--input=/work/in0-dem.tif", "--output=/work/output.geojson"]);
assert!(given.notes.is_empty(), "{:?}", given.notes);
// A layer has the name already: numbered, and said.
let taken = job(json!({"input": "dem", "output": "pts"})).unwrap();
assert_eq!(taken.outputs[0].1, "pts 2");
assert!(taken.notes.iter().any(|n| n.contains("1 output name(s)") && n.contains("'pts' is now 'pts 2'")), "{:?}", taken.notes);
// Too long: cut, and said.
let long = job(json!({"input": "dem", "output": "x".repeat(300)})).unwrap();
assert_eq!(long.outputs[0].1.chars().count(), MAX_OUTPUT_NAME);
assert!(long.notes.iter().any(|n| n.contains("cut from 300 to 200")), "{:?}", long.notes);
// Not text: an error, not a guess.
let e = job(json!({"input": "dem", "output": 5})).unwrap_err();
assert!(e.contains("must be text"), "{e}");

// Several outputs: each adds its label to the name, and two can't take one name.
let two = json!({
"id": "flow", "display_name": "Flow", "category": "Hydrology", "summary": "",
"params": [
{"name": "dem", "io_role": "input", "data_kind": "raster", "required": true},
{"name": "streams", "io_role": "output", "data_kind": "raster"},
{"name": "basins", "io_role": "output", "data_kind": "raster"}
]
});
let (spec2, meta2) = spec_of(&two).unwrap();
let names = |params: Value| {
let params = rustgis_analysis::resolve_params(&spec2, &params).unwrap();
prepare_with(&spec2, &meta2, &f, &params).unwrap().outputs.into_iter().map(|(_, n)| n).collect::<Vec<_>>()
};
assert_eq!(names(json!({"dem": "dem"})), ["Flow streams", "Flow basins"]);
assert_eq!(names(json!({"dem": "dem", "output": "Rio Doce"})), ["Rio Doce streams", "Rio Doce basins"]);
// A long name leaves room for each output's own: every name within the limit, still apart (review).
let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "x".repeat(200)})).unwrap();
let long = prepare_with(&spec2, &meta2, &f, &params).unwrap();
let long_names: Vec<&str> = long.outputs.iter().map(|(_, n)| n.as_str()).collect();
assert!(long_names.iter().all(|n| n.chars().count() == MAX_OUTPUT_NAME), "{long_names:?}");
assert!(long_names[0].ends_with("x streams") && long_names[1].ends_with("x basins"), "{long_names:?}");
assert_eq!(long.notes.iter().filter(|n| n.contains("cut to fit")).count(), 1, "{:?}", long.notes);
// Both names in use: one notice with the count, not one per output (review).
let fg = TakenNames(&f, &["Taken streams", "Taken basins"]);
let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "Taken"})).unwrap();
let both = prepare_with(&spec2, &meta2, &fg, &params).unwrap();
assert_eq!(both.outputs.iter().map(|(_, n)| n.as_str()).collect::<Vec<_>>(), ["Taken streams 2", "Taken basins 2"]);
let numbered_notes: Vec<&String> = both.notes.iter().filter(|n| n.contains("numbered")).collect();
assert!(matches!(numbered_notes[..], [n] if n.contains("2 output name(s)")), "{:?}", both.notes);
// A long name whose output name is taken: the number goes after the output's name, which is
// kept whole (review).
let long_streams = format!("{} streams", "x".repeat(192));
let fl = TakenNames(&f, &[long_streams.as_str()]);
let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "x".repeat(200)})).unwrap();
let near = prepare_with(&spec2, &meta2, &fl, &params).unwrap();
let first = &near.outputs[0].1;
assert!(first.ends_with("x streams 2") && first.chars().count() == MAX_OUTPUT_NAME, "{first}");
assert_eq!(numbered("a", "", |n| ["a", "a 2"].contains(&n)), "a 3");
assert_eq!(numbered(&"y".repeat(200), "", |n| n.chars().all(|c| c == 'y')).chars().count(), MAX_OUTPUT_NAME);

// A tool whose own option is called `output` keeps it; its outputs keep the tool's name.
let own = json!({
"id": "own", "display_name": "Own", "category": "Raster", "summary": "",
"params": [
{"name": "output", "data_kind": "string", "required": false, "schema": {"kind": "string"}},
{"name": "result", "io_role": "output", "data_kind": "raster"}
]
});
let (spec3, meta3) = spec_of(&own).unwrap();
assert!(!meta3.names_outputs && spec3.params.iter().filter(|p| p.name == OUTPUT).all(|p| !is_output_name(p)));
let params = rustgis_analysis::resolve_params(&spec3, &json!({"output": "fast"})).unwrap();
let j = prepare_with(&spec3, &meta3, &f, &params).unwrap();
assert_eq!(j.outputs[0].1, "Own");
assert!(j.argv("/work").contains(&"--output=fast".to_string()), "{:?}", j.argv("/work"));
}

#[test]
fn composite_bands_legacy_manifest_selects_and_stages_rasters_in_order() {
// The input/output subset of `geolibre manifests` in 1.8.0 and 1.8.1 (#1684).
Expand Down
5 changes: 5 additions & 0 deletions docs/user-guide/analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -1401,6 +1401,11 @@ list syntax, and check the tool's own help for what a weight field left blank me
become standalone tables; text reports appear in the tool's messages.
- LiDAR and other inputs RustGIS doesn't open as layers take a file path, read like Add Data
reads one. Outputs are written to a fresh scratch folder and loaded from there.
- **Output Name** names the new layer, as on the built-in tools; left empty, the layer takes the
tool's name (in English). A tool with several outputs adds each output's name to it
(`Flow streams`, `Flow basins`). A name a layer or table already has gets a number
(`Contours 2`), and a name you typed that gets one is said in the messages. From the command
line it is the same `output` key: `"params":{"input":"dem","output":"Slope 30 m"}`.
- Each run is a separate `geolibre` process, so a tool that fails can't take RustGIS down.
- From the command line: `gp.run={"tool":"geolibre:slope","params":{"input":"dem"}}`;
`gp.tools` lists every tool's parameters, `gp.geolibre` shows the runner in use and
Expand Down
Loading