//! View tab (Link Views, Thumbnail, Animation, Profile Viewing, Workflow Manager), Home and Data //! (Infographics, Offline, Feature Cache) and Help (Diagnostic Monitor) commands. use base64::Engine; use rustgis_data::{Geometry, GeometryType}; use rustgis_geom::{Coord, Extent}; use rustgis_map::view::Keyframe; use serde_json::{Value, json}; use super::{b, f, ps}; use crate::project::{Job, OfflineArea, Project}; use crate::{CmdResult, CommandSpec as C, Session}; /// Removes every Shapefile index not in use and says what it freed, what stayed and why, and which /// cache folder it couldn't empty. fn empty_indexes(s: &mut Session, _p: &Value) -> CmdResult { #[cfg(not(target_arch = "wasm32"))] { let e = rustgis_data::source::shp::empty_index_cache(); if e.folders == 0 && !e.failed.is_empty() { return Err(format!("couldn't empty the Shapefile index cache: {}", e.failed.join("; "))); } for (text, error) in empty_notices(&e) { s.notify(text, error); } Ok(json!({ "removed": e.removed, "freedBytes": e.removed_bytes, "inUse": e.in_use, "inUseBytes": e.in_use_bytes, "keptBytes": e.kept_bytes, "failed": e.failed, })) } #[cfg(target_arch = "wasm32")] { let _ = s; Err("the browser keeps no Shapefile index cache".to_string()) } } /// What emptying the Shapefile index cache has to tell the user beyond its counts, each with /// whether it is an error: nothing when all went. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn empty_notices(e: &rustgis_data::source::shp::Emptied) -> Vec<(String, bool)> { let size = |bytes: u64| { if bytes < 1024 * 1024 { format!("{:.1} KB", bytes as f64 / 1024.0) } else { format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)) } }; let mut notices: Vec<(String, bool)> = e.failed.iter().map(|f| (format!("Shapefile index cache: couldn't empty {f}"), true)).collect(); if e.in_use > 0 { let what = if e.in_use == 1 { "1 index".to_string() } else { format!("{} indexes", e.in_use) }; notices.push(( format!("Shapefile index cache: {what} in use by open layers or another RustGIS window kept ({})", size(e.in_use_bytes)), false, )); } if e.kept_bytes > 0 { notices.push(( format!("Shapefile index cache: {} of files not removed (no readable lease, or refused by the system)", size(e.kept_bytes)), false, )); } notices } fn now() -> f64 { web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) } /// The most lines `profile.alongSelected` profiles. const MAX_PROFILED_LINES: usize = 50; /// Separates in-memory cache controls from commands that read or remove files on disk. pub fn commands() -> Vec { vec![ C::new("view.linkViews", "Link Views", "View › Link", |s, p| { s.project.link_views = b(p, "on").unwrap_or(!s.project.link_views); if s.project.link_views { s.sync_linked_views(); } Ok(json!({"linked": s.project.link_views})) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"on"?: bool}"#), C::new("project.thumbnail", "Create Thumbnail", "Publish › Thumbnail", |s, p| { let t = thumbnail(s, p)?; s.project.thumbnail = t; Ok(json!({"thumbnail": s.project.thumbnail.is_some()})) }).inputs(thumbnail_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"create"?: bool (from the map view), "image"?: base64 PNG/JPEG, "path"?: image file, "clear"?: bool}"#), C::new("map.thumbnail", "Map Thumbnail", "Publish › Thumbnail", |s, p| { let t = thumbnail(s, p)?; s.map_mut().thumbnail = t; Ok(json!({"thumbnail": s.map().thumbnail.is_some()})) }).inputs(thumbnail_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"create"?: bool, "image"?: base64 PNG/JPEG, "path"?: image file, "clear"?: bool}"#), // Workflow Manager. C::new("job.new", "Workflow Manager", "View › Windows", |s, p| { let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or("name is required")?.chars().take(200).collect(); if s.project.jobs.len() >= 1000 { return Err("a project keeps at most 1000 jobs; remove finished ones first".into()); } let id = s.project.jobs.iter().map(|j| j.id).max().unwrap_or(0).saturating_add(1); let extent = if b(p, "viewExtent").unwrap_or(false) { Some(view_extent(s)) } else { None }; let t = now(); s.project.jobs.push(Job { id, name, description: ps(p, "description").unwrap_or("").chars().take(4000).collect(), status: "new".into(), assigned: ps(p, "assigned").unwrap_or("").chars().take(200).collect(), extent, created: t, updated: t, }); Ok(json!({"job": id})) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": string, "description"?, "assigned"?, "viewExtent"?: bool (the job covers the map view)}"#), C::new("job.update", "Update Job", "View › Windows", |s, p| { let id = p.get("job").and_then(Value::as_u64).ok_or("job is required")?; let status = ps(p, "status").map(str::to_string); if status.as_deref().is_some_and(|st| !matches!(st, "new" | "in progress" | "on hold" | "done")) { return Err("status is new, in progress, on hold or done".into()); } let j = s.project.jobs.iter_mut().find(|j| u64::from(j.id) == id).ok_or_else(|| format!("no job {id}"))?; if let Some(st) = status { j.status = st; } if let Some(a) = ps(p, "assigned") { j.assigned = a.chars().take(200).collect(); } if let Some(d) = ps(p, "description") { j.description = d.chars().take(4000).collect(); } j.updated = now(); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"job": id, "status"?: "new"|"in progress"|"on hold"|"done", "assigned"?, "description"?}"#), C::new("job.remove", "Delete Job", "View › Windows", |s, p| { let id = p.get("job").and_then(Value::as_u64).ok_or("job is required")?; let before = s.project.jobs.len(); s.project.jobs.retain(|j| u64::from(j.id) != id); if s.project.jobs.len() == before { Err(format!("no job {id}")) } else { Ok(Value::Null) } }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"job": id}"#), // Animation. C::new("animation.add", "Add Keyframe", "View › Animation", |s, p| { let c = s.map().center_lonlat(); let k = Keyframe { center: c, scale: s.scale(), seconds: f(p, "seconds").unwrap_or(2.0).clamp(0.1, 600.0) }; let m = s.map_mut(); if m.animation.len() >= 500 { return Err("an animation has at most 500 keyframes".into()); } m.animation.push(k); Ok(json!({"keyframes": m.animation.len()})) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"seconds"?: time from the previous keyframe}"#), C::new("animation.remove", "Remove Keyframe", "View › Animation", |s, p| { let m = s.map_mut(); match p.get("index").and_then(Value::as_u64) { Some(i) if (i as usize) < m.animation.len() => { m.animation.remove(i as usize); } Some(i) => return Err(format!("no keyframe {i}")), None if b(p, "all").unwrap_or(false) => m.animation.clear(), None => { m.animation.pop().ok_or("the map has no keyframes")?; } } Ok(json!({"keyframes": m.animation.len()})) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"index"?: number (the last one when omitted), "all"?: bool}"#), C::new("animation.export", "Export Animation", "View › Animation", |s, p| { let written = s.notice_mark(); let path = ps(p, "path").ok_or("path is required (a .zip of PNG frames)")?.to_string(); let bytes = animation_zip(s, p)?; rustgis_data::io::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; s.retain_written_notices(written); Ok(json!({"path": path, "bytes": bytes.len()})) }).inputs(map_render_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.zip", "fps"?: 1..30, "width"?, "height"?: px}"#), // Profiles. C::new("profile.create", "Create Profile", "View › Profile Viewing", |s, p| { let pts = points(p)?; profile(s, p, &pts) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer": elevation raster, "points": [[lon, lat], …], "samples"?: number}"#), C::new("profile.autoComplete", "Auto-complete Profile", "View › Profile Viewing", |s, p| { // Continue the line from its first point through its second to the raster's edge. let pts = points(p)?; let (a, b2) = (pts.first().copied().ok_or("give two points")?, pts.get(1).copied().ok_or("give two points")?); let r = dem(s, p)?; let e = r.extent(); let (dx, dy) = (b2.x - a.x, b2.y - a.y); if dx == 0.0 && dy == 0.0 { return Err("the two points are the same".into()); } let mut t = 1.0; while t < 1e4 && e.contains(Coord::new(a.x + dx * t * 1.1, a.y + dy * t * 1.1)) { t *= 1.1; } profile(s, p, &[a, Coord::new(a.x + dx * t, a.y + dy * t)]) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer": elevation raster, "samples"?: number (default 200), "points": [[lon, lat], [lon, lat]] (a start and a direction)}"#), C::new("profile.crossSection", "Cross Section", "View › Profile Viewing", |s, p| { // Across a line at a point: perpendicular, `width` metres long. let pts = points(p)?; let (a, b2) = (pts.first().copied().ok_or("give the line's two points")?, pts.get(1).copied().ok_or("give the line's two points")?); let t = f(p, "at").unwrap_or(0.5).clamp(0.0, 1.0); let mid = Coord::new(a.x + (b2.x - a.x) * t, a.y + (b2.y - a.y) * t); let k = mid.y.to_radians().cos().max(0.01); let (dx, dy) = ((b2.x - a.x) * k, b2.y - a.y); let len = (dx * dx + dy * dy).sqrt().max(1e-12); let half_deg = f(p, "width").unwrap_or(2000.0).clamp(1.0, 1e6) / 2.0 / 111_320.0; let (nx, ny) = (-dy / len * half_deg / k, dx / len * half_deg); profile(s, p, &[Coord::new(mid.x - nx, mid.y - ny), Coord::new(mid.x + nx, mid.y + ny)]) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params( r#"{"layer": elevation raster, "samples"?: number (default 200), "points": [[lon, lat], [lon, lat]] (the line crossed), "at"?: 0..1 along it, "width"?: metres}"#, ), C::new("profile.alongLine", "Profile Along a Line", "View › Profile Viewing", |s, p| { let lines = selected_lines(s, p, false)?; let first = lines.into_iter().next().ok_or("no line")?; profile(s, p, &first) }).inputs(profile_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer": elevation raster, "samples"?: number (default 200), "lines": line layer, "row"?: number (the first selected when omitted)}"#), C::new("profile.alongSelected", "Profile Along Selected Lines", "View › Profile Viewing", |s, p| { let lines = selected_lines(s, p, true)?; // The lines past the first 50 get no profile, and that is said (#1896). if lines.len() > MAX_PROFILED_LINES { s.notify(format!("Profile Along Selected Lines: the first {MAX_PROFILED_LINES} of the {} lines are profiled", lines.len()), false); } let out: Vec = lines.iter().take(MAX_PROFILED_LINES).map(|l| profile(s, p, l)).collect::>()?; Ok(Value::Array(out)) }).inputs(profile_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer": elevation raster, "samples"?: number (default 200), "lines": line layer}"#), // Infographics and diagnostics. C::new("info.infographic", "Infographics", "Home › Inspect", infographic).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer"? (every visible feature layer when omitted)}"#), C::new("info.diagnostics", "Diagnostic Monitor", "Help › Performance", |s, _| Ok(diagnostics(s))).roles(&[]).effects(crate::policy::Effects::NONE).view(), // Offline areas. C::new("offline.download", "Download Map", "Data › Offline", offline_download).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: string, "extent"?: [minLon, minLat, maxLon, maxLat] (the map view when omitted)}"#), C::new("offline.package", "Package for the Field", "Data › Offline", |s, p| { let written = s.notice_mark(); let path = super::ps(p, "path").ok_or("path is required")?.to_string(); super::field::not_the_project(s, std::path::Path::new(&path))?; let had = s.project.offline_areas.len(); let (area, bytes, notes) = super::field::package_output(s, p)?; if let Err(e) = rustgis_data::io::write_atomic(std::path::Path::new(&path), &bytes) { super::field::forget_new_areas(s, had); return Err(format!("{path}: {e}")); } for note in notes { s.notify(note, false); } s.retain_written_notices(written); Ok(super::field::packaged(&path, &area, bytes.len())) }) .roles(&[]) .effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"path": "*.rgisfield", "name"?: offline area name, "extent"?: [minLon, minLat, maxLon, maxLat], "legacyReturn"?: "native User only: send an old ID-less field project saved as a plain project; its return requires explicit legacyArea confirmation at home"}"#), C::new("offline.bringBack", "Bring Back Edits", "Data › Offline", super::field::bring_back) .roles(&[]) .effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"path"?: "*.rgisfield", "data"?: base64 of one, "legacyArea"?: "native User only: explicitly verified home offline area for an entirely ID-less legacy return; cannot override any present or incomplete identity"}"#), C::new("offline.sync", "Sync", "Data › Offline", offline_sync).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": offline area}"#), C::new("offline.remove", "Remove", "Data › Offline", |s, p| { let n = ps(p, "name").ok_or("name is required")?; let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?; let area = s.project.offline_areas.remove(ai); let kept = offline_map_index(&s.project, &area); // A copy kept as the only map is no longer the area's: neither its saved association // nor its title may still claim the area that is gone. for m in &mut s.project.maps { if !area.id.is_empty() && m.offline_area_id.as_deref() == Some(area.id.as_str()) { m.offline_area_id = None; } } if let Some(i) = kept && s.project.maps.len() > 1 { s.project.maps.remove(i); // The active map stays the same map; if it was the removed one, a neighbour. let a = s.project.active_map; s.project.active_map = if a > i { a - 1 } else { a.min(s.project.maps.len().saturating_sub(1)) }; if a == i { s.active_layer = s.map().layers.first().map(|l| l.id); } } else if let Some(m) = kept.and_then(|i| s.project.maps.get_mut(i)) && m.name.eq_ignore_ascii_case(&offline_map_name(&area.name)) { let old = std::mem::replace(&mut m.name, format!("{} (kept)", area.name)); let kept = m.name.clone(); // Layouts, presentations and other areas made from it follow, as on a rename. super::navigate::follow_renamed_map(s, &old, &kept); s.notify(format!("The offline area's map was the only one, so it was kept as '{kept}'"), false); } Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": offline area}"#), C::new("offline.open", "Open Offline Map", "Data › Offline", |s, p| { let n = ps(p, "name").ok_or("name is required")?; let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?; let a = s.project.offline_areas.get_mut(ai).ok_or("no such area")?; crate::project::ensure_map_imports_complete(&a.data)?; let id = ensure_area_id(a)?; let a = s.project.offline_areas.get(ai).ok_or("no such area")?; let extent = a.extent; if let Some(i) = offline_map_index(&s.project, a) { if let Some(m) = s.project.maps.get_mut(i) { // Upgrade a legacy name match while the association is still known. m.offline_area_id = Some(id); let unbound = unbind_map_table_edits(m); let copy = format!("the offline map '{}'", m.name); note_unbound(s, unbound, ©); } s.project.active_map = i; } else { let mut m = a.data.clone(); let map_name = offline_map_name(&a.name); let taken = |n: &str| s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(n)); m.name = if taken(&map_name) { super::numbered(&map_name, taken) } else { map_name }; m.offline_area_id = Some(id); m.renew_instance_id(); // An area saved before offline copies were unlinked from their tables. let unbound = unbind_map_table_edits(&mut m); note_unbound(s, unbound, &format!("the offline map '{}'", m.name)); // Reading a project checks only maps' layers, not offline snapshots', so their // selections are put right here. for l in &mut m.layers { l.renew_instance_id(); l.normalize_selection(); } // As a project's maps say when opened (#1596). for (_, text) in crate::project::label_losses::hidden(m.layers.iter()) { s.notify(text, false); } s.project.maps.push(m); s.project.active_map = s.project.maps.len() - 1; } s.active_layer = s.map().layers.first().map(|l| l.id); s.zoom_to(&extent); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": offline area}"#), // Feature cache. C::new("cache.fill", "Fill Cache", "Data › Feature Cache", |s, _| { let n = fill_cache(s); Ok(json!({"cached": n})) }).roles(&[]).effects(crate::policy::Effects::NONE) .view(), C::new("cache.empty", "Empty Cache", "Data › Feature Cache", |s, _| { let mut n = 0; for m in &mut s.project.maps { for l in &mut m.layers { l.clear_cache(); n += 1; } } Ok(json!({"emptied": n})) }).roles(&[]).effects(crate::policy::Effects::NONE) .view(), // The Shapefile index cache on disk, shared by every project (#1259). Command search, // scripts and the CLI run it; it has no ribbon button. C::new("cache.emptyIndexes", "Empty Index Cache", "Data › Shapefile Index Cache", empty_indexes).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view(), // A fill runs to the end in one go (it's quick); cancelling stops the automatic fills // that follow projection changes. C::new("cache.cancel", "Cancel Caching", "Data › Feature Cache", |s, _| { s.auto_cache = false; Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .view(), C::new("cache.auto", "Auto Cache", "Data › Feature Cache", |s, p| { s.auto_cache = b(p, "on").unwrap_or(!s.auto_cache); if s.auto_cache { fill_cache(s); } Ok(json!({"autoCache": s.auto_cache})) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"on"?: bool}"#), ] } /// Fills every layer's projected geometry cache. pub(crate) fn fill_cache(s: &mut Session) -> usize { let mut n = 0; for m in &mut s.project.maps { let (flat, key) = (m.flat(), m.projection.code()); for l in &mut m.layers { // Counts the layers this fill actually projected. if !l.is_raster() && !l.is_cached(&key) { l.projected_in(&flat, &key); n += 1; } } } n } /// The longitude/latitude extent the flat map's view shows. pub fn view_extent(s: &Session) -> Extent { view_extent_of(s.map(), s.view_size) } /// The longitude/latitude extent a `size` view of map `m` shows. pub fn view_extent_of(m: &rustgis_map::Map, (w, h): (f64, f64)) -> Extent { let e = m.camera.extent(w, h); let mut ll = Extent::EMPTY; for i in 0..=8 { for j in 0..=8 { let c = Coord::new(e.min_x + e.width() * i as f64 / 8.0, e.min_y + e.height() * j as f64 / 8.0); if let Some(x) = m.to_lonlat(c) { ll.expand(x); } } } ll } /// Connects active-map rendering to the common layer and raw tile route bindings. fn map_render_inputs(input: &super::InputContext<'_>, _: &Value) -> Result { Ok(super::tiles::render_inputs(input.map())) } /// Clearing wins; otherwise only an explicit create request asks the map renderer. fn creates_thumbnail(p: &Value) -> bool { !b(p, "clear").unwrap_or(false) && b(p, "create").unwrap_or(false) } /// Adds renderer bindings only on the branch that creates a thumbnail from the map. fn thumbnail_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { if creates_thumbnail(p) { map_render_inputs(input, p) } else { Ok(super::Inputs::layers(std::iter::empty())) } } /// Clears, renders, or accepts a supplied picture in the same precedence as its selector. fn thumbnail(s: &mut Session, p: &Value) -> Result, String> { if b(p, "clear").unwrap_or(false) { return Ok(None); } if creates_thumbnail(p) { let png = super::share::map_png(s, Some(240.0), Some(160.0), Some(96.0))?; return Ok(Some(base64::engine::general_purpose::STANDARD.encode(png))); } let b64 = super::graphics::picture(p)?; Ok(Some(b64)) } fn points(p: &Value) -> Result, String> { let pts: Vec = p .get("points") .and_then(Value::as_array) .ok_or("points is required")? .iter() .take(10_000) .filter_map(|v| Some(Coord::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) .filter(|c| c.is_finite()) .collect(); if pts.len() < 2 { Err("a profile needs two or more points".into()) } else { Ok(pts) } } fn dem(s: &Session, p: &Value) -> Result, String> { let n = ps(p, "layer").ok_or("layer (an elevation raster) is required")?; s.map().layer_by_name(n).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).ok_or_else(|| format!("no raster layer '{n}'")) } /// An elevation profile with its summary. fn profile(s: &Session, p: &Value, path: &[Coord]) -> CmdResult { let r = dem(s, p)?; let samples = p.get("samples").and_then(Value::as_u64).unwrap_or(200) as usize; let prof = rustgis_analysis::rasterops::profile(&r, 0, path, samples); let zs: Vec = prof.iter().filter_map(|x| x.2).collect(); if zs.is_empty() { return Err("the line doesn't cross the raster".into()); } let (lo, hi) = zs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), z| (a.min(*z), b.max(*z))); let (mut gain, mut loss) = (0.0, 0.0); for w in zs.windows(2) { if let [a, b2] = w { if b2 > a { gain += b2 - a } else { loss += a - b2 } } } let rows: Vec = prof.iter().map(|(d, c, z)| json!({"distance": d, "lon": c.x, "lat": c.y, "elevation": z})).collect(); Ok(json!({"length": prof.last().map_or(0.0, |x| x.0), "min": lo, "max": hi, "gain": gain, "loss": loss, "samples": rows})) } fn selected_lines(s: &Session, p: &Value, all: bool) -> Result>, String> { let n = profile_lines(p)?; let l = s.map().layer_by_name(n).filter(|l| l.geometry_type() == GeometryType::Polyline).ok_or_else(|| format!("no line layer '{n}'"))?; let rows: Vec = match p.get("row").and_then(Value::as_u64) { Some(r) if !all => vec![r as usize], _ if l.selection.is_empty() => return Err(format!("select lines in {n} first")), _ if all => l.selection.clone(), _ => l.selection.iter().take(1).copied().collect(), }; // Sampled in longitude/latitude, whatever system the layer holds its coordinates in. let mut out: Vec> = Vec::new(); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{n}: {e}"))?; for f in rows.iter().filter_map(|r| l.dataset.features.row(*r)) { let Some(g) = f.geometry().filter(|g| matches!(g, Geometry::Line(_))) else { continue }; if let Geometry::Line(parts) = &*rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))? { let v: Vec = parts.iter().flatten().copied().collect(); if v.len() >= 2 { out.push(v); } } } if out.is_empty() { Err("no usable lines".into()) } else { Ok(out) } } /// Every keyframe-to-keyframe move rendered as PNG frames in a zip. fn animation_zip(s: &mut Session, p: &Value) -> Result, String> { let keys = s.map().animation.clone(); if keys.len() < 2 { return Err("add at least two keyframes".into()); } let fps = f(p, "fps").unwrap_or(10.0).clamp(1.0, 30.0); let (w, h) = (f(p, "width").unwrap_or(640.0).clamp(64.0, 1920.0), f(p, "height").unwrap_or(400.0).clamp(64.0, 1080.0)); // The frames as they will be made (each move rounded, plus the last), within a count and a // pixel budget (every PNG is held until the zip is written). let count: usize = keys.windows(2).map(|w| w.get(1).map_or(1, |k| (k.seconds * fps).round().max(1.0) as usize)).sum::() + 1; if count > 3000 || count as f64 * w * h > 1.5e9 { return Err(format!("the animation would have {count} frames at {w:.0} × {h:.0}; lower the fps, the durations or the size")); } let saved = s.map().camera; let saved_size = s.view_size; s.view_size = (w, h); let mut frames = Vec::new(); let mut n = 0; let mut render = |s: &mut Session, c: Coord, scale: f64| -> Result<(), String> { let m = s.map_mut(); if let Some(mc) = m.to_map(c) { m.camera.center = mc; } m.set_scale(scale); let png = super::share::map_png(s, Some(w), Some(h), Some(96.0))?; n += 1; frames.push((format!("frame_{n:04}.png"), png)); Ok(()) }; let mut result = Ok(()); 'frames: for pair in keys.windows(2) { let [a, b2] = pair else { continue }; let steps = (b2.seconds * fps).round().max(1.0) as usize; for i in 0..steps { let t = i as f64 / steps as f64; // Smooth in and out; scale changes geometrically. let e = t * t * (3.0 - 2.0 * t); let c = Coord::new(a.center.x + (b2.center.x - a.center.x) * e, a.center.y + (b2.center.y - a.center.y) * e); let sc = rustgis_map::camera::scale_between(a.scale, b2.scale, e); if let Err(e) = render(s, c, sc) { result = Err(e); break 'frames; } } } if result.is_ok() && let Some(last) = keys.last() { result = render(s, last.center, last.scale); } s.map_mut().camera = saved; s.view_size = saved_size; result?; rustgis_data::zip::write(&frames) } /// The project's size and the session's state (Diagnostic Monitor). Read-only, so the monitor can /// show it without running a command. pub fn diagnostics(s: &Session) -> Value { let mut features = 0usize; let mut vertices = 0usize; let mut pixels = 0usize; let mut cached = 0usize; let mut layers = 0usize; for m in &s.project.maps { let key = m.projection.code(); for l in &m.layers { layers += 1; features += l.dataset.features.len(); vertices = vertices .saturating_add(l.dataset.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.coord_count()).sum::()); pixels = pixels.saturating_add( l.raster .as_ref() .and_then(|r| r.data.as_ref()) .map_or(0, |d| (d.width as usize).saturating_mul(d.height as usize).saturating_mul(d.band_count())), ); cached += usize::from(l.is_cached(&key)); } } json!({ "maps": s.project.maps.len(), "layers": layers, "features": features, "vertices": vertices, "rasterPixels": pixels, "cachedLayers": cached, "estimatedMemoryMB": ((vertices as f64 * 16.0 + features as f64 * 64.0 + pixels as f64 * 4.0) / 1_048_576.0 * 10.0).round() / 10.0, "commands": s.registry.commands.len(), "revision": s.revision, "undo": s.undo_depth(), "notices": s.notices.len(), "layouts": s.project.layouts.len(), "geoprocessingRuns": s.project.gp_history.len(), }) } fn infographic(s: &mut Session, p: &Value) -> CmdResult { Ok(infographic_of(s, ps(p, "layer"))) } /// Cards summarising the features in view, for every visible feature layer or just `only`. pub fn infographic_of(s: &Session, only: Option<&str>) -> Value { let e = view_extent(s); let only = only.map(str::to_ascii_lowercase); let mut cards = Vec::new(); for l in s.map().layers.iter().filter(|l| s.map().shows(l) && !l.is_raster() && !l.graphics) { if only.as_ref().is_some_and(|o| *o != l.name.to_ascii_lowercase()) { continue; } // The view in the layer's own coordinates, as its features' boxes are. let own = l.dataset.extent_from_lonlat(&e); let rows: Vec = l .visible_rows() .iter() .enumerate() .filter(|(r, v)| { **v && l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()).is_some_and(|g| g.extent().intersects(&own)) }) .map(|(r, _)| r) .collect(); let numbers: Vec = l .dataset .fields .iter() .enumerate() .filter(|(_, fd)| fd.ty.is_numeric()) .take(4) .map(|(fi, fd)| { let v: Vec = rows.iter().filter_map(|r| l.dataset.value(*r, fi).as_f64()).filter(|x| x.is_finite()).collect(); let sum: f64 = v.iter().sum(); json!({"field": fd.name, "sum": sum, "mean": if v.is_empty() { None } else { Some(sum / v.len() as f64) }, "max": v.iter().copied().fold(None, |m: Option, x| Some(m.map_or(x, |m| m.max(x))))}) }) .collect(); let category = l.dataset.fields.iter().enumerate().find(|(_, fd)| !fd.ty.is_numeric() && !fd.name.eq_ignore_ascii_case("name")); let top: Vec = category .map(|(fi, _)| { let mut counts: std::collections::HashMap = std::collections::HashMap::new(); for r in &rows { *counts.entry(l.dataset.value(*r, fi).to_string()).or_insert(0) += 1; } let mut v: Vec<(String, usize)> = counts.into_iter().collect(); v.sort_by(|a, b2| b2.1.cmp(&a.1).then_with(|| a.0.cmp(&b2.0))); v.into_iter().take(5).map(|(k, n)| json!({"value": k, "count": n})).collect() }) .unwrap_or_default(); cards.push(json!({"layer": l.name, "count": rows.len(), "numbers": numbers, "category": category.map(|(_, f)| f.name.clone()), "top": top})); } json!({"extent": [e.min_x, e.min_y, e.max_x, e.max_y], "layers": cards}) } /// The map's feature layers clipped to an extent (rasters stay behind: they're files already). fn snapshot(m: &mut rustgis_map::Map, e: &Extent) -> rustgis_map::Map { // The layers (the bulk) are set aside while the rest of the map is copied, then each // feature layer is copied without its features, and only the features in the extent added. let layers = std::mem::take(&mut m.layers); let mut out = m.clone(); out.offline_area_id = None; m.layers = layers; for l in m.layers.iter_mut().filter(|l| !l.is_raster()) { let features = std::mem::take(&mut l.dataset.features); let mut c = l.clone(); l.dataset.features = features; // The extent in the layer's own coordinates, as its features' boxes are. let own = l.dataset.extent_from_lonlat(e); c.dataset.features = l.dataset.features.iter().filter(|f| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&own))).cloned().collect(); c.selection.clear(); // Only part of the rows read: no longer the layer its file's record describes. c.synced = None; // Nor the rows a GeoPackage or PostGIS table was loaded with: saved to the table, the rows // left outside the extent would be deleted from it. Its edits go back by Sync or Bring Back. unbind_table_edits(&mut c); c.touch_geometry(); out.layers.push(c); } out } /// Takes away a layer's link to the GeoPackage or PostGIS table it was loaded from for editing /// (`gpkg.saveEdits`, `pg.saveEdits`), for a copy that holds only some of its rows: an offline /// area's or a field package's. Saving such a copy to the table would delete every row the copy /// lacks. Returns whether it had one. pub(crate) fn unbind_table_edits(l: &mut rustgis_map::Layer) -> bool { let had = l.gpkg.is_some() || l.postgis.is_some(); l.gpkg = None; l.postgis = None; had } /// [`unbind_table_edits`] for each layer of `m`, as the number of layers that had a link. pub(crate) fn unbind_map_table_edits(m: &mut rustgis_map::Map) -> usize { m.layers.iter_mut().map(unbind_table_edits).filter(|had| *had).count() } fn offline_map_name(area: &str) -> String { format!("{area}{}", super::field::OFFLINE) } /// Legacy areas were saved without IDs. Give one an ID before binding a map to it. fn ensure_area_id(area: &mut OfflineArea) -> Result { if area.id.is_empty() { area.id = crate::project::field_id()?; } Ok(area.id.clone()) } /// Finds the open copy by identity before trying the original title of an unmarked map. fn offline_map_index(project: &Project, area: &OfflineArea) -> Option { let maps = &project.maps; let by_id = maps.iter().position(|m| m.offline_area_id.as_deref().is_some_and(|id| id == area.id)); by_id.or_else(|| { let name = offline_map_name(&area.name); maps.iter() .position(|m| m.offline_area_id.is_none() && m.name.eq_ignore_ascii_case(&name) && !m.name.eq_ignore_ascii_case(&area.map)) }) } /// Resolves the reverse association using the same precedence as opening the area. pub(crate) fn map_area_index(project: &Project, map: usize) -> Option { project.offline_areas.iter().position(|area| offline_map_index(project, area) == Some(map)) } /// Before a rename takes away a legacy copy's only link to its area, record the area ID. pub(crate) fn bind_offline_map_before_rename(project: &mut Project, map: usize) -> Result<(), String> { if project.maps.get(map).is_some_and(|m| m.offline_area_id.is_none()) && let Some(area) = map_area_index(project, map).and_then(|i| project.offline_areas.get_mut(i)) { let id = ensure_area_id(area)?; if let Some(m) = project.maps.get_mut(map) { m.offline_area_id = Some(id); } } Ok(()) } /// Unlinks table edits on marked offline copies and on legacy copies matched to an area. pub(crate) fn unbind_offline_maps(project: &mut Project) -> usize { let offline: Vec = project.offline_areas.iter().filter_map(|a| offline_map_index(project, a)).collect(); project .maps .iter_mut() .enumerate() .filter(|(i, m)| m.offline_area_id.is_some() || offline.contains(i)) .map(|(_, m)| unbind_map_table_edits(m)) .sum() } /// Says that `n` layers of an offline copy no longer save to their tables, when `n` isn't 0. pub(crate) fn note_unbound(s: &mut Session, n: usize, copy: &str) { if n > 0 { s.notify( format!( "{n} layer(s) of {copy} were loaded for editing from a GeoPackage or PostGIS table: the copy holds only some of their rows, so it doesn't save to the table. Bring its edits back with Sync or Bring Back, then save the table from the map they come back to" ), false, ); } } /// Most offline areas a project keeps (each holds a copy of its features). const MAX_AREAS: usize = 20; /// Makes an offline area of the active map: a snapshot of its feature layers' features in `extent` /// (the view's, unless one is given), which a later sync or a field package's return is compared /// against. It gets its identities and its home project's here; its return check waits until a /// field package is first made of it. pub(crate) fn offline_download(s: &mut Session, p: &Value) -> CmdResult { crate::project::ensure_map_imports_complete(s.map())?; let e = match p.get("extent").and_then(Value::as_array) { Some(a) => { let n: Vec = a.iter().filter_map(Value::as_f64).collect(); match n.as_slice() { [x0, y0, x1, y1] if x0 < x1 && y0 < y1 => Extent::new(*x0, *y0, *x1, *y1), _ => return Err("extent is [minLon, minLat, maxLon, maxLat]".into()), } } None => view_extent(s), }; if e.is_empty() { return Err("the extent is empty".into()); } let base = ps(p, "name") .map(str::trim) .filter(|n| !n.is_empty()) .map(|n| n.chars().take(200).collect()) .unwrap_or_else(|| format!("{} offline", s.map().name)); let mut name = base.clone(); let mut i = 1; // Unique among areas, and its offline map's name (" (offline)") unused by other maps. let taken = |s: &Session, n: &str| { s.project.offline_areas.iter().any(|a| a.name.eq_ignore_ascii_case(n)) || s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(&offline_map_name(n))) }; while taken(s, &name) { i += 1; name = format!("{base} {i}"); } if s.project.offline_areas.len() >= MAX_AREAS { return Err(format!("a project keeps at most {MAX_AREAS} offline areas; remove one first")); } let id = crate::project::field_id()?; let origin_id = if s.project.origin_id.is_empty() { crate::project::field_id()? } else { s.project.origin_id.clone() }; let bound = s.map().layers.iter().filter(|l| !l.is_raster() && (l.gpkg.is_some() || l.postgis.is_some())).count(); let data = snapshot(s.map_mut(), &e); let features: usize = data.layers.iter().map(|l| l.dataset.features.len()).sum(); let t = now(); s.project.origin_id = origin_id; s.project.offline_areas.push(OfflineArea { id, name: name.clone(), map: s.map().name.clone(), extent: e, created: t, synced: t, generation: String::new(), data, }); note_unbound(s, bound, &format!("the offline area '{name}'")); Ok(json!({"name": name, "features": features})) } fn offline_fields_match(a: &[rustgis_data::Field], b: &[rustgis_data::Field]) -> bool { // Attribute values are positional; aliases are display metadata and field lookup ignores case. a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.name.eq_ignore_ascii_case(&y.name) && x.ty == y.ty) } /// Copies edits made to an offline area (in its offline map, if open) back to its source map by /// feature id: changed and new features update the source, deleted ones are removed from it. /// A feature changed in the source too since the last sync takes the area's version (or its /// deletion), and is reported with a warning, as is an offline edit to a feature since deleted /// from the source. /// Then the area is refreshed from the source. fn offline_sync(s: &mut Session, p: &Value) -> CmdResult { let n = ps(p, "name").ok_or("name is required")?; let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?; let area = s.project.offline_areas.get(ai).cloned().ok_or("no such area")?; let edited = offline_map_index(&s.project, &area).and_then(|i| s.project.maps.get(i)).cloned().unwrap_or_else(|| area.data.clone()); sync_area(s, ai, &edited) } /// Copies the edits `edited` holds of offline area `ai` (its offline map, here or from a field /// package) back to the area's source map, as [`offline_sync`] describes, and refreshes the area. /// /// A feature added offline keeps its id when the source doesn't use it, so the next sync of the /// same copy (a field package's phone keeps its ids) finds it again as the same feature. One whose /// id is taken gets a fresh one, counted in `renumbered` (a field package's Bring Back says it; an /// offline map here is renewed from the source after the sync, so it has the new id): a later sync /// of a copy that kept the old id finds it under it, so the source's copy is deleted and the /// area's added again (no feature twice, but a new id, and a change made to it here meanwhile is /// said as a conflict). pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) -> CmdResult { let area = s.project.offline_areas.get(ai).cloned().ok_or("no such area")?; let offline_map = offline_map_index(&s.project, &area); let si = s .project .maps .iter() .position(|m| m.name.eq_ignore_ascii_case(&area.map)) .ok_or_else(|| format!("the source map '{}' is gone", area.map))?; crate::project::ensure_map_imports_complete(s.project.maps.get(si).ok_or("the source map is gone")?)?; // The area's packages are of the state it has now; after this sync it is another: a package // made before it (one a phone still holds) would no longer be of the area as it is. An area no // package was made of has none to tell apart. let next_generation = if area.generation.is_empty() { None } else { Some(crate::project::field_id()?) }; let (mut updated, mut added, mut deleted, mut skipped) = (0, 0, 0, 0); // Added offline, given a fresh id: theirs was taken. let mut renumbered = 0usize; // Features changed in the source since the last sync whose changes the area's version (or its // deletion) replaced, and features changed offline whose edits a deletion in the source // dropped, as "layer #id". let (mut conflicts, mut dropped) = (Vec::new(), Vec::new()); let tag = |layer: &str, id: u64| format!("{layer} #{id}"); if let Some(src) = s.project.maps.get_mut(si) { for ol in &edited.layers { // Layers are matched by id (the snapshot keeps them), so same-named layers don't mix. // Layers removed from either side since the download are left alone. let Some(sl) = src.layers.iter_mut().find(|l| l.id == ol.id && !l.is_raster()) else { continue }; // Compared and merged in longitude/latitude, as a package returns its features, whatever // system the source, its last synced copy or the package hold them in; the source is // written back in its own, its unchanged places as stored (`results_from_lonlat`). let ol_ds = ol.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; let last_synced = area.data.layers.iter().find(|l| l.id == ol.id).map(|l| &l.dataset); let baseline = last_synced.map(|d| d.in_lonlat()).transpose().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; // Whether a feature was edited offline: the returned copy against the last synced one, // as they are when both are held in the same system (as an offline map in the project // and its area are), so a conversion that changed meanwhile (a datum grid downloaded) // can't make an unedited feature look edited; else both in longitude/latitude. type ById<'a> = std::collections::HashMap>; fn by_id(d: &rustgis_data::Dataset) -> ById<'_> { d.features.rows().map(|r| (r.id(), r)).collect() } let raw: Option<(ById<'_>, ById<'_>)> = last_synced.filter(|b| b.coord_crs() == ol.dataset.coord_crs()).map(|b| (by_id(b), by_id(&ol.dataset))); let same_row = |a: rustgis_data::RowRef, b: rustgis_data::RowRef| a.geometry() == b.geometry() && a.values().eq(b.values()); // `lonlat_base` and `lonlat_now`, the copies in longitude/latitude, are used only when // the two aren't held in the same system. let unchanged_offline = |fid: u64, lonlat_base: Option<&&rustgis_data::Feature>, lonlat_now: &rustgis_data::Feature| match &raw { Some((raw_base, raw_now)) => raw_base.get(&fid).is_some_and(|b| raw_now.get(&fid).is_some_and(|n| same_row(*b, *n))), None => lonlat_base.is_some_and(|b| *b == lonlat_now), }; let same_as_last = match (&raw, &baseline) { (Some(_), Some(_)) => last_synced.is_some_and(|b| b.features == ol.dataset.features), (None, Some(b)) => b.features == ol_ds.features, _ => false, }; if !offline_fields_match(&sl.dataset.fields, &ol_ds.fields) && baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || !same_as_last) { return Err(format!("cannot sync layer '{}': source and offline fields differ; align the fields before syncing", ol.name)); } let held = (sl.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat).then(|| sl.dataset.clone()); if held.is_some() { sl.dataset = sl.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?.into_owned(); } // The ids the area held when it was last synced. let had: std::collections::HashSet = baseline.as_ref().map(|b| b.features.iter().map(|f| f.id).collect()).unwrap_or_default(); let now_ids: std::collections::HashSet = ol_ds.features.iter().map(|f| f.id).collect(); // The area's copies as last synced: only features changed offline since then go back, // so edits made to the source meanwhile aren't overwritten by stale copies. let base: std::collections::HashMap = baseline.as_ref().map(|b| b.features.iter().map(|f| (f.id, f)).collect()).unwrap_or_default(); // The features this sync writes, by their ids in the source: only these are converted // back to a held source's system. let mut written = std::collections::HashSet::new(); // Deletions first, so a fresh id given to a new feature below can't be swept away. let before = sl.dataset.features.len(); sl.dataset.features.retain(|x| { let keep = !had.contains(&x.id) || now_ids.contains(&x.id); // Deleted offline but changed in the source meanwhile. if !keep && base.get(&x.id).is_some_and(|b| *b != x) { conflicts.push(tag(&sl.name, x.id)); } keep }); deleted += before - sl.dataset.features.len(); for f in &ol_ds.features { let fid = f.id; if had.contains(&fid) { let changed_offline = !unchanged_offline(fid, base.get(&fid), f); match sl.dataset.features.iter_mut().find(|x| x.id == fid) { Some(x) if changed_offline && x != f => { if base.get(&fid).is_some_and(|b| *b != x) { conflicts.push(tag(&sl.name, fid)); } *x = f.clone(); written.insert(fid); updated += 1; } // Changed offline but deleted from the source meanwhile: left deleted, and // reported. None if changed_offline => { skipped += 1; dropped.push(tag(&sl.name, fid)); } _ => {} } } else { // Added offline: its own id when the source and the area haven't used it, else // a fresh one above any they have (its id clashed with one outside the area). let taken = sl.dataset.features.iter().any(|x| x.id == f.id) || had.contains(&f.id); let id = if taken { renumbered += 1; sl.dataset.features.iter().map(|x| x.id).chain(had.iter().copied()).max().unwrap_or(0).saturating_add(1) } else { f.id }; sl.dataset.features.push(rustgis_data::Feature { id, ..f.clone() }); written.insert(id); added += 1; } } if let Some(own) = held { // Its own coordinates back while the merge is converted (and kept, should that fail): // the features it left as they were stay as stored, only those it wrote are converted. let merged = std::mem::replace(&mut sl.dataset, own); sl.dataset = sl.dataset.merged_from_lonlat(merged, &written).map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; } sl.selection.clear(); sl.touch_geometry(); } } let fresh = s.project.maps.get_mut(si).map(|m| snapshot(m, &area.extent)).ok_or("the source map is gone")?; if let Some(m) = offline_map.and_then(|i| s.project.maps.get_mut(i)) { let name = m.name.clone(); *m = fresh.clone(); m.name = name; m.offline_area_id = (!area.id.is_empty()).then(|| area.id.clone()); // A copy of the source map: a map, and layers, of its own. m.renew_instance_id(); for l in &mut m.layers { l.renew_instance_id(); } } if let Some(a) = s.project.offline_areas.get_mut(ai) { a.data = fresh; a.synced = now(); if let Some(id) = next_generation { a.generation = id; } } // Never silent: say which features lost an edit, so they can be checked (Undo puts the // source's versions back). let listed = |ids: &[String]| { let mut said: Vec = ids.iter().take(20).cloned().collect(); if ids.len() > 20 { said.push(format!("{} more", ids.len() - 20)); } said.join(", ") }; if !conflicts.is_empty() { s.notify( format!( "Offline area '{}': {} feature(s) were changed in the map '{}' since the last sync and also edited or deleted in the area, so the area's version replaced the map's changes: {}. Undo restores the map's versions", area.name, conflicts.len(), area.map, listed(&conflicts) ), false, ); } if !dropped.is_empty() { s.notify( format!( "Offline area '{}': {} feature(s) edited in the area were deleted from the map '{}' meanwhile, so those edits were dropped: {}", area.name, dropped.len(), area.map, listed(&dropped) ), false, ); } Ok( json!({"updated": updated, "added": added, "deleted": deleted, "skipped": skipped, "conflicts": conflicts.len(), "renumbered": renumbered}), ) } /// Binds the elevation raster and literal selected-line source. fn profile_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; super::Inputs::named(s.map(), [super::imagery::raster_name(p)?, profile_lines(p)?]) } /// Parses the same required line-layer name used by profile extraction. fn profile_lines(p: &Value) -> Result<&str, String> { ps(p, "lines").ok_or("lines (a line layer) is required".into()) }