diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 54e6ce163f..0cbf71bf3c 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -657,6 +657,8 @@ fn search_commands(s: &Session, a: &Value) -> Result { .iter() // Internal plumbing the model has no use for. .filter(|c| !matches!(c.id, "gp.finish" | "info.commands")) + // Commands of an extension the user turned off (#1752). + .filter(|c| s.extensions().blocks(c.id).is_none()) .filter_map(|c| { let (id, label, loc, params) = (c.id.to_lowercase(), c.label.to_lowercase(), c.location.to_lowercase(), c.params.to_lowercase()); diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index fc5d907a17..e551e09fd5 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -25,10 +25,10 @@ use super::ps; use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { - vec![C::new("cube.trend", "Trend Analysis", "Analyze › Image Analysis", trend_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( + vec![C::new("cube.trend", "Trend Analysis", "Analyze › Workflows", trend_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI, "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, ), - C::new("cube.reduce", "Summarise a Data Cube over Time", "Analyze › Image Analysis", reduce_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( + C::new("cube.reduce", "Summarise a Data Cube over Time", "Analyze › Workflows", reduce_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, )] } diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index 578b6bc58b..a3f9b58c07 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -1,5 +1,5 @@ -//! Analyze › Image Classification (Deep Learning Tools), Publish › Package (Deep Learning) and -//! Analyze › Imagery Sharing (Create Hosted Imagery): neural-network pixel classification with models kept +//! Imagery › Image Classification (Deep Learning Tools), Publish › Package (Deep Learning) and +//! Imagery › Imagery Sharing (Create Hosted Imagery): neural-network pixel classification with models kept //! in the project and shared as packages, and rasters cut into web map tiles. use std::collections::HashMap; @@ -62,7 +62,7 @@ fn need_model(s: &Session) -> Option<&'static str> { pub fn commands() -> Vec { vec![ - C::new("dl.train", "Train Deep Learning Model", "Analyze › Image Classification", |s, p| { + C::new("dl.train", "Train Deep Learning Model", "Imagery › Image Classification", |s, p| { let (m, unread) = train(s, p)?; unread.say(s); let mut r = json!({"model": m.name, "accuracy": m.accuracy, "classes": m.model.classes, "epochs": m.epochs}); @@ -72,7 +72,7 @@ pub fn commands() -> Vec { }).inputs(training_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_raster) .params(r#"{"layer": raster, "training": polygon layer, "classField": field naming each polygon's class, "bands"?: [1-based], "hidden"?: [units per hidden layer] (default [32, 16]), "epochs"?: 1..500 (default 60), "model"?: name}"#), - C::new("dl.classify", "Deep Learning Tools", "Analyze › Image Classification", classify).inputs(classify_inputs).roles(&[]).effects(crate::policy::Effects::NONE).when(need_raster).params( + C::new("dl.classify", "Deep Learning Tools", "Imagery › Image Classification", classify).inputs(classify_inputs).roles(&[]).effects(crate::policy::Effects::NONE).when(need_raster).params( r#"{"layer": raster, "model"?: a trained model's name, "training"?: polygon layer, "classField"?: field, "bands"?: [1-based], "hidden"?: [units], "epochs"?: 1..500 (without a model: train one first, as dl.train), "name"?: output, "ran"?: (internal: classes the app has worked out)}"#, ), C::new("dl.package", "Deep Learning Package", "Publish › Package", |s, p| { @@ -84,7 +84,7 @@ pub fn commands() -> Vec { .view() .when(need_model) .params(r#"{"model"?: name (default: the last trained), "path": "*.rgisdlpk"}"#), - C::new("dl.import", "Import Deep Learning Package", "Analyze › Image Classification", |s, p| { + C::new("dl.import", "Import Deep Learning Package", "Imagery › Image Classification", |s, p| { let bytes = read_bytes(p)?; // Only the model is inflated, whatever else the package holds. let entries = rustgis_data::zip::read_matching(&bytes, |n| n == "model.json")?; @@ -110,14 +110,14 @@ pub fn commands() -> Vec { Ok(json!({"model": name})) }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"path"?: "*.rgisdlpk", "data"?: base64}"#), - C::new("dl.remove", "Delete Model", "Analyze › Image Classification", |s, p| { + C::new("dl.remove", "Delete Model", "Imagery › Image Classification", |s, p| { let i = model_index(s, p)?; s.project.dl_models.remove(i); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_model) .params(r#"{"model": name}"#), - C::new("imagery.hostedImagery", "Create Hosted Imagery", "Analyze › Imagery Sharing", hosted).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().when(need_raster).params( + C::new("imagery.hostedImagery", "Create Hosted Imagery", "Imagery › Imagery Sharing", hosted).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().when(need_raster).params( r#"{"layer": raster, "path": "*.zip" (z/x/y.png tiles, tiles.json and a viewer page), "minZoom"?: 0..22, "maxZoom"?: 0..22 (default: the raster's resolution)}"#, ), ] diff --git a/crates/engine/src/cmd/extensions.rs b/crates/engine/src/cmd/extensions.rs new file mode 100644 index 0000000000..cf83680a8a --- /dev/null +++ b/crates/engine/src/cmd/extensions.rs @@ -0,0 +1,49 @@ +//! Extensions (#1752): list them, and turn them on or off. See [`crate::extensions`]. + +use serde_json::{Value, json}; + +use super::{bool_value, ps}; +use crate::{CmdResult, CommandSpec as C, Session}; + +pub fn commands() -> Vec { + use crate::policy::{Effect, Effects}; + vec![ + // Listing reads nothing of the user's and changes nothing; turning one on or off is + // Reserved, as `plugin.enable` is. + C::new("extension.list", "Extensions", "Plugins › Extensions", list).roles(&[]).effects(Effects::NONE).view(), + C::new("extension.enable", "Enable Extension", "Plugins › Extensions", enable) + .roles(&[]) + .effects(Effects::NONE.with(Effect::Reserved)) + .view() + .params(r#"{"id": extension id (see extension.list), "enabled"?: bool (default true)}"#), + C::new("extension.disable", "Disable Extension", "Plugins › Extensions", disable) + .roles(&[]) + .effects(Effects::NONE.with(Effect::Reserved)) + .view() + .params(r#"{"id": extension id (see extension.list)}"#), + ] +} + +fn list(s: &mut Session, _: &Value) -> CmdResult { + Ok(s.extensions().list()) +} + +fn enable(s: &mut Session, p: &Value) -> CmdResult { + // Text that isn't clearly true or false is refused, not read as false: it would turn a whole + // part of RustGIS off. + let on = match p.get("enabled") { + None | Some(Value::Null) => true, + Some(v) => bool_value(v).ok_or("enabled must be true or false")?, + }; + set(s, p, on) +} + +fn disable(s: &mut Session, p: &Value) -> CmdResult { + set(s, p, false) +} + +fn set(s: &mut Session, p: &Value, on: bool) -> CmdResult { + let id = ps(p, "id").map(str::trim).filter(|id| !id.is_empty()).ok_or("id is required (see extension.list)")?; + let e = s.set_extension(id, on)?; + Ok(json!({"id": e.id, "name": e.name, "enabled": on, "tab": e.tab})) +} diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 9391cbb44e..298b9ce73f 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -38,45 +38,45 @@ fn first() -> String { pub fn commands() -> Vec { vec![ - C::new("raster.georeference", "Georeference", "Analyze › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("raster.georeference", "Georeference", "Imagery › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minLon, minLat, maxLon, maxLat], "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326), "crs"?: the output's (default pointsCrs), "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF)}"#, ), - C::new("raster.project", "Project Raster", "Analyze › Alignment", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("raster.project", "Project Raster", "Analyze › Raster", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), - C::new("raster.rasterize", "Polygons to Raster", "Analyze › Alignment", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, ), // A fit is a measurement of the points, not a project change: no undo step. - C::new("raster.gcpFit", "Control Point Fit", "Analyze › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( + C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"points": [[column, row, x, y, on?], …] (on: 1/0 or true/false, default on), "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (default: similarity under 3 points, else affine), "compare"?: bool (fit every transform and recommend one; transform and leaveOneOut are then ignored), "leaveOneOut"?: bool (default true)}"#, ), - C::new("raster.change", "Change Detection", "Analyze › Image Analysis", change).inputs(change_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("raster.change", "Change Detection", "Imagery › Image Analysis", change).inputs(change_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"before": raster, "after": raster, "band"?: 1-based, "method"?: "difference"|"ratio"|"percent", "name"?, "ran"?: (internal: a raster the app has worked out)}"#), - C::new("raster.spectral", "Spectral Analysis", "Analyze › Image Analysis", spectral).inputs(spectral_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("raster.spectral", "Spectral Analysis", "Imagery › Image Analysis", spectral).inputs(spectral_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of its selected or first polygon's pixels)}"#), - C::new("raster.classify", "Classification Wizard", "Analyze › Image Classification", |s, p| { + C::new("raster.classify", "Classification Wizard", "Imagery › Image Classification", |s, p| { super::workflows::made_or_ran(s, p, "raster.classify") }).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "classes"?: 2..50, "bands"?: [1-based], "name"?: output, "ran"?: (internal: classes the app has worked out)}"#), - C::new("raster.classifySupervised", "Classification Tools", "Analyze › Image Classification", supervised).inputs(supervised_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("raster.classifySupervised", "Classification Tools", "Imagery › Image Classification", supervised).inputs(supervised_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "training": polygon layer, "classField": field, "bands"?: [1-based], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), - C::new("raster.index", "Indices", "Analyze › Imagery Tools", index).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("raster.index", "Indices", "Imagery › Imagery Tools", index).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": raster, "index": "ndvi"|"ndwi"|"savi"|"nbr"|"ndbi"|"evi", "red"?, "green"?, "blue"?, "nir"?, "swir"?: band numbers, "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), - C::new("raster.process", "Process", "Analyze › Imagery Tools", process).inputs(process_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("raster.process", "Process", "Imagery › Imagery Tools", process).inputs(process_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "operation": "clip"|"resample", "extent"?: [minLon, minLat, maxLon, maxLat] (clip; the view when omitted), "polygon"?: polygon layer (clip to its selected or all polygons; cells outside become no-data), "selectedOnly"?: bool (clip to selected polygons when true, all when false), "factor"?: n (resample: n×n pixels become one), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), - C::new("raster.mosaic", "Mosaic Rasters", "Analyze › Imagery Tools", raster_mosaic).inputs(mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( + C::new("raster.mosaic", "Mosaic Rasters", "Imagery › Imagery Tools", raster_mosaic).inputs(mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"inputs": [raster layer or file path, …] (two or more, in one coordinate system and cell size; where they overlap the first wins), "name"?: output, "path"?: GeoTIFF to write the mosaic to}"#, ), - C::new("raster.editPixels", "Pixel Editor", "Analyze › Imagery Tools", edit_pixels).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("raster.editPixels", "Pixel Editor", "Imagery › Imagery Tools", edit_pixels).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "polygon": [[lon, lat], …], "value"?: number (no-data when omitted), "band"?: 1-based (all when omitted)}"#), // Measurements are session results, not project changes: no undo step. - C::new("raster.measure", "Mensuration Tools", "Analyze › Mensuration", measure).inputs(measure_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view().params( + C::new("raster.measure", "Mensuration Tools", "Imagery › Mensuration", measure).inputs(measure_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"layer"?: elevation raster, "kind": "distance"|"area"|"height"|"volume", "points": [[lon, lat], …], "base"?: metres (volume)}"#, ), - C::new("raster.measurements", "Results", "Analyze › Mensuration", |s, p| { + C::new("raster.measurements", "Results", "Imagery › Mensuration", |s, p| { if b(p, "clear").unwrap_or(false) { s.measurements.clear(); } @@ -84,10 +84,10 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"clear"?: bool}"#), - C::new("imagery.workspace", "New Workspace", "Analyze › Ortho Mapping", new_workspace).inputs(workspace_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("imagery.workspace", "New Workspace", "Imagery › Ortho Mapping", new_workspace).inputs(workspace_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"kind": "ortho"|"reality", "name"?: string, "images": [raster layers], "cellSize"?: degrees, "method"?: "first"|"mean"}"#, ), - C::new("imagery.workspaceOptions", "Workspace Options", "Analyze › Ortho Mapping", |s, p| { + C::new("imagery.workspaceOptions", "Workspace Options", "Imagery › Ortho Mapping", |s, p| { let n = ps(p, "name").ok_or("name is required")?; let w = s.project.workspaces.iter_mut().find(|w| w.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no workspace '{n}'"))?; if p.get("cellSize").is_some() { @@ -99,8 +99,8 @@ pub fn commands() -> Vec { serde_json::to_value(&*w).map_err(|e| e.to_string()) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": workspace, "cellSize"?: degrees|null, "method"?: "first"|"mean"}"#), - C::new("imagery.mosaic", "Build Mosaic", "Analyze › Ortho Mapping", mosaic).inputs(workspace_mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": workspace, "ran"?: (internal: a raster the app has worked out)}"#), - C::new("imagery.mesh", "Export Mesh", "Analyze › Reality Mapping", mesh).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("imagery.mosaic", "Build Mosaic", "Imagery › Ortho Mapping", mosaic).inputs(workspace_mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": workspace, "ran"?: (internal: a raster the app has worked out)}"#), + C::new("imagery.mesh", "Export Mesh", "Imagery › Reality Mapping", mesh).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"layer": elevation raster, "path"?: "*.obj" (the text is returned without one), "step"?: pixels between vertices}"#), ] diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 3b163efc13..7f215160fb 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -15,6 +15,7 @@ pub mod edit; pub mod effects; pub mod embeddings; pub mod exports; +pub mod extensions; pub mod geocode; pub mod geolibre; pub mod gp; @@ -113,6 +114,7 @@ pub fn all() -> Vec { v.extend(pg::commands()); v.extend(gpkg::commands()); v.extend(plugins::commands()); + v.extend(extensions::commands()); v.extend(sharing::commands()); v.extend(stac::commands()); v.extend(portals::commands()); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 234bfc3d65..18206d192b 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -631,6 +631,8 @@ const SCRIPT_AHEAD: &str = "script.run"; pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> super::reads::ReadWork { let name = if command == SCRIPT_AHEAD { "Run Script" } else { "Run Model" }; let (project, trusted) = (s.project.clone(), s.trusted_models.clone()); + // The copy follows the extensions turned on or off here (#1752). + let extensions = s.extensions().clone(); let (view_size, active_layer, p) = (s.view_size, s.active_layer, p.clone()); // What its tools ask of servers and files goes in this session's Diagnostics, as when they // run here: the run here takes their results and asks nothing. @@ -639,6 +641,7 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su let mut copy = Session::new(project); copy.requests_into = Some(requests); copy.trusted_models = trusted; + copy.set_extensions(extensions); copy.view_size = view_size; copy.active_layer = active_layer; copy.tools_ahead = Some(super::gp::Ahead::Recording(Vec::new())); diff --git a/crates/engine/src/extensions.rs b/crates/engine/src/extensions.rs new file mode 100644 index 0000000000..30f2cba2df --- /dev/null +++ b/crates/engine/src/extensions.rs @@ -0,0 +1,344 @@ +//! Extensions: optional sets of RustGIS's own commands that the user turns on or off (#1752). +//! +//! A plugin is a package the user installs; an extension ships with RustGIS and needs nothing +//! downloaded. While an extension is off, the commands it owns are refused with a message that +//! says so (from the ribbon, command search, the command line, scripts, models, Python and the +//! AI Assistant alike), and the front end hides its tab and buttons. +//! +//! What the user chose is the session's [`State`]. The desktop and web apps keep it as the +//! `extensions` setting ([`State::from_setting`], [`State::to_setting`]) and start each extension +//! the setting says nothing about at its default ([`Extension::default_on`]). A session of its +//! own (the command line, Python, a test) starts with every extension on, so scripts keep +//! working; `extension.disable` turns one off there too. A setting from a newer RustGIS may name +//! extensions this version doesn't know: they are kept as they were and written back unchanged. + +use std::collections::BTreeMap; + +use serde_json::{Map, Value, json}; + +/// An extension: what it is called, what it owns and whether it starts on. +#[derive(Debug)] +pub struct Extension { + /// Its id, in commands and the setting (`imagery`). + pub id: &'static str, + /// Its name in the interface. + pub name: &'static str, + /// One sentence on what it adds. + pub description: &'static str, + /// The caption of its own ribbon tab (`extension:`), or `None` for a group on the Plugins + /// tab. + pub tab: Option<&'static str>, + /// Whether the desktop and web apps start with it on until the user says otherwise. + pub default_on: bool, + /// The command ids it owns. + pub commands: &'static [&'static str], +} + +/// Imagery: orthomosaics, surface models, georeferencing, image analysis and classification, +/// deep learning, mensuration and hosted imagery, on a tab of its own. +pub const IMAGERY: Extension = Extension { + id: "imagery", + name: "Imagery", + description: "Ortho and reality mapping, georeferencing, image analysis and classification, deep learning, mensuration and hosted imagery, on a tab of its own.", + tab: Some("Imagery"), + default_on: false, + commands: &[ + "imagery.workspace", + "imagery.workspaceOptions", + "imagery.mosaic", + "imagery.mesh", + "imagery.hostedImagery", + "raster.georeference", + "raster.gcpFit", + "raster.change", + "raster.spectral", + "raster.classify", + "raster.classifySupervised", + "raster.index", + "raster.process", + "raster.mosaic", + "raster.editPixels", + "raster.measure", + "raster.measurements", + "dl.train", + "dl.classify", + "dl.package", + "dl.import", + "dl.remove", + ], +}; + +/// Every extension, in the order the Extensions window lists them. +pub const ALL: &[Extension] = &[IMAGERY]; + +/// The most entries the setting keeps (a hand-edited or hostile one can't grow without bound). +const MAX_ENTRIES: usize = 256; +/// The longest extension id the setting keeps. +const MAX_ID: usize = 64; + +/// The extension with id `id`. +pub fn get(id: &str) -> Option<&'static Extension> { + ALL.iter().find(|e| e.id == id) +} + +/// The extension that owns command `command`, if one does. +pub fn owner(command: &str) -> Option<&'static Extension> { + ALL.iter().find(|e| e.commands.contains(&command)) +} + +/// The tab id of an extension's own tab. +pub fn tab_id(id: &str) -> String { + format!("extension:{id}") +} + +/// What the user turned on or off, by extension id. Ids this version doesn't know (from a newer +/// RustGIS) are kept, so saving writes them back as they were. The default state (a session of +/// its own) has every extension on; one read from the setting starts each at its default. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct State { + chosen: BTreeMap, + /// Entries of the setting this version couldn't read (not true or false, an over-long id, + /// past [`MAX_ENTRIES`]): written back as they were. + kept: Map, + /// Whether the setting couldn't be read at all (not a JSON object): it is never written over. + unreadable: bool, + /// Whether an extension the user said nothing about is at its default (the apps) rather + /// than on. + defaults: bool, +} + +impl State { + /// Whether extension `id` is on: what the user chose, else its default in the apps and on + /// elsewhere. An unknown id is off. + pub fn is_on(&self, id: &str) -> bool { + match get(id) { + Some(e) => self.chosen.get(id).copied().unwrap_or(!self.defaults || e.default_on), + None => false, + } + } + + /// Turns extension `id` on or off. An id that is no extension is an error. + pub fn set(&mut self, id: &str, on: bool) -> Result<&'static Extension, String> { + let e = get(id).ok_or_else(|| unknown(id))?; + self.kept.remove(e.id); + self.chosen.insert(e.id.to_string(), on); + Ok(e) + } + + /// Why command `command` can't run now: its extension is off. `None` when it can. + pub fn blocks(&self, command: &str) -> Option { + let e = owner(command)?; + (!self.is_on(e.id)).then(|| { + format!("{command} is part of the {} extension, which is off; turn it on in Plugins › Extensions (extension.enable)", e.name) + }) + } + + /// The state the `extensions` setting holds (`{"": true|false, …}`) and what of it couldn't + /// be read, said in one line (`None` when all of it could): entries that aren't true or false, + /// over-long ids and those past [`MAX_ENTRIES`] are ignored and kept to be written back as + /// they were. A setting that isn't a JSON object is ignored and never written over. An empty + /// or missing setting is every extension at its default. + pub fn from_setting(text: Option<&str>) -> (State, Option) { + let at_defaults = State { defaults: true, ..State::default() }; + let Some(text) = text.map(str::trim).filter(|t| !t.is_empty()) else { return (at_defaults, None) }; + let map = match serde_json::from_str::(text) { + Ok(Value::Object(map)) => map, + Ok(_) | Err(_) => { + let said = "the extensions setting isn't a JSON object; every extension is at its default, and what you turn on or off isn't saved over the setting"; + return (State { unreadable: true, ..at_defaults }, Some(said.into())); + } + }; + let mut chosen = BTreeMap::new(); + let mut kept = Map::new(); + for (id, on) in map { + match on.as_bool() { + // The cap is for ids this version doesn't know: a known extension's choice is + // always read. + Some(on) if !id.is_empty() && id.chars().count() <= MAX_ID && (get(&id).is_some() || chosen.len() < MAX_ENTRIES) => { + chosen.insert(id, on); + } + _ => { + kept.insert(id, on); + } + } + } + let skipped = kept.len(); + let said = (skipped > 0).then(|| { + format!( + "{skipped} entr{} of the extensions setting couldn't be read (not true or false, an id over {MAX_ID} characters, or past {MAX_ENTRIES} entries): ignored, and kept as {} when the setting is saved", + if skipped == 1 { "y" } else { "ies" }, + if skipped == 1 { "it was" } else { "they were" } + ) + }); + (State { chosen, kept, unreadable: false, defaults: true }, said) + } + + /// The `extensions` setting: every choice made, known ids or not, and the entries this + /// version couldn't read as they were. `None` when the setting read couldn't be read at all + /// (it isn't written over). + pub fn to_setting(&self) -> Option { + if self.unreadable { + return None; + } + let mut map = self.kept.clone(); + map.extend(self.chosen.iter().map(|(k, v)| (k.clone(), Value::Bool(*v)))); + Some(Value::Object(map).to_string()) + } + + /// Every extension with whether it's on, for `extension.list` and the Extensions window. + pub fn list(&self) -> Value { + Value::Array( + ALL.iter() + .map(|e| { + json!({ + "id": e.id, + "name": e.name, + "description": e.description, + "tab": e.tab, + "enabled": self.is_on(e.id), + "default": e.default_on, + "chosen": self.chosen.get(e.id), + "commands": e.commands, + }) + }) + .collect(), + ) + } +} + +/// The error for an id that is no extension, naming the ones there are. +fn unknown(id: &str) -> String { + let id: String = id.chars().take(MAX_ID).collect(); + let ids: Vec<&str> = ALL.iter().map(|e| e.id).collect(); + format!("no extension '{id}' (there are: {})", ids.join(", ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_owned_command_is_registered_and_owned_once() { + let registry = crate::cmd::all(); + for e in ALL { + assert!(e.id.chars().all(|c| c.is_ascii_lowercase() || c == '-'), "{}", e.id); + for c in e.commands { + assert!(registry.iter().any(|s| s.id == *c), "{} owns {c}, which isn't a command", e.id); + assert_eq!(owner(c).map(|o| o.id), Some(e.id), "{c} is owned twice"); + } + } + } + + #[test] + fn a_session_of_its_own_has_every_extension_on_and_the_apps_start_at_the_defaults() { + const { assert!(!IMAGERY.default_on) }; + assert!(State::default().is_on("imagery")); + let (apps, said) = State::from_setting(None); + assert_eq!(said, None); + assert!(!apps.is_on("imagery")); + assert!(apps.blocks("raster.classify").is_some()); + let (chosen, _) = State::from_setting(Some(r#"{"imagery": true}"#)); + assert!(chosen.is_on("imagery")); + } + + #[test] + fn defaults_choices_and_unknown_ids() { + let mut st = State::default(); + assert!(st.is_on("imagery")); + assert!(!st.is_on("nonesuch")); + assert_eq!(st.blocks("raster.classify"), None); + assert_eq!(st.blocks("layer.zoomTo"), None); + assert!(st.set("nonesuch", true).is_err()); + assert!(st.set("imagery", false).is_ok()); + let why = st.blocks("raster.classify").unwrap_or_default(); + assert!(why.contains("Imagery extension, which is off"), "{why}"); + assert_eq!(st.blocks("layer.zoomTo"), None); + } + + #[test] + fn setting_round_trips_and_keeps_what_a_newer_version_wrote() { + let (st, said) = State::from_setting(Some(r#"{"imagery": false, "from-newer": true}"#)); + assert_eq!(said, None); + assert!(!st.is_on("imagery")); + // Not an extension here, so off here; but kept for the version that knows it. + assert!(!st.is_on("from-newer")); + let (again, _) = State::from_setting(st.to_setting().as_deref()); + assert_eq!(again, st); + assert!(again.to_setting().is_some_and(|t| t.contains("\"from-newer\":true"))); + } + + #[test] + fn a_session_refuses_an_off_extensions_commands_every_way_in() { + let mut s = crate::Session::new(crate::Project::default()); + let listed = s.run("extension.list", &json!({})).unwrap_or_default(); + assert_eq!(listed[0]["id"], "imagery"); + assert_eq!(listed[0]["enabled"], true); + assert!(s.run("extension.disable", &json!({"id": "nonesuch"})).is_err_and(|e| e.contains("no extension 'nonesuch'"))); + assert!(s.run("extension.enable", &json!({"id": "imagery", "enabled": "maybe"})).is_err()); + assert!(s.run("extension.enable", &json!({})).is_err()); + let off = s.run("extension.disable", &json!({"id": "imagery"})).unwrap_or_default(); + assert_eq!(off["enabled"], false); + assert!(!s.extensions().is_on("imagery")); + let off_said = |r: Result| r.is_err_and(|e| e.contains("Imagery extension, which is off")); + assert!(off_said(s.run("raster.classify", &json!({})))); + assert!(off_said(s.run("dl.remove", &json!({"name": "m"})))); + // A background raster run is refused before it starts. + #[cfg(not(target_arch = "wasm32"))] + assert!(s.start_raster("raster.classify", &json!({})).is_err_and(|e| e.contains("Imagery extension, which is off"))); + // A refused command makes no layer active and reads none of its parameters. + s.run("project.sample", &Value::Null).unwrap_or_default(); + let ids: Vec = s.map().layers.iter().map(|l| l.id).collect(); + let (a, b) = (ids.first().copied(), ids.get(1).copied()); + s.active_layer = a; + let before = s.notices.len(); + assert!(off_said(s.run("raster.classify", &json!({"layer": b, "bogus": 1})))); + assert_eq!(s.active_layer, a); + assert!(!s.notices.iter().skip(before).any(|n| n.text.contains("ignores"))); + // A completion of a run is refused too. + assert!(off_said(s.run("raster.classify", &json!({"ran": 999})))); + // Commands no extension owns still run. + assert!(s.run("extension.list", &json!({})).is_ok()); + s.run("extension.enable", &json!({"id": "imagery", "enabled": true})).unwrap_or_default(); + assert!(!off_said(s.run("raster.classify", &json!({})))); + } + + #[test] + fn unreadable_setting_is_said() { + let at_defaults = State { defaults: true, ..State::default() }; + assert_eq!(State::from_setting(None), (at_defaults.clone(), None)); + assert_eq!(State::from_setting(Some(" ")), (at_defaults.clone(), None)); + let (mut st, said) = State::from_setting(Some("[1, 2]")); + assert!(!st.is_on("imagery")); + assert!(said.is_some_and(|s| s.contains("isn't a JSON object"))); + // Never written over, even after a change. + assert!(st.set("imagery", true).is_ok()); + assert_eq!(st.to_setting(), None); + let long = "x".repeat(MAX_ID + 1); + let (mut st, said) = State::from_setting(Some(&format!(r#"{{"imagery": "no", "{long}": true, "ok": false, "foo": {{"x": 1}}}}"#))); + // Left at its default. + assert!(!st.is_on("imagery")); + assert!(said.is_some_and(|s| s.starts_with("3 entries"))); + // Kept as they were, unless a choice replaces one. + let text = st.to_setting().unwrap_or_default(); + assert!( + text.contains(&format!("\"{long}\":true")) && text.contains("\"foo\":{\"x\":1}") && text.contains("\"imagery\":\"no\""), + "{text}" + ); + assert!(st.set("imagery", true).is_ok()); + assert!(st.to_setting().is_some_and(|t| t.contains("\"imagery\":true") && t.contains("\"foo\""))); + let many: Map = (0..MAX_ENTRIES + 3).map(|i| (format!("e{i}"), Value::Bool(true))).collect(); + let (st, said) = State::from_setting(Some(&Value::Object(many).to_string())); + assert_eq!(st.chosen.len(), MAX_ENTRIES); + assert!(said.is_some_and(|s| s.starts_with("3 entries"))); + let (again, _) = State::from_setting(st.to_setting().as_deref()); + assert_eq!(again.chosen.len() + again.kept.len(), MAX_ENTRIES + 3); + // A known extension's choice is never lost to the cap. + let full: Map = (0..MAX_ENTRIES).map(|i| (format!("from-newer-{i:03}"), Value::Bool(true))).collect(); + let (mut st, said) = State::from_setting(Some(&Value::Object(full).to_string())); + assert_eq!(said, None); + assert!(st.set("imagery", true).is_ok()); + let (again, said) = State::from_setting(st.to_setting().as_deref()); + assert_eq!(said, None); + assert!(again.is_on("imagery")); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4084510aa3..c06f12cb41 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ pub mod cmd; pub mod connections; pub mod durable; +pub mod extensions; pub mod geometry_calc; pub mod model; mod notice_text; @@ -663,6 +664,8 @@ pub struct Session { /// Favourite, recent and saved data sources (kept with the app's preferences, not the /// project). pub sources: sources::Sources, + /// Which extensions are on (#1752): the commands of one that is off are refused. + extensions: extensions::State, /// Saved connections (`connection.*`): kept with the app's preferences, not the project; never a secret. pub connections: connections::Connections, /// The runtime token of each saved S3 connection's login in this session, by saved id (see @@ -747,7 +750,7 @@ pub struct Session { pub(crate) saved_over: Vec, /// The feature cache fills itself after projection changes (Data › Feature Cache). pub auto_cache: bool, - /// Mensuration results (Analyze › Mensuration › Results). + /// Mensuration results (Imagery › Mensuration › Results). pub measurements: Vec, /// The last topology check's errors (Edit › Error Inspector). pub topology_errors: Vec, @@ -1124,6 +1127,7 @@ impl Session { states: 0, saved: Some(0), sources: sources::Sources::default(), + extensions: extensions::State::default(), connections: connections::Connections::default(), s3_bindings: std::collections::BTreeMap::new(), s3_pending: Vec::new(), @@ -1604,6 +1608,11 @@ impl Session { return self.invoke(op, policy::Txn::Own); } let Some(&spec) = self.registry.get(id) else { return Err(format!("unknown command '{}'", project_log::log_identifier(id))) }; + // A command of an extension that is off says so before anything else about it (before + // its parameters are read or a layer is made active for its conditions). + if let Some(why) = self.extensions.blocks(id) { + return Err(why); + } // Keys the command does not read: said, so a script or an agent can correct itself. if let (Value::Object(given), Some(known)) = (params, spec.param_keys()) { // Bounded: the keys come from the caller (the first few, each clipped). @@ -2661,6 +2670,33 @@ impl Session { .ok_or_else(|| format!("unknown colour scheme '{name}'")) } + /// Which extensions are on (#1752). + pub fn extensions(&self) -> &extensions::State { + &self.extensions + } + + /// Takes the saved `extensions` setting (the desktop and web apps, at start), over each + /// extension's default where it says nothing: what of it couldn't be read is said as a notice. + pub fn load_extensions(&mut self, setting: Option<&str>) { + let (state, said) = extensions::State::from_setting(setting); + self.extensions = state; + if let Some(said) = said { + self.warn(said); + } + } + + /// Takes another session's extension choices (a copy that runs a model or script ahead, on + /// the desktop only). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn set_extensions(&mut self, state: extensions::State) { + self.extensions = state; + } + + /// Turns extension `id` on or off (`extension.enable` and `extension.disable`). + pub(crate) fn set_extension(&mut self, id: &str, on: bool) -> Result<&'static extensions::Extension, String> { + self.extensions.set(id, on) + } + /// Resolves a `layer` parameter (name or id), defaulting to the active layer. pub fn layer_id(&self, p: &Value) -> Result { cmd::InputSource::input_context(self).layer_id(p) diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 8d21782204..c6e0f2e5e3 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -689,6 +689,20 @@ impl Session { } /// Resolves the command once or retrieves a restricted owner-only completion token. pub(crate) fn authorize(&mut self, id: &str, params: &Value) -> Result, String> { + // Every way in (a background raster or export, a read ahead, a completion) refuses a + // command of an extension that is off, as `Session::run` does: the one asked for, and + // the one a completion finishes. + if let Some(why) = self.extensions().blocks(id) { + return Err(why); + } + let op = self.authorize_unchecked(id, params)?; + if let Some(why) = self.extensions().blocks(op.node.id()) { + return Err(why); + } + Ok(op) + } + /// [`Self::authorize`] before the extension check. + fn authorize_unchecked(&mut self, id: &str, params: &Value) -> Result, String> { if let Some(id_of_run) = params.get("ran").and_then(Value::as_u64) && let Some(c) = self.raster_results.iter().find(|(n, _)| *n == id_of_run).and_then(|(_, m)| m.continuation.clone()) { @@ -827,6 +841,12 @@ impl Session { if !self.policy.scopes.is_empty() { self.continuation_owner(&c)?; } + // A run whose extension was turned off while it ran is never finished: its raster is + // let go here rather than kept to no end. + if let Some(why) = self.extensions().blocks(c.node.id()) { + self.raster_results.retain(|(n, _)| *n != id); + return Err(why); + } let mut params = params.clone(); params.as_object_mut().ok_or("raster completion parameters must be an object")?.insert("ran".into(), json!(id)); self.resume(&c, |s| s.run(command, ¶ms))? diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index f5b0986882..9a94af648c 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -433,6 +433,32 @@ pub const SECTIONS: &[(&str, &str)] = &[ ("reality", "Reality Mapping"), ]; +/// The extension (#1752) that owns Workflows section `section`: it is hidden while that +/// extension is off. +pub fn section_extension(section: &str) -> Option<&'static str> { + match section { + "georeference" | "change" | "spectral" | "classify" | "supervised" | "deepLearning" | "hosted" | "indices" | "process" + | "pixels" | "mensuration" | "ortho" | "reality" => Some(rustgis_engine::extensions::IMAGERY.id), + _ => None, + } +} + +/// Whether Workflows section `section` shows: its extension, if it has one, is on. +pub fn section_shown(session: &rustgis_engine::Session, section: &str) -> bool { + section_extension(section).is_none_or(|e| session.extensions().is_on(e)) +} + +/// Why Workflows section `section` can't open: its extension is off. `None` when it can. +pub fn section_blocked(session: &rustgis_engine::Session, section: &str) -> Option { + let e = section_extension(section).and_then(rustgis_engine::extensions::get)?; + (!session.extensions().is_on(e.id)).then(|| { + crate::i18n::fmt( + "{section} is part of the {name} extension, which is off; turn it on in Plugins › Extensions", + &[("section", tl_raw!(SECTIONS.iter().find(|s| s.0 == section).map_or(section, |s| s.1))), ("name", tl_raw!(e.name))], + ) + }) +} + /// Starts picking `needed` map points for a workflow. fn pick_button(app: &mut RustGisApp, ui: &mut Ui, purpose: &'static str, needed: usize, label: &str) { let active = app.workflow.pick.as_ref().is_some_and(|p| p.purpose == purpose); @@ -448,14 +474,15 @@ fn picked(app: &mut RustGisApp, purpose: &str) -> Option, + /// The choices last written to the setting (or read from it at start). + saved: Option, +} + +/// Takes the saved choices (at start). +pub fn load(app: &mut RustGisApp) { + let text = app.services.load_pref.as_ref().and_then(|load| load(SETTING)); + app.session.load_extensions(text.as_deref()); + app.extensions.saved = Some(app.session.extensions().clone()); +} + +/// Writes the choices when they changed since they were last written. +pub fn persist(app: &mut RustGisApp) { + let now = app.session.extensions(); + if app.extensions.saved.as_ref() == Some(now) { + return; + } + let now = now.clone(); + // A setting that couldn't be read is never written over (said when it was read). + if let (Some(save), Some(text)) = (&app.services.save_pref, now.to_setting()) { + save(SETTING, &text); + } + app.extensions.saved = Some(now); +} + +/// Turns extension `id` on or off from the window, saying what happened. +fn set(app: &mut RustGisApp, id: &str, on: bool) { + match app.run("extension.enable", json!({"id": id, "enabled": on})) { + Ok(_) => { + let name = extensions::get(id).map_or(id, |e| e.name); + let text = if on { + crate::i18n::fmt("{name} is on.", &[("name", tl_raw!(name))]) + } else { + crate::i18n::fmt("{name} is off: its tab and commands are hidden.", &[("name", tl_raw!(name))]) + }; + app.extensions.message = Some((true, text)); + } + Err(e) => app.extensions.message = Some((false, e)), + } +} + +/// The window, while it's open. +pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { + if !app.extensions.open { + return; + } + let t = Tokens::get(ctx); + let mut open = true; + let screen = ctx.content_rect(); + egui::Window::new(tl!("Extensions")) + .id(egui::Id::unique("extensions_window")) + .open(&mut open) + .collapsible(false) + .resizable(true) + .default_size(vec2(480.0_f32.min(screen.width() - 32.0), 320.0_f32.min(screen.height() - 80.0))) + .pivot(Align2::CENTER_CENTER) + .default_pos(screen.center()) + .show(ctx, |ui| { + ui.label( + egui::RichText::new(tl!( + "Extensions are optional parts of RustGIS: nothing to download. Turn one off to hide its tab and commands." + )) + .size(12.0) + .color(t.text_dim), + ); + if let Some((ok, text)) = app.extensions.message.clone() { + ui.add_space(4.0); + ui.label(egui::RichText::new(text).size(12.0).color(if ok { t.green } else { t.red })); + } + ui.separator(); + egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| { + for e in extensions::ALL { + ui.push_id(e.id, |ui| row(app, ui, &t, e)); + ui.separator(); + } + }); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Add more with plugins:")).size(12.0).color(t.text_dim)); + if ui.link(tl!("Plugin Manager")).clicked() { + let _ = app.run("ui.plugins", json!({"open": true})); + } + }); + }); + if !open { + app.extensions.open = false; + app.extensions.message = None; + } +} + +/// One extension: its switch, name and description, and where it is. +fn row(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens, e: &extensions::Extension) { + let was = app.session.extensions().is_on(e.id); + let mut on = was; + ui.horizontal(|ui| { + ui.checkbox(&mut on, egui::RichText::new(tl_raw!(e.name)).strong().size(13.5)); + if let (true, Some(caption)) = (was, e.tab) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let label = crate::i18n::fmt("Open the {tab} tab", &[("tab", tl_raw!(caption))]); + if ui.link(label).clicked() { + let _ = app.run("ui.tab", json!({"tab": extensions::tab_id(e.id)})); + } + }); + } + }); + ui.label(egui::RichText::new(tl_raw!(e.description)).size(12.0)); + let place = match e.tab { + Some(caption) => crate::i18n::fmt("On its own tab, {tab}.", &[("tab", tl_raw!(caption))]), + None => tl!("On the Plugins tab.").to_string(), + }; + let count = e.commands.len().to_string(); + let said = crate::i18n::fmt("{place} {count} commands.", &[("place", &place), ("count", &count)]); + ui.label(egui::RichText::new(said).size(11.5).color(t.text_dim)); + if on != was { + set(app, e.id, on); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + /// An app whose settings live in `prefs`. + fn app_with_prefs(prefs: &Arc>>) -> RustGisApp { + let mut app = RustGisApp::with_sample(); + let (load, save) = (Arc::clone(prefs), Arc::clone(prefs)); + app.services.load_pref = + Some(Box::new(move |k: &str| load.lock().ok().and_then(|p| p.iter().rev().find(|(key, _)| key == k).map(|(_, v)| v.clone())))); + app.services.save_pref = Some(Box::new(move |k: &str, v: &str| { + if let Ok(mut p) = save.lock() { + p.push((k.to_string(), v.to_string())); + } + })); + app + } + + #[test] + fn turning_imagery_off_hides_its_tab_sections_and_commands_and_is_saved() { + let prefs = Arc::new(Mutex::new(vec![(SETTING.to_string(), r#"{"imagery": true, "from-newer": true}"#.to_string())])); + let mut app = app_with_prefs(&prefs); + load(&mut app); + let tab = extensions::tab_id("imagery"); + assert!(crate::ribbon::tab_exists(&app, &tab)); + app.run("ui.tab", json!({"tab": tab})).unwrap(); + app.run("ui.pane.workflows", json!({"section": "ortho"})).unwrap(); + + app.run("ui.extensions", json!({"open": true})).unwrap(); + assert!(app.extensions.open); + set(&mut app, "imagery", false); + assert!(app.extensions.message.as_ref().is_some_and(|(ok, _)| *ok)); + assert!(!crate::ribbon::tab_exists(&app, &tab)); + // A refused section leaves a pick started elsewhere alone. + app.workflow.pick = Some(crate::analysispane::Pick { purpose: "test", needed: 1, points: Vec::new() }); + let why = app.run("ui.pane.workflows", json!({"section": "ortho"})).unwrap_err(); + assert!(app.workflow.pick.is_some()); + assert!(why.contains("Imagery extension, which is off"), "{why}"); + assert!(!crate::analysispane::section_shown(&app.session, "classify")); + assert!(crate::analysispane::section_shown(&app.session, "rasterFunctions")); + let why = app.run("raster.classify", json!({})).unwrap_err(); + assert!(why.contains("Imagery extension, which is off"), "{why}"); + + // Saved with what a newer version wrote, and read again at the next start. + persist(&mut app); + let saved = prefs.lock().unwrap().iter().rev().find(|(k, _)| k == SETTING).map(|(_, v)| v.clone()).unwrap(); + assert!(saved.contains("\"imagery\":false") && saved.contains("\"from-newer\":true"), "{saved}"); + let mut again = app_with_prefs(&prefs); + load(&mut again); + assert!(!again.session.extensions().is_on("imagery")); + assert!(!crate::ribbon::tab_exists(&again, &tab)); + + // On again: the tab is back. + again.run("extension.enable", json!({"id": "imagery"})).unwrap(); + assert!(crate::ribbon::tab_exists(&again, &tab)); + assert!(again.run("ui.pane.workflows", json!({"section": "ortho"})).is_ok()); + } + + #[test] + fn an_unreadable_setting_is_said_and_nothing_is_off() { + let prefs = Arc::new(Mutex::new(vec![(SETTING.to_string(), "not json".to_string())])); + let mut app = app_with_prefs(&prefs); + load(&mut app); + // At its default. + assert!(!app.session.extensions().is_on("imagery")); + assert!(app.session.notices.iter().any(|n| n.text.contains("extensions setting isn't a JSON object"))); + // Not written over by a change. + set(&mut app, "imagery", true); + persist(&mut app); + assert!(prefs.lock().unwrap().iter().all(|(_, v)| v == "not json")); + // A clean setting says nothing. + let prefs = Arc::new(Mutex::new(vec![(SETTING.to_string(), r#"{"imagery": true}"#.to_string())])); + let mut app = app_with_prefs(&prefs); + load(&mut app); + assert!(!app.session.notices.iter().any(|n| n.text.contains("extensions setting"))); + } + + #[test] + fn the_app_starts_with_imagery_off_until_it_is_turned_on() { + let prefs = Arc::new(Mutex::new(Vec::new())); + let mut app = app_with_prefs(&prefs); + load(&mut app); + let tab = extensions::tab_id("imagery"); + assert!(!crate::ribbon::tab_exists(&app, &tab)); + assert!(app.run("raster.classify", json!({})).is_err_and(|e| e.contains("Imagery extension, which is off"))); + // Nothing chosen yet: nothing written. + persist(&mut app); + assert!(prefs.lock().unwrap().is_empty()); + set(&mut app, "imagery", true); + assert!(crate::ribbon::tab_exists(&app, &tab)); + persist(&mut app); + assert!(prefs.lock().unwrap().iter().any(|(k, v)| k == SETTING && v.contains("\"imagery\":true"))); + } + + #[test] + fn show_me_opens_an_extensions_tab_for_its_commands() { + let mut app = RustGisApp::with_sample(); + let step = |command: &str| rustgis_engine::project::TaskStep { + title: String::new(), + instructions: String::new(), + command: command.into(), + params: json!({}), + }; + crate::showme::start(&mut app, &step("raster.classify")); + assert_eq!(app.ui.tab, "extension:imagery"); + // While the extension is off its tab isn't there to open. + app.run("ui.tab", json!({"tab": "Home"})).unwrap(); + app.run("extension.disable", json!({"id": "imagery"})).unwrap(); + app.ui.show_me = None; + let said = crate::showme::start(&mut app, &step("raster.classify")); + assert_eq!(app.ui.tab, "Home"); + assert!(said.contains("Imagery extension, which is off"), "{said}"); + assert!(app.ui.show_me.is_none()); + } + + #[test] + fn an_extensions_tab_comes_after_help() { + let app = RustGisApp::with_sample(); + let ids: Vec = crate::ribbon::all_tabs(&app).into_iter().map(|(id, _)| id).collect(); + let at = |t: &str| ids.iter().position(|i| i == t); + assert!(at("extension:imagery") > at("Help") && at("Help").is_some(), "{ids:?}"); + } + + #[test] + fn the_legacy_imagery_tab_name_opens_the_extension_tab() { + assert_eq!(crate::ribbon::current_tab("Imagery"), "extension:imagery"); + assert_eq!(crate::ribbon::current_hidden_tabs(vec!["extension:imagery".into()]), vec!["extension:imagery".to_string()]); + } +} diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index cbb25cdbaf..c958ce0cc2 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -1172,6 +1172,13 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(x - 1.6, 18.5), (x + 1.6, 18.5)], 1.3, ink); } } + "extension" => { + // A puzzle piece with an on/off switch. + p.rect(2.5, 4.5, 12.0, 11.0, Some(p.tint(40)), Some((1.3, ink)), 2.0); + p.circle(8.5, 4.0, 2.4, Some(accent), Some((1.2, ink))); + p.rect(10.0, 15.0, 12.0, 6.5, Some(green), Some((1.1, ink)), 3.25); + p.circle(18.75, 18.25, 2.2, Some(Color32::WHITE), None); + } "plugin" | "plugin_add" => { // A puzzle piece: a body with two knobs. p.rect(3.5, 7.5, 13.0, 13.0, Some(p.tint(40)), Some((1.3, ink)), 2.0); @@ -1204,6 +1211,7 @@ pub const ALL: &[&str] = &[ "maneuver_merge", "plugin", "plugin_add", + "extension", "explore", "zoom_full", "zoom_world", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 966cc90d13..bbc7d9b936 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -37,6 +37,7 @@ mod editpanes; mod embeddingsui; #[cfg(not(target_arch = "wasm32"))] mod exportjob; +mod extensionsui; mod failureui; mod fieldlists; mod fieldmenu; @@ -1085,6 +1086,8 @@ pub struct RustGisApp { pub time: timebar::TimeBarState, /// The Plugin Manager and plugin downloads. pub plugins: pluginsui::PluginsState, + /// The Extensions window and the saved extension choices (#1752). + pub extensions: extensionsui::ExtensionsState, /// Help › Check for Updates. pub update: update::UpdateState, pub reports: reportpane::ReportState, @@ -1314,6 +1317,7 @@ impl RustGisApp { ws: workspacepanes::WorkspaceState::default(), time: timebar::TimeBarState::default(), plugins: pluginsui::PluginsState::default(), + extensions: extensionsui::ExtensionsState::default(), update: update::UpdateState::default(), reports: reportpane::ReportState::default(), docs: docpanes::DocState::default(), @@ -1467,6 +1471,8 @@ impl RustGisApp { // take_saved_look finds a saved theme only once the folder is read. self.load_themes(); self.take_saved_look(); + // Which extensions are on, before the tabs they add are looked at. + extensionsui::load(&mut self); self.ui.hidden_tabs = ribbon::current_hidden_tabs(list(self.services.load_pref.as_ref().and_then(|load| load("hidden_tabs")))); self.ui.quick_access = list(self.services.load_pref.as_ref().and_then(|load| load("quick_access"))); // The browser's GeoLibre tools, loaded in an earlier visit: load them again (the runner @@ -2829,6 +2835,10 @@ impl RustGisApp { // Opens the Workflows pane at a section (staying open when switching sections). "ui.pane.workflows" => { let section = p.get("section").and_then(Value::as_str); + // A section of an extension that is off is refused before anything changes. + if let Some(why) = section.and_then(|s| analysispane::section_blocked(&self.session, s)) { + return Err(why); + } // A map pick started in another section (or before the pane closes) ends here. self.workflow.pick = None; match section.and_then(|s| analysispane::SECTIONS.iter().find(|x| x.0 == s)) { @@ -3173,6 +3183,9 @@ impl RustGisApp { }; } } + "ui.extensions" => { + self.extensions.open = p.get("open").and_then(Value::as_bool).unwrap_or(!self.extensions.open); + } "ui.installPlugin" => pluginsui::install_from_file(self, p.get("path").and_then(Value::as_str)), // What a click with Explore does: identify there and show the popup. "ui.identify" => { @@ -5308,6 +5321,7 @@ impl RustGisApp { zarrui::poll(self, ctx); geolibreui::poll(self, ctx); pluginsui::poll(self, ctx); + extensionsui::persist(self); assistantpane::poll(self, ctx); // A project the MCP relay, the assistant or a plugin opened or saved this frame (they run // on the session directly) becomes Last Project now, not a frame later the app may not @@ -5541,6 +5555,7 @@ impl RustGisApp { autosave::offer(self, &ctx); saveprompt::show(self, &ctx); pluginsui::show(self, &ctx); + extensionsui::show(self, &ctx); plugindialog::show(self, &ctx); update::show(self, &ctx); showme::tick(self, &ctx); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index fea13cccad..172f55d731 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -28,11 +28,15 @@ pub fn current_tab(name: &str) -> &str { "Map" => "Home", "Insert" | "Raster Data" => "Data", "Feature Layer" | "Raster Layer" => "Style", - "Analysis" | "Imagery" => "Analyze", + "Analysis" => "Analyze", "Share" | "Layout" => "Publish", _ => name, }; - if TABS.contains(&tab) || tab.starts_with("plugin:") { tab } else { "Home" } + // The imagery groups were on Analyze, then moved to the Imagery extension's tab (#1752). + if tab == "Imagery" { + return "extension:imagery"; + } + if TABS.contains(&tab) || tab.starts_with("plugin:") || tab.starts_with("extension:") { tab } else { "Home" } } /// Saved hidden tabs under the current names: renamed tabs carry over, and names of tabs whose @@ -47,7 +51,10 @@ pub fn current_hidden_tabs(saved: Vec) -> Vec { "Share" => "Publish", n => n, }; - if (TABS.contains(&tab) || tab.starts_with("plugin:")) && !FIXED_TABS.contains(&tab) && !out.iter().any(|t| t == tab) { + if (TABS.contains(&tab) || tab.starts_with("plugin:") || tab.starts_with("extension:")) + && !FIXED_TABS.contains(&tab) + && !out.iter().any(|t| t == tab) + { out.push(tab.to_string()); } } @@ -69,10 +76,40 @@ fn plugin_tabs(app: &RustGisApp) -> Vec<(String, String)> { .collect() } +/// The extensions that are on with a tab of their own (#1752): (tab id, caption in the interface +/// language). +fn extension_tabs(app: &RustGisApp) -> Vec<(String, String)> { + rustgis_engine::extensions::ALL + .iter() + .filter(|e| app.session.extensions().is_on(e.id)) + .filter_map(|e| e.tab.map(|caption| (rustgis_engine::extensions::tab_id(e.id), tl_raw!(caption).to_string()))) + .collect() +} + +/// RustGIS's tabs, then the tabs of extensions that are on (after Help), then plugins' own tabs: +/// (tab id, caption in the interface language). +pub(crate) fn all_tabs(app: &RustGisApp) -> Vec<(String, String)> { + let mut tabs: Vec<(String, String)> = TABS.iter().map(|t| (t.to_string(), tl!(*t).to_string())).collect(); + tabs.extend(extension_tabs(app)); + tabs.extend(plugin_tabs(app)); + tabs +} + +/// Whether tab `tab` (one of RustGIS's, an extension's or a plugin's) is there to show. +pub fn tab_exists(app: &RustGisApp, tab: &str) -> bool { + if tab.starts_with("plugin:") { + plugin_tabs(app).iter().any(|(id, _)| id == tab) + } else if tab.starts_with("extension:") { + extension_tabs(app).iter().any(|(id, _)| id == tab) + } else { + TABS.contains(&tab) + } +} + pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - // A plugin's tab whose plugin was turned off or removed. - if app.ui.tab.starts_with("plugin:") && !plugin_tabs(app).iter().any(|(id, _)| *id == app.ui.tab) { + // A tab whose plugin or extension was turned off or removed. + if !tab_exists(app, &app.ui.tab) { app.ui.tab = "Plugins".into(); } egui::Panel::top("tabs") @@ -102,6 +139,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let tab = app.ui.tab.clone(); match tab.as_str() { t if t.starts_with("plugin:") => plugin_tab(app, ui, t.trim_start_matches("plugin:")), + t if t.starts_with("extension:") => extension_groups(app, ui, t.trim_start_matches("extension:")), "Data" => data_tab(app, ui), "Style" => style_tab(app, ui), "Labeling" => labeling_tab(app, ui), @@ -214,9 +252,8 @@ fn tab_strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.ui.backstage = true; } ui.add_space(6.0); - // RustGIS's tabs, then plugins' own tabs; the user can hide any of them. - let mut tabs: Vec<(String, String)> = TABS.iter().map(|t| (t.to_string(), tl!(*t).to_string())).collect(); - tabs.extend(plugin_tabs(app)); + // RustGIS's tabs, extensions' and plugins' own tabs; the user can hide any of them. + let mut tabs = all_tabs(app); tabs.retain(|(id, _)| !app.ui.hidden_tabs.iter().any(|h| h == id)); // The tabs scroll between the Project button and the right-side controls (the collapse // button and the active tool indicator) when the window is too narrow for them. @@ -1689,10 +1726,14 @@ fn analysis_groups(app: &mut RustGisApp, ui: &mut Ui) { "Workflows", "Guided analysis: suitability, visibility, networks, interpolation and more.", |ui, app| { - for (id, title) in crate::analysispane::SECTIONS + let shown: Vec<&(&str, &str)> = crate::analysispane::SECTIONS .iter() - .filter(|s| !matches!(s.0, "rasterFunctions" | "functionEditor" | "environments" | "models")) - { + .filter(|s| { + !matches!(s.0, "rasterFunctions" | "functionEditor" | "environments" | "models") + && crate::analysispane::section_shown(&app.session, s.0) + }) + .collect(); + for (id, title) in shown { menu_item(ui, app, "geoprocessing", title, "ui.pane.workflows", json!({"section": id})); } }, @@ -2371,11 +2412,21 @@ fn layer_hint(ui: &mut Ui, text: &str) { }); } -/// The Analyze tab: geoprocessing, workflows, imagery and notebooks. +/// The Analyze tab: geoprocessing, workflows and notebooks. Its imagery groups are on the Imagery extension's tab (#1752). fn analyze_tab(app: &mut RustGisApp, ui: &mut Ui) { analysis_groups(app, ui); notebook_group(app, ui); - imagery_groups(app, ui); +} + +/// An extension's groups (#1752), on its own tab or, for one without a tab, on the Plugins tab. +/// Nothing while it is off. +fn extension_groups(app: &mut RustGisApp, ui: &mut Ui, id: &str) { + if !app.session.extensions().is_on(id) { + return; + } + if id == rustgis_engine::extensions::IMAGERY.id { + imagery_groups(app, ui); + } } /// The Publish tab: the open layout's groups first, then reports, presentations, export and @@ -2835,16 +2886,19 @@ fn share_groups(app: &mut RustGisApp, ui: &mut Ui) { Value::Null, app.ui.right == Some(RightPane::Shares), ); - small( - ui, - app, - "modelbuilder", - "Deep Learning", - "Package a trained deep learning model.", - "ui.saveItem", - json!({"kind": "dlPackage"}), - false, - ); + // Deep learning packages are the Imagery extension's (#1752). + if app.session.extensions().is_on(rustgis_engine::extensions::IMAGERY.id) { + small( + ui, + app, + "modelbuilder", + "Deep Learning", + "Package a trained deep learning model.", + "ui.saveItem", + json!({"kind": "dlPackage"}), + false, + ); + } }); }); group(ui, "Layout", |ui| { @@ -3262,6 +3316,23 @@ fn plugins_tab(app: &mut RustGisApp, ui: &mut Ui) { ); }); }); + group(ui, "Extensions", |ui| { + big( + ui, + app, + "extension", + "Extensions", + "Turn on or off the optional parts of RustGIS, such as Imagery.", + "ui.extensions", + Value::Null, + app.extensions.open, + false, + ); + }); + // The groups of the extensions that are on and have no tab of their own. + for e in rustgis_engine::extensions::ALL.iter().filter(|e| e.tab.is_none()) { + extension_groups(app, ui, e.id); + } // A group per enabled plugin with commands, in the interface language when it has one // (plugins with a tab of their own are on that tab instead). let lang = app.lang().code(); @@ -3474,10 +3545,9 @@ fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) { }); group(ui, "Customize", |ui| { let hidden = app.ui.hidden_tabs.clone(); - // RustGIS's tabs and plugins' tabs. - let mut all: Vec<(String, String)> = - TABS.iter().filter(|t| !FIXED_TABS.contains(*t)).map(|t| (t.to_string(), tl!(*t).to_string())).collect(); - all.extend(plugin_tabs(app)); + // RustGIS's tabs, extensions' and plugins' tabs. + let mut all = all_tabs(app); + all.retain(|(id, _)| !FIXED_TABS.contains(&id.as_str())); big_form_menu(ui, app, "settings", "Ribbon", "Choose which tabs the ribbon shows.", move |ui, app| { for (tab, caption) in &all { let mut on = !hidden.iter().any(|h| h == tab); diff --git a/crates/ui-egui/src/showme.rs b/crates/ui-egui/src/showme.rs index b1aac02ab9..bb30fd2148 100644 --- a/crates/ui-egui/src/showme.rs +++ b/crates/ui-egui/src/showme.rs @@ -52,6 +52,10 @@ pub fn start(app: &mut RustGisApp, st: &TaskStep) -> String { app.ui.open_right(RightPane::Symbology); return tl!("It's in the Symbology pane, open on the step's layer.").to_string(); } + // A command of an extension that is off isn't on the ribbon: say how to turn it on. + if let Some(why) = app.session.extensions().blocks(id) { + return why; + } let spec = app.session.registry.get(id); let label = spec.map_or_else(|| id.to_string(), |c| tl!(c.label).to_string()); let (target, key, fallback) = match id { @@ -66,8 +70,13 @@ pub fn start(app: &mut RustGisApp, st: &TaskStep) -> String { None => (id, None, None), }, }; - if let Some(tab) = spec.and_then(|c| c.location.split(" › ").next()).filter(|t| ribbon::TABS.contains(t)) { - app.ui.tab = tab.to_string(); + // A command of an extension with a tab of its own is on that tab (#1752). + let tab = match rustgis_engine::extensions::owner(id).filter(|e| e.tab.is_some()) { + Some(e) => Some(rustgis_engine::extensions::tab_id(e.id)), + None => spec.and_then(|c| c.location.split(" › ").next()).filter(|t| ribbon::TABS.contains(t)).map(str::to_string), + }; + if let Some(tab) = tab.filter(|t| ribbon::tab_exists(app, t)) { + app.ui.tab = tab; app.ui.backstage = false; // A minimized ribbon draws no buttons: show it, as a click on a tab does. if app.ui.ribbon_minimized { diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 2664f060a8..b1571e89fa 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -1810,7 +1810,8 @@ fn show_me_points_at_where_a_steps_command_is() { fn old_and_unknown_tab_names_open_a_current_tab() { let mut h = harness(); for (asked, opened) in [ - ("Imagery", "Analyze"), + // The imagery groups are on the Imagery extension's tab (#1752). + ("Imagery", "extension:imagery"), ("Feature Layer", "Style"), ("Labeling", "Labeling"), ("Share", "Publish"), diff --git a/docs/plugins.md b/docs/plugins.md index 7fc45ab14e..83dc59adf2 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -4,6 +4,8 @@ Plugins add commands, geoprocessing tools and assistant skills to RustGIS. A plu `plugin.json` manifest and is packaged as a `.rgplugin` file. WebAssembly plugins run sandboxed in the desktop app, on the command line and in the web app. [Process plugins](#process-plugins) run a local program instead and need the desktop app or command line. +Parts of RustGIS itself that you can turn on or off without installing anything are +[extensions](user-guide/index.md#extensions). Browse the [plugin catalog](https://plugins.rustgis.app/catalog/). [opengeos/rustgis-plugins](https://github.com/opengeos/rustgis-plugins) holds the registry, diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 118cec3f57..12a89586e2 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1438,7 +1438,8 @@ save and run models without the canvas: ## Imagery -The Analyze tab's imagery groups open their tools in the Workflows pane: +The Imagery tab's groups open their tools in the Workflows pane. The tab belongs to the Imagery +[extension](index.md#extensions): turn it on in Plugins › Extensions to show the tab: - **Ortho Mapping** and **Reality Mapping** workspaces mosaic georeferenced images into an orthomosaic, or elevation rasters into a surface model that exports as a 3D mesh (OBJ). @@ -1755,11 +1756,11 @@ the wrong field. ## Deep learning and hosted imagery -**Analyze › Deep Learning Tools** trains a neural network (a multilayer perceptron) on the pixels +**Imagery › Deep Learning Tools** trains a neural network (a multilayer perceptron) on the pixels under training polygons and classifies every pixel, adding a class raster with a confidence band and reporting the accuracy on held-back pixels. Run from its pane in the desktop app, it trains on every sampled pixel for all the epochs asked, however long that takes, and can be cancelled; elsewhere it keeps to a few seconds of work (see the limits above). Trained models stay in the project; **Publish › -Share As › Deep Learning** saves one as a package to apply in other projects. **Analyze › Create +Share As › Deep Learning** saves one as a package to apply in other projects. **Imagery › Create Hosted Imagery** cuts a raster into XYZ web map tiles (PNG, transparent outside the raster) with a TileJSON file and a viewer page. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index ae2fe6bbe9..34b856ccef 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -28,7 +28,7 @@ Formats](data-formats.md). | ASCII grid (`.asc`, with an optional `.prj`) | Yes | No | | Unreferenced TIFF and PNG scans; JPEG with `"as": "scan"` | Yes | GeoTIFF after georeferencing | | Through GDAL: JPEG 2000, ERDAS Imagine, SRTM HGT, DTED, NetCDF, HDF, ENVI, SAGA… | Yes (desktop, when GDAL is installed) | No | -| Web tiles: XYZ/TMS/WMS rasters, Mapbox Vector Tiles, MapLibre styles, PMTiles and MBTiles archives | Yes | Yes (Analyze › Create Hosted Imagery) | +| Web tiles: XYZ/TMS/WMS rasters, Mapbox Vector Tiles, MapLibre styles, PMTiles and MBTiles archives | Yes | Yes (Imagery › Create Hosted Imagery) | | RustGIS project (`.rgis`; older `.rgisx` files open too) | Yes | Yes | Add data with **Home › Add › Add Data**: its main button opens the file picker, and its menu offers diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 91d15a3179..5197835692 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -159,15 +159,50 @@ Review copied diagnostics for private layer names or file paths before sharing t | **Style** | For the layer selected in Layers. A feature layer: Visibility Range, Effects, Drawing, Drawing Effects, Extrusion for polygons (with Faces and Light and Shadow once on) and Layer. A raster layer: Visibility Range, Effects, Compare, Raster Effects, Rendering, Enhancement and Layer. Both: Styles | | **Labeling** | For the feature layer selected in Layers: Labels (Label, Properties), Label Class (Class, Field), Text Symbol (Size, Color, Bold, Halo), Label Placement and Label Range. Whatever is selected: Map Labeling (Lock, Pause, View Unplaced, Convert) | | **Edit** | Manage Edits (Edit, Save, Undo, Redo, Status, Save to PostGIS and Discard PostGIS Edits on the desktop while a [PostGIS layer is loaded for editing](data.md#editing-postgis-tables), Settings, Templates, Topology), Snapping, Features (Create, Delete, Edit Vertices, Modify), Tools, Elevation, Corrections, Graphics, Graphics and Text, Clipboard | -| **Analyze** | Geoprocessing (History, Tools, Model Builder, Script, SQL, Environments), Tasks (the Tasks pane; Task: Record Task, New Task From History, Import Task, run a task), AI (AI Assistant), Portal (Feature Analysis, Raster Analysis), Workflows, Raster (Raster Functions, Function Editor), Tools (the tool gallery), Selection, Notebook, the imagery groups (Ortho Mapping, Reality Mapping, Alignment, Image Analysis, Image Classification, Imagery Sharing, Mensuration, Imagery Tools) | +| **Analyze** | Geoprocessing (History, Tools, Model Builder, Script, SQL, Environments), Tasks (the Tasks pane; Task: Record Task, New Task From History, Import Task, run a task), AI (AI Assistant), Portal (Feature Analysis, Raster Analysis), Workflows, Raster (Raster Functions, Function Editor), Tools (the tool gallery), Selection, Notebook | | **View** | Display (Graticule, GPU Rendering), View (Globe, Projection, Global; Local on the desktop), Effects, Scene, Windows, Navigation, Link, Workspace, Animation, Time (Time Slider), Profile (Profile; Time Series on the desktop) | | **Publish** | While a layout is open, its groups first (Page, Map Frames, Map Surrounds, Shapes, Text, Export); then Report, Presentation, Output (Export Map, Export Features, Print Map, Capture To Clipboard, Report, Presentation, Export To 3D), Package, Share As, Layout, Save As, Thumbnail | -| **Plugins** | Plugins (Plugin Manager, Install From File, Browse Plugins), plus a group for each enabled [plugin](../plugins.md) with commands or tools; a plugin with its own tab adds that tab instead | +| **Plugins** | Plugins (Plugin Manager, Install From File, Browse Plugins), Extensions (the [Extensions](#extensions) window), plus a group for each enabled [plugin](../plugins.md) with commands or tools; a plugin with its own tab adds that tab instead | | **Settings** | Theme (the theme list, Follow the System, Interface Scale), Customize (Ribbon, Quick Access), Language (interface language and worldview), Start-up (Start With, Projection, Extent), Autosave on the desktop | | **Help** | Performance (Diagnostic Monitor), Learn (Learning Resources), Help (About, Check for Updates on the desktop, Command Search, Shortcuts) | +| **Imagery** | The [Imagery extension](#extensions)'s tab, after Help, while it is on (it is off until you turn it on): Ortho Mapping, Reality Mapping, Alignment, Image Analysis, Image Classification, Imagery Sharing, Mensuration, Imagery Tools | The tabs stay the same whatever is selected: Style, Labeling and Data act on the layer selected in Layers. +### Extensions + +Extensions are optional parts of RustGIS that you turn on or off. Unlike a +[plugin](../plugins.md), an extension ships with RustGIS: there is nothing to download or install. +**Plugins › Extensions** opens the Extensions window, which lists each extension with a switch, +what it adds and where it shows. An extension with a tab of its own adds that tab after Help +(before plugins' own tabs) while it is on; one without a tab adds a group to the Plugins tab. + +| Extension | Default | Adds | +| --- | --- | --- | +| **Imagery** (`imagery`) | Off | The Imagery tab: Ortho Mapping, Reality Mapping, Alignment (Georeference), Image Analysis, Image Classification (with Deep Learning Tools), Imagery Sharing, Mensuration and Imagery Tools, and their commands (`imagery.*`, `dl.*`, and the `raster.*` commands those groups run) | + +While an extension is off, its tab, its buttons, its Workflows pane sections and its commands in +Command Search and the AI Assistant's command search are hidden. Its commands are refused with a +message naming the extension, whoever runs them: a script, a model, the command line, Python or +the assistant. Hiding the extension's tab in Settings › Customize › Ribbon only hides the tab; the +commands still run. + +The desktop and web apps start each extension at its default and remember your choices (the +`extensions` setting). A setting saved by a newer RustGIS that names extensions this version +doesn't have keeps them unchanged, and so do entries that can't be read (each kind is reported +in Messages). A setting that can't be read at all is reported, leaves every extension at its +default and is never written over. The command line and Python start with every extension +on, so scripts that use its commands keep working; models and scripts run in the apps follow the +apps' choices. Turn one off or on in a run with: + +```bash +rustgis-cli run --sample --cmd extension.list \ + --cmd 'extension.disable={"id":"imagery"}' \ + --cmd 'extension.enable={"id":"imagery","enabled":true}' +``` + +`extension.enable` takes `"enabled": true` or `false` (default `true`) and refuses other values. + Menus with checkboxes stay open while you change options: stack or show web basemaps, combine Visual and Camera Effects, or customize Ribbon tabs and Quick Access buttons. Click outside the menu to dismiss it. The time slider's Layers menu likewise stays open while binding layers.