From b30c184a88430dfda80aea533fd41b5ecbd3c242 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 01:06:11 -0500 Subject: [PATCH 01/18] feat(mobile): the capture form marks required fields, follows contingent values, has a calendar, and stays above the soft keyboard (#1902) --- Cargo.lock | 1 + apps/rustgis-mobile/README.md | 21 +- .../java/org/rustgis/mobile/MainActivity.java | 9 +- apps/rustgis-mobile/src/lib.rs | 36 ++ crates/ui-egui/src/icons.rs | 12 + crates/ui-touch/Cargo.toml | 2 + crates/ui-touch/src/form.rs | 318 ++++++++++++++++++ crates/ui-touch/src/lib.rs | 195 ++++++++++- 8 files changed, 570 insertions(+), 24 deletions(-) create mode 100644 crates/ui-touch/src/form.rs diff --git a/Cargo.lock b/Cargo.lock index 867bfb7ab8..637adbdca5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5062,6 +5062,7 @@ dependencies = [ "egui", "rustgis-ui-egui", "serde_json", + "web-time", ] [[package]] diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 2252f4d5d6..4190565ccb 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -91,7 +91,19 @@ The form follows the layer's data design. A field with a list of values (a coded the layer's subtypes, or yes and no) shows a chip for each: one is tapped to choose it, and tapped again to leave the field empty. A field with a range says its limits. When the layer has feature templates, a **Template** row chooses one, and its defaults fill what the form leaves -empty; the template stays chosen for the next feature. +empty; the template stays chosen for the next feature. A field a constraint rule requires (the +rule asks `IS NOT NULL` of it, alone or joined to other clauses by `AND`) is marked with `*`, and a +feature with it empty, and no default for it from the template or subtype chosen, isn't added: the +sheet names the fields to fill in. A field in a contingent value set offers only the values that +fit what the set's other fields hold, as chips (a value chosen before the others changed stays, +so the conflict shows). A date or date and time field has a calendar button: a month of days a +finger's width each, with **Today** (in UTC; the phone's time zone isn't asked) and, for a date and +time, **Now**. + +While a field is typed in, the sheet takes most of the window and stays above the soft keyboard: +the activity's Java half counts the keyboard in the window's bottom inset, the app looks again +for it while a field wants the keyboard (Android doesn't wake the app when it comes or goes), the +field is scrolled into view, and closing the keyboard ends the typing. **Show My Position**, in the More sheet, asks Android for the device's position (and the user, the first time, for leave to use it). The position is drawn on the map as a dot in a ring as wide @@ -100,9 +112,8 @@ sheet and at the top of the Capture sheet, moves the map so the capture cross is or a vertex added then is at the device's position. **Hide My Position** stops asking, which spares the battery. -What it doesn't do yet: moving or deleting a vertex once the feature is added, snapping, a new -layer to capture into, marking which fields a rule requires, and keeping the field being typed in -above the soft keyboard (the keyboard covers the lower fields: close it to reach them). +What it doesn't do yet: moving or deleting a vertex once the feature is added, snapping, and a +new layer to capture into. The interface keeps out of the room the system's bars take: the activity's Java half reports the insets, and the bars' icons are drawn dark over a light theme's ground and light over a dark @@ -117,7 +128,7 @@ one's. | Folders | Settings, app data and the cache are in the app's internal storage, set once at start-up (`rustgis_data::dirs::set_root`) | | GeoLibre tools, GDAL formats, DuckDB | Not available: a phone can't run their programs | | Preferences, the keychain, autosave | Not wired up yet | -| Soft keyboard | It opens for a text field. `NativeActivity`'s is poor; a real app moves to `GameActivity` | +| Soft keyboard | It opens for a text field, and the touch interface keeps the field above it. `NativeActivity`'s text input is still poor (no suggestions, no composing): a real app moves to `GameActivity` | ## What phase 0 found diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index daa9d73760..dda148c34d 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -299,8 +299,8 @@ public String takeEvents() { } /** - * The room the system's bars and a camera cutout take at the window's edges, in pixels, as - * "left top right bottom"; empty before the window is laid out. + * The room the system's bars, a camera cutout and the soft keyboard take at the window's + * edges, in pixels, as "left top right bottom"; empty before the window is laid out. */ public String insets() { return insets; @@ -314,7 +314,10 @@ private static String describe(android.view.WindowInsets insets) { left = bars.left; top = bars.top; right = bars.right; - bottom = bars.bottom; + // The soft keyboard, while it is up, takes the bottom too: what is typed in is kept + // above it. (The Rust side looks again while a field wants the keyboard, so the + // room comes back when it goes.) + bottom = Math.max(bars.bottom, insets.getInsets(android.view.WindowInsets.Type.ime()).bottom); } else { left = insets.getSystemWindowInsetLeft(); top = insets.getSystemWindowInsetTop(); diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 87911e2c53..443e295766 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -74,6 +74,14 @@ mod android { use std::sync::{Arc, Mutex}; use winit::platform::android::activity::AndroidApp; + /// How long the window keeps looking for the soft keyboard's room after a field last wanted + /// it: long enough for the keyboard to finish closing. + const KEYBOARD_SETTLES: std::time::Duration = std::time::Duration::from_millis(1500); + + /// How much the window's bottom room shrinks, in points, when the soft keyboard closes, at the + /// least: more than the navigation bar coming and going. + const KEYBOARD_LEAST: f32 = 120.0; + /// What a service couldn't do, kept until the next frame says it in the window (a service has /// no session to tell). type Refusals = Rc>>; @@ -88,6 +96,12 @@ mod android { poll: Option, /// Whether the phone was last asked for positions (`RustGisApp::locate`, as last seen). locating: bool, + /// The room last taken at the window's bottom, in points: the soft keyboard's going + /// shows as it shrinking. + bottom: Option, + /// Until when the window looks again for the soft keyboard's room: a moment after the + /// last frame a field wanted the keyboard. + typing: Option, /// Whether the system bars' icons were last asked to be dark (a light ground); `None` /// before the first frame. bars_light: Option, @@ -350,10 +364,30 @@ mod android { if let Some(wait) = self.poll { ctx.request_repaint_after(std::time::Duration::from_millis(wait)); } + // The soft keyboard comes and goes without waking the app: while a field wants it, + // and a moment after, the window looks again for the room it takes (`insets`). + let now = std::time::Instant::now(); + if ctx.egui_wants_keyboard_input() { + self.typing = Some(now + KEYBOARD_SETTLES); + } + if self.typing.is_some_and(|until| now < until) { + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + } else { + self.typing = None; + } } fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { raw_input.safe_area_insets = insets(self.phone.as_deref(), ctx.pixels_per_point()); + // The soft keyboard closed (Back, or its own button) while a field still has the + // focus: typing is over, so the field lets it go. Kept, the interface would stay laid + // out for typing until the next tap, and move what that tap was aimed at. + if let Some(egui::SafeAreaInsets(edges)) = raw_input.safe_area_insets { + if self.bottom.is_some_and(|before| edges.bottom < before - KEYBOARD_LEAST) && ctx.egui_wants_keyboard_input() { + ctx.memory_mut(|m| m.stop_text_input()); + } + self.bottom = Some(edges.bottom); + } self.take_phone_events(ctx, raw_input); // The pushed files open as files dropped on the desktop window do: once the window // runs, read off its thread with progress and Cancel, each failure said in the window. @@ -487,6 +521,8 @@ mod android { app, poll: None, locating: false, + typing: None, + bottom: None, bars_light: None, pushed, phone, diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c958ce0cc2..1e08d0372a 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -465,6 +465,17 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(12.5, 7.0), (12.5, 12.0), (16.0, 14.0)], 1.6, ink); p.fill(&[(1.5, 9.5), (6.0, 9.5), (3.5, 13.5)], ink); } + "calendar" => { + // A page of a calendar: its rings over a band, and a day marked in the grid below. + p.rect(3.0, 5.0, 18.0, 16.0, Some(p.tint(30)), Some((1.4, ink)), 2.0); + p.line(&[(3.0, 9.5), (21.0, 9.5)], 1.4, ink); + p.line(&[(8.0, 3.0), (8.0, 7.0)], 1.6, ink); + p.line(&[(16.0, 3.0), (16.0, 7.0)], 1.6, ink); + for (x, y) in [(6.5, 13.0), (10.5, 13.0), (6.5, 17.0), (10.5, 17.0), (14.5, 17.0)] { + p.rect(x - 1.0, y - 1.0, 2.0, 2.0, Some(ink), None, 0.0); + } + p.rect(13.0, 11.5, 4.0, 3.5, Some(p.acc), None, 0.5); + } "time_slider" => { // A clock over a slider track with its thumb. p.circle(12.0, 9.0, 7.0, Some(p.tint(40)), Some((1.4, ink))); @@ -1255,6 +1266,7 @@ pub const ALL: &[&str] = &[ "modelbuilder", "python", "history", + "calendar", "time_slider", "time_off", "time_first", diff --git a/crates/ui-touch/Cargo.toml b/crates/ui-touch/Cargo.toml index 4008135ab6..51abf6bd1e 100644 --- a/crates/ui-touch/Cargo.toml +++ b/crates/ui-touch/Cargo.toml @@ -12,3 +12,5 @@ workspace = true rustgis-ui-egui = { workspace = true } egui = { workspace = true } serde_json = { workspace = true } +# Today's date and this moment, for the form's calendar. +web-time = { workspace = true } diff --git a/crates/ui-touch/src/form.rs b/crates/ui-touch/src/form.rs new file mode 100644 index 0000000000..da81069dad --- /dev/null +++ b/crates/ui-touch/src/form.rs @@ -0,0 +1,318 @@ +//! What the capture form reads from a layer's data design beyond its value lists: the fields its +//! constraint rules require, the values its contingent value sets leave a field, and a calendar +//! for date fields that a finger can use. + +use egui::{RichText, Ui, Vec2}; +use rustgis_ui_egui::rustgis_engine::data::query::{Expr, parse}; +use rustgis_ui_egui::rustgis_engine::data::{Date, DateTime, FieldType, Value}; +use rustgis_ui_egui::rustgis_engine::map::Layer; +use rustgis_ui_egui::theme::Tokens; +use rustgis_ui_egui::tl; +use std::collections::BTreeMap; + +/// A value as the form holds it: a yes/no as `true` or `false` (what its chips store), anything +/// else as its text. +pub(crate) fn stored(value: &Value) -> String { + match value { + Value::Bool(b) => b.to_string(), + other => other.to_string(), + } +} + +/// The fields a layer's constraint rules require to hold a value, by name, in the layer's field +/// order: those a rule asks `IS NOT NULL` of, alone or as one of the clauses joined by `AND` at +/// its top. A rule that can't be read, or that asks it only under a condition (inside an `OR`), +/// requires nothing here; the engine still checks the rule itself when the feature is added. +pub(crate) fn required(layer: &Layer) -> Vec { + use rustgis_ui_egui::rustgis_engine::map::design::RuleKind; + let mut found = vec![false; layer.dataset.fields.len()]; + for rule in layer.design.rules.iter().filter(|r| r.kind == RuleKind::Constraint) { + if let Ok(e) = parse(&rule.expression, &layer.dataset) { + not_null(&e, &mut found); + } + } + layer.dataset.fields.iter().zip(found).filter(|(_, on)| *on).map(|(f, _)| f.name.clone()).collect() +} + +/// Marks in `found` the fields `e` requires to hold a value, looking through `AND`s only. +fn not_null(e: &Expr, found: &mut [bool]) { + match e { + Expr::And(clauses) => clauses.iter().for_each(|c| not_null(c, found)), + Expr::IsNull { field, negate: true } => { + if let Some(on) = found.get_mut(*field) { + *on = true; + } + } + Expr::Not(inner) => { + if let Expr::IsNull { field, negate: false } = inner.as_ref() + && let Some(on) = found.get_mut(*field) + { + *on = true; + } + } + _ => {} + } +} + +/// What the layer's contingent value sets leave `field` to take, given what `values` (the form, +/// by field name) holds for the sets' other fields, as the form stores them: `None` when the sets +/// leave it anything (it is in none, or a combination that fits leaves it open). An empty list +/// means no combination fits the other values chosen, whatever this field holds. +pub(crate) fn contingent(layer: &Layer, field: &str, values: &BTreeMap) -> Option> { + let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b); + let mut left: Option> = None; + for set in &layer.design.contingent { + let Some(at) = set.fields.iter().position(|f| same(f, field)) else { continue }; + // What the form holds for each of the set's fields; this one's own value doesn't narrow it. + let chosen: Vec> = set + .fields + .iter() + .enumerate() + .map(|(i, f)| { + if i == at { + return None; + } + values.iter().find(|(name, _)| same(name, f)).map(|(_, v)| v.trim()).filter(|v| !v.is_empty()) + }) + .collect(); + let fits = + |combo: &&Vec| combo.iter().zip(&chosen).all(|(want, got)| want.is_null() || got.is_none_or(|got| stored(want) == got)); + let mut these: Vec = Vec::new(); + let mut open = false; + for combo in set.combos.iter().filter(fits) { + match combo.get(at) { + Some(v) if !v.is_null() => { + let v = stored(v); + if !these.contains(&v) { + these.push(v); + } + } + // A combination that fits and leaves this field empty lets it take anything. + _ => open = true, + } + } + if open { + continue; + } + left = Some(match left { + None => these, + Some(before) => before.into_iter().filter(|v| these.contains(v)).collect(), + }); + } + left +} + +/// Today's date, in UTC: the phone's own time zone isn't asked for. +pub(crate) fn today() -> Option { + let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).ok()?.as_secs(); + Date::from_days(i64::try_from(secs / 86_400).ok()?) +} + +/// This moment, in UTC (`…Z`), to the second, as a date and time field takes it. +pub(crate) fn now() -> Option { + let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).ok()?.as_secs(); + let micros = i64::try_from(secs).ok()?.checked_mul(1_000_000)?; + DateTime::with_offset(micros, 0).map(|t| t.to_string()) +} + +/// The day a date field's text names, if it names one: its date, or a date and time's date. +pub(crate) fn day_of(text: &str) -> Option { + let text = text.trim(); + Date::parse(text).or_else(|| DateTime::parse(text).map(DateTime::date)) +} + +/// A field's text with its day set to `day`: a date for a date field; for a date and time +/// field, the time it held kept (from the eleventh character on), else the day alone, which +/// reads as its midnight. +pub(crate) fn with_day(text: &str, day: Date, ty: FieldType) -> String { + let date = day.to_string(); + let text = text.trim(); + match (ty, text.get(10..)) { + (FieldType::DateTime, Some(time)) if DateTime::parse(text).is_some() && !time.is_empty() => format!("{date}{time}"), + _ => date, + } +} + +/// The month a calendar shows, as year and month. +pub(crate) type Month = (i64, i64); + +/// The month before or after `month`, `step` months away, within years 1 to 9999. +pub(crate) fn step(month: Month, step: i64) -> Month { + let index = (month.0 * 12 + month.1 - 1 + step).clamp(12, 9999 * 12 + 11); + (index / 12, index % 12 + 1) +} + +/// The calendar's rows besides its weeks: the month with its arrows, and the weekdays. +pub(crate) const CALENDAR_ROWS: usize = 8; + +/// A month's calendar, a finger's width to each day: tapping a day sets `text` to it (see +/// [`with_day`]). The arrows move `month`. Says whether a day was tapped. +pub(crate) fn calendar(ui: &mut Ui, t: &Tokens, month: &mut Month, text: &mut String, ty: FieldType) -> bool { + let width = ui.available_width(); + let gap = ui.spacing().item_spacing.x; + let cell = ((width - 6.0 * gap) / 7.0).max(1.0); + let height = super::TARGET - 8.0; + let mut picked = false; + ui.horizontal(|ui| { + if ui.add(egui::Button::new(RichText::new("‹").size(20.0)).min_size(Vec2::new(super::TARGET, height))).clicked() { + *month = step(*month, -1); + } + let name = month_name(month.1); + let title = rustgis_ui_egui::i18n::fmt("{month} {year}", &[("month", name), ("year", &month.0.to_string())]); + ui.add_sized([width - 3.0 * super::TARGET - 3.0 * gap, height], egui::Label::new(RichText::new(title).size(16.0).color(t.text))); + if ui.add(egui::Button::new(RichText::new("›").size(20.0)).min_size(Vec2::new(super::TARGET, height))).clicked() { + *month = step(*month, 1); + } + if let Some(day) = today() + && ui.add(egui::Button::new(RichText::new(tl!("Today")).size(13.0)).min_size(Vec2::new(super::TARGET, height))).clicked() + { + *text = with_day(text, day, ty); + let (y, m, _) = day.ymd(); + *month = (y, m); + picked = true; + } + }); + let weekdays = [tl!("Mo"), tl!("Tu"), tl!("We"), tl!("Th"), tl!("Fr"), tl!("Sa"), tl!("Su")]; + ui.horizontal(|ui| { + for name in weekdays { + ui.add_sized([cell, 20.0], egui::Label::new(RichText::new(name).size(12.0).color(t.text_dim))); + } + }); + let Some(first) = Date::from_ymd(month.0, month.1, 1) else { return picked }; + // 1970-01-01 was a Thursday: Monday is 0. + let lead = (i64::from(first.days()) + 3).rem_euclid(7); + let chosen = day_of(text); + let now = today(); + let mut day = 1 - lead; + for _ in 0..6 { + ui.horizontal(|ui| { + for _ in 0..7 { + match Date::from_ymd(month.0, month.1, day) { + Some(date) => { + let on = chosen == Some(date); + let ink = if on { t.on_accent } else { t.text }; + let label = RichText::new(day.to_string()).size(15.0).color(ink); + let mut button = + egui::Button::new(label).min_size(Vec2::new(cell, height)).fill(if on { t.accent } else { t.input }); + if now == Some(date) && !on { + button = button.stroke(egui::Stroke::new(1.5, t.accent)); + } + if ui.add(button).clicked() { + *text = with_day(text, date, ty); + picked = true; + } + } + None => { + ui.add_space(cell); + } + } + day += 1; + } + }); + } + picked +} + +/// A month's name, translated. +fn month_name(month: i64) -> &'static str { + match month { + 1 => tl!("January"), + 2 => tl!("February"), + 3 => tl!("March"), + 4 => tl!("April"), + 5 => tl!("May"), + 6 => tl!("June"), + 7 => tl!("July"), + 8 => tl!("August"), + 9 => tl!("September"), + 10 => tl!("October"), + 11 => tl!("November"), + _ => tl!("December"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_ui_egui::rustgis_engine::data::{Dataset, Field, GeometryType}; + use rustgis_ui_egui::rustgis_engine::map::design::{AttributeRule, ContingentSet, RuleKind}; + + fn layer() -> Layer { + let fields = vec![ + Field::new("name", FieldType::Text), + Field::new("kind", FieldType::Text), + Field::new("size", FieldType::Text), + Field::new("surveyed", FieldType::Boolean), + ]; + Layer::new(1, Dataset::new("Trees", GeometryType::Point, fields)) + } + + fn rule(expression: &str) -> AttributeRule { + AttributeRule { name: "r".into(), kind: RuleKind::Constraint, field: String::new(), expression: expression.into() } + } + + #[test] + fn a_field_a_rule_asks_is_not_null_of_is_required() { + let mut l = layer(); + assert!(required(&l).is_empty()); + l.design.rules = vec![rule("name IS NOT NULL AND (size = 'big' OR size IS NOT NULL)"), rule("NOT surveyed IS NULL")]; + assert_eq!(required(&l), ["name", "surveyed"]); + // Only under a condition, or in a calculation rule, or unreadable: not required. + l.design.rules = vec![rule("name IS NOT NULL OR kind = 'oak'"), rule("no_such_field IS NOT NULL")]; + l.design.rules.push(AttributeRule { kind: RuleKind::Calculation, ..rule("kind IS NOT NULL") }); + assert!(required(&l).is_empty()); + } + + #[test] + fn contingent_values_narrow_a_field_to_what_fits_the_others_chosen() { + let mut l = layer(); + let text = |s: &str| Value::Text(s.into()); + l.design.contingent = vec![ContingentSet { + name: "kind and size".into(), + fields: vec!["kind".into(), "size".into()], + combos: vec![vec![text("oak"), text("big")], vec![text("oak"), text("small")], vec![text("pine"), text("tall")]], + }]; + let mut values = BTreeMap::new(); + // Nothing chosen: every value the set has for the field; a field in no set is open. + assert_eq!(contingent(&l, "size", &values), Some(vec!["big".into(), "small".into(), "tall".into()])); + assert_eq!(contingent(&l, "name", &values), None); + values.insert("kind".to_string(), "oak".to_string()); + assert_eq!(contingent(&l, "size", &values), Some(vec!["big".into(), "small".into()])); + // A field's own value doesn't narrow it. + values.insert("size".to_string(), "big".to_string()); + assert_eq!(contingent(&l, "size", &values), Some(vec!["big".into(), "small".into()])); + assert_eq!(contingent(&l, "kind", &values), Some(vec!["oak".into()])); + // Nothing fits: no value is left. + values.insert("kind".to_string(), "birch".to_string()); + assert_eq!(contingent(&l, "size", &values), Some(vec![])); + // A combination that fits and leaves the field empty lets it take anything. + l.design.contingent[0].combos.push(vec![text("birch"), Value::Null]); + assert_eq!(contingent(&l, "size", &values), None); + // Yes and no are held as the chips hold them. + l.design.contingent.push(ContingentSet { + name: "surveyed".into(), + fields: vec!["name".into(), "surveyed".into()], + combos: vec![vec![text("Camp"), Value::Bool(true)]], + }); + assert_eq!(contingent(&l, "surveyed", &BTreeMap::new()), Some(vec!["true".into()])); + } + + #[test] + fn a_day_tapped_sets_the_date_and_keeps_a_date_times_time() { + let day = Date::from_ymd(2026, 3, 5).unwrap(); + assert_eq!(with_day("", day, FieldType::Date), "2026-03-05"); + assert_eq!(with_day("2025-01-01T08:30:00", day, FieldType::Date), "2026-03-05"); + assert_eq!(with_day("2025-01-01T08:30:00Z", day, FieldType::DateTime), "2026-03-05T08:30:00Z"); + assert_eq!(with_day("2025-01-01", day, FieldType::DateTime), "2026-03-05"); + assert_eq!(with_day("soon", day, FieldType::DateTime), "2026-03-05"); + assert_eq!(day_of("2025-01-01T08:30:00Z"), Date::from_ymd(2025, 1, 1)); + assert_eq!(day_of("soon"), None); + // Months step across years, and stay in years 1 to 9999. + assert_eq!(step((2026, 1), -1), (2025, 12)); + assert_eq!(step((2026, 12), 1), (2027, 1)); + assert_eq!(step((1, 1), -1), (1, 1)); + assert_eq!(step((9999, 12), 1), (9999, 12)); + assert!(today().is_some()); + assert!(now().is_some_and(|t| t.ends_with('Z') && DateTime::parse(&t).is_some())); + } +} diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index a4b6ee67ff..5c31fd355e 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -11,7 +11,10 @@ //! lists, ranges and feature templates) and the More sheet (full extent, project, undo, the //! desktop interface, the device's position). Where a shell reports the device's position //! (`RustGisApp::position`), it is drawn on the map and the capture cross can be put on it. -//! Not yet: editing a shape's vertices, snapping, and text input that suits a soft keyboard. +//! The form marks the fields the layer's constraint rules require, narrows a field to the values +//! its contingent value sets leave it, has a calendar for dates, and keeps the field being typed +//! in above the soft keyboard (see [`form`]). +//! Not yet: editing a shape's vertices and snapping. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use egui::{Align, Color32, CornerRadius, Layout, Rect, RichText, Sense, Stroke, Ui, Vec2}; @@ -19,12 +22,17 @@ use rustgis_ui_egui::theme::Tokens; use rustgis_ui_egui::{RustGisApp, icons, tl}; use serde_json::{Value, json}; +mod form; + /// The smallest side of anything a finger taps, in points (Android's guidance is 48). pub const TARGET: f32 = 48.0; /// The bar's height: an icon over its label. const BAR: f32 = 64.0; /// The most of the window's height a sheet takes, so the map stays in view above it. const SHEET_SHARE: f32 = 0.55; +/// The most a sheet takes while the soft keyboard is wanted: what is typed in matters more than +/// the map then, and the keyboard has taken much of the window. +const TYPING_SHARE: f32 = 0.9; /// The room above and below a sheet's rows. const SHEET_MARGIN: f32 = 4.0; /// The More sheet's rows with the position hidden. @@ -78,7 +86,8 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { }; let spacing = ui.spacing().item_spacing.y; let wanted = (rows + 1) as f32 * (TARGET + spacing) + 2.0 * SHEET_MARGIN; - let height = wanted.min(ui.available_height() * SHEET_SHARE); + let share = if ctx.egui_wants_keyboard_input() { TYPING_SHARE } else { SHEET_SHARE }; + let height = wanted.min(ui.available_height() * share); let margin = egui::Margin::symmetric(8, SHEET_MARGIN as i8); egui::Panel::bottom("touch_sheet").resizable(false).exact_size(height).frame(frame.inner_margin(margin)).show( ui, @@ -310,6 +319,11 @@ struct Form { template: Option, /// The vertices of the line or polygon being drawn, as longitude and latitude, in order. vertices: Vec<(f64, f64)>, + /// The date field whose calendar is open, by name, and the month it shows. + calendar: Option<(String, form::Month)>, + /// The height of the window the sheet was last drawn in: when it changes (the soft keyboard + /// came or went), the field being typed in is scrolled back into view. + window: f32, } impl Form { @@ -321,6 +335,7 @@ impl Form { self.values.clear(); self.vertices.clear(); self.template = None; + self.calendar = None; self.shown = Some(instance); } self @@ -383,10 +398,13 @@ fn capture_layer(app: &RustGisApp, form: &Form) -> Option { /// The Capture sheet's rows, for its height: its layers, its fields, where the cross is, and /// its buttons (two rows of them for a line or polygon). fn capture_rows(app: &RustGisApp, ctx: &egui::Context) -> usize { - let Some(target) = capture_layer(app, &form(ctx)) else { return 2 }; + let state = form(ctx); + let Some(target) = capture_layer(app, &state) else { return 2 }; let layer = app.session.map().layer(target.id); - let fields = layer.map_or(0, |l| l.dataset.fields.len() + usize::from(!l.design.templates.is_empty())); - fields + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) + let fields = layer + .map_or(0, |l| l.dataset.fields.len() + usize::from(!l.design.templates.is_empty()) + usize::from(!form::required(l).is_empty())); + let calendar = if state.calendar.is_some() { form::CALENDAR_ROWS } else { 0 }; + fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) } /// A value typed for a field, as the command takes it: a number for a field of numbers, a truth @@ -482,6 +500,18 @@ fn add_feature(app: &mut RustGisApp, id: u32, form: &Form, geometry: Value) -> b ); return false; } + // A field a rule requires, left empty and not filled by the template or the subtype chosen, + // is named here: the rule's own refusal would only quote its expression. + let empty: Vec = form::required(layer) + .into_iter() + .filter(|name| !attributes.contains_key(name) && !defaulted(layer, form, name)) + .map(|name| layer.dataset.fields.iter().find(|f| f.name == name).map_or(name.clone(), |f| f.display().to_string())) + .collect(); + if !empty.is_empty() { + let fields = empty.join(", "); + app.session.notify(rustgis_ui_egui::i18n::fmt("Nothing was added. Fill in: {fields}.", &[("fields", &fields)]), true); + return false; + } if !app.session.map().editing.settings.enabled { if app.run_by_user("edit.enable", json!({"on": true})).is_err() { return false; @@ -509,6 +539,20 @@ fn add_feature(app: &mut RustGisApp, id: u32, form: &Form, geometry: Value) -> b true } +/// Whether the field `name` of a new feature takes a value from what the form chose: the default +/// of the feature template chosen, or of the subtype its subtype field holds. +fn defaulted(layer: &rustgis_ui_egui::rustgis_engine::map::Layer, form: &Form, name: &str) -> bool { + let has = |defaults: &[(String, rustgis_ui_egui::rustgis_engine::data::Value)]| { + defaults.iter().any(|(field, value)| field.eq_ignore_ascii_case(name) && !value.is_null()) + }; + let template = form.template.as_ref().and_then(|t| layer.design.templates.iter().find(|x| &x.name == t)); + let subtype = layer.design.subtypes.as_ref().and_then(|s| { + let code = form.values.iter().find(|(field, _)| field.eq_ignore_ascii_case(&s.field))?.1.trim().parse::().ok()?; + s.subtypes.iter().find(|x| x.code == code) + }); + template.is_some_and(|t| has(&t.defaults)) || subtype.is_some_and(|s| has(&s.defaults)) +} + /// Adds a point to layer `id` where the middle of the map is, with what the form holds. A cross /// on no place of the map's projection adds none, and says so. fn add_point(app: &mut RustGisApp, id: u32, form: &Form) -> bool { @@ -553,6 +597,16 @@ fn choices( .then(|| vec![("true".to_string(), tl!("Yes").to_string()), ("false".to_string(), tl!("No").to_string())]) } +/// A coded domain's codes with their descriptions, as (what is stored, what is shown); none for a +/// range. +fn described(domain: &rustgis_ui_egui::rustgis_engine::map::design::Domain) -> Vec<(String, String)> { + use rustgis_ui_egui::rustgis_engine::map::design::DomainKind; + match &domain.kind { + DomainKind::Coded(codes) => codes.iter().map(|(code, says)| (form::stored(code), says.clone())).collect(), + DomainKind::Range { .. } => Vec::new(), + } +} + /// The limits of a field's range domain, when it has one. fn range_of(layer: &rustgis_ui_egui::rustgis_engine::map::Layer, field: &str) -> Option<(f64, f64)> { use rustgis_ui_egui::rustgis_engine::map::design::DomainKind; @@ -716,15 +770,25 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); }); // Read first: the rows change the form, not the layer. - let (fields, templates, lists): (Vec<_>, Vec, Vec>>) = match app.session.map().layer(target.id) - { + let layer = app.session.map().layer(target.id); + let (fields, templates, lists, required): (Vec<_>, Vec, Vec>>, Vec) = match layer { Some(l) => ( l.dataset.fields.clone(), l.design.templates.iter().map(|template| template.name.clone()).collect(), l.dataset.fields.iter().map(|f| choices(l, f)).collect(), + form::required(l), ), None => Default::default(), }; + // What the contingent value sets leave each field, given what the others hold now. + let left: Vec>> = + fields.iter().map(|f| layer.and_then(|l| form::contingent(l, &f.name, &state.values))).collect(); + let ranges: Vec> = fields.iter().map(|f| layer.and_then(|l| range_of(l, &f.name))).collect(); + let described: Vec>> = + fields.iter().map(|f| layer.and_then(|l| l.design.domain(&f.name)).map(described)).collect(); + if !required.is_empty() { + ui.label(RichText::new(tl!("Fields marked * need a value.")).size(13.0).color(t.text_dim)); + } // The layer's feature templates: one fills in its defaults for what the form leaves empty. if !templates.is_empty() { ui.horizontal(|ui| { @@ -739,19 +803,47 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } }); } - for (field, list) in fields.iter().zip(lists) { + // The soft keyboard came or went: the field being typed in is brought back into view. + let window = ctx.content_rect().height(); + let resized = (window - state.window).abs() > 0.5; + state.window = window; + for (i, (field, list)) in fields.iter().zip(lists).enumerate() { use rustgis_ui_egui::rustgis_engine::data::FieldType; - let label = field.alias.clone().filter(|a| !a.trim().is_empty()).unwrap_or_else(|| field.name.clone()); + let name = field.alias.clone().filter(|a| !a.trim().is_empty()).unwrap_or_else(|| field.name.clone()); + let needed = required.contains(&field.name); + let label = if needed { format!("{name} *") } else { name }; + let left = left.get(i).cloned().flatten(); + // A list narrowed by the contingent values: what the domain lists and the sets leave, + // or, with no list of its own, the values the sets leave. The value chosen stays, + // marked, even when the others no longer fit it, so the conflict shows. + let list = match (list, left.as_ref()) { + (Some(list), Some(left)) => Some(list.into_iter().filter(|(stored, _)| left.contains(stored)).collect()), + (None, Some(left)) => { + let said = described.get(i).cloned().flatten().unwrap_or_default(); + Some( + left.iter().map(|v| (v.clone(), said.iter().find(|(c, _)| c == v).map_or(v.clone(), |(_, d)| d.clone()))).collect(), + ) + } + (list, None) => list, + }; + let dated = matches!(field.ty, FieldType::Date | FieldType::DateTime); ui.horizontal(|ui| { ui.set_min_height(TARGET); - ui.add_sized([110.0, TARGET], egui::Label::new(RichText::new(&label).size(14.0).color(t.text_dim)).truncate()); + let ink = if needed { t.text } else { t.text_dim }; + ui.add_sized([110.0, TARGET], egui::Label::new(RichText::new(&label).size(14.0).color(ink)).truncate()); let value = state.values.entry(field.name.clone()).or_default(); - if let Some(list) = list { - // A list of values: one is tapped, and tapped again to leave the field empty. - chips(ui, t, ("touch_capture_values", &field.name), &list, value); + if let Some(mut list) = list { + if !value.is_empty() && !list.iter().any(|(stored, _)| stored == value) { + list.insert(0, (value.clone(), value.clone())); + } + if list.is_empty() { + ui.label(RichText::new(tl!("No value fits the others chosen.")).size(13.0).color(t.red)); + } else { + // A list of values: one is tapped, and tapped again to leave the field empty. + chips(ui, t, ("touch_capture_values", &field.name), &list, value); + } } else { - let range = app.session.map().layer(target.id).and_then(|l| range_of(l, &field.name)); - let hint = match (field.ty, range) { + let hint = match (field.ty, ranges.get(i).copied().flatten()) { (_, Some((min, max))) => rustgis_ui_egui::i18n::fmt( "a number from {min} to {max}", &[("min", &min.to_string()), ("max", &max.to_string())], @@ -765,9 +857,44 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .hint_text(hint) .font(egui::FontId::proportional(15.0)) .margin(egui::Margin::symmetric(8, 10)); - ui.add_sized([ui.available_width(), TARGET - 6.0], edit); + // A date field keeps room for the button that opens its calendar. + let room = if dated { ui.available_width() - TARGET - ui.spacing().item_spacing.x } else { ui.available_width() }; + let typed = ui.add_sized([room.max(TARGET), TARGET - 6.0], edit); + if typed.gained_focus() || (typed.has_focus() && resized) { + typed.scroll_to_me(Some(Align::Center)); + } + if dated { + let open = state.calendar.as_ref().is_some_and(|(name, _)| name == &field.name); + let hint = if open { tl!("Close the calendar") } else { tl!("Choose a date") }; + if toggle_button(ui, t, "calendar", hint, true) { + state.calendar = if open { + None + } else { + let day = form::day_of(value).or_else(form::today); + let month = day.map_or((2026, 1), |d| { + let (y, m, _) = d.ymd(); + (y, m) + }); + Some((field.name.clone(), month)) + }; + } + } } }); + // The calendar, under its field, while it is open. + if let Some((name, month)) = state.calendar.as_mut().filter(|(name, _)| name == &field.name) { + let name = name.clone(); + let value = state.values.entry(name).or_default(); + if field.ty == FieldType::DateTime + && let Some(now) = form::now() + && action(ui, t, tl!("Now"), ui.available_width(), false, true) + { + *value = now; + } + if form::calendar(ui, t, month, value, field.ty) { + state.calendar = None; + } + } } }); // The layer is kept only when a chip chose it: until then the sheet follows the active layer. @@ -1147,6 +1274,42 @@ mod tests { } } + #[test] + fn a_required_field_left_empty_is_named_and_a_default_fills_it() { + use rustgis_ui_egui::rustgis_engine::data::FieldType; + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + let cities = target(&mut app, GeometryType::Point); + let text = + app.session.map().layer(cities.id).unwrap().dataset.fields.iter().find(|f| f.ty == FieldType::Text).unwrap().name.clone(); + let rule = json!({"layer": cities.id, "name": "named", "kind": "constraint", "expression": format!("{text} IS NOT NULL")}); + run(&mut app, "data.attributeRule", rule); + assert_eq!(form::required(app.session.map().layer(cities.id).unwrap()), std::slice::from_ref(&text)); + // Empty: nothing is added, and the field is named. + let before = count(&app, cities.id); + let mark = app.session.notice_mark(); + assert!(!add_point(&mut app, cities.id, &Form::default())); + assert_eq!(count(&app, cities.id), before); + let said: Vec<_> = app.session.notices_since(mark).iter().filter(|n| n.error).map(|n| n.text.clone()).collect(); + assert!(said.len() == 1 && said[0].contains(&text), "{said:?}"); + // Filled, or filled by the template chosen: added. + let mut state = Form::default(); + state.values.insert(text.clone(), "Camp".into()); + assert!(add_point(&mut app, cities.id, &state)); + run(&mut app, "edit.template", json!({"layer": cities.id, "name": "Camp", "defaults": {text.clone(): "Camp"}})); + assert!(add_point(&mut app, cities.id, &Form { template: Some("Camp".into()), ..Form::default() })); + assert_eq!(count(&app, cities.id), before + 2); + // The sheet draws the marked field, a contingent set's chips and an open calendar. + let number = + app.session.map().layer(cities.id).unwrap().dataset.fields.iter().find(|f| f.ty != FieldType::Text).unwrap().name.clone(); + let set = json!({"layer": cities.id, "name": "pair", "fields": [text, number], "combos": [["Camp", 1], ["Town", 2]]}); + run(&mut app, "data.contingentValues", set); + assert_eq!(form::contingent(app.session.map().layer(cities.id).unwrap(), &text, &state.values).map(|v| v.len()), Some(2)); + set_form(&ctx, Form { shown: Some(cities.instance), calendar: Some((text, (2026, 3))), ..Form::default() }); + frame(&mut app, &ctx, Sheet::Capture); + assert!(form(&ctx).calendar.is_some()); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); From 08798c8572372b44132216c25c8243d3018280d1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 01:19:20 -0500 Subject: [PATCH 02/18] feat(mobile): edit a shape's vertices by touch, and snap the capture cross (#1902) --- apps/rustgis-mobile/README.md | 22 ++- crates/ui-touch/src/edit.rs | 182 +++++++++++++++++++++++ crates/ui-touch/src/lib.rs | 268 ++++++++++++++++++++++++++++++++-- 3 files changed, 455 insertions(+), 17 deletions(-) create mode 100644 crates/ui-touch/src/edit.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 4190565ccb..46c7dc3de7 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -3,9 +3,8 @@ RustGIS on Android ([#1902](https://github.com/opengeos/RustGIS/issues/1902)). It runs the desktop front end (`rustgis-ui-egui`) in a `NativeActivity`, with the system's file picker for opening and saving, and the touch interface (`rustgis-ui-touch`) around its map, which can capture points, -lines and polygons with their attributes and show where the device is. It is not a field app yet: -a captured shape can't be edited by touch afterwards, positions aren't averaged or logged as a -track, and there are no photos. +lines and polygons with their attributes, edit their shapes, snap, and show where the device is. +It is not a field app yet: positions aren't averaged or logged as a track, and there are no photos. ## Build @@ -112,8 +111,21 @@ sheet and at the top of the Capture sheet, moves the map so the capture cross is or a vertex added then is at the device's position. **Hide My Position** stops asking, which spares the battery. -What it doesn't do yet: moving or deleting a vertex once the feature is added, snapping, and a -new layer to capture into. +**Edit**, beside **Add** at the top of the Capture sheet, changes the shapes already on the +map, the same way: the map is moved under the cross. **Pick Feature at Cross** picks the layer's +feature drawn on top under it (within half a finger) and draws its vertices. For a line or polygon, +**Pick Vertex at Cross** picks the vertex nearest the cross, and then **Move Here** moves it to +where the cross is next, **Add After** puts a new vertex there after it, and **Delete Vertex** +removes it (a line keeps two, a ring three). For a point, **Move Point Here** moves it. **Delete +Feature** deletes it (only it: the other layers' selections are cleared first), and **Done** lets +it go. Each change is one edit, undone by Undo in the More sheet. + +**Snap** turns the map's snapping on and off (its settings are the desktop's: Edit › Snapping). +With it on, the cross's place snaps to a vertex, a line's end or an edge in reach, for adding and +editing alike: a green ring marks where, and the sheet says what it snapped to. A vertex being +moved doesn't snap to itself or its own edges. + +What it doesn't do yet: editing an existing feature's attributes, and a new layer to capture into. The interface keeps out of the room the system's bars take: the activity's Java half reports the insets, and the bars' icons are drawn dark over a light theme's ground and light over a dark diff --git a/crates/ui-touch/src/edit.rs b/crates/ui-touch/src/edit.rs new file mode 100644 index 0000000000..29ff575aad --- /dev/null +++ b/crates/ui-touch/src/edit.rs @@ -0,0 +1,182 @@ +//! Editing a shape already on the map by touch, and snapping: the Capture sheet's Edit mode. +//! +//! As for capturing, the map is moved under the cross, which a finger does more exactly than a +//! tap: the feature under the cross is picked, then a vertex near it, and that vertex is moved to +//! where the cross is next, deleted, or followed by a new one there. With snapping on, the cross's +//! place is snapped to the map's features first (the map's own snapping settings), for capturing +//! and editing alike. + +use egui::{Color32, Stroke}; +use rustgis_ui_egui::rustgis_engine::data::{Coord, Geometry, GeometryType, VertexId}; +use rustgis_ui_egui::theme::Tokens; +use rustgis_ui_egui::{RustGisApp, i18n, tl}; +use serde_json::json; + +/// How far from the cross, in points, a vertex or a feature is still under it: half a finger. +pub(crate) const REACH: f32 = super::TARGET / 2.0; + +/// The feature being edited: by its id, which stays the same while rows come and go, and the +/// vertex picked on it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Editing { + pub feature: u64, + pub vertex: Option, +} + +/// The place the cross snapped to, as longitude and latitude, and what it snapped to (`vertex`, +/// `edge`, `end`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Snapped { + pub lon: f64, + pub lat: f64, + pub kind: &'static str, +} + +/// The row of layer `id` holding the feature `feature`, if it is still there. +pub(crate) fn row_of(app: &RustGisApp, id: u32, feature: u64) -> Option { + app.session.map().layer(id)?.dataset.features.iter().position(|f| f.id == feature) +} + +/// The shape of the feature in row `row` of layer `id`. +pub(crate) fn shape(app: &RustGisApp, id: u32, row: usize) -> Option { + app.session.map().layer(id)?.dataset.features.get(row)?.geometry.clone() +} + +/// The feature of layer `id` drawn on top under the cross (within [`REACH`]), by its id. +pub(crate) fn feature_at_cross(app: &mut RustGisApp, id: u32) -> Option { + let map = app.session.map(); + let (at, tolerance) = (map.camera.center, f64::from(REACH) * map.camera.res); + let scale = app.session.scale(); + let (layer, row) = app.session.map_mut().hit(at, tolerance, scale, |l| l.id == id)?; + app.session.map().layer(layer)?.dataset.features.get(row).map(|f| f.id) +} + +/// The vertex of `shape` nearest the screen point `cross`, within [`REACH`]. +pub(crate) fn vertex_near(app: &RustGisApp, shape: &Geometry, cross: egui::Pos2) -> Option { + shape + .vertices() + .into_iter() + .filter_map(|(v, c)| app.lonlat_to_screen(c.x, c.y).map(|p| (v, p.distance(cross)))) + .filter(|(_, d)| *d <= REACH) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(v, _)| v) +} + +/// Where the cross's place snaps to with the map's snapping on: `None` with it off, or with +/// nothing in reach. A vertex being moved (`moving`: layer, row and vertex) doesn't snap to itself +/// or the edges it ends, but does to the rest of its shape. +pub(crate) fn snap(app: &mut RustGisApp, at: (f64, f64), moving: Option<(u32, usize, VertexId)>) -> Option { + use rustgis_ui_egui::rustgis_engine::cmd::design::{snap_at, snap_vertex_except}; + if !app.session.map().editing.snapping.enabled { + return None; + } + let c = Coord::new(at.0, at.1); + let (to, kind) = match moving { + Some(skip) => snap_vertex_except(&mut app.session, c, Some(skip)), + None => snap_at(&mut app.session, c), + }?; + Some(Snapped { lon: to.x, lat: to.y, kind }) +} + +/// What the cross snapped to, said for the sheet. +pub(crate) fn snapped_to(kind: &str) -> &'static str { + match kind { + "vertex" => tl!("snapped to a vertex"), + "end" => tl!("snapped to a line's end"), + _ => tl!("snapped to an edge"), + } +} + +/// Turns editing on for the map when it is off, and says so. Says whether it is on. +pub(crate) fn ensure_editing(app: &mut RustGisApp) -> bool { + if app.session.map().editing.settings.enabled { + return true; + } + if app.run_by_user("edit.enable", json!({"on": true})).is_err() { + return false; + } + app.session.notify(tl!("Editing was turned on for this map."), false); + true +} + +/// Runs `edit.vertex` on the vertex `v` of row `row` of layer `id`: `move` it to `at`, `insert` +/// one at `at` after it, or `delete` it. The vertex picked afterwards: the one moved, the one +/// inserted, or none once deleted. `None` when it was refused (the front end says why). +pub(crate) fn vertex( + app: &mut RustGisApp, + id: u32, + row: usize, + v: VertexId, + action: &str, + at: Option<(f64, f64)>, +) -> Option> { + if !ensure_editing(app) { + return None; + } + let mut params = json!({"layer": id, "row": row, "part": v.part, "ring": v.ring, "index": v.index, "action": action}); + if let Some((lon, lat)) = at { + params["lon"] = json!(lon); + params["lat"] = json!(lat); + } + let done = app.run_by_user("edit.vertex", params).ok()?; + if action == "delete" { + return Some(None); + } + let read = |k: &str| done.get(k).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); + Some(match (read("part"), read("ring"), read("index")) { + (Some(part), Some(ring), Some(index)) => Some(VertexId::new(part, ring, index)), + _ => Some(v), + }) +} + +/// Deletes the feature in row `row` of layer `id`, as one edit that undoes. Says whether it was. +pub(crate) fn delete_feature(app: &mut RustGisApp, id: u32, row: usize) -> bool { + if !ensure_editing(app) { + return false; + } + // Only this feature: Delete takes every layer's selection. + app.run_by_user("select.clear", serde_json::Value::Null).is_ok() + && app.run_by_user("select.rows", json!({"layer": id, "rows": [row]})).is_ok() + && app.run_by_user("edit.delete", serde_json::Value::Null).is_ok() +} + +/// Draws the feature being edited over the map: every vertex, the picked one larger and filled. +pub(crate) fn draw(app: &RustGisApp, painter: &egui::Painter, shape: &Geometry, picked: Option, t: &Tokens) { + if matches!(shape.kind(), GeometryType::Polyline | GeometryType::Polygon) { + for (_, a, b) in shape.edges() { + if let (Some(a), Some(b)) = (app.lonlat_to_screen(a.x, a.y), app.lonlat_to_screen(b.x, b.y)) { + painter.line_segment([a, b], Stroke::new(2.0, t.accent)); + } + } + } + for (v, c) in shape.vertices() { + let Some(at) = app.lonlat_to_screen(c.x, c.y) else { continue }; + if Some(v) == picked { + painter.circle(at, 9.0, t.accent, Stroke::new(2.0, Color32::WHITE)); + } else { + painter.circle(at, 5.5, Color32::WHITE, Stroke::new(2.0, t.accent)); + } + } +} + +/// Draws where the cross snapped to: a ring there, joined to the cross. +pub(crate) fn draw_snap(app: &RustGisApp, painter: &egui::Painter, snapped: Snapped, cross: egui::Pos2, t: &Tokens) { + let Some(at) = app.lonlat_to_screen(snapped.lon, snapped.lat) else { return }; + painter.line_segment([cross, at], Stroke::new(1.0, t.accent)); + painter.circle_stroke(at, 10.0, Stroke::new(3.0, Color32::WHITE)); + painter.circle_stroke(at, 10.0, Stroke::new(2.0, t.green)); +} + +/// The text the sheet shows for the feature being edited. +pub(crate) fn status(kind: GeometryType, shape: &Geometry, picked: Option) -> String { + if kind == GeometryType::Point { + return tl!("Move the map to where the point goes, then Move Point Here.").to_string(); + } + match picked.and_then(|v| shape.vertices().iter().position(|(id, _)| *id == v)) { + Some(n) => i18n::fmt( + "Vertex {n} of {all} picked: move the map to where it goes, then Move Here. Add After puts a new vertex at the cross after it.", + &[("n", &(n + 1).to_string()), ("all", &shape.vertices().len().to_string())], + ), + None => tl!("Put the cross on a vertex and pick it.").to_string(), + } +} diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 5c31fd355e..f07fbbe4c2 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -14,7 +14,8 @@ //! The form marks the fields the layer's constraint rules require, narrows a field to the values //! its contingent value sets leave it, has a calendar for dates, and keeps the field being typed //! in above the soft keyboard (see [`form`]). -//! Not yet: editing a shape's vertices and snapping. +//! Its Edit mode picks a feature under the cross and moves, inserts or deletes its vertices, or +//! deletes it; with Snap on, the cross's place snaps to the map's features (see [`edit`]). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use egui::{Align, Color32, CornerRadius, Layout, Rect, RichText, Sense, Stroke, Ui, Vec2}; @@ -22,6 +23,7 @@ use rustgis_ui_egui::theme::Tokens; use rustgis_ui_egui::{RustGisApp, icons, tl}; use serde_json::{Value, json}; +mod edit; mod form; /// The smallest side of anything a finger taps, in points (Android's guidance is 48). @@ -110,7 +112,19 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { if shown == Sheet::Capture && let Some((map, _)) = app.map.view_rect { - sketch(app, &ui.painter().with_clip_rect(map), map.center(), &t, &ctx); + let painter = ui.painter().with_clip_rect(map); + sketch(app, &painter, map.center(), &t, &ctx); + // The feature being edited, and where the cross snapped to. + let state = form(&ctx); + if state.edit_mode + && let (Some(target), Some(editing)) = (capture_layer(app, &state), state.editing) + && let Some(shape) = edit::row_of(app, target.id, editing.feature).and_then(|row| edit::shape(app, target.id, row)) + { + edit::draw(app, &painter, &shape, editing.vertex, &t); + } + if let Some(snapped) = state.snap { + edit::draw_snap(app, &painter, snapped, map.center(), &t); + } cross(ui.painter(), map.center(), &t); } }); @@ -321,6 +335,12 @@ struct Form { vertices: Vec<(f64, f64)>, /// The date field whose calendar is open, by name, and the month it shows. calendar: Option<(String, form::Month)>, + /// The sheet edits the shapes on the map instead of adding new ones. + edit_mode: bool, + /// The feature being edited, in Edit mode. + editing: Option, + /// Where the cross's place snapped to on the last frame, with snapping on. + snap: Option, /// The height of the window the sheet was last drawn in: when it changes (the soft keyboard /// came or went), the field being typed in is scrolled back into view. window: f32, @@ -336,6 +356,8 @@ impl Form { self.vertices.clear(); self.template = None; self.calendar = None; + self.editing = None; + self.snap = None; self.shown = Some(instance); } self @@ -364,7 +386,7 @@ fn set_form(ctx: &egui::Context, form: Form) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique("touch_capture"), form)); } -use rustgis_ui_egui::rustgis_engine::data::GeometryType; +use rustgis_ui_egui::rustgis_engine::data::{GeometryType, VertexId}; /// A layer a feature can be captured into. #[derive(Clone)] @@ -403,8 +425,17 @@ fn capture_rows(app: &RustGisApp, ctx: &egui::Context) -> usize { let layer = app.session.map().layer(target.id); let fields = layer .map_or(0, |l| l.dataset.fields.len() + usize::from(!l.design.templates.is_empty()) + usize::from(!form::required(l).is_empty())); + // The mode row, then in Edit mode its words, its buttons and the layers; else the form. + if state.edit_mode { + let buttons = match (state.editing, target.kind) { + (None, _) => 1, + (Some(_), GeometryType::Point) => 2, + (Some(_), _) => 3, + }; + return 4 + buttons + usize::from(app.locate); + } let calendar = if state.calendar.is_some() { form::CALENDAR_ROWS } else { 0 }; - fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) + 1 + fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) } /// A value typed for a field, as the command takes it: a number for a field of numbers, a truth @@ -553,10 +584,11 @@ fn defaulted(layer: &rustgis_ui_egui::rustgis_engine::map::Layer, form: &Form, n template.is_some_and(|t| has(&t.defaults)) || subtype.is_some_and(|s| has(&s.defaults)) } -/// Adds a point to layer `id` where the middle of the map is, with what the form holds. A cross -/// on no place of the map's projection adds none, and says so. +/// Adds a point to layer `id` where the middle of the map is (where it snapped to, with snapping +/// on), with what the form holds. A cross on no place of the map's projection adds none, and says +/// so. fn add_point(app: &mut RustGisApp, id: u32, form: &Form) -> bool { - let Some(at) = cross_place(app) else { + let Some(at) = form.snap.map(|s| (s.lon, s.lat)).or_else(|| cross_place(app)) else { app.session.notify(tl!("Nothing was added: the cross is off the map. Move the map under it."), true); return false; }; @@ -700,13 +732,25 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.session.notify(rustgis_ui_egui::i18n::fmt("The template {name} is no longer on this layer.", &[("name", gone)]), false); } let fresh = stale.is_none(); + // The feature being edited, while it is still there (an undo may have taken it away). + let picked = state.editing.and_then(|e| edit::row_of(app, target.id, e.feature).map(|row| (row, e))); + if picked.is_none() { + state.editing = None; + } + // The cross's place, snapped with snapping on: a vertex being moved doesn't snap to itself. + let moving = picked.filter(|_| state.edit_mode).and_then(|(row, e)| e.vertex.map(|v| (target.id, row, v))); + state.snap = cross_place(app).and_then(|at| edit::snap(app, at, moving)); + let cross = state.snap.map(|s| (s.lon, s.lat)).or_else(|| cross_place(app)); // The buttons stay in reach above the fields, however many the layer has. - let cross = cross_place(app); - let place = match cross { - Some((lon, lat)) => { + let place = match (cross, state.snap) { + (Some((lon, lat)), Some(snapped)) => rustgis_ui_egui::i18n::fmt( + "At the cross, {snapped}: {lon}, {lat}", + &[("snapped", edit::snapped_to(snapped.kind)), ("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))], + ), + (Some((lon, lat)), None) => { rustgis_ui_egui::i18n::fmt("At the cross: {lon}, {lat}", &[("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))]) } - None => tl!("The cross is off the map: move the map under it.").to_string(), + (None, _) => tl!("The cross is off the map: move the map under it.").to_string(), }; ui.label(RichText::new(place).size(13.0).color(t.text_dim)); let width = ui.available_width(); @@ -714,7 +758,27 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if app.locate && action(ui, t, tl!("Go to My Position"), width, false, app.position.is_some()) { go_to_position(app); } - if target.kind == GeometryType::Point { + // Add or Edit, and Snap. + ui.horizontal(|ui| { + ui.set_min_height(TARGET); + let gap = ui.spacing().item_spacing.x; + let third = (width - 2.0 * gap) / 3.0; + if toggle_chip(ui, t, tl!("Add"), third, !state.edit_mode) { + state.edit_mode = false; + state.editing = None; + } + if toggle_chip(ui, t, tl!("Edit"), third, state.edit_mode) { + state.edit_mode = true; + state.vertices.clear(); + } + let snapping = app.session.map().editing.snapping.enabled; + if toggle_chip(ui, t, tl!("Snap"), third, snapping) { + run(app, "edit.snapping", json!({"on": !snapping})); + } + }); + if state.edit_mode { + edit_sheet(app, ui, t, &target, &mut state, picked, cross, width); + } else if target.kind == GeometryType::Point { if action(ui, t, tl!("Add Point Here"), width, true, true) && fresh && add_point(app, target.id, &state) { state.values.clear(); } @@ -753,6 +817,7 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } }); } + let edit_mode = state.edit_mode; egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| { // The layer: one chip for each layer that takes features, in a row that scrolls sideways. egui::ScrollArea::horizontal().id_salt("touch_capture_layers").show(ui, |ui| { @@ -769,6 +834,10 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } }); }); + // Edit mode changes shapes, not attributes: the form is for a new feature. + if edit_mode { + return; + } // Read first: the rows change the form, not the layer. let layer = app.session.map().layer(target.id); let (fields, templates, lists, required): (Vec<_>, Vec, Vec>>, Vec) = match layer { @@ -901,6 +970,94 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { set_form(&ctx, state); } +/// A chip a finger's height, `width` wide, marked while `on`. Says whether it was tapped. +fn toggle_chip(ui: &mut Ui, t: &Tokens, label: &str, width: f32, on: bool) -> bool { + let text = RichText::new(label).size(15.0).color(if on { t.accent_text } else { t.text }); + ui.add(egui::Button::new(text).fill(if on { t.checked } else { t.input }).min_size(Vec2::new(width, TARGET - 8.0))).clicked() +} + +/// The Capture sheet in Edit mode: pick the feature under the cross, then a vertex of it near the +/// cross, and move the vertex to where the cross is next, insert one there after it, or delete it; +/// or move a point, or delete the feature. `cross` is the cross's place, snapped with snapping on. +#[allow(clippy::too_many_arguments)] +fn edit_sheet( + app: &mut RustGisApp, + ui: &mut Ui, + t: &Tokens, + target: &Target, + state: &mut Form, + picked: Option<(usize, edit::Editing)>, + cross: Option<(f64, f64)>, + width: f32, +) { + let gap = ui.spacing().item_spacing.x; + let Some((row, editing)) = picked else { + let says = rustgis_ui_egui::i18n::fmt("Put the cross on a feature of {layer} and pick it.", &[("layer", &target.name)]); + ui.label(RichText::new(says).size(14.0).color(t.text)); + if action(ui, t, tl!("Pick Feature at Cross"), width, true, true) { + match edit::feature_at_cross(app, target.id) { + Some(feature) => state.editing = Some(edit::Editing { feature, vertex: None }), + None => app + .session + .notify(rustgis_ui_egui::i18n::fmt("No feature of {layer} is under the cross.", &[("layer", &target.name)]), true), + } + } + return; + }; + let Some(shape) = edit::shape(app, target.id, row) else { + state.editing = None; + return; + }; + ui.label(RichText::new(edit::status(target.kind, &shape, editing.vertex)).size(14.0).color(t.text)); + let off = || tl!("Nothing was changed: the cross is off the map. Move the map under it."); + if target.kind == GeometryType::Point { + if action(ui, t, tl!("Move Point Here"), width, true, true) { + match cross { + Some(at) => { + let first = VertexId::new(0, 0, 0); + let _ = edit::vertex(app, target.id, row, first, "move", Some(at)); + } + None => app.session.notify(off(), true), + } + } + } else { + let has = editing.vertex.is_some(); + if action(ui, t, tl!("Pick Vertex at Cross"), width, !has, true) { + let middle = app.map.view_rect.map(|(rect, _)| rect.center()); + match middle.and_then(|at| edit::vertex_near(app, &shape, at)) { + Some(v) => state.editing = Some(edit::Editing { vertex: Some(v), ..editing }), + None => app.session.notify(tl!("No vertex is near the cross. Move the map so the cross is on one."), true), + } + } + ui.horizontal(|ui| { + let third = (width - 2.0 * gap) / 3.0; + for (label, act, main) in + [(tl!("Move Here"), "move", true), (tl!("Add After"), "insert", false), (tl!("Delete Vertex"), "delete", false)] + { + if action(ui, t, label, third, main && has, has) + && let Some(v) = editing.vertex + { + let at = if act == "delete" { None } else { cross }; + if act != "delete" && at.is_none() { + app.session.notify(off(), true); + } else if let Some(next) = edit::vertex(app, target.id, row, v, act, at) { + state.editing = Some(edit::Editing { vertex: next, ..editing }); + } + } + } + }); + } + ui.horizontal(|ui| { + let half = (width - gap) / 2.0; + if action(ui, t, tl!("Delete Feature"), half, false, true) && edit::delete_feature(app, target.id, row) { + state.editing = None; + } + if action(ui, t, tl!("Done"), half, false, true) { + state.editing = None; + } + }); +} + /// The More sheet: what is done now and then, each a row as tall as a finger. fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { heading(ui, t, tl!("More")); @@ -1310,6 +1467,93 @@ mod tests { assert!(form(&ctx).calendar.is_some()); } + #[test] + fn a_feature_under_the_cross_is_picked_and_its_vertices_moved_inserted_and_deleted() { + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + let rivers = target(&mut app, GeometryType::Polyline); + let shape = app.session.map().layer(rivers.id).unwrap().dataset.features[0].geometry.clone().unwrap(); + let feature = app.session.map().layer(rivers.id).unwrap().dataset.features[0].id; + let (first, at) = shape.vertices()[1]; + // The cross on the river's second vertex, close in. + run(&mut app, "map.goToXY", json!({"lon": at.x, "lat": at.y, "scale": 50_000})); + frame(&mut app, &ctx, Sheet::Capture); + assert_eq!(edit::feature_at_cross(&mut app, rivers.id), Some(feature)); + let row = edit::row_of(&app, rivers.id, feature).unwrap(); + let middle = app.map.view_rect.unwrap().0.center(); + assert_eq!(edit::vertex_near(&app, &shape, middle), Some(first)); + let vertices = shape.vertices().len(); + // Moved, then a vertex inserted after it (and picked), then that one deleted. + let moved = (at.x + 0.001, at.y + 0.001); + assert_eq!(edit::vertex(&mut app, rivers.id, row, first, "move", Some(moved)), Some(Some(first))); + let now = edit::shape(&app, rivers.id, row).unwrap(); + assert_eq!(now.vertex(first).map(|c| (c.x, c.y)), Some(moved)); + let inserted = edit::vertex(&mut app, rivers.id, row, first, "insert", Some((at.x, at.y))).unwrap(); + assert_eq!(inserted, Some(VertexId::new(first.part, first.ring, first.index + 1))); + assert_eq!(edit::shape(&app, rivers.id, row).unwrap().vertices().len(), vertices + 1); + assert_eq!(edit::vertex(&mut app, rivers.id, row, inserted.unwrap(), "delete", None), Some(None)); + assert_eq!(edit::shape(&app, rivers.id, row).unwrap().vertices().len(), vertices); + // The sheet draws in Edit mode with the feature and its vertex picked. + set_form( + &ctx, + Form { + shown: Some(rivers.instance), + edit_mode: true, + editing: Some(edit::Editing { feature, vertex: Some(first) }), + ..Form::default() + }, + ); + frame(&mut app, &ctx, Sheet::Capture); + assert_eq!(form(&ctx).editing.map(|e| e.feature), Some(feature)); + // Deleted, only it: the sheet lets it go. + let before = count(&app, rivers.id); + // A selection on another layer is left alone. + let cities = app.session.map().layers.iter().find(|l| l.geometry_type() == GeometryType::Point).unwrap().id; + run(&mut app, "select.rows", json!({"layer": cities, "rows": [0]})); + let cities_before = count(&app, cities); + assert!(edit::delete_feature(&mut app, rivers.id, row)); + assert_eq!(count(&app, rivers.id), before - 1); + assert_eq!(count(&app, cities), cities_before); + assert_eq!(edit::row_of(&app, rivers.id, feature), None); + frame(&mut app, &ctx, Sheet::Capture); + assert_eq!(form(&ctx).editing, None); + // Undone: it comes back. + run(&mut app, "edit.undo", Value::Null); + assert_eq!(count(&app, rivers.id), before); + } + + #[test] + fn with_snapping_on_the_cross_snaps_to_a_feature_in_reach() { + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + let cities = target(&mut app, GeometryType::Point); + let at = match app.session.map().layer(cities.id).unwrap().dataset.features[0].geometry.clone().unwrap() { + rustgis_ui_egui::rustgis_engine::data::Geometry::Point(c) => c, + other => panic!("{other:?}"), + }; + run(&mut app, "map.goToXY", json!({"lon": at.x + 0.0005, "lat": at.y, "scale": 50_000})); + frame(&mut app, &ctx, Sheet::Capture); + let near = cross_place(&app).unwrap(); + // Off: no snapping. On: the city's place. + run(&mut app, "edit.snapping", json!({"on": false})); + assert_eq!(edit::snap(&mut app, near, None), None); + run(&mut app, "edit.snapping", json!({"on": true})); + let snapped = edit::snap(&mut app, near, None).unwrap(); + assert!((snapped.lon - at.x).abs() < 1e-9 && (snapped.lat - at.y).abs() < 1e-9, "{snapped:?}"); + // A point added then is where it snapped, and the sheet shows it snapped. + frame(&mut app, &ctx, Sheet::Capture); + let state = form(&ctx); + assert!(state.snap.is_some()); + assert!(add_point(&mut app, cities.id, &state)); + // There to within a round trip through the map's projection. + match app.session.map().layer(cities.id).unwrap().dataset.features.last().unwrap().geometry.clone() { + Some(rustgis_ui_egui::rustgis_engine::data::Geometry::Point(c)) => { + assert!((c.x - at.x).abs() < 1e-9 && (c.y - at.y).abs() < 1e-9) + } + other => panic!("{other:?}"), + } + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); From 6b2433235ca4427ca0c6b4766ed46e2e40cdb623 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 01:41:57 -0500 Subject: [PATCH 03/18] feat(mobile): average the device's positions, and record a track (#1902) --- apps/rustgis-mobile/README.md | 16 +- .../java/org/rustgis/mobile/MainActivity.java | 5 +- apps/rustgis-mobile/src/lib.rs | 2 +- crates/engine/src/platform.rs | 55 +++- crates/ui-egui/src/lib.rs | 22 ++ crates/ui-touch/src/lib.rs | 128 +++++++- crates/ui-touch/src/track.rs | 289 ++++++++++++++++++ 7 files changed, 490 insertions(+), 27 deletions(-) create mode 100644 crates/ui-touch/src/track.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 46c7dc3de7..2174003ab5 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -4,7 +4,8 @@ RustGIS on Android ([#1902](https://github.com/opengeos/RustGIS/issues/1902)). I front end (`rustgis-ui-egui`) in a `NativeActivity`, with the system's file picker for opening and saving, and the touch interface (`rustgis-ui-touch`) around its map, which can capture points, lines and polygons with their attributes, edit their shapes, snap, and show where the device is. -It is not a field app yet: positions aren't averaged or logged as a track, and there are no photos. +It averages positions and records tracks. It is not a field app yet: there are no photos, and a +track stops while the app is out of sight. ## Build @@ -111,6 +112,19 @@ sheet and at the top of the Capture sheet, moves the map so the capture cross is or a vertex added then is at the device's position. **Hide My Position** stops asking, which spares the battery. +**Average Position**, beside Go to My Position in the Capture sheet, averages the positions that +come while it runs: each weighted by how exact Android says it is (one over its accuracy squared), +and the sheet says how many and how far they lie from their average. **Use Average** puts the +cross there, for a point or a vertex more exact than one position. + +**Record a Track**, in the More sheet with the position shown, draws where the device goes as it +goes, with a bar over the buttons that counts its positions and has **Stop**. Stopping (or Hide My +Position) adds the track as one line to the map's **Tracks** layer, made when the map has none, +named for when it started, with its count and length in minutes. A position less exact than 50 m +is left out, and the notice says how many were. Every position Android reports reaches the track, +not only the last one each frame (`RustGisApp::fixes`). The track is kept in memory until it is +stopped: an app the system ends loses it. + **Edit**, beside **Add** at the top of the Capture sheet, changes the shapes already on the map, the same way: the map is moved under the cross. **Pick Feature at Cross** picks the layer's feature drawn on top under it (within half a finger) and draws its vertices. For a line or polygon, diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index dda148c34d..0ab46d86f9 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -21,7 +21,8 @@ * picked purpose name path a chosen file, copied to the app's storage * cancelled a picker closed without a choice * saved name a file written where the user chose - * position lon lat accuracy where the device is (accuracy in metres, or empty) + * position lon lat accuracy time where the device is (accuracy in metres, or empty; + * time in milliseconds since 1970) * stopped positioning ended without being asked to * failed text what went wrong, to show the user */ @@ -182,7 +183,7 @@ private void startLocating() { @Override public void onLocationChanged(android.location.Location fix) { add("position\t" + fix.getLongitude() + "\t" + fix.getLatitude() + "\t" - + (fix.hasAccuracy() ? Float.toString(fix.getAccuracy()) : "")); + + (fix.hasAccuracy() ? Float.toString(fix.getAccuracy()) : "") + "\t" + fix.getTime()); } @Override diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 443e295766..7452f1486b 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -159,7 +159,7 @@ mod android { Event::Picked { purpose, name, path } => self.waiting.push((purpose, name, path)), Event::Cancelled => {} Event::Saved { name } => self.app.session.notify(i18n::fmt("Saved {name}.", &[("name", &name)]), false), - Event::Position(fix) if self.locating => self.app.position = Some(fix), + Event::Position(fix) if self.locating => self.app.report_position(fix), // A fix that was on its way when positioning was turned off. Event::Position(_) => {} // Android ended positioning itself (its reason is a failure beside this): the diff --git a/crates/engine/src/platform.rs b/crates/engine/src/platform.rs index 6dbf5932d2..686954ee89 100644 --- a/crates/engine/src/platform.rs +++ b/crates/engine/src/platform.rs @@ -17,6 +17,8 @@ pub struct Fix { /// The radius the system gives the position to (about two times in three), in metres, when /// it says. pub accuracy: Option, + /// When the system found it, in milliseconds since 1970 (UTC), when it says. + pub time: Option, } /// What the system did since the front end last asked. @@ -50,7 +52,8 @@ pub enum Event { impl Event { /// Reads an event a shell passed as one line of tab-separated fields (`picked`, `cancelled`, /// `saved`, `position`, `stopped`, `failed`). A line that is none of these is a failure that quotes it: nothing a - /// shell reports is dropped. + /// shell reports is dropped. A position is `position`, longitude, latitude, accuracy (empty + /// when unknown) and, optionally, its time in milliseconds since 1970. pub fn parse(line: &str) -> Event { let fields: Vec<&str> = line.split('\t').collect(); match fields.as_slice() { @@ -61,19 +64,32 @@ impl Event { ["stopped"] => Event::Stopped, // A name is the user's own text and may hold a tab: the rest of the line is the name. ["saved", name @ ..] if !name.is_empty() => Event::Saved { name: name.join("\t") }, - ["position", lon, lat, accuracy] => match (lon.parse::(), lat.parse::()) { - // A place on the Earth, or it is no position: a failure that quotes the line. - (Ok(lon), Ok(lat)) if (-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat) => { - // No accuracy given is no accuracy; one given that isn't a distance is a line - // RustGIS doesn't know, not a position quietly taken without it. - match accuracy.parse::() { - _ if accuracy.is_empty() => Event::Position(Fix { lon, lat, accuracy: None }), - Ok(metres) if metres.is_finite() && metres >= 0.0 => Event::Position(Fix { lon, lat, accuracy: Some(metres) }), - _ => Event::Failed(format!("The system reported something RustGIS doesn't know: {line}")), + ["position", lon, lat, accuracy, rest @ ..] if rest.len() <= 1 => { + let unknown = || Event::Failed(format!("The system reported something RustGIS doesn't know: {line}")); + // A time given that isn't one is a line RustGIS doesn't know, as below. + let time = match rest.first() { + None => None, + Some(ms) => match ms.parse::() { + Ok(ms) if ms >= 0 => Some(ms), + _ => return unknown(), + }, + }; + match (lon.parse::(), lat.parse::()) { + // A place on the Earth, or it is no position: a failure that quotes the line. + (Ok(lon), Ok(lat)) if (-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat) => { + // No accuracy given is no accuracy; one given that isn't a distance is a + // line RustGIS doesn't know, not a position quietly taken without it. + match accuracy.parse::() { + _ if accuracy.is_empty() => Event::Position(Fix { lon, lat, accuracy: None, time }), + Ok(metres) if metres.is_finite() && metres >= 0.0 => { + Event::Position(Fix { lon, lat, accuracy: Some(metres), time }) + } + _ => unknown(), + } } + _ => unknown(), } - _ => Event::Failed(format!("The system reported something RustGIS doesn't know: {line}")), - }, + } ["failed", text @ ..] => Event::Failed(text.join("\t")), _ => Event::Failed(format!("The system reported something RustGIS doesn't know: {line}")), } @@ -115,9 +131,17 @@ mod tests { ); assert_eq!(Event::parse("cancelled"), Event::Cancelled); assert_eq!(Event::parse("stopped"), Event::Stopped); - assert_eq!(Event::parse("position\t-83.92\t35.96\t4.5"), Event::Position(Fix { lon: -83.92, lat: 35.96, accuracy: Some(4.5) })); + assert_eq!( + Event::parse("position\t-83.92\t35.96\t4.5"), + Event::Position(Fix { lon: -83.92, lat: 35.96, accuracy: Some(4.5), time: None }) + ); // No accuracy given: the position stands without it. - assert_eq!(Event::parse("position\t10\t20\t"), Event::Position(Fix { lon: 10.0, lat: 20.0, accuracy: None })); + assert_eq!(Event::parse("position\t10\t20\t"), Event::Position(Fix { lon: 10.0, lat: 20.0, accuracy: None, time: None })); + // With its time. + assert_eq!( + Event::parse("position\t10\t20\t3\t1794787200000"), + Event::Position(Fix { lon: 10.0, lat: 20.0, accuracy: Some(3.0), time: Some(1_794_787_200_000) }) + ); assert_eq!(Event::parse("saved\tmap.png"), Event::Saved { name: "map.png".into() }); assert_eq!(Event::parse("saved\tmy\tmap.png"), Event::Saved { name: "my\tmap.png".into() }); // A failure's text is kept whole, tabs and all. @@ -137,6 +161,9 @@ mod tests { "position\t10\t20\t-1", "position\t10\t20\tabc", "position\t10\t20\tinf", + "position\t10\t20\t3\tsoon", + "position\t10\t20\t3\t-5", + "position\t10\t20\t3\t1\t2", ] { match Event::parse(line) { Event::Failed(text) => assert!(text.ends_with(line), "{text}"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 27a904d0b4..a9888f0aac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1113,6 +1113,22 @@ const CAPTURE_PIXELS: f64 = 16_000_000.0; /// The lowest dpi a layout is copied at: a page that would need less is an error. const CAPTURE_MIN_DPI: f64 = 36.0; +/// The most positions [`RustGisApp::fixes`] keeps for an interface to take: a day of one a second. +pub const FIXES_KEPT: usize = 86_400; + +impl RustGisApp { + /// Keeps a position the shell reported: the last one in [`RustGisApp::position`], and each in + /// [`RustGisApp::fixes`] until an interface takes them (the oldest dropped past + /// [`FIXES_KEPT`]). + pub fn report_position(&mut self, fix: rustgis_engine::platform::Fix) { + self.position = Some(fix); + if self.fixes.len() >= FIXES_KEPT { + self.fixes.pop_front(); + } + self.fixes.push_back(fix); + } +} + pub struct RustGisApp { pub session: Session, pub ui: UiState, @@ -1144,6 +1160,11 @@ pub struct RustGisApp { /// Where the device is, as the shell last reported it; `None` until it has, and again once /// positioning is off. An interface draws it on the map and can capture at it. pub position: Option, + /// Every position the shell reported since an interface last took them, oldest first (at most + /// [`FIXES_KEPT`]: the oldest go first). [`RustGisApp::position`] is only the last: a track + /// or an average needs each, including those that arrived together after the app was out of + /// sight. + pub fixes: std::collections::VecDeque, /// Watches linked local files for changes made outside RustGIS and offers Reload Data /// (the desktop app; see [`diskwatch`]). Off for tests, unless one turns it on (as `ui_shot`'s /// `watchFiles` does). @@ -1413,6 +1434,7 @@ impl RustGisApp { chrome: None, locate: false, position: None, + fixes: std::collections::VecDeque::new(), #[cfg(not(target_arch = "wasm32"))] watch_files: false, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index f07fbbe4c2..91491c98b1 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -25,6 +25,7 @@ use serde_json::{Value, json}; mod edit; mod form; +mod track; /// The smallest side of anything a finger taps, in points (Android's guidance is 48). pub const TARGET: f32 = 48.0; @@ -39,6 +40,8 @@ const TYPING_SHARE: f32 = 0.9; const SHEET_MARGIN: f32 = 4.0; /// The More sheet's rows with the position hidden. const MORE_ROWS: usize = 8; +/// The More sheet's rows shown only with the position on: Go to My Position, and the track. +const MORE_POSITION_ROWS: usize = 2; /// The sheet risen over the map. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -66,8 +69,27 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); let t = Tokens::get(&ctx); let shown = sheet(&ctx); + // Each position the shell reported goes to the average and the track being taken. + track::take(app, &ctx); let frame = egui::Frame::NONE.fill(t.pane).stroke(Stroke::new(1.0, t.border)); egui::Panel::bottom("touch_bar").exact_size(BAR).frame(frame).show(ui, |ui| bar(app, ui, &t, shown)); + // A track being recorded says so over the bar, with its Stop, whatever sheet is up. + if let Some(recording) = track::field(&ctx).track { + let margin = egui::Margin::symmetric(12, 0); + egui::Panel::bottom("touch_track").exact_size(TARGET).frame(frame.inner_margin(margin)).show(ui, |ui| { + ui.horizontal_centered(|ui| { + ui.label(RichText::new(track::track_text(&recording, app.locate)).size(14.0).color(t.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if action(ui, &t, tl!("Stop"), 88.0, true, true) { + stop_track(app, &ctx); + } + if !app.locate && action(ui, &t, tl!("Resume"), 96.0, false, true) { + app.locate = true; + } + }); + }); + }); + } // Work running off the window's thread (a file being read, an export) shows its progress // and Cancel over the bar, where the desktop's status bar would. if app.background_busy() { @@ -82,7 +104,7 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { let rows = match shown { Sheet::Layers => (app.session.map().layers.len() + app.session.map().tiles.len()).max(1), // Go to My Position is there only while the position is shown. - Sheet::More => MORE_ROWS + usize::from(app.locate), + Sheet::More => MORE_ROWS + if app.locate { MORE_POSITION_ROWS } else { 0 }, Sheet::Capture => capture_rows(app, &ctx), Sheet::None => 0, }; @@ -109,6 +131,17 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { if let (Some(fix), Some((map, _))) = (app.position, app.map.view_rect) { position(app, &ui.painter().with_clip_rect(map), fix, &t); } + // The track being recorded, as it grows. + if let (Some(recording), Some((map, _))) = (track::field(&ctx).track, app.map.view_rect) { + let painter = ui.painter().with_clip_rect(map); + let points: Vec> = recording.points.iter().map(|f| app.lonlat_to_screen(f.lon, f.lat)).collect(); + for pair in points.windows(2) { + if let [Some(a), Some(b)] = pair { + painter.line_segment([*a, *b], Stroke::new(5.0, Color32::WHITE)); + painter.line_segment([*a, *b], Stroke::new(3.0, t.green)); + } + } + } if shown == Sheet::Capture && let Some((map, _)) = app.map.view_rect { @@ -130,6 +163,24 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { }); } +/// Starts recording a track, turning the device's position on when it is off. +fn start_track(app: &mut RustGisApp, ctx: &egui::Context) { + let mut state = track::field(ctx); + state.track = Some(track::Track::new()); + track::set_field(ctx, state); + app.locate = true; + app.session.notify(tl!("Recording a track: its positions are drawn on the map. Stop adds it to the Tracks layer."), false); +} + +/// Stops the track being recorded and adds it to the map. +fn stop_track(app: &mut RustGisApp, ctx: &egui::Context) { + let mut state = track::field(ctx); + if let Some(recorded) = state.track.take() { + track::set_field(ctx, state); + track::finish(app, recorded); + } +} + /// Draws where the device is: a dot, in a ring as wide as the position is good to. fn position(app: &RustGisApp, painter: &egui::Painter, fix: rustgis_ui_egui::rustgis_engine::platform::Fix, t: &Tokens) { let Some(at) = app.lonlat_to_screen(fix.lon, fix.lat) else { return }; @@ -435,7 +486,8 @@ fn capture_rows(app: &RustGisApp, ctx: &egui::Context) -> usize { return 4 + buttons + usize::from(app.locate); } let calendar = if state.calendar.is_some() { form::CALENDAR_ROWS } else { 0 }; - 1 + fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) + let averaging = usize::from(app.locate && track::field(ctx).averaging.is_some()); + 1 + averaging + fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) } /// A value typed for a field, as the command takes it: a number for a field of numbers, a truth @@ -754,9 +806,10 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }; ui.label(RichText::new(place).size(13.0).color(t.text_dim)); let width = ui.available_width(); - // With the device's position shown, one tap puts the cross on it. - if app.locate && action(ui, t, tl!("Go to My Position"), width, false, app.position.is_some()) { - go_to_position(app); + // With the device's position shown, one tap puts the cross on it; or the positions that come + // while Average runs are averaged, and Use Average puts the cross on their average. + if app.locate { + position_buttons(app, ui, t, &ctx, width); } // Add or Edit, and Snap. ui.horizontal(|ui| { @@ -970,6 +1023,45 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { set_form(&ctx, state); } +/// The Capture sheet's buttons for the device's position: Go to My Position and Average, or, +/// while an average is being taken, what it holds, Use Average and Cancel. +fn position_buttons(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context, width: f32) { + let mut state = track::field(ctx); + let half = (width - ui.spacing().item_spacing.x) / 2.0; + match &state.averaging { + None => { + ui.horizontal(|ui| { + if action(ui, t, tl!("Go to My Position"), half, false, app.position.is_some()) { + go_to_position(app); + } + if action(ui, t, tl!("Average Position"), half, false, true) { + state.averaging = Some(Vec::new()); + } + }); + } + Some(fixes) => { + ui.label(RichText::new(track::averaging_text(fixes)).size(14.0).color(t.text)); + let found = track::average(fixes); + ui.horizontal(|ui| { + let label = match found { + Some(a) => rustgis_ui_egui::i18n::fmt("Use Average ({n})", &[("n", &a.count.to_string())]), + None => tl!("Use Average").to_string(), + }; + if action(ui, t, &label, half, found.is_some(), found.is_some()) + && let Some(a) = found + { + run(app, "map.goToXY", json!({"lon": a.lon, "lat": a.lat})); + state.averaging = None; + } + if action(ui, t, tl!("Cancel"), half, false, true) { + state.averaging = None; + } + }); + } + } + track::set_field(ctx, state); +} + /// A chip a finger's height, `width` wide, marked while `on`. Says whether it was tapped. fn toggle_chip(ui: &mut Ui, t: &Tokens, label: &str, width: f32, on: bool) -> bool { let text = RichText::new(label).size(15.0).color(if on { t.accent_text } else { t.text }); @@ -1079,15 +1171,33 @@ fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } } // The device's position, where the shell can report one (it asks the user's leave first). + let ctx = ui.ctx().clone(); let locate = if app.locate { tl!("Hide My Position") } else { tl!("Show My Position") }; if row(ui, t, "explore", locate) { - set_sheet(ui.ctx(), Sheet::None); + set_sheet(&ctx, Sheet::None); + // Hidden, no more positions come: a track being recorded is added as it is. + if app.locate { + stop_track(app, &ctx); + } app.locate = !app.locate; } if app.locate && row(ui, t, "zoom_full", tl!("Go to My Position")) { - set_sheet(ui.ctx(), Sheet::None); + set_sheet(&ctx, Sheet::None); go_to_position(app); } + // A track: where the device goes, drawn as it goes, and added to the map when stopped. + let recording = track::field(&ctx).track.is_some(); + if app.locate || recording { + let label = if recording { tl!("Stop the Track") } else { tl!("Record a Track") }; + if row(ui, t, "line_tool", label) { + set_sheet(&ctx, Sheet::None); + if recording { + stop_track(app, &ctx); + } else { + start_track(app, &ctx); + } + } + } // The whole of RustGIS is still there, for a tablet or a job the touch interface has no // button for yet. The Project page's Start brings this interface back at the next start. if row(ui, t, "pane", tl!("Use the Desktop Interface")) { @@ -1417,14 +1527,14 @@ mod tests { assert_eq!(app.session.notices_since(mark).len(), 1); // With one, the map's middle (the capture cross) goes to it. app.locate = true; - app.position = Some(Fix { lon: 30.0, lat: -2.0, accuracy: Some(5.0) }); + app.position = Some(Fix { lon: 30.0, lat: -2.0, accuracy: Some(5.0), time: None }); go_to_position(&mut app); let (lon, lat) = cross_place(&app).unwrap(); assert!((lon - 30.0).abs() < 1e-6 && (lat + 2.0).abs() < 1e-6, "{lon} {lat}"); // Every sheet draws with the position on the map, its ring too (a wide one, to be drawn). // An accuracy out of all measure draws too, without its ring. for accuracy in [500_000.0, 1e300, f64::INFINITY] { - app.position = Some(Fix { lon: 30.0, lat: -2.0, accuracy: Some(accuracy) }); + app.position = Some(Fix { lon: 30.0, lat: -2.0, accuracy: Some(accuracy), time: None }); for shown in [Sheet::None, Sheet::Capture, Sheet::More] { frame(&mut app, &ctx, shown); } diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs new file mode 100644 index 0000000000..1a8992876c --- /dev/null +++ b/crates/ui-touch/src/track.rs @@ -0,0 +1,289 @@ +//! Field positions: the average of the device's positions for one place, and a track of where it +//! went. Both take each position the shell reported ([`RustGisApp::fixes`]), not only the last, +//! so none is lost between frames or while the app was out of sight. +//! +//! An average is taken in the Capture sheet: the positions that come while it runs are averaged, +//! and **Use Average** puts the capture cross there. A track is recorded from the More sheet: its +//! positions are drawn over the map as they come, and stopping it adds them as one line to the +//! map's **Tracks** layer (made when the map has none), with when it started and how many +//! positions it holds. + +use rustgis_ui_egui::rustgis_engine::platform::Fix; +use rustgis_ui_egui::{RustGisApp, i18n, tl}; +use serde_json::{Value, json}; + +/// A position less exact than this, in metres, is left out of a track (and the track says how +/// many were): one off by more would draw a spike. +pub(crate) const TRACK_ACCURACY: f64 = 50.0; +/// The name of the layer a track is added to. +pub(crate) const TRACKS: &str = "Tracks"; + +/// A track being recorded. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Track { + /// The positions kept, oldest first. + pub points: Vec, + /// The positions left out, less exact than [`TRACK_ACCURACY`]. + pub poor: usize, + /// When it was started, in milliseconds since 1970, when the clock could say. + pub started: Option, +} + +impl Track { + /// A track started now. + pub fn new() -> Track { + Track { started: now_ms(), ..Track::default() } + } + + /// Keeps a position, unless it is less exact than [`TRACK_ACCURACY`] (counted instead). + pub fn push(&mut self, fix: Fix) { + if fix.accuracy.is_some_and(|m| m > TRACK_ACCURACY) { + self.poor += 1; + } else { + self.points.push(fix); + } + } + + /// How long it ran, in whole minutes, from its first position's time to its last. + pub fn minutes(&self) -> Option { + let first = self.points.first()?.time?; + let last = self.points.last()?.time?; + Some((last - first).max(0) / 60_000) + } +} + +/// What the field positions hold between frames: an average being taken, and a track being +/// recorded. Kept in egui's memory, as the interface keeps its other state. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Field { + /// The positions averaged so far, while an average is being taken. + pub averaging: Option>, + pub track: Option, +} + +pub(crate) fn field(ctx: &egui::Context) -> Field { + ctx.data(|d| d.get_temp(egui::Id::unique("touch_field"))).unwrap_or_default() +} + +pub(crate) fn set_field(ctx: &egui::Context, field: Field) { + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("touch_field"), field)); +} + +/// Takes the positions the shell reported since the last frame into the average and the track +/// being taken, if any. Taken each frame either way, so positions don't wait for one to start. +pub(crate) fn take(app: &mut RustGisApp, ctx: &egui::Context) { + if app.fixes.is_empty() { + return; + } + let mut state = field(ctx); + for fix in app.fixes.drain(..) { + if let Some(fixes) = &mut state.averaging { + fixes.push(fix); + } + if let Some(track) = &mut state.track { + track.push(fix); + } + } + set_field(ctx, state); +} + +/// The average of some positions. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Average { + pub lon: f64, + pub lat: f64, + /// How far the positions lie from it, in metres (their root mean square distance). + pub spread: f64, + /// The mean of the accuracies they gave, in metres, when every one gave one. + pub accuracy: Option, + pub count: usize, +} + +/// The average of `fixes`: each weighted by how exact it says it is (one over its accuracy +/// squared) when every one says, else equally. Longitudes are taken about the first one's, so +/// positions on both sides of the antimeridian average to a place between them. `None` for none. +pub(crate) fn average(fixes: &[Fix]) -> Option { + let first = fixes.first()?; + let weighed = fixes.iter().all(|f| f.accuracy.is_some_and(|m| m > 0.0)); + let weight = |f: &Fix| if weighed { f.accuracy.map_or(1.0, |m| 1.0 / (m * m)) } else { 1.0 }; + let near = |lon: f64| first.lon + (lon - first.lon + 540.0).rem_euclid(360.0) - 180.0; + let total: f64 = fixes.iter().map(weight).sum(); + if !(total.is_finite() && total > 0.0) { + return None; + } + let lon = fixes.iter().map(|f| weight(f) * near(f.lon)).sum::() / total; + let lat = fixes.iter().map(|f| weight(f) * f.lat).sum::() / total; + let metres = |f: &Fix| { + let dx = (near(f.lon) - lon) * lat.to_radians().cos() * 111_320.0; + let dy = (f.lat - lat) * 110_540.0; + dx * dx + dy * dy + }; + let spread = (fixes.iter().map(metres).sum::() / fixes.len() as f64).sqrt(); + let accuracy = fixes.iter().map(|f| f.accuracy).sum::>().map(|sum| sum / fixes.len() as f64); + Some(Average { lon: (lon + 540.0).rem_euclid(360.0) - 180.0, lat, spread, accuracy, count: fixes.len() }) +} + +/// What the Capture sheet says of an average being taken. +pub(crate) fn averaging_text(fixes: &[Fix]) -> String { + match average(fixes) { + None => tl!("Averaging: waiting for the first position…").to_string(), + Some(a) => i18n::fmt( + "Averaging {n} positions: about {spread} m from their average (root mean square).", + &[("n", &a.count.to_string()), ("spread", &format!("{:.1}", a.spread))], + ), + } +} + +/// The line the track bar shows while a track is being recorded. +pub(crate) fn track_text(track: &Track, locating: bool) -> String { + if !locating { + return tl!("Track paused: this device's position is off.").to_string(); + } + let n = track.points.len().to_string(); + match track.minutes() { + Some(m) => i18n::fmt("Recording a track: {n} positions, {m} min", &[("n", &n), ("m", &m.to_string())]), + None => i18n::fmt("Recording a track: {n} positions", &[("n", &n)]), + } +} + +/// Adds a finished track to the map's Tracks layer, made when the map has none, and says what was +/// added and what was left out. A track of fewer than two positions adds nothing, and says so. +/// Says whether a line was added. +pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { + let left_out = |app: &mut RustGisApp| { + if track.poor > 0 { + let text = i18n::fmt( + "{n} positions were left out of the track: each was less exact than {m} m.", + &[("n", &track.poor.to_string()), ("m", &TRACK_ACCURACY.to_string())], + ); + app.session.notify(text, false); + } + }; + if track.points.len() < 2 { + app.session.notify(tl!("The track wasn't added: it has fewer than two positions."), true); + left_out(app); + return false; + } + let Some(layer) = tracks_layer(app) else { return false }; + if !super::edit::ensure_editing(app) { + return false; + } + let started = track.started.or(track.points.first().and_then(|f| f.time)).and_then(stamp).unwrap_or_default(); + let name = if started.is_empty() { tl!("Track").to_string() } else { i18n::fmt("Track {start}", &[("start", &started)]) }; + let notes = match track.minutes() { + Some(m) => i18n::fmt("{n} positions over {m} min", &[("n", &track.points.len().to_string()), ("m", &m.to_string())]), + None => i18n::fmt("{n} positions", &[("n", &track.points.len().to_string())]), + }; + let line: Vec = track.points.iter().map(|f| json!([f.lon, f.lat])).collect(); + let feature = json!({ + "layer": layer, + "geometry": {"type": "LineString", "coordinates": line}, + "attributes": {"name": name, "notes": notes}, + }); + if app.run_by_user("edit.addFeature", feature).is_err() { + return false; + } + app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", TRACKS), ("notes", ¬es)]), false); + left_out(app); + true +} + +/// The map's Tracks layer: its line layer of that name, or one made for it (with a name and a +/// notes field). +fn tracks_layer(app: &mut RustGisApp) -> Option { + use rustgis_ui_egui::rustgis_engine::data::GeometryType; + let found = app.session.map().layers.iter().find(|l| l.name == TRACKS && l.geometry_type() == GeometryType::Polyline).map(|l| l.id); + if found.is_some() { + return found; + } + let made = app.run_by_user("layer.template", json!({"template": "lines", "name": TRACKS})).ok()?; + made.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) +} + +/// Milliseconds since 1970 as a date and time in UTC, to the minute (`2026-11-14 10:05Z`). +fn stamp(ms: i64) -> Option { + use rustgis_ui_egui::rustgis_engine::data::DateTime; + let text = DateTime::with_offset(ms.checked_div(60_000)?.checked_mul(60_000_000)?, 0)?.to_string(); + // `2026-11-14T10:05:00Z`: the seconds are always nought here. + Some(format!("{} {}Z", text.get(..10)?, text.get(11..16)?)) +} + +/// Now, in milliseconds since 1970. +fn now_ms() -> Option { + let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).ok()?; + i64::try_from(since.as_millis()).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fix(lon: f64, lat: f64, accuracy: Option, time: Option) -> Fix { + Fix { lon, lat, accuracy, time } + } + + #[test] + fn an_average_weighs_each_position_by_how_exact_it_says_it_is() { + assert_eq!(average(&[]), None); + // Equal accuracies: the middle. + let a = average(&[fix(10.0, 20.0, Some(5.0), None), fix(10.0002, 20.0, Some(5.0), None)]).unwrap(); + assert!((a.lon - 10.0001).abs() < 1e-9 && (a.lat - 20.0).abs() < 1e-9, "{a:?}"); + assert_eq!(a.count, 2); + assert_eq!(a.accuracy, Some(5.0)); + // About 10.5 m apart: each about 5.2 m from the middle. + assert!((a.spread - 10.46).abs() < 0.2, "{a:?}"); + // One three times as exact counts nine times as much. + let b = average(&[fix(10.0, 20.0, Some(1.0), None), fix(10.001, 20.0, Some(3.0), None)]).unwrap(); + assert!((b.lon - 10.0001).abs() < 1e-9, "{b:?}"); + // One without an accuracy: all count the same, and no accuracy is given. + let c = average(&[fix(10.0, 20.0, Some(1.0), None), fix(10.001, 20.0, None, None)]).unwrap(); + assert!((c.lon - 10.0005).abs() < 1e-9 && c.accuracy.is_none(), "{c:?}"); + // Either side of the antimeridian: a place between them, not the other side of the Earth. + let d = average(&[fix(179.9999, 0.0, None, None), fix(-179.9999, 0.0, None, None)]).unwrap(); + assert!(d.lon.abs() > 179.99, "{d:?}"); + } + + #[test] + fn a_track_leaves_out_poor_positions_and_counts_them() { + let mut track = Track::default(); + track.push(fix(1.0, 1.0, Some(3.0), Some(0))); + track.push(fix(1.1, 1.0, Some(500.0), Some(60_000))); + track.push(fix(1.2, 1.0, None, Some(600_000))); + assert_eq!((track.points.len(), track.poor), (2, 1)); + assert_eq!(track.minutes(), Some(10)); + assert_eq!(stamp(1_794_614_460_123).as_deref(), Some("2026-11-14 00:01Z")); + } + + #[test] + fn a_finished_track_is_added_to_the_tracks_layer_and_what_was_left_out_is_said() { + let mut app = RustGisApp::with_sample(); + let ctx = egui::Context::default(); + // Positions reported before a track starts aren't in it. + app.report_position(fix(30.0, -2.0, Some(4.0), Some(0))); + take(&mut app, &ctx); + set_field(&ctx, Field { track: Some(Track::default()), averaging: Some(Vec::new()) }); + for (i, accuracy) in [4.0, 4.0, 80.0, 4.0].into_iter().enumerate() { + app.report_position(fix(30.0 + i as f64 * 0.001, -2.0, Some(accuracy), Some(i as i64 * 60_000))); + } + take(&mut app, &ctx); + assert!(app.fixes.is_empty()); + let state = field(&ctx); + let track = state.track.clone().unwrap(); + assert_eq!((track.points.len(), track.poor), (3, 1)); + assert_eq!(state.averaging.as_ref().map(Vec::len), Some(4)); + // Added as one line to a new Tracks layer, and the position left out said. + let mark = app.session.notice_mark(); + assert!(finish(&mut app, track.clone())); + let tracks = app.session.map().layers.iter().find(|l| l.name == TRACKS).unwrap(); + assert_eq!(tracks.dataset.features.len(), 1); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("left out")), "{said:?}"); + // A second goes to the same layer. + assert!(finish(&mut app, track)); + assert_eq!(app.session.map().layers.iter().filter(|l| l.name == TRACKS).count(), 1); + // Too short: nothing, said as an error. + let mark = app.session.notice_mark(); + assert!(!finish(&mut app, Track { points: vec![fix(1.0, 1.0, None, None)], ..Track::default() })); + assert!(app.session.notices_since(mark).iter().any(|n| n.error)); + } +} From 0917e82e2374e673733786e299af2359d8841d48 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:17:03 -0500 Subject: [PATCH 04/18] fix(mobile): contingent values match numbers by value, calculated and subtype-filled fields aren't asked for, typing ends when the keyboard goes --- .../java/org/rustgis/mobile/MainActivity.java | 7 ++- apps/rustgis-mobile/src/lib.rs | 28 +++++++++--- apps/rustgis-mobile/src/phone.rs | 14 +++--- crates/ui-touch/src/form.rs | 35 ++++++++++++++- crates/ui-touch/src/lib.rs | 43 +++++++++++++++++-- 5 files changed, 108 insertions(+), 19 deletions(-) diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index dda148c34d..d4c513f8f8 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -300,7 +300,8 @@ public String takeEvents() { /** * The room the system's bars, a camera cutout and the soft keyboard take at the window's - * edges, in pixels, as "left top right bottom"; empty before the window is laid out. + * edges, in pixels, as "left top right bottom", then (Android 11 and later) 1 or 0 for + * whether the keyboard is up; empty before the window is laid out. */ public String insets() { return insets; @@ -318,6 +319,10 @@ private static String describe(android.view.WindowInsets insets) { // above it. (The Rust side looks again while a field wants the keyboard, so the // room comes back when it goes.) bottom = Math.max(bars.bottom, insets.getInsets(android.view.WindowInsets.Type.ime()).bottom); + // Whether the keyboard is up, which its height alone doesn't tell (it shrinks when + // the phone turns): the Rust side ends the typing only when it goes. + boolean keyboard = insets.isVisible(android.view.WindowInsets.Type.ime()); + return left + " " + top + " " + right + " " + bottom + " " + (keyboard ? 1 : 0); } else { left = insets.getSystemWindowInsetLeft(); top = insets.getSystemWindowInsetTop(); diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 443e295766..4603197811 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -99,6 +99,8 @@ mod android { /// The room last taken at the window's bottom, in points: the soft keyboard's going /// shows as it shrinking. bottom: Option, + /// Whether the soft keyboard was up, where the phone says. + keyboard: Option, /// Until when the window looks again for the soft keyboard's room: a moment after the /// last frame a field wanted the keyboard. typing: Option, @@ -305,9 +307,11 @@ mod android { /// The room the system's bars take at the window's edges (the status bar, the navigation bar, /// a camera cutout), in points: egui keeps every panel out of it. `None` when the phone /// can't say, which leaves egui's last answer in place. - fn insets(phone: Option<&Phone>, pixels_per_point: f32) -> Option { - let [left, top, right, bottom] = phone?.insets()?.map(|edge| edge.max(0.0) / pixels_per_point.max(0.1)); - Some(egui::SafeAreaInsets(egui::epaint::MarginF32 { left, top, right, bottom })) + /// With the room, whether the soft keyboard is up, where the phone says. + fn insets(phone: Option<&Phone>, pixels_per_point: f32) -> Option<(egui::SafeAreaInsets, Option)> { + let (edges, keyboard) = phone?.insets()?; + let [left, top, right, bottom] = edges.map(|edge| edge.max(0.0) / pixels_per_point.max(0.1)); + Some((egui::SafeAreaInsets(egui::epaint::MarginF32 { left, top, right, bottom }), keyboard)) } /// What starts the name of a file from the picker for `purpose` in the inbox, as the browser's @@ -378,15 +382,24 @@ mod android { } fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { - raw_input.safe_area_insets = insets(self.phone.as_deref(), ctx.pixels_per_point()); + let room = insets(self.phone.as_deref(), ctx.pixels_per_point()); + raw_input.safe_area_insets = room.map(|(edges, _)| edges); // The soft keyboard closed (Back, or its own button) while a field still has the // focus: typing is over, so the field lets it go. Kept, the interface would stay laid - // out for typing until the next tap, and move what that tap was aimed at. - if let Some(egui::SafeAreaInsets(edges)) = raw_input.safe_area_insets { - if self.bottom.is_some_and(|before| edges.bottom < before - KEYBOARD_LEAST) && ctx.egui_wants_keyboard_input() { + // out for typing until the next tap, and move what that tap was aimed at. Android 11 + // and later say when the keyboard goes; before, the room it took shrinking a lot is + // taken for it going (a keyboard that only shrinks, as on turning, may end it there). + if let Some((egui::SafeAreaInsets(edges), keyboard)) = room { + let gone = match (self.keyboard, keyboard) { + (Some(true), Some(false)) => true, + (_, Some(_)) => false, + _ => self.bottom.is_some_and(|before| edges.bottom < before - KEYBOARD_LEAST), + }; + if gone && ctx.egui_wants_keyboard_input() { ctx.memory_mut(|m| m.stop_text_input()); } self.bottom = Some(edges.bottom); + self.keyboard = keyboard; } self.take_phone_events(ctx, raw_input); // The pushed files open as files dropped on the desktop window do: once the window @@ -523,6 +536,7 @@ mod android { locating: false, typing: None, bottom: None, + keyboard: None, bars_light: None, pushed, phone, diff --git a/apps/rustgis-mobile/src/phone.rs b/apps/rustgis-mobile/src/phone.rs index 5ec6877acd..e8f5ba0204 100644 --- a/apps/rustgis-mobile/src/phone.rs +++ b/apps/rustgis-mobile/src/phone.rs @@ -50,10 +50,11 @@ impl Phone { .map_err(|e| i18n::fmt("Android refused: {error}", &[("error", &e.to_string())])) } - /// The room the system's bars and a camera cutout take at the window's edges, in pixels: - /// left, top, right, bottom. `None` before the window is laid out, or when the activity - /// can't be asked. - pub fn insets(&self) -> Option<[f32; 4]> { + /// The room the system's bars, a camera cutout and the soft keyboard take at the window's + /// edges, in pixels (left, top, right, bottom), and whether the keyboard is up where Android + /// says (11 and later). `None` before the window is laid out, or when the activity can't be + /// asked. + pub fn insets(&self) -> Option<([f32; 4], Option)> { let text = self .java(|env, activity| { let taken = env.call_method(activity, jni_str!("insets"), jni_sig!(() -> JString), &[])?.l()?; @@ -63,8 +64,9 @@ impl Phone { env.cast_local::(taken)?.try_to_string(env) }) .ok()?; - let edges: Vec = text.split(' ').filter_map(|edge| edge.parse().ok()).collect(); - <[f32; 4]>::try_from(edges).ok() + let fields: Vec = text.split(' ').filter_map(|edge| edge.parse().ok()).collect(); + let edges = <[f32; 4]>::try_from(fields.get(..4)?).ok()?; + Some((edges, fields.get(4).map(|up| *up > 0.5))) } /// Draws the system bars' icons dark (`light` ground under them) or light (a dark one). diff --git a/crates/ui-touch/src/form.rs b/crates/ui-touch/src/form.rs index da81069dad..3ce8b545ef 100644 --- a/crates/ui-touch/src/form.rs +++ b/crates/ui-touch/src/form.rs @@ -19,10 +19,24 @@ pub(crate) fn stored(value: &Value) -> String { } } +/// Whether the form's text `got` is the value `want`: a number by its value, so `3.0` and `03` +/// are `3`; yes and no as the chips hold them; anything else by its text. +fn holds(want: &Value, got: &str) -> bool { + let number = |n: f64| got.trim().parse::().is_ok_and(|g| g == n); + match want { + Value::Int(i) => number(*i as f64), + Value::Float(f) => number(*f), + Value::Bool(b) => got.trim() == if *b { "true" } else { "false" }, + Value::Text(t) => t == got, + other => other.to_string() == got, + } +} + /// The fields a layer's constraint rules require to hold a value, by name, in the layer's field /// order: those a rule asks `IS NOT NULL` of, alone or as one of the clauses joined by `AND` at /// its top. A rule that can't be read, or that asks it only under a condition (inside an `OR`), /// requires nothing here; the engine still checks the rule itself when the feature is added. +/// A field a calculation rule sets isn't asked for either: the engine fills it before it checks. pub(crate) fn required(layer: &Layer) -> Vec { use rustgis_ui_egui::rustgis_engine::map::design::RuleKind; let mut found = vec![false; layer.dataset.fields.len()]; @@ -31,7 +45,8 @@ pub(crate) fn required(layer: &Layer) -> Vec { not_null(&e, &mut found); } } - layer.dataset.fields.iter().zip(found).filter(|(_, on)| *on).map(|(f, _)| f.name.clone()).collect() + let calculated = |name: &str| layer.design.rules.iter().any(|r| r.kind == RuleKind::Calculation && r.field.eq_ignore_ascii_case(name)); + layer.dataset.fields.iter().zip(found).filter(|(f, on)| *on && !calculated(&f.name)).map(|(f, _)| f.name.clone()).collect() } /// Marks in `found` the fields `e` requires to hold a value, looking through `AND`s only. @@ -76,7 +91,7 @@ pub(crate) fn contingent(layer: &Layer, field: &str, values: &BTreeMap| combo.iter().zip(&chosen).all(|(want, got)| want.is_null() || got.is_none_or(|got| stored(want) == got)); + |combo: &&Vec| combo.iter().zip(&chosen).all(|(want, got)| want.is_null() || got.is_none_or(|got| holds(want, got))); let mut these: Vec = Vec::new(); let mut open = false; for combo in set.combos.iter().filter(fits) { @@ -257,6 +272,9 @@ mod tests { assert!(required(&l).is_empty()); l.design.rules = vec![rule("name IS NOT NULL AND (size = 'big' OR size IS NOT NULL)"), rule("NOT surveyed IS NULL")]; assert_eq!(required(&l), ["name", "surveyed"]); + // A field a calculation rule fills isn't asked for. + l.design.rules.push(AttributeRule { kind: RuleKind::Calculation, field: "name".into(), ..rule("'x'") }); + assert_eq!(required(&l), ["surveyed"]); // Only under a condition, or in a calculation rule, or unreadable: not required. l.design.rules = vec![rule("name IS NOT NULL OR kind = 'oak'"), rule("no_such_field IS NOT NULL")]; l.design.rules.push(AttributeRule { kind: RuleKind::Calculation, ..rule("kind IS NOT NULL") }); @@ -282,6 +300,19 @@ mod tests { values.insert("size".to_string(), "big".to_string()); assert_eq!(contingent(&l, "size", &values), Some(vec!["big".into(), "small".into()])); assert_eq!(contingent(&l, "kind", &values), Some(vec!["oak".into()])); + // A number typed another way is the same number. + let mut numbers = layer(); + numbers.design.contingent = vec![ContingentSet { + name: "count".into(), + fields: vec!["kind".into(), "size".into()], + combos: vec![vec![Value::Int(1), text("restricted")], vec![Value::Float(2.5), text("open")]], + }]; + for typed in ["01", "1.0"] { + let chosen = BTreeMap::from([("kind".to_string(), typed.to_string())]); + assert_eq!(contingent(&numbers, "size", &chosen), Some(vec!["restricted".into()]), "{typed}"); + } + let chosen = BTreeMap::from([("kind".to_string(), "2.50".to_string())]); + assert_eq!(contingent(&numbers, "size", &chosen), Some(vec!["open".into()])); // Nothing fits: no value is left. values.insert("kind".to_string(), "birch".to_string()); assert_eq!(contingent(&l, "size", &values), Some(vec![])); diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 5c31fd355e..103c752408 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -403,7 +403,15 @@ fn capture_rows(app: &RustGisApp, ctx: &egui::Context) -> usize { let layer = app.session.map().layer(target.id); let fields = layer .map_or(0, |l| l.dataset.fields.len() + usize::from(!l.design.templates.is_empty()) + usize::from(!form::required(l).is_empty())); - let calendar = if state.calendar.is_some() { form::CALENDAR_ROWS } else { 0 }; + // A date and time's calendar has its Now row too. + let calendar = match (&state.calendar, layer) { + (Some((name, _)), Some(l)) => { + let timed = + l.dataset.fields.iter().any(|f| &f.name == name && f.ty == rustgis_ui_egui::rustgis_engine::data::FieldType::DateTime); + form::CALENDAR_ROWS + usize::from(timed) + } + _ => 0, + }; fields + calendar + if target.kind == GeometryType::Point { 3 } else { 4 } + usize::from(app.locate) } @@ -546,8 +554,13 @@ fn defaulted(layer: &rustgis_ui_egui::rustgis_engine::map::Layer, form: &Form, n defaults.iter().any(|(field, value)| field.eq_ignore_ascii_case(name) && !value.is_null()) }; let template = form.template.as_ref().and_then(|t| layer.design.templates.iter().find(|x| &x.name == t)); + // The subtype the form chose, or else the one the template gives, as the engine reads it. let subtype = layer.design.subtypes.as_ref().and_then(|s| { - let code = form.values.iter().find(|(field, _)| field.eq_ignore_ascii_case(&s.field))?.1.trim().parse::().ok()?; + let typed = form.values.iter().find(|(field, v)| field.eq_ignore_ascii_case(&s.field) && !v.trim().is_empty()); + let code = match typed { + Some((_, v)) => v.trim().parse::().ok()?, + None => template?.defaults.iter().find(|(field, _)| field.eq_ignore_ascii_case(&s.field))?.1.as_f64()? as i64, + }; s.subtypes.iter().find(|x| x.code == code) }); template.is_some_and(|t| has(&t.defaults)) || subtype.is_some_and(|s| has(&s.defaults)) @@ -871,7 +884,8 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { None } else { let day = form::day_of(value).or_else(form::today); - let month = day.map_or((2026, 1), |d| { + // Without a clock, the calendar starts at 1970's first month. + let month = day.map_or((1970, 1), |d| { let (y, m, _) = d.ymd(); (y, m) }); @@ -1310,6 +1324,29 @@ mod tests { assert!(form(&ctx).calendar.is_some()); } + #[test] + fn a_subtype_the_template_chooses_fills_a_required_field_with_its_default() { + let mut app = RustGisApp::with_sample(); + let cities = target(&mut app, GeometryType::Point); + run(&mut app, "edit.addField", json!({"layer": cities.id, "name": "kind", "type": "long"})); + run(&mut app, "edit.addField", json!({"layer": cities.id, "name": "status", "type": "text"})); + let subtypes = + json!({"layer": cities.id, "field": "kind", "subtypes": [{"code": 1, "name": "Well", "defaults": {"status": "active"}}]}); + run(&mut app, "data.subtypes", subtypes); + run( + &mut app, + "data.attributeRule", + json!({"layer": cities.id, "name": "status", "kind": "constraint", "expression": "status IS NOT NULL"}), + ); + run(&mut app, "edit.template", json!({"layer": cities.id, "name": "Well", "defaults": {"kind": 1}})); + let layer = app.session.map().layer(cities.id).unwrap(); + // The template gives the subtype, whose default fills the required field. + let state = Form { template: Some("Well".into()), ..Form::default() }; + assert!(defaulted(layer, &state, "status")); + assert!(!defaulted(layer, &Form::default(), "status")); + assert!(add_point(&mut app, cities.id, &state)); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); From bdbcb54f67566ded53d2617f3301efdcd56ae4e3 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:18:41 -0500 Subject: [PATCH 05/18] fix(mobile): Delete Feature works with nothing selected, and leaves other selections as they were --- crates/ui-touch/src/edit.rs | 19 +++++++++++++++---- crates/ui-touch/src/lib.rs | 13 +++++++++++-- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/ui-touch/src/edit.rs b/crates/ui-touch/src/edit.rs index 29ff575aad..2ab744ee34 100644 --- a/crates/ui-touch/src/edit.rs +++ b/crates/ui-touch/src/edit.rs @@ -130,14 +130,25 @@ pub(crate) fn vertex( } /// Deletes the feature in row `row` of layer `id`, as one edit that undoes. Says whether it was. +/// The map's selections are set aside while it is (Delete takes every layer's selection) and +/// put back after, the rows of layer `id` past it moved up one. pub(crate) fn delete_feature(app: &mut RustGisApp, id: u32, row: usize) -> bool { if !ensure_editing(app) { return false; } - // Only this feature: Delete takes every layer's selection. - app.run_by_user("select.clear", serde_json::Value::Null).is_ok() - && app.run_by_user("select.rows", json!({"layer": id, "rows": [row]})).is_ok() - && app.run_by_user("edit.delete", serde_json::Value::Null).is_ok() + let kept: Vec<(u32, Vec)> = app.session.map_mut().layers.iter_mut().map(|l| (l.id, std::mem::take(&mut l.selection))).collect(); + let deleted = app.run_by_user("select.rows", json!({"layer": id, "rows": [row]})).is_ok() + && app.run_by_user("edit.delete", serde_json::Value::Null).is_ok(); + for (layer, mut rows) in kept { + if layer == id && deleted { + rows.retain(|r| *r != row); + rows.iter_mut().filter(|r| **r > row).for_each(|r| *r -= 1); + } + if let Some(l) = app.session.map_mut().layer_mut(layer) { + l.selection = rows; + } + } + deleted } /// Draws the feature being edited over the map: every vertex, the picked one larger and filled. diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 499a1c25a9..3a37a5c156 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -1521,13 +1521,22 @@ mod tests { assert_eq!(form(&ctx).editing.map(|e| e.feature), Some(feature)); // Deleted, only it: the sheet lets it go. let before = count(&app, rivers.id); - // A selection on another layer is left alone. + // With nothing selected anywhere it is deleted too (Pick Feature selects nothing). let cities = app.session.map().layers.iter().find(|l| l.geometry_type() == GeometryType::Point).unwrap().id; - run(&mut app, "select.rows", json!({"layer": cities, "rows": [0]})); + let before = count(&app, rivers.id); + let last = before - 1; + assert!(app.session.map().layers.iter().all(|l| l.selection.is_empty())); + assert!(edit::delete_feature(&mut app, rivers.id, last)); + assert_eq!(count(&app, rivers.id), before - 1); + run(&mut app, "edit.undo", Value::Null); + assert_eq!(count(&app, rivers.id), before); + // A selection on another layer is left as it was. + run(&mut app, "select.rows", json!({"layer": cities, "rows": [0, 2]})); let cities_before = count(&app, cities); assert!(edit::delete_feature(&mut app, rivers.id, row)); assert_eq!(count(&app, rivers.id), before - 1); assert_eq!(count(&app, cities), cities_before); + assert_eq!(app.session.map().layer(cities).unwrap().selection, [0, 2]); assert_eq!(edit::row_of(&app, rivers.id, feature), None); frame(&mut app, &ctx, Sheet::Capture); assert_eq!(form(&ctx).editing, None); From 03d1299f807536225e6bb5f367600d422318f816 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:19:04 -0500 Subject: [PATCH 06/18] test(mobile): drop an unused count --- crates/ui-touch/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 3a37a5c156..f7f4666d2d 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -1520,7 +1520,6 @@ mod tests { frame(&mut app, &ctx, Sheet::Capture); assert_eq!(form(&ctx).editing.map(|e| e.feature), Some(feature)); // Deleted, only it: the sheet lets it go. - let before = count(&app, rivers.id); // With nothing selected anywhere it is deleted too (Pick Feature selects nothing). let cities = app.session.map().layers.iter().find(|l| l.geometry_type() == GeometryType::Point).unwrap().id; let before = count(&app, rivers.id); From d47bfcdc9d56ebeb04498650ee87281373f422d6 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:22:02 -0500 Subject: [PATCH 07/18] fix(mobile): an average stops with the position, a refused track still says what it left out, the track isn't copied each frame --- crates/ui-touch/src/lib.rs | 24 +++++++++++++++++++- crates/ui-touch/src/track.rs | 43 +++++++++++++++++++++++++----------- 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 0a0e88920f..c2baa4efb4 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -71,6 +71,14 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { let shown = sheet(&ctx); // Each position the shell reported goes to the average and the track being taken. track::take(app, &ctx); + // With positioning off (Hide My Position, or Android ending it), an average being taken + // stops: the sheet no longer shows it, and positions from before would mix into the next. + if !app.locate { + let mut state = track::field(&ctx); + if state.averaging.take().is_some() { + track::set_field(&ctx, state); + } + } let frame = egui::Frame::NONE.fill(t.pane).stroke(Stroke::new(1.0, t.border)); egui::Panel::bottom("touch_bar").exact_size(BAR).frame(frame).show(ui, |ui| bar(app, ui, &t, shown)); // A track being recorded says so over the bar, with its Stop, whatever sheet is up. @@ -1049,7 +1057,7 @@ fn position_buttons(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::C go_to_position(app); } if action(ui, t, tl!("Average Position"), half, false, true) { - state.averaging = Some(Vec::new()); + state.averaging = Some(std::sync::Arc::default()); } }); } @@ -1709,6 +1717,20 @@ mod tests { assert!(add_point(&mut app, cities.id, &state)); } + #[test] + fn an_average_being_taken_stops_with_the_position() { + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + app.locate = true; + track::set_field(&ctx, track::Field { averaging: Some(std::sync::Arc::default()), ..Default::default() }); + frame(&mut app, &ctx, Sheet::Capture); + assert!(track::field(&ctx).averaging.is_some()); + // Hidden (or ended by the system): the average goes with it. + app.locate = false; + frame(&mut app, &ctx, Sheet::Capture); + assert!(track::field(&ctx).averaging.is_none()); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index 1a8992876c..74db3f3d6c 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -11,6 +11,7 @@ use rustgis_ui_egui::rustgis_engine::platform::Fix; use rustgis_ui_egui::{RustGisApp, i18n, tl}; use serde_json::{Value, json}; +use std::sync::Arc; /// A position less exact than this, in metres, is left out of a track (and the track says how /// many were): one off by more would draw a spike. @@ -22,7 +23,9 @@ pub(crate) const TRACKS: &str = "Tracks"; #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Track { /// The positions kept, oldest first. - pub points: Vec, + /// Shared, so reading the field positions each frame doesn't copy them: a track runs for + /// hours, a position a second. + pub points: Arc>, /// The positions left out, less exact than [`TRACK_ACCURACY`]. pub poor: usize, /// When it was started, in milliseconds since 1970, when the clock could say. @@ -40,7 +43,7 @@ impl Track { if fix.accuracy.is_some_and(|m| m > TRACK_ACCURACY) { self.poor += 1; } else { - self.points.push(fix); + Arc::make_mut(&mut self.points).push(fix); } } @@ -57,7 +60,7 @@ impl Track { #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Field { /// The positions averaged so far, while an average is being taken. - pub averaging: Option>, + pub averaging: Option>>, pub track: Option, } @@ -78,7 +81,7 @@ pub(crate) fn take(app: &mut RustGisApp, ctx: &egui::Context) { let mut state = field(ctx); for fix in app.fixes.drain(..) { if let Some(fixes) = &mut state.averaging { - fixes.push(fix); + Arc::make_mut(fixes).push(fix); } if let Some(track) = &mut state.track { track.push(fix); @@ -100,12 +103,14 @@ pub(crate) struct Average { } /// The average of `fixes`: each weighted by how exact it says it is (one over its accuracy -/// squared) when every one says, else equally. Longitudes are taken about the first one's, so -/// positions on both sides of the antimeridian average to a place between them. `None` for none. +/// squared, the accuracy taken as at least a centimetre and at most a thousand kilometres, so +/// no weight is infinite or nothing) when every one says, else equally. Longitudes are taken +/// about the first one's, so positions on both sides of the antimeridian average to a place +/// between them. `None` for none. pub(crate) fn average(fixes: &[Fix]) -> Option { let first = fixes.first()?; - let weighed = fixes.iter().all(|f| f.accuracy.is_some_and(|m| m > 0.0)); - let weight = |f: &Fix| if weighed { f.accuracy.map_or(1.0, |m| 1.0 / (m * m)) } else { 1.0 }; + let weighed = fixes.iter().all(|f| f.accuracy.is_some()); + let weight = |f: &Fix| if weighed { f.accuracy.map_or(1.0, |m| 1.0 / m.clamp(0.01, 1e6).powi(2)) } else { 1.0 }; let near = |lon: f64| first.lon + (lon - first.lon + 540.0).rem_euclid(360.0) - 180.0; let total: f64 = fixes.iter().map(weight).sum(); if !(total.is_finite() && total > 0.0) { @@ -164,10 +169,16 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { left_out(app); return false; } - let Some(layer) = tracks_layer(app) else { return false }; + // Editing first: a Tracks layer isn't made for a track that then can't be added. Every way + // out still says what was left out (the refusal itself the front end says). if !super::edit::ensure_editing(app) { + left_out(app); return false; } + let Some(layer) = tracks_layer(app) else { + left_out(app); + return false; + }; let started = track.started.or(track.points.first().and_then(|f| f.time)).and_then(stamp).unwrap_or_default(); let name = if started.is_empty() { tl!("Track").to_string() } else { i18n::fmt("Track {start}", &[("start", &started)]) }; let notes = match track.minutes() { @@ -181,6 +192,7 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { "attributes": {"name": name, "notes": notes}, }); if app.run_by_user("edit.addFeature", feature).is_err() { + left_out(app); return false; } app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", TRACKS), ("notes", ¬es)]), false); @@ -230,7 +242,7 @@ mod tests { assert!((a.lon - 10.0001).abs() < 1e-9 && (a.lat - 20.0).abs() < 1e-9, "{a:?}"); assert_eq!(a.count, 2); assert_eq!(a.accuracy, Some(5.0)); - // About 10.5 m apart: each about 5.2 m from the middle. + // About 21 m apart: each about 10.5 m from the middle. assert!((a.spread - 10.46).abs() < 0.2, "{a:?}"); // One three times as exact counts nine times as much. let b = average(&[fix(10.0, 20.0, Some(1.0), None), fix(10.001, 20.0, Some(3.0), None)]).unwrap(); @@ -238,6 +250,11 @@ mod tests { // One without an accuracy: all count the same, and no accuracy is given. let c = average(&[fix(10.0, 20.0, Some(1.0), None), fix(10.001, 20.0, None, None)]).unwrap(); assert!((c.lon - 10.0005).abs() < 1e-9 && c.accuracy.is_none(), "{c:?}"); + // Accuracies out of all measure, or of nothing, still weigh: none is infinite or nothing. + let e = average(&[fix(10.0, 20.0, Some(1e300), None), fix(10.001, 20.0, Some(1e300), None)]).unwrap(); + assert!((e.lon - 10.0005).abs() < 1e-9, "{e:?}"); + let z = average(&[fix(10.0, 20.0, Some(0.0), None), fix(10.001, 20.0, Some(5.0), None)]).unwrap(); + assert!((z.lon - 10.0).abs() < 1e-6, "{z:?}"); // Either side of the antimeridian: a place between them, not the other side of the Earth. let d = average(&[fix(179.9999, 0.0, None, None), fix(-179.9999, 0.0, None, None)]).unwrap(); assert!(d.lon.abs() > 179.99, "{d:?}"); @@ -261,7 +278,7 @@ mod tests { // Positions reported before a track starts aren't in it. app.report_position(fix(30.0, -2.0, Some(4.0), Some(0))); take(&mut app, &ctx); - set_field(&ctx, Field { track: Some(Track::default()), averaging: Some(Vec::new()) }); + set_field(&ctx, Field { track: Some(Track::default()), averaging: Some(Arc::default()) }); for (i, accuracy) in [4.0, 4.0, 80.0, 4.0].into_iter().enumerate() { app.report_position(fix(30.0 + i as f64 * 0.001, -2.0, Some(accuracy), Some(i as i64 * 60_000))); } @@ -270,7 +287,7 @@ mod tests { let state = field(&ctx); let track = state.track.clone().unwrap(); assert_eq!((track.points.len(), track.poor), (3, 1)); - assert_eq!(state.averaging.as_ref().map(Vec::len), Some(4)); + assert_eq!(state.averaging.as_ref().map(|a| a.len()), Some(4)); // Added as one line to a new Tracks layer, and the position left out said. let mark = app.session.notice_mark(); assert!(finish(&mut app, track.clone())); @@ -283,7 +300,7 @@ mod tests { assert_eq!(app.session.map().layers.iter().filter(|l| l.name == TRACKS).count(), 1); // Too short: nothing, said as an error. let mark = app.session.notice_mark(); - assert!(!finish(&mut app, Track { points: vec![fix(1.0, 1.0, None, None)], ..Track::default() })); + assert!(!finish(&mut app, Track { points: Arc::new(vec![fix(1.0, 1.0, None, None)]), ..Track::default() })); assert!(app.session.notices_since(mark).iter().any(|n| n.error)); } } From 7a5fadc2f687f6453cb0f92199dce83d32c689a3 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:57:12 -0500 Subject: [PATCH 08/18] fix(mobile): typing ends only when Android says the keyboard went, and whole-number codes match exactly --- apps/rustgis-mobile/README.md | 2 +- apps/rustgis-mobile/src/lib.rs | 22 ++++------------------ crates/ui-touch/src/form.rs | 15 +++++++++++++-- 3 files changed, 18 insertions(+), 21 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 4190565ccb..316e7e73fe 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -103,7 +103,7 @@ time, **Now**. While a field is typed in, the sheet takes most of the window and stays above the soft keyboard: the activity's Java half counts the keyboard in the window's bottom inset, the app looks again for it while a field wants the keyboard (Android doesn't wake the app when it comes or goes), the -field is scrolled into view, and closing the keyboard ends the typing. +field is scrolled into view, and closing the keyboard ends the typing (Android 11 and later, which say when it goes; before, the field keeps the focus until the next tap, and the keyboard's room isn't counted). **Show My Position**, in the More sheet, asks Android for the device's position (and the user, the first time, for leave to use it). The position is drawn on the map as a dot in a ring as wide diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 4603197811..3a02959d1d 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -78,10 +78,6 @@ mod android { /// it: long enough for the keyboard to finish closing. const KEYBOARD_SETTLES: std::time::Duration = std::time::Duration::from_millis(1500); - /// How much the window's bottom room shrinks, in points, when the soft keyboard closes, at the - /// least: more than the navigation bar coming and going. - const KEYBOARD_LEAST: f32 = 120.0; - /// What a service couldn't do, kept until the next frame says it in the window (a service has /// no session to tell). type Refusals = Rc>>; @@ -96,9 +92,6 @@ mod android { poll: Option, /// Whether the phone was last asked for positions (`RustGisApp::locate`, as last seen). locating: bool, - /// The room last taken at the window's bottom, in points: the soft keyboard's going - /// shows as it shrinking. - bottom: Option, /// Whether the soft keyboard was up, where the phone says. keyboard: Option, /// Until when the window looks again for the soft keyboard's room: a moment after the @@ -387,18 +380,12 @@ mod android { // The soft keyboard closed (Back, or its own button) while a field still has the // focus: typing is over, so the field lets it go. Kept, the interface would stay laid // out for typing until the next tap, and move what that tap was aimed at. Android 11 - // and later say when the keyboard goes; before, the room it took shrinking a lot is - // taken for it going (a keyboard that only shrinks, as on turning, may end it there). - if let Some((egui::SafeAreaInsets(edges), keyboard)) = room { - let gone = match (self.keyboard, keyboard) { - (Some(true), Some(false)) => true, - (_, Some(_)) => false, - _ => self.bottom.is_some_and(|before| edges.bottom < before - KEYBOARD_LEAST), - }; - if gone && ctx.egui_wants_keyboard_input() { + // and later say when the keyboard goes. Before, it isn't reported at all (nor its + // room), and the field keeps the focus until the next tap. + if let Some((_, keyboard)) = room { + if self.keyboard == Some(true) && keyboard == Some(false) && ctx.egui_wants_keyboard_input() { ctx.memory_mut(|m| m.stop_text_input()); } - self.bottom = Some(edges.bottom); self.keyboard = keyboard; } self.take_phone_events(ctx, raw_input); @@ -535,7 +522,6 @@ mod android { poll: None, locating: false, typing: None, - bottom: None, keyboard: None, bars_light: None, pushed, diff --git a/crates/ui-touch/src/form.rs b/crates/ui-touch/src/form.rs index 3ce8b545ef..62c623d879 100644 --- a/crates/ui-touch/src/form.rs +++ b/crates/ui-touch/src/form.rs @@ -20,11 +20,16 @@ pub(crate) fn stored(value: &Value) -> String { } /// Whether the form's text `got` is the value `want`: a number by its value, so `3.0` and `03` -/// are `3`; yes and no as the chips hold them; anything else by its text. +/// are `3` (a whole number exactly, past what a float holds); yes and no as the chips hold them; +/// anything else by its text. fn holds(want: &Value, got: &str) -> bool { let number = |n: f64| got.trim().parse::().is_ok_and(|g| g == n); match want { - Value::Int(i) => number(*i as f64), + Value::Int(i) => match got.trim().parse::() { + Ok(g) => g == *i, + // `3.0`: a whole number written with a fraction, within what a float holds exactly. + Err(_) => got.trim().parse::().is_ok_and(|g| g.fract() == 0.0 && g.abs() < 9.0e15 && g as i64 == *i), + }, Value::Float(f) => number(*f), Value::Bool(b) => got.trim() == if *b { "true" } else { "false" }, Value::Text(t) => t == got, @@ -311,6 +316,12 @@ mod tests { let chosen = BTreeMap::from([("kind".to_string(), typed.to_string())]); assert_eq!(contingent(&numbers, "size", &chosen), Some(vec!["restricted".into()]), "{typed}"); } + // Whole numbers past a float's precision stay apart. + numbers.design.contingent[0].combos = + vec![vec![Value::Int(9_007_199_254_740_992), text("A")], vec![Value::Int(9_007_199_254_740_993), text("B")]]; + let chosen = BTreeMap::from([("kind".to_string(), "9007199254740993".to_string())]); + assert_eq!(contingent(&numbers, "size", &chosen), Some(vec!["B".into()])); + numbers.design.contingent[0].combos = vec![vec![Value::Int(1), text("restricted")], vec![Value::Float(2.5), text("open")]]; let chosen = BTreeMap::from([("kind".to_string(), "2.50".to_string())]); assert_eq!(contingent(&numbers, "size", &chosen), Some(vec!["open".into()])); // Nothing fits: no value is left. From 1853e562f3c279231f1af46de48b8d09067c5c3c Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 03:58:54 -0500 Subject: [PATCH 09/18] fix(mobile): a picked vertex an undo moved or took away is let go --- apps/rustgis-mobile/README.md | 2 +- crates/ui-touch/src/edit.rs | 30 ++++++++++++++++++++++++++---- crates/ui-touch/src/lib.rs | 34 +++++++++++++++++++++++++++------- 3 files changed, 54 insertions(+), 12 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index a650d78605..b127abfc3a 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -117,7 +117,7 @@ feature drawn on top under it (within half a finger) and draws its vertices. For **Pick Vertex at Cross** picks the vertex nearest the cross, and then **Move Here** moves it to where the cross is next, **Add After** puts a new vertex there after it, and **Delete Vertex** removes it (a line keeps two, a ring three). For a point, **Move Point Here** moves it. **Delete -Feature** deletes it (only it: the other layers' selections are cleared first), and **Done** lets +Feature** deletes it (only it: the map's other selections are kept), and **Done** lets it go. Each change is one edit, undone by Undo in the More sheet. **Snap** turns the map's snapping on and off (its settings are the desktop's: Edit › Snapping). diff --git a/crates/ui-touch/src/edit.rs b/crates/ui-touch/src/edit.rs index 2ab744ee34..17ad85b9f3 100644 --- a/crates/ui-touch/src/edit.rs +++ b/crates/ui-touch/src/edit.rs @@ -21,6 +21,31 @@ pub(crate) const REACH: f32 = super::TARGET / 2.0; pub(crate) struct Editing { pub feature: u64, pub vertex: Option, + /// Where the picked vertex was when it was picked or last changed here: one found elsewhere + /// (an Undo moved or took it away, or its index now names another) is let go. + pub at: Option<(f64, f64)>, +} + +impl Editing { + /// The feature `feature`, with no vertex picked. + pub fn feature(feature: u64) -> Editing { + Editing { feature, vertex: None, at: None } + } + + /// The same feature with vertex `v` of `shape` picked (none when `shape` has no such vertex). + pub fn picking(self, v: Option, shape: Option<&Geometry>) -> Editing { + let at = v.and_then(|v| shape?.vertex(v)).map(|c| (c.x, c.y)); + Editing { vertex: v.filter(|_| at.is_some()), at, ..self } + } + + /// Lets the picked vertex go when `shape` has it elsewhere than it was, or not at all. + pub fn checked(self, shape: Option<&Geometry>) -> Editing { + match self.vertex { + Some(v) if shape.and_then(|g| g.vertex(v)).map(|c| (c.x, c.y)) == self.at => self, + Some(_) => Editing { vertex: None, at: None, ..self }, + None => self, + } + } } /// The place the cross snapped to, as longitude and latitude, and what it snapped to (`vertex`, @@ -123,10 +148,7 @@ pub(crate) fn vertex( return Some(None); } let read = |k: &str| done.get(k).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); - Some(match (read("part"), read("ring"), read("index")) { - (Some(part), Some(ring), Some(index)) => Some(VertexId::new(part, ring, index)), - _ => Some(v), - }) + Some(Some(VertexId::new(read("part")?, read("ring")?, read("index")?))) } /// Deletes the feature in row `row` of layer `id`, as one edit that undoes. Says whether it was. diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index f7f4666d2d..a98bb4b14c 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -747,9 +747,9 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let fresh = stale.is_none(); // The feature being edited, while it is still there (an undo may have taken it away). let picked = state.editing.and_then(|e| edit::row_of(app, target.id, e.feature).map(|row| (row, e))); - if picked.is_none() { - state.editing = None; - } + // A picked vertex an Undo moved or took away is let go. + let picked = picked.map(|(row, e)| (row, e.checked(edit::shape(app, target.id, row).as_ref()))); + state.editing = picked.map(|(_, e)| e); // The cross's place, snapped with snapping on: a vertex being moved doesn't snap to itself. let moving = picked.filter(|_| state.edit_mode).and_then(|(row, e)| e.vertex.map(|v| (target.id, row, v))); state.snap = cross_place(app).and_then(|at| edit::snap(app, at, moving)); @@ -1010,7 +1010,7 @@ fn edit_sheet( ui.label(RichText::new(says).size(14.0).color(t.text)); if action(ui, t, tl!("Pick Feature at Cross"), width, true, true) { match edit::feature_at_cross(app, target.id) { - Some(feature) => state.editing = Some(edit::Editing { feature, vertex: None }), + Some(feature) => state.editing = Some(edit::Editing::feature(feature)), None => app .session .notify(rustgis_ui_egui::i18n::fmt("No feature of {layer} is under the cross.", &[("layer", &target.name)]), true), @@ -1039,7 +1039,7 @@ fn edit_sheet( if action(ui, t, tl!("Pick Vertex at Cross"), width, !has, true) { let middle = app.map.view_rect.map(|(rect, _)| rect.center()); match middle.and_then(|at| edit::vertex_near(app, &shape, at)) { - Some(v) => state.editing = Some(edit::Editing { vertex: Some(v), ..editing }), + Some(v) => state.editing = Some(editing.picking(Some(v), Some(&shape))), None => app.session.notify(tl!("No vertex is near the cross. Move the map so the cross is on one."), true), } } @@ -1055,7 +1055,8 @@ fn edit_sheet( if act != "delete" && at.is_none() { app.session.notify(off(), true); } else if let Some(next) = edit::vertex(app, target.id, row, v, act, at) { - state.editing = Some(edit::Editing { vertex: next, ..editing }); + let now = edit::shape(app, target.id, row); + state.editing = Some(editing.picking(next, now.as_ref())); } } } @@ -1513,7 +1514,7 @@ mod tests { Form { shown: Some(rivers.instance), edit_mode: true, - editing: Some(edit::Editing { feature, vertex: Some(first) }), + editing: Some(edit::Editing::feature(feature).picking(Some(first), edit::shape(&app, rivers.id, row).as_ref())), ..Form::default() }, ); @@ -1599,6 +1600,25 @@ mod tests { assert!(add_point(&mut app, cities.id, &state)); } + #[test] + fn a_picked_vertex_an_undo_moved_or_took_away_is_let_go() { + use rustgis_ui_egui::rustgis_engine::data::{Coord, Geometry}; + let line = |points: &[(f64, f64)]| Geometry::Line(vec![points.iter().map(|(x, y)| Coord::new(*x, *y)).collect()]); + let abc = line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)]); + // B picked, then N added after it and picked: index 2 is N. + let with_n = line(&[(0.0, 0.0), (1.0, 0.0), (1.5, 1.0), (2.0, 0.0)]); + let picked = edit::Editing::feature(7).picking(Some(VertexId::new(0, 0, 2)), Some(&with_n)); + assert_eq!(picked.checked(Some(&with_n)), picked); + // Undone: index 2 is now C, elsewhere than N was: let go. + assert_eq!(picked.checked(Some(&abc)).vertex, None); + // N was the last vertex: the index is gone, and so is the pick. + let n_last = line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0)]); + let last = edit::Editing::feature(7).picking(Some(VertexId::new(0, 0, 3)), Some(&n_last)); + assert_eq!(last.checked(Some(&abc)).vertex, None); + // A vertex the shape doesn't have isn't picked at all. + assert_eq!(edit::Editing::feature(7).picking(Some(VertexId::new(0, 0, 9)), Some(&abc)).vertex, None); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); From 3016f5f0c15bc2ea3e1d76cc4809f14b9cb33030 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 04:03:06 -0500 Subject: [PATCH 10/18] fix(mobile): a track goes to a Tracks layer with its fields, is added to in place, drawn as one line, and its minutes can't overflow --- crates/ui-touch/src/lib.rs | 17 ++++++++---- crates/ui-touch/src/track.rs | 50 ++++++++++++++++++++++++++++++------ 2 files changed, 54 insertions(+), 13 deletions(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 2580a8386e..4867e79134 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -142,13 +142,20 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { // The track being recorded, as it grows. if let (Some(recording), Some((map, _))) = (track::field(&ctx).track, app.map.view_rect) { let painter = ui.painter().with_clip_rect(map); - let points: Vec> = recording.points.iter().map(|f| app.lonlat_to_screen(f.lon, f.lat)).collect(); - for pair in points.windows(2) { - if let [Some(a), Some(b)] = pair { - painter.line_segment([*a, *b], Stroke::new(5.0, Color32::WHITE)); - painter.line_segment([*a, *b], Stroke::new(3.0, t.green)); + // One line for each run of points the view shows (a point behind the globe breaks it), + // a point on the pixel of the last left out: hours of a track stay a few shapes. + let mut runs: Vec> = vec![Vec::new()]; + for at in recording.points.iter().map(|f| app.lonlat_to_screen(f.lon, f.lat)) { + match (at, runs.last_mut()) { + (Some(p), Some(run)) if run.last().is_none_or(|q| q.distance(p) >= 1.0) => run.push(p), + (Some(_), _) => {} + (None, _) => runs.push(Vec::new()), } } + for run in runs.into_iter().filter(|r| r.len() > 1) { + painter.add(egui::Shape::line(run.clone(), Stroke::new(5.0, Color32::WHITE))); + painter.add(egui::Shape::line(run, Stroke::new(3.0, t.green))); + } } if shown == Sheet::Capture && let Some((map, _)) = app.map.view_rect diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index 74db3f3d6c..b2d24b298c 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -51,7 +51,7 @@ impl Track { pub fn minutes(&self) -> Option { let first = self.points.first()?.time?; let last = self.points.last()?.time?; - Some((last - first).max(0) / 60_000) + Some(last.saturating_sub(first).max(0) / 60_000) } } @@ -78,7 +78,9 @@ pub(crate) fn take(app: &mut RustGisApp, ctx: &egui::Context) { if app.fixes.is_empty() { return; } - let mut state = field(ctx); + // Taken out of egui's memory while positions go in, so the points' `Arc` has one owner and + // `make_mut` adds to it in place instead of copying the track. + let mut state: Field = ctx.data_mut(|d| d.remove_temp(egui::Id::unique("touch_field"))).unwrap_or_default(); for fix in app.fixes.drain(..) { if let Some(fixes) = &mut state.averaging { Arc::make_mut(fixes).push(fix); @@ -195,16 +197,27 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { left_out(app); return false; } - app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", TRACKS), ("notes", ¬es)]), false); + let named = app.session.map().layer(layer).map_or_else(|| TRACKS.to_string(), |l| l.name.clone()); + app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", &named), ("notes", ¬es)]), false); left_out(app); true } -/// The map's Tracks layer: its line layer of that name, or one made for it (with a name and a -/// notes field). +/// The map's Tracks layer: its line layer of that name with a text `name` and `notes` field, or +/// one made for it with them. A Tracks layer without them is passed over: the track's name and +/// notes would be dropped from it. fn tracks_layer(app: &mut RustGisApp) -> Option { - use rustgis_ui_egui::rustgis_engine::data::GeometryType; - let found = app.session.map().layers.iter().find(|l| l.name == TRACKS && l.geometry_type() == GeometryType::Polyline).map(|l| l.id); + use rustgis_ui_egui::rustgis_engine::data::{FieldType, GeometryType}; + let has = |l: &rustgis_ui_egui::rustgis_engine::map::Layer, name: &str| { + l.dataset.fields.iter().any(|f| f.name.eq_ignore_ascii_case(name) && f.ty == FieldType::Text) + }; + let found = app + .session + .map() + .layers + .iter() + .find(|l| tracks_name(&l.name) && l.geometry_type() == GeometryType::Polyline && has(l, "name") && has(l, "notes")) + .map(|l| l.id); if found.is_some() { return found; } @@ -212,6 +225,13 @@ fn tracks_layer(app: &mut RustGisApp) -> Option { made.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) } +/// Whether a layer's name is a Tracks layer's: `Tracks`, or `Tracks (2)`… as one made beside +/// another is named. +fn tracks_name(name: &str) -> bool { + let numbered = name.strip_prefix(TRACKS).and_then(|n| n.strip_prefix(" (")).and_then(|n| n.strip_suffix(')')); + name == TRACKS || numbered.is_some_and(|n| n.parse::().is_ok()) +} + /// Milliseconds since 1970 as a date and time in UTC, to the minute (`2026-11-14 10:05Z`). fn stamp(ms: i64) -> Option { use rustgis_ui_egui::rustgis_engine::data::DateTime; @@ -268,6 +288,11 @@ mod tests { track.push(fix(1.2, 1.0, None, Some(600_000))); assert_eq!((track.points.len(), track.poor), (2, 1)); assert_eq!(track.minutes(), Some(10)); + // Times out of all measure don't overflow. + let wide = Track { points: Arc::new(vec![fix(0.0, 0.0, None, Some(i64::MAX)), fix(1.0, 0.0, None, Some(0))]), ..Track::default() }; + assert_eq!(wide.minutes(), Some(0)); + let wide = Track { points: Arc::new(vec![fix(0.0, 0.0, None, Some(0)), fix(1.0, 0.0, None, Some(i64::MAX))]), ..Track::default() }; + assert_eq!(wide.minutes(), Some(i64::MAX / 60_000)); assert_eq!(stamp(1_794_614_460_123).as_deref(), Some("2026-11-14 00:01Z")); } @@ -296,8 +321,17 @@ mod tests { let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("left out")), "{said:?}"); // A second goes to the same layer. - assert!(finish(&mut app, track)); + assert!(finish(&mut app, track.clone())); assert_eq!(app.session.map().layers.iter().filter(|l| l.name == TRACKS).count(), 1); + // A Tracks layer without the fields is passed over: one with them is made. + let tracks = app.session.map().layers.iter().find(|l| l.name == TRACKS).map(|l| l.id).unwrap(); + app.run_by_user("edit.deleteField", json!({"layer": tracks, "field": "notes"})).unwrap(); + assert!(finish(&mut app, track.clone())); + assert_eq!(app.session.map().layers.iter().filter(|l| tracks_name(&l.name)).count(), 2); + // And it is the one the next track goes to. + assert!(finish(&mut app, track)); + assert_eq!(app.session.map().layers.iter().filter(|l| tracks_name(&l.name)).count(), 2); + assert!(tracks_name("Tracks (2)") && !tracks_name("Tracks of deer") && !tracks_name("My Tracks")); // Too short: nothing, said as an error. let mark = app.session.notice_mark(); assert!(!finish(&mut app, Track { points: Arc::new(vec![fix(1.0, 1.0, None, None)]), ..Track::default() })); From c4fc886aa335243ce98b767c124e32ffcc5d0482 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 04:51:31 -0500 Subject: [PATCH 11/18] fix(mobile): a calendar closes when its field is narrowed to chips, and its days are a finger tall --- apps/rustgis-mobile/README.md | 2 +- crates/ui-touch/src/form.rs | 3 ++- crates/ui-touch/src/lib.rs | 16 ++++++++++++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 316e7e73fe..77815ccf78 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -97,7 +97,7 @@ feature with it empty, and no default for it from the template or subtype chosen sheet names the fields to fill in. A field in a contingent value set offers only the values that fit what the set's other fields hold, as chips (a value chosen before the others changed stays, so the conflict shows). A date or date and time field has a calendar button: a month of days a -finger's width each, with **Today** (in UTC; the phone's time zone isn't asked) and, for a date and +finger tall each, with **Today** (in UTC; the phone's time zone isn't asked) and, for a date and time, **Now**. While a field is typed in, the sheet takes most of the window and stays above the soft keyboard: diff --git a/crates/ui-touch/src/form.rs b/crates/ui-touch/src/form.rs index 62c623d879..50724c12d4 100644 --- a/crates/ui-touch/src/form.rs +++ b/crates/ui-touch/src/form.rs @@ -171,7 +171,8 @@ pub(crate) fn calendar(ui: &mut Ui, t: &Tokens, month: &mut Month, text: &mut St let width = ui.available_width(); let gap = ui.spacing().item_spacing.x; let cell = ((width - 6.0 * gap) / 7.0).max(1.0); - let height = super::TARGET - 8.0; + // A finger's height; the width is what seven columns leave (about 42 points on a narrow phone). + let height = super::TARGET; let mut picked = false; ui.horizontal(|ui| { if ui.add(egui::Button::new(RichText::new("‹").size(20.0)).min_size(Vec2::new(super::TARGET, height))).clicked() { diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 103c752408..0c072313a6 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -829,7 +829,7 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // A list narrowed by the contingent values: what the domain lists and the sets leave, // or, with no list of its own, the values the sets leave. The value chosen stays, // marked, even when the others no longer fit it, so the conflict shows. - let list = match (list, left.as_ref()) { + let list: Option> = match (list, left.as_ref()) { (Some(list), Some(left)) => Some(list.into_iter().filter(|(stored, _)| left.contains(stored)).collect()), (None, Some(left)) => { let said = described.get(i).cloned().flatten().unwrap_or_default(); @@ -839,6 +839,7 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } (list, None) => list, }; + let chosen_from_list = list.is_some(); let dated = matches!(field.ty, FieldType::Date | FieldType::DateTime); ui.horizontal(|ui| { ui.set_min_height(TARGET); @@ -895,7 +896,11 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } } }); - // The calendar, under its field, while it is open. + // The calendar, under its field, while it is open and the field is typed into: a field + // the contingent values narrowed to chips (its toggle gone) closes it. + if chosen_from_list && state.calendar.as_ref().is_some_and(|(name, _)| name == &field.name) { + state.calendar = None; + } if let Some((name, month)) = state.calendar.as_mut().filter(|(name, _)| name == &field.name) { let name = name.clone(); let value = state.values.entry(name).or_default(); @@ -1319,8 +1324,15 @@ mod tests { let set = json!({"layer": cities.id, "name": "pair", "fields": [text, number], "combos": [["Camp", 1], ["Town", 2]]}); run(&mut app, "data.contingentValues", set); assert_eq!(form::contingent(app.session.map().layer(cities.id).unwrap(), &text, &state.values).map(|v| v.len()), Some(2)); + // A calendar open on a field the contingent values narrow to chips closes: its toggle is + // gone with the text box. set_form(&ctx, Form { shown: Some(cities.instance), calendar: Some((text, (2026, 3))), ..Form::default() }); frame(&mut app, &ctx, Sheet::Capture); + assert!(form(&ctx).calendar.is_none()); + // On a date field typed into, it stays open and draws. + run(&mut app, "edit.addField", json!({"layer": cities.id, "name": "seen", "type": "date"})); + set_form(&ctx, Form { shown: Some(cities.instance), calendar: Some(("seen".into(), (2026, 3))), ..Form::default() }); + frame(&mut app, &ctx, Sheet::Capture); assert!(form(&ctx).calendar.is_some()); } From 53603e869e2294818c24a2f8d31899688befef04 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 04:52:24 -0500 Subject: [PATCH 12/18] fix(mobile): Move Point Here refuses a multipoint, which it would move only part of --- crates/ui-touch/src/edit.rs | 13 +++++++++++++ crates/ui-touch/src/lib.rs | 21 +++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ui-touch/src/edit.rs b/crates/ui-touch/src/edit.rs index 17ad85b9f3..45de2751c6 100644 --- a/crates/ui-touch/src/edit.rs +++ b/crates/ui-touch/src/edit.rs @@ -151,6 +151,19 @@ pub(crate) fn vertex( Some(Some(VertexId::new(read("part")?, read("ring")?, read("index")?))) } +/// Moves the point in row `row` of layer `id` to `at`. A multipoint isn't moved, and that is said: +/// its points can't be moved one at a time by touch, and moving its first would leave the rest. +/// Says whether it moved. +pub(crate) fn move_point(app: &mut RustGisApp, id: u32, row: usize, at: (f64, f64)) -> bool { + match shape(app, id, row) { + Some(Geometry::Point(_)) => vertex(app, id, row, VertexId::new(0, 0, 0), "move", Some(at)).is_some(), + _ => { + app.session.notify(tl!("Nothing was moved: only a single point moves here, not a multipoint's points."), true); + false + } + } +} + /// Deletes the feature in row `row` of layer `id`, as one edit that undoes. Says whether it was. /// The map's selections are set aside while it is (Delete takes every layer's selection) and /// put back after, the rows of layer `id` past it moved up one. diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 3951dea292..7ad572f2e6 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -1033,8 +1033,7 @@ fn edit_sheet( if action(ui, t, tl!("Move Point Here"), width, true, true) { match cross { Some(at) => { - let first = VertexId::new(0, 0, 0); - let _ = edit::vertex(app, target.id, row, first, "move", Some(at)); + edit::move_point(app, target.id, row, at); } None => app.session.notify(off(), true), } @@ -1631,6 +1630,24 @@ mod tests { assert_eq!(edit::Editing::feature(7).picking(Some(VertexId::new(0, 0, 9)), Some(&abc)).vertex, None); } + #[test] + fn move_point_here_moves_a_point_and_refuses_a_multipoint() { + let mut app = RustGisApp::with_sample(); + let cities = target(&mut app, GeometryType::Point); + assert!(edit::move_point(&mut app, cities.id, 0, (12.0, 34.0))); + let moved = app.session.map().layer(cities.id).unwrap().dataset.features[0].geometry.clone(); + assert!(matches!(moved, Some(rustgis_ui_egui::rustgis_engine::data::Geometry::Point(c)) if c.x == 12.0 && c.y == 34.0)); + // A multipoint in a point layer: nothing moves, and that is said. + let multi = json!({"layer": cities.id, "geometry": {"type": "MultiPoint", "coordinates": [[1.0, 1.0], [2.0, 2.0]]}}); + run(&mut app, "edit.addFeature", multi); + let row = count(&app, cities.id) - 1; + let before = app.session.map().layer(cities.id).unwrap().dataset.features[row].geometry.clone(); + let mark = app.session.notice_mark(); + assert!(!edit::move_point(&mut app, cities.id, row, (5.0, 5.0))); + assert_eq!(app.session.map().layer(cities.id).unwrap().dataset.features[row].geometry, before); + assert!(app.session.notices_since(mark).iter().any(|n| n.error && n.text.contains("multipoint"))); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); From c40e715b0c890d81c75e8dd48f7b3ca2de5de2f1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 04:52:43 -0500 Subject: [PATCH 13/18] fix(mobile): import VertexId where it is used --- crates/ui-touch/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 7ad572f2e6..ac9ac85b06 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -386,7 +386,7 @@ fn set_form(ctx: &egui::Context, form: Form) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique("touch_capture"), form)); } -use rustgis_ui_egui::rustgis_engine::data::{GeometryType, VertexId}; +use rustgis_ui_egui::rustgis_engine::data::GeometryType; /// A layer a feature can be captured into. #[derive(Clone)] @@ -1149,6 +1149,7 @@ fn run(app: &mut RustGisApp, command: &str, params: Value) { #[cfg(test)] mod tests { use super::*; + use rustgis_ui_egui::rustgis_engine::data::VertexId; /// Draws a frame of the interface for a phone's window with `shown` up. fn frame(app: &mut RustGisApp, ctx: &egui::Context, shown: Sheet) { From 8a2c7782c70fe402d8be51be15fa4221bc43fea9 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 04:55:17 -0500 Subject: [PATCH 14/18] fix(mobile): a Tracks layer needs its fields by their exact names, and the desktop interface adds a track being recorded first --- crates/ui-touch/src/lib.rs | 21 +++++++++++++++++++++ crates/ui-touch/src/track.rs | 22 +++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 0a8febc255..cd5d07447d 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -1236,6 +1236,8 @@ fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // button for yet. The Project page's Start brings this interface back at the next start. if row(ui, t, "pane", tl!("Use the Desktop Interface")) { set_sheet(ui.ctx(), Sheet::None); + // A track being recorded is added before the bar that stops it goes away. + stop_track(app, &ctx); app.chrome = None; app.session.notify(tl!("The desktop interface is on until RustGIS is started again."), false); } @@ -1788,6 +1790,25 @@ mod tests { assert!(app.session.notices_since(mark).iter().any(|n| n.error && n.text.contains("multipoint"))); } + #[test] + fn the_desktop_interface_adds_the_track_being_recorded_first() { + use rustgis_ui_egui::rustgis_engine::platform::Fix; + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + start_track(&mut app, &ctx); + for i in 0..3 { + app.report_position(Fix { lon: 10.0 + f64::from(i) * 0.01, lat: 5.0, accuracy: Some(3.0), time: Some(i64::from(i) * 1000) }); + } + frame(&mut app, &ctx, Sheet::None); + // As the More sheet's row does: the track is added, then the interface goes. + let mut state = track::field(&ctx); + assert_eq!(state.track.as_ref().map(|t| t.points.len()), Some(3)); + stop_track(&mut app, &ctx); + state = track::field(&ctx); + assert!(state.track.is_none()); + assert!(app.session.map().layers.iter().any(|l| l.name == track::TRACKS && l.dataset.features.len() == 1)); + } + #[test] fn what_is_typed_for_one_layer_is_dropped_for_another() { let mut state = Form::default().for_layer(1); diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index b2d24b298c..52555b5aa4 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -209,7 +209,8 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { fn tracks_layer(app: &mut RustGisApp) -> Option { use rustgis_ui_egui::rustgis_engine::data::{FieldType, GeometryType}; let has = |l: &rustgis_ui_egui::rustgis_engine::map::Layer, name: &str| { - l.dataset.fields.iter().any(|f| f.name.eq_ignore_ascii_case(name) && f.ty == FieldType::Text) + // By its exact name: `edit.addFeature` stores an attribute under the field of that name. + l.dataset.fields.iter().any(|f| f.name == name && f.ty == FieldType::Text) }; let found = app .session @@ -280,6 +281,25 @@ mod tests { assert!(d.lon.abs() > 179.99, "{d:?}"); } + #[test] + fn a_tracks_layer_whose_fields_are_named_otherwise_is_passed_over() { + let mut app = RustGisApp::with_sample(); + // A user's own Tracks layer, its fields `Name` and `Notes`. + let made = app.run_by_user("layer.template", json!({"template": "lines", "name": TRACKS})).unwrap(); + let theirs = made["layer"].as_u64().unwrap() as u32; + for (old, new) in [("name", "Name"), ("notes", "Notes")] { + app.run_by_user("edit.deleteField", json!({"layer": theirs, "field": old})).unwrap(); + app.run_by_user("edit.addField", json!({"layer": theirs, "name": new, "type": "text"})).unwrap(); + } + let track = Track { points: Arc::new(vec![fix(1.0, 1.0, None, Some(0)), fix(1.1, 1.0, None, Some(60_000))]), ..Track::default() }; + assert!(finish(&mut app, track)); + // Not theirs: a layer of its own, holding the track's name. + assert!(app.session.map().layer(theirs).unwrap().dataset.features.is_empty()); + let ours = app.session.map().layers.iter().find(|l| l.id != theirs && tracks_name(&l.name)).unwrap(); + let name = ours.dataset.field_index("name").unwrap(); + assert!(ours.dataset.value(0, name).to_string().starts_with("Track")); + } + #[test] fn a_track_leaves_out_poor_positions_and_counts_them() { let mut track = Track::default(); From b8053e37316a345577a9b854a9c4a714c9f9afe7 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 09:06:55 -0500 Subject: [PATCH 15/18] Address Claude review feedback - Tapping Edit keeps the vertices drawn so far in Add, instead of dropping them without a word; they are drawn only while Add is on. - Move Here and Add After refuse, and say why, a place on the vertex next to the picked one (a snapped cross lands there), which would make an edge of no length; tested both ways. - The edited feature's shape is borrowed, not cloned, where it is drawn and checked each frame; status lists the vertices once; snapping is looked for again only when the cross, the zoom, the vertex being moved or the project changed. --- crates/ui-touch/src/edit.rs | 31 ++++++++++++++-- crates/ui-touch/src/lib.rs | 71 ++++++++++++++++++++++++++++++++----- 2 files changed, 91 insertions(+), 11 deletions(-) diff --git a/crates/ui-touch/src/edit.rs b/crates/ui-touch/src/edit.rs index 45de2751c6..5a6a8e5981 100644 --- a/crates/ui-touch/src/edit.rs +++ b/crates/ui-touch/src/edit.rs @@ -64,7 +64,31 @@ pub(crate) fn row_of(app: &RustGisApp, id: u32, feature: u64) -> Option { /// The shape of the feature in row `row` of layer `id`. pub(crate) fn shape(app: &RustGisApp, id: u32, row: usize) -> Option { - app.session.map().layer(id)?.dataset.features.get(row)?.geometry.clone() + shape_ref(app, id, row).cloned() +} + +/// [`shape`], borrowed: what is drawn and checked each frame isn't copied for it. +pub(crate) fn shape_ref(app: &RustGisApp, id: u32, row: usize) -> Option<&Geometry> { + app.session.map().layer(id)?.dataset.features.get(row)?.geometry.as_ref() +} + +/// Whether putting vertex `v` of `shape` at `at` (`move`), or a new one there after it +/// (`insert`), would leave two vertices in one place in a row: on the screen, within a point of +/// each other. The edge between them would have no length, which the capture draft refuses too. +pub(crate) fn doubles(app: &RustGisApp, shape: &Geometry, v: VertexId, action: &str, at: (f64, f64)) -> bool { + let edges = shape.edges(); + let ring = matches!(shape, Geometry::Polygon(_)); + let mine = || edges.iter().filter(|e| e.0.part == v.part && e.0.ring == v.ring); + let count = mine().count(); + let after = mine().find(|e| e.0 == v).map(|e| e.2); + let before = mine().find(|e| e.0.index + 1 == v.index || (ring && v.index == 0 && e.0.index + 1 == count)).map(|e| e.1); + let near = match action { + "move" => [before, after], + "insert" => [shape.vertex(v), after], + _ => return false, + }; + let Some(cross) = app.lonlat_to_screen(at.0, at.1) else { return false }; + near.into_iter().flatten().filter_map(|c| app.lonlat_to_screen(c.x, c.y)).any(|p| p.distance(cross) < 1.0) } /// The feature of layer `id` drawn on top under the cross (within [`REACH`]), by its id. @@ -218,10 +242,11 @@ pub(crate) fn status(kind: GeometryType, shape: &Geometry, picked: Option i18n::fmt( "Vertex {n} of {all} picked: move the map to where it goes, then Move Here. Add After puts a new vertex at the cross after it.", - &[("n", &(n + 1).to_string()), ("all", &shape.vertices().len().to_string())], + &[("n", &(n + 1).to_string()), ("all", &vertices.len().to_string())], ), None => tl!("Put the cross on a vertex and pick it.").to_string(), } diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index ac9ac85b06..dc8f9a13f9 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -113,14 +113,17 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { && let Some((map, _)) = app.map.view_rect { let painter = ui.painter().with_clip_rect(map); - sketch(app, &painter, map.center(), &t, &ctx); - // The feature being edited, and where the cross snapped to. + // The shape being drawn, kept while Edit is on but drawn only in Add; the feature + // being edited, and where the cross snapped to. let state = form(&ctx); + if !state.edit_mode { + sketch(app, &painter, map.center(), &t, &ctx); + } if state.edit_mode && let (Some(target), Some(editing)) = (capture_layer(app, &state), state.editing) - && let Some(shape) = edit::row_of(app, target.id, editing.feature).and_then(|row| edit::shape(app, target.id, row)) + && let Some(shape) = edit::row_of(app, target.id, editing.feature).and_then(|row| edit::shape_ref(app, target.id, row)) { - edit::draw(app, &painter, &shape, editing.vertex, &t); + edit::draw(app, &painter, shape, editing.vertex, &t); } if let Some(snapped) = state.snap { edit::draw_snap(app, &painter, snapped, map.center(), &t); @@ -341,6 +344,9 @@ struct Form { editing: Option, /// Where the cross's place snapped to on the last frame, with snapping on. snap: Option, + /// What [`Form::snap`] was found for: it is looked for again only when the cross moved, the + /// map zoomed, the vertex being moved changed or the project did. + snap_for: Option, /// The height of the window the sheet was last drawn in: when it changes (the soft keyboard /// came or went), the field being typed in is scrolled back into view. window: f32, @@ -358,6 +364,7 @@ impl Form { self.calendar = None; self.editing = None; self.snap = None; + self.snap_for = None; self.shown = Some(instance); } self @@ -378,6 +385,17 @@ impl Form { } } +/// What the cross's place was snapped for: its place, the vertex being moved, the project's state, +/// the map's resolution and whether snapping was on. +#[derive(Clone, Copy, Debug, PartialEq)] +struct SnapFor { + at: Option<(f64, f64)>, + moving: Option<(u32, usize, rustgis_ui_egui::rustgis_engine::data::VertexId)>, + state: u64, + res: f64, + on: bool, +} + fn form(ctx: &egui::Context) -> Form { ctx.data(|d| d.get_temp(egui::Id::unique("touch_capture"))).unwrap_or_default() } @@ -748,12 +766,20 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // The feature being edited, while it is still there (an undo may have taken it away). let picked = state.editing.and_then(|e| edit::row_of(app, target.id, e.feature).map(|row| (row, e))); // A picked vertex an Undo moved or took away is let go. - let picked = picked.map(|(row, e)| (row, e.checked(edit::shape(app, target.id, row).as_ref()))); + let picked = picked.map(|(row, e)| (row, e.checked(edit::shape_ref(app, target.id, row)))); state.editing = picked.map(|(_, e)| e); // The cross's place, snapped with snapping on: a vertex being moved doesn't snap to itself. let moving = picked.filter(|_| state.edit_mode).and_then(|(row, e)| e.vertex.map(|v| (target.id, row, v))); - state.snap = cross_place(app).and_then(|at| edit::snap(app, at, moving)); - let cross = state.snap.map(|s| (s.lon, s.lat)).or_else(|| cross_place(app)); + // Snapping looks through every visible layer, so it is done again only when what it depends + // on changed, not on every frame. + let at = cross_place(app); + let map = app.session.map(); + let wants = SnapFor { at, moving, state: app.session.state(), res: map.camera.res, on: map.editing.snapping.enabled }; + if state.snap_for != Some(wants) { + state.snap = at.and_then(|at| edit::snap(app, at, moving)); + state.snap_for = Some(wants); + } + let cross = state.snap.map(|s| (s.lon, s.lat)).or(at); // The buttons stay in reach above the fields, however many the layer has. let place = match (cross, state.snap) { (Some((lon, lat)), Some(snapped)) => rustgis_ui_egui::i18n::fmt( @@ -780,9 +806,9 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { state.edit_mode = false; state.editing = None; } + // The vertices drawn so far are kept for Add to go on with. if toggle_chip(ui, t, tl!("Edit"), third, state.edit_mode) { state.edit_mode = true; - state.vertices.clear(); } let snapping = app.session.map().editing.snapping.enabled; if toggle_chip(ui, t, tl!("Snap"), third, snapping) { @@ -1058,6 +1084,11 @@ fn edit_sheet( let at = if act == "delete" { None } else { cross }; if act != "delete" && at.is_none() { app.session.notify(off(), true); + } else if at.is_some_and(|at| edit::doubles(app, &shape, v, act, at)) { + app.session.notify( + tl!("Nothing was changed: the cross is on the vertex next to it, and two in one place make an edge of no length. Move the map."), + true, + ); } else if let Some(next) = edit::vertex(app, target.id, row, v, act, at) { let now = edit::shape(app, target.id, row); state.editing = Some(editing.picking(next, now.as_ref())); @@ -1494,6 +1525,30 @@ mod tests { assert!(form(&ctx).calendar.is_some()); } + #[test] + fn a_vertex_put_on_the_one_next_to_it_is_found_and_a_place_apart_is_not() { + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + let rivers = target(&mut app, GeometryType::Polyline); + let shape = app.session.map().layer(rivers.id).unwrap().dataset.features[0].geometry.clone().unwrap(); + let vertices = shape.vertices(); + let ((first, a), (second, b), (_, c)) = (vertices[0], vertices[1], vertices[2]); + run(&mut app, "map.goToXY", json!({"lon": b.x, "lat": b.y, "scale": 50_000})); + frame(&mut app, &ctx, Sheet::Capture); + // Moved onto the vertex before or after it, or one added after it on itself or the next. + assert!(edit::doubles(&app, &shape, second, "move", (a.x, a.y))); + assert!(edit::doubles(&app, &shape, second, "move", (c.x, c.y))); + assert!(edit::doubles(&app, &shape, second, "insert", (b.x, b.y))); + assert!(edit::doubles(&app, &shape, second, "insert", (c.x, c.y))); + assert!(edit::doubles(&app, &shape, first, "insert", (b.x, b.y))); + // A place between them is fine, and so is moving a vertex where it already is. + let between = ((b.x + c.x) / 2.0, (b.y + c.y) / 2.0); + assert!(!edit::doubles(&app, &shape, second, "move", between)); + assert!(!edit::doubles(&app, &shape, second, "insert", between)); + assert!(!edit::doubles(&app, &shape, second, "move", (b.x, b.y))); + assert!(!edit::doubles(&app, &shape, second, "delete", (a.x, a.y))); + } + #[test] fn a_feature_under_the_cross_is_picked_and_its_vertices_moved_inserted_and_deleted() { let ctx = egui::Context::default(); From 94e25ce2fdfc817e9f0ee610875d4c9ca1186777 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 09:43:28 -0500 Subject: [PATCH 16/18] Address review feedback - A track that can't be added (editing or the layer refused it) is kept being recorded and said, so Stop tries again instead of losing its positions; the desktop interface isn't switched to while it is kept; tested. - Positions dropped past FIXES_KEPT are counted and said when a track or an average missed them; tested. - The More sheet is sized for the track's row while a track is recorded with positioning off. - Typing in a sheet the keyboard leaves short (a phone held sideways), the rows above the capture fields step aside until the keyboard goes, so the field stays in sight. --- crates/ui-egui/src/lib.rs | 5 + crates/ui-touch/src/lib.rs | 222 +++++++++++++++++++++++------------ crates/ui-touch/src/track.rs | 54 +++++---- 3 files changed, 181 insertions(+), 100 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 338c411c29..aa931c702c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1125,6 +1125,7 @@ impl RustGisApp { self.position = Some(fix); if self.fixes.len() >= FIXES_KEPT { self.fixes.pop_front(); + self.fixes_dropped += 1; } self.fixes.push_back(fix); } @@ -1166,6 +1167,9 @@ pub struct RustGisApp { /// or an average needs each, including those that arrived together after the app was out of /// sight. pub fixes: std::collections::VecDeque, + /// How many positions were dropped from [`RustGisApp::fixes`] past [`FIXES_KEPT`] since an + /// interface last took them: the interface says so when a track or an average missed them. + pub fixes_dropped: usize, /// Watches linked local files for changes made outside RustGIS and offers Reload Data /// (the desktop app; see [`diskwatch`]). Off for tests, unless one turns it on (as `ui_shot`'s /// `watchFiles` does). @@ -1436,6 +1440,7 @@ impl RustGisApp { locate: false, position: None, fixes: std::collections::VecDeque::new(), + fixes_dropped: 0, #[cfg(not(target_arch = "wasm32"))] watch_files: false, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index db68c1ddda..eac358a650 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -36,6 +36,9 @@ const SHEET_SHARE: f32 = 0.55; /// The most a sheet takes while the soft keyboard is wanted: what is typed in matters more than /// the map then, and the keyboard has taken much of the window. const TYPING_SHARE: f32 = 0.9; +/// Below this many rows of room for the Capture sheet's body while a field is typed in, the rows +/// above its fields step aside so the field stays in sight. +const CROWDED_ROWS: f32 = 7.0; /// The room above and below a sheet's rows. const SHEET_MARGIN: f32 = 4.0; /// The More sheet's rows with the position hidden. @@ -112,7 +115,18 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { let rows = match shown { Sheet::Layers => (app.session.map().layers.len() + app.session.map().tiles.len()).max(1), // Go to My Position is there only while the position is shown. - Sheet::More => MORE_ROWS + if app.locate { MORE_POSITION_ROWS } else { 0 }, + // The position rows while it is shown; the track's row alone while one is recorded + // with it off. + Sheet::More => { + MORE_ROWS + + if app.locate { + MORE_POSITION_ROWS + } else if track::field(&ctx).track.is_some() { + 1 + } else { + 0 + } + } Sheet::Capture => capture_rows(app, &ctx), Sheet::None => 0, }; @@ -190,13 +204,19 @@ fn start_track(app: &mut RustGisApp, ctx: &egui::Context) { app.session.notify(tl!("Recording a track: its positions are drawn on the map. Stop adds it to the Tracks layer."), false); } -/// Stops the track being recorded and adds it to the map. -fn stop_track(app: &mut RustGisApp, ctx: &egui::Context) { +/// Stops the track being recorded and adds it to the map. A track that couldn't be added is kept +/// being recorded, and that is said, so its positions aren't lost: Stop tries again. Says whether +/// no track is being recorded now. +fn stop_track(app: &mut RustGisApp, ctx: &egui::Context) -> bool { let mut state = track::field(ctx); - if let Some(recorded) = state.track.take() { - track::set_field(ctx, state); - track::finish(app, recorded); - } + let Some(recorded) = state.track.take() else { return true }; + track::set_field(ctx, state); + let Err(kept) = track::finish(app, recorded) else { return true }; + let mut state = track::field(ctx); + state.track = Some(kept); + track::set_field(ctx, state); + app.session.notify(tl!("The track is kept and still recorded: Stop tries to add it again."), true); + false } /// Draws where the device is: a dot, in a ring as wide as the position is good to. @@ -847,82 +867,92 @@ fn capture(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { state.snap_for = Some(wants); } let cross = state.snap.map(|s| (s.lon, s.lat)).or(at); - // The buttons stay in reach above the fields, however many the layer has. - let place = match (cross, state.snap) { - (Some((lon, lat)), Some(snapped)) => rustgis_ui_egui::i18n::fmt( - "At the cross, {snapped}: {lon}, {lat}", - &[("snapped", edit::snapped_to(snapped.kind)), ("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))], - ), - (Some((lon, lat)), None) => { - rustgis_ui_egui::i18n::fmt("At the cross: {lon}, {lat}", &[("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))]) - } - (None, _) => tl!("The cross is off the map: move the map under it.").to_string(), - }; - ui.label(RichText::new(place).size(13.0).color(t.text_dim)); - let width = ui.available_width(); - // With the device's position shown, one tap puts the cross on it; or the positions that come - // while Average runs are averaged, and Use Average puts the cross on their average. - if app.locate { - position_buttons(app, ui, t, &ctx, width); - } - // Add or Edit, and Snap. - ui.horizontal(|ui| { - ui.set_min_height(TARGET); - let gap = ui.spacing().item_spacing.x; - let third = (width - 2.0 * gap) / 3.0; - if toggle_chip(ui, t, tl!("Add"), third, !state.edit_mode) { - state.edit_mode = false; - state.editing = None; - } - // The vertices drawn so far are kept for Add to go on with. - if toggle_chip(ui, t, tl!("Edit"), third, state.edit_mode) { - state.edit_mode = true; - } - let snapping = app.session.map().editing.snapping.enabled; - if toggle_chip(ui, t, tl!("Snap"), third, snapping) { - run(app, "edit.snapping", json!({"on": !snapping})); - } - }); - if state.edit_mode { - edit_sheet(app, ui, t, &target, &mut state, picked, cross, width); - } else if target.kind == GeometryType::Point { - if action(ui, t, tl!("Add Point Here"), width, true, true) && fresh && add_point(app, target.id, &state) { - state.values.clear(); - } + // Typing in a window the soft keyboard leaves short (a phone held sideways), the rows above + // the fields would take all of it and hide the field: they step aside until the keyboard + // goes. + let crowded = ctx.egui_wants_keyboard_input() && ui.available_height() < CROWDED_ROWS * TARGET; + if crowded { + ui.label(RichText::new(tl!("Close the keyboard for the buttons.")).size(13.0).color(t.text_dim)); } else { - let placed = state.vertices.len(); - // Enough, once the vertices make the layer's kind of shape. - let enough = geometry(target.kind, &state.vertices).is_some(); - if action(ui, t, tl!("Add Vertex Here"), width, !enough, true) { - match cross { - Some(at) if state.place(at) => {} - Some(_) => app.session.notify(tl!("No vertex was added: the cross is where the last one is. Move the map under it."), true), - None => app.session.notify(tl!("No vertex was added: the cross is off the map. Move the map under it."), true), + // The buttons stay in reach above the fields, however many the layer has. + let place = match (cross, state.snap) { + (Some((lon, lat)), Some(snapped)) => rustgis_ui_egui::i18n::fmt( + "At the cross, {snapped}: {lon}, {lat}", + &[("snapped", edit::snapped_to(snapped.kind)), ("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))], + ), + (Some((lon, lat)), None) => { + rustgis_ui_egui::i18n::fmt("At the cross: {lon}, {lat}", &[("lon", &format!("{lon:.6}")), ("lat", &format!("{lat:.6}"))]) } + (None, _) => tl!("The cross is off the map: move the map under it.").to_string(), + }; + ui.label(RichText::new(place).size(13.0).color(t.text_dim)); + let width = ui.available_width(); + // With the device's position shown, one tap puts the cross on it; or the positions that come + // while Average runs are averaged, and Use Average puts the cross on their average. + if app.locate { + position_buttons(app, ui, t, &ctx, width); } + // Add or Edit, and Snap. ui.horizontal(|ui| { + ui.set_min_height(TARGET); let gap = ui.spacing().item_spacing.x; let third = (width - 2.0 * gap) / 3.0; - if action(ui, t, tl!("Undo Vertex"), third, false, placed > 0) { - state.vertices.pop(); + if toggle_chip(ui, t, tl!("Add"), third, !state.edit_mode) { + state.edit_mode = false; + state.editing = None; } - if action(ui, t, tl!("Start Over"), third, false, placed > 0) { - state.vertices.clear(); + // The vertices drawn so far are kept for Add to go on with. + if toggle_chip(ui, t, tl!("Edit"), third, state.edit_mode) { + state.edit_mode = true; } - // Finish is the one to tap once the shape has enough vertices. - let finish = match target.kind { - GeometryType::Polygon => tl!("Finish Polygon"), - _ => tl!("Finish Line"), - }; - if action(ui, t, finish, third, enough, enough) - && fresh - && let Some(shape) = geometry(target.kind, &state.vertices) - && add_feature(app, target.id, &state, shape) - { - state.values.clear(); - state.vertices.clear(); + let snapping = app.session.map().editing.snapping.enabled; + if toggle_chip(ui, t, tl!("Snap"), third, snapping) { + run(app, "edit.snapping", json!({"on": !snapping})); } }); + if state.edit_mode { + edit_sheet(app, ui, t, &target, &mut state, picked, cross, width); + } else if target.kind == GeometryType::Point { + if action(ui, t, tl!("Add Point Here"), width, true, true) && fresh && add_point(app, target.id, &state) { + state.values.clear(); + } + } else { + let placed = state.vertices.len(); + // Enough, once the vertices make the layer's kind of shape. + let enough = geometry(target.kind, &state.vertices).is_some(); + if action(ui, t, tl!("Add Vertex Here"), width, !enough, true) { + match cross { + Some(at) if state.place(at) => {} + Some(_) => { + app.session.notify(tl!("No vertex was added: the cross is where the last one is. Move the map under it."), true) + } + None => app.session.notify(tl!("No vertex was added: the cross is off the map. Move the map under it."), true), + } + } + ui.horizontal(|ui| { + let gap = ui.spacing().item_spacing.x; + let third = (width - 2.0 * gap) / 3.0; + if action(ui, t, tl!("Undo Vertex"), third, false, placed > 0) { + state.vertices.pop(); + } + if action(ui, t, tl!("Start Over"), third, false, placed > 0) { + state.vertices.clear(); + } + // Finish is the one to tap once the shape has enough vertices. + let finish = match target.kind { + GeometryType::Polygon => tl!("Finish Polygon"), + _ => tl!("Finish Line"), + }; + if action(ui, t, finish, third, enough, enough) + && fresh + && let Some(shape) = geometry(target.kind, &state.vertices) + && add_feature(app, target.id, &state, shape) + { + state.values.clear(); + state.vertices.clear(); + } + }); + } } let edit_mode = state.edit_mode; egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| { @@ -1267,10 +1297,12 @@ fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // button for yet. The Project page's Start brings this interface back at the next start. if row(ui, t, "pane", tl!("Use the Desktop Interface")) { set_sheet(ui.ctx(), Sheet::None); - // A track being recorded is added before the bar that stops it goes away. - stop_track(app, &ctx); - app.chrome = None; - app.session.notify(tl!("The desktop interface is on until RustGIS is started again."), false); + // A track being recorded is added before the bar that stops it goes away; one that + // couldn't be keeps this interface, which can still stop it. + if stop_track(app, &ctx) { + app.chrome = None; + app.session.notify(tl!("The desktop interface is on until RustGIS is started again."), false); + } } }); } @@ -1845,6 +1877,42 @@ mod tests { assert!(app.session.notices_since(mark).iter().any(|n| n.error && n.text.contains("multipoint"))); } + #[test] + fn a_track_that_cant_be_added_is_kept_being_recorded() { + use rustgis_ui_egui::rustgis_engine::platform::Fix; + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + start_track(&mut app, &ctx); + // A position the line can't hold makes the layer refuse the track. + for lon in [f64::NAN, 10.0, 10.01] { + app.report_position(Fix { lon, lat: 5.0, accuracy: Some(3.0), time: None }); + } + frame(&mut app, &ctx, Sheet::None); + let mark = app.session.notice_mark(); + assert!(!stop_track(&mut app, &ctx)); + assert_eq!(track::field(&ctx).track.map(|t| t.points.len()), Some(3)); + assert!(app.session.notices_since(mark).iter().any(|n| n.error && n.text.contains("kept"))); + // The More sheet has room for its row while positioning is off. + app.locate = false; + frame(&mut app, &ctx, Sheet::More); + assert!(track::field(&ctx).track.is_some()); + } + + #[test] + fn positions_dropped_past_the_cap_are_said_while_a_track_is_recorded() { + use rustgis_ui_egui::rustgis_engine::platform::Fix; + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + start_track(&mut app, &ctx); + for i in 0..rustgis_ui_egui::FIXES_KEPT + 5 { + app.report_position(Fix { lon: 10.0, lat: 5.0, accuracy: Some(3.0), time: i64::try_from(i).ok() }); + } + let mark = app.session.notice_mark(); + frame(&mut app, &ctx, Sheet::None); + assert!(app.session.notices_since(mark).iter().any(|n| n.text.starts_with("5 of the oldest positions"))); + assert_eq!(app.fixes_dropped, 0); + } + #[test] fn the_desktop_interface_adds_the_track_being_recorded_first() { use rustgis_ui_egui::rustgis_engine::platform::Fix; diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index 52555b5aa4..e765c5eee0 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -81,6 +81,16 @@ pub(crate) fn take(app: &mut RustGisApp, ctx: &egui::Context) { // Taken out of egui's memory while positions go in, so the points' `Arc` has one owner and // `make_mut` adds to it in place instead of copying the track. let mut state: Field = ctx.data_mut(|d| d.remove_temp(egui::Id::unique("touch_field"))).unwrap_or_default(); + // More came than are kept between frames (a day of them, with the app out of sight): the + // oldest are gone, which a track or an average being taken missed. + let dropped = std::mem::take(&mut app.fixes_dropped); + if dropped > 0 && (state.track.is_some() || state.averaging.is_some()) { + let text = i18n::fmt( + "{n} of the oldest positions were dropped before they could be taken: at most {kept} are kept between looks.", + &[("n", &dropped.to_string()), ("kept", &rustgis_ui_egui::FIXES_KEPT.to_string())], + ); + app.session.notify(text, true); + } for fix in app.fixes.drain(..) { if let Some(fixes) = &mut state.averaging { Arc::make_mut(fixes).push(fix); @@ -155,31 +165,30 @@ pub(crate) fn track_text(track: &Track, locating: bool) -> String { /// Adds a finished track to the map's Tracks layer, made when the map has none, and says what was /// added and what was left out. A track of fewer than two positions adds nothing, and says so. -/// Says whether a line was added. -pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { - let left_out = |app: &mut RustGisApp| { - if track.poor > 0 { +/// `Ok` once a line was added or the track was too short to be one; a track that couldn't be +/// added (editing or the layer refused, the front end says why) comes back, to be kept rather +/// than lost. +pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> Result<(), Track> { + let left_out = |app: &mut RustGisApp, poor: usize| { + if poor > 0 { let text = i18n::fmt( "{n} positions were left out of the track: each was less exact than {m} m.", - &[("n", &track.poor.to_string()), ("m", &TRACK_ACCURACY.to_string())], + &[("n", &poor.to_string()), ("m", &TRACK_ACCURACY.to_string())], ); app.session.notify(text, false); } }; if track.points.len() < 2 { app.session.notify(tl!("The track wasn't added: it has fewer than two positions."), true); - left_out(app); - return false; + left_out(app, track.poor); + return Ok(()); } - // Editing first: a Tracks layer isn't made for a track that then can't be added. Every way - // out still says what was left out (the refusal itself the front end says). + // Editing first: a Tracks layer isn't made for a track that then can't be added. if !super::edit::ensure_editing(app) { - left_out(app); - return false; + return Err(track); } let Some(layer) = tracks_layer(app) else { - left_out(app); - return false; + return Err(track); }; let started = track.started.or(track.points.first().and_then(|f| f.time)).and_then(stamp).unwrap_or_default(); let name = if started.is_empty() { tl!("Track").to_string() } else { i18n::fmt("Track {start}", &[("start", &started)]) }; @@ -194,13 +203,12 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> bool { "attributes": {"name": name, "notes": notes}, }); if app.run_by_user("edit.addFeature", feature).is_err() { - left_out(app); - return false; + return Err(track); } let named = app.session.map().layer(layer).map_or_else(|| TRACKS.to_string(), |l| l.name.clone()); app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", &named), ("notes", ¬es)]), false); - left_out(app); - true + left_out(app, track.poor); + Ok(()) } /// The map's Tracks layer: its line layer of that name with a text `name` and `notes` field, or @@ -292,7 +300,7 @@ mod tests { app.run_by_user("edit.addField", json!({"layer": theirs, "name": new, "type": "text"})).unwrap(); } let track = Track { points: Arc::new(vec![fix(1.0, 1.0, None, Some(0)), fix(1.1, 1.0, None, Some(60_000))]), ..Track::default() }; - assert!(finish(&mut app, track)); + assert!(finish(&mut app, track).is_ok()); // Not theirs: a layer of its own, holding the track's name. assert!(app.session.map().layer(theirs).unwrap().dataset.features.is_empty()); let ours = app.session.map().layers.iter().find(|l| l.id != theirs && tracks_name(&l.name)).unwrap(); @@ -335,26 +343,26 @@ mod tests { assert_eq!(state.averaging.as_ref().map(|a| a.len()), Some(4)); // Added as one line to a new Tracks layer, and the position left out said. let mark = app.session.notice_mark(); - assert!(finish(&mut app, track.clone())); + assert!(finish(&mut app, track.clone()).is_ok()); let tracks = app.session.map().layers.iter().find(|l| l.name == TRACKS).unwrap(); assert_eq!(tracks.dataset.features.len(), 1); let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("left out")), "{said:?}"); // A second goes to the same layer. - assert!(finish(&mut app, track.clone())); + assert!(finish(&mut app, track.clone()).is_ok()); assert_eq!(app.session.map().layers.iter().filter(|l| l.name == TRACKS).count(), 1); // A Tracks layer without the fields is passed over: one with them is made. let tracks = app.session.map().layers.iter().find(|l| l.name == TRACKS).map(|l| l.id).unwrap(); app.run_by_user("edit.deleteField", json!({"layer": tracks, "field": "notes"})).unwrap(); - assert!(finish(&mut app, track.clone())); + assert!(finish(&mut app, track.clone()).is_ok()); assert_eq!(app.session.map().layers.iter().filter(|l| tracks_name(&l.name)).count(), 2); // And it is the one the next track goes to. - assert!(finish(&mut app, track)); + assert!(finish(&mut app, track).is_ok()); assert_eq!(app.session.map().layers.iter().filter(|l| tracks_name(&l.name)).count(), 2); assert!(tracks_name("Tracks (2)") && !tracks_name("Tracks of deer") && !tracks_name("My Tracks")); // Too short: nothing, said as an error. let mark = app.session.notice_mark(); - assert!(!finish(&mut app, Track { points: Arc::new(vec![fix(1.0, 1.0, None, None)]), ..Track::default() })); + assert!(finish(&mut app, Track { points: Arc::new(vec![fix(1.0, 1.0, None, None)]), ..Track::default() }).is_ok()); assert!(app.session.notices_since(mark).iter().any(|n| n.error)); } } From 5f14be5f5a85606eba8c7ceb7d7866d1a8ecf5f2 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 10:03:09 -0500 Subject: [PATCH 17/18] Address review feedback - A track with breaks where the device's position was off is stored in parts, one for each run, not joined across the gap; the overlay breaks there too, and the parts and any position alone between breaks are said; tested. - A position older than the last kept is left out and counted, so the line doesn't double back; tested. - The track overlay starts a new run where consecutive positions are across the antimeridian. - `finish` says in its doc comment why it runs on the window's thread. - The kept-track test checks that the reason the layer refused it is said before that it is kept. --- crates/ui-touch/src/lib.rs | 31 +++++++-- crates/ui-touch/src/track.rs | 129 ++++++++++++++++++++++++++++++----- 2 files changed, 137 insertions(+), 23 deletions(-) diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index eac358a650..b89b730849 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -84,6 +84,15 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { } let frame = egui::Frame::NONE.fill(t.pane).stroke(Stroke::new(1.0, t.border)); egui::Panel::bottom("touch_bar").exact_size(BAR).frame(frame).show(ui, |ui| bar(app, ui, &t, shown)); + // The device's position off while a track is recorded (Android stopped it): the next + // position starts a run of its own, the track not joined across the gap. + let mut field = track::field(&ctx); + if !app.locate + && let Some(recording) = field.track.as_mut().filter(|t| !t.broken) + { + recording.broken = true; + track::set_field(&ctx, field); + } // A track being recorded says so over the bar, with its Stop, whatever sheet is up. if let Some(recording) = track::field(&ctx).track { let margin = egui::Margin::symmetric(12, 0); @@ -156,10 +165,19 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { // The track being recorded, as it grows. if let (Some(recording), Some((map, _))) = (track::field(&ctx).track, app.map.view_rect) { let painter = ui.painter().with_clip_rect(map); - // One line for each run of points the view shows (a point behind the globe breaks it), - // a point on the pixel of the last left out: hours of a track stay a few shapes. + // One line for each run of points the view shows (a point behind the globe breaks it, + // as do a break in the track and a step across the antimeridian, which would be drawn + // the long way round), a point on the pixel of the last left out: hours of a track + // stay a few shapes. let mut runs: Vec> = vec![Vec::new()]; - for at in recording.points.iter().map(|f| app.lonlat_to_screen(f.lon, f.lat)) { + let mut before: Option = None; + for (i, f) in recording.points.iter().enumerate() { + let across = before.is_some_and(|lon| (f.lon - lon).abs() > 180.0); + before = Some(f.lon); + if (across || recording.runs.contains(&i)) && runs.last().is_some_and(|r| !r.is_empty()) { + runs.push(Vec::new()); + } + let at = app.lonlat_to_screen(f.lon, f.lat); match (at, runs.last_mut()) { (Some(p), Some(run)) if run.last().is_none_or(|q| q.distance(p) >= 1.0) => run.push(p), (Some(_), _) => {} @@ -1891,11 +1909,14 @@ mod tests { let mark = app.session.notice_mark(); assert!(!stop_track(&mut app, &ctx)); assert_eq!(track::field(&ctx).track.map(|t| t.points.len()), Some(3)); - assert!(app.session.notices_since(mark).iter().any(|n| n.error && n.text.contains("kept"))); + // Why it was refused is said, then that it is kept. + let said: Vec = app.session.notices_since(mark).iter().filter(|n| n.error).map(|n| n.text.clone()).collect(); + assert!(said.len() >= 2 && said.last().is_some_and(|t| t.contains("kept")), "{said:?}"); // The More sheet has room for its row while positioning is off. app.locate = false; frame(&mut app, &ctx, Sheet::More); - assert!(track::field(&ctx).track.is_some()); + // With positioning off, the next position starts a run of its own. + assert!(track::field(&ctx).track.is_some_and(|t| t.broken)); } #[test] diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index e765c5eee0..2837fe6fce 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -30,6 +30,14 @@ pub(crate) struct Track { pub poor: usize, /// When it was started, in milliseconds since 1970, when the clock could say. pub started: Option, + /// Where a later run of positions starts, by index into `points`: the device's position was + /// off in between (Android stopped it), so the track isn't joined across the gap. + pub runs: Vec, + /// The device's position went off since the last position kept: the next starts a run. + pub broken: bool, + /// The positions left out because they came after a later one (two providers' positions + /// out of order): kept, the line would double back. + pub late: usize, } impl Track { @@ -38,13 +46,32 @@ impl Track { Track { started: now_ms(), ..Track::default() } } - /// Keeps a position, unless it is less exact than [`TRACK_ACCURACY`] (counted instead). + /// Keeps a position, unless it is less exact than [`TRACK_ACCURACY`] or older than the last + /// kept (each counted instead). The first after a break starts a run of its own. pub fn push(&mut self, fix: Fix) { if fix.accuracy.is_some_and(|m| m > TRACK_ACCURACY) { self.poor += 1; - } else { - Arc::make_mut(&mut self.points).push(fix); + return; } + let last = self.points.last().and_then(|f| f.time); + if let (Some(last), Some(time)) = (last, fix.time) + && time < last + { + self.late += 1; + return; + } + if std::mem::take(&mut self.broken) && !self.points.is_empty() { + self.runs.push(self.points.len()); + } + Arc::make_mut(&mut self.points).push(fix); + } + + /// The runs of positions, each between two breaks. + pub fn parts(&self) -> Vec<&[Fix]> { + let mut starts = vec![0]; + starts.extend(self.runs.iter().copied().filter(|i| *i > 0 && *i < self.points.len())); + starts.push(self.points.len()); + starts.windows(2).filter_map(|w| self.points.get(*w.first()?..*w.get(1)?)).collect() } /// How long it ran, in whole minutes, from its first position's time to its last. @@ -167,20 +194,39 @@ pub(crate) fn track_text(track: &Track, locating: bool) -> String { /// added and what was left out. A track of fewer than two positions adds nothing, and says so. /// `Ok` once a line was added or the track was too short to be one; a track that couldn't be /// added (editing or the layer refused, the front end says why) comes back, to be kept rather -/// than lost. +/// than lost. A track with breaks (the device's position was off) is stored in parts, one for +/// each run of positions, and that is said. +/// +/// Runs on the window's thread, as `edit.addFeature` does: it is one feature, one edit that +/// undoes, of a line of a position a second (a day's track is under 100,000 coordinates, read and +/// copied once), not work that grows with the map's data. pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> Result<(), Track> { - let left_out = |app: &mut RustGisApp, poor: usize| { - if poor > 0 { + let left_out = |app: &mut RustGisApp, track: &Track, alone: usize| { + if track.poor > 0 { let text = i18n::fmt( "{n} positions were left out of the track: each was less exact than {m} m.", - &[("n", &poor.to_string()), ("m", &TRACK_ACCURACY.to_string())], + &[("n", &track.poor.to_string()), ("m", &TRACK_ACCURACY.to_string())], + ); + app.session.notify(text, false); + } + if track.late > 0 { + let text = + i18n::fmt("{n} positions were left out of the track: each came after a later one.", &[("n", &track.late.to_string())]); + app.session.notify(text, false); + } + if alone > 0 { + let text = i18n::fmt( + "{n} positions were left out of the track: each was alone between two breaks, too few for a line.", + &[("n", &alone.to_string())], ); app.session.notify(text, false); } }; - if track.points.len() < 2 { + let parts: Vec<&[Fix]> = track.parts().into_iter().filter(|p| p.len() >= 2).collect(); + let alone = track.points.len() - parts.iter().map(|p| p.len()).sum::(); + if parts.is_empty() { app.session.notify(tl!("The track wasn't added: it has fewer than two positions."), true); - left_out(app, track.poor); + left_out(app, &track, 0); return Ok(()); } // Editing first: a Tracks layer isn't made for a track that then can't be added. @@ -192,22 +238,30 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> Result<(), Track> { }; let started = track.started.or(track.points.first().and_then(|f| f.time)).and_then(stamp).unwrap_or_default(); let name = if started.is_empty() { tl!("Track").to_string() } else { i18n::fmt("Track {start}", &[("start", &started)]) }; + let kept = (track.points.len() - alone).to_string(); let notes = match track.minutes() { - Some(m) => i18n::fmt("{n} positions over {m} min", &[("n", &track.points.len().to_string()), ("m", &m.to_string())]), - None => i18n::fmt("{n} positions", &[("n", &track.points.len().to_string())]), + Some(m) => i18n::fmt("{n} positions over {m} min", &[("n", &kept), ("m", &m.to_string())]), + None => i18n::fmt("{n} positions", &[("n", &kept)]), }; - let line: Vec = track.points.iter().map(|f| json!([f.lon, f.lat])).collect(); - let feature = json!({ - "layer": layer, - "geometry": {"type": "LineString", "coordinates": line}, - "attributes": {"name": name, "notes": notes}, - }); + let line = |part: &[Fix]| -> Vec { part.iter().map(|f| json!([f.lon, f.lat])).collect() }; + let geometry = match parts.as_slice() { + [one] => json!({"type": "LineString", "coordinates": line(one)}), + many => json!({"type": "MultiLineString", "coordinates": many.iter().map(|p| line(p)).collect::>()}), + }; + let feature = json!({"layer": layer, "geometry": geometry, "attributes": {"name": name, "notes": notes}}); if app.run_by_user("edit.addFeature", feature).is_err() { return Err(track); } let named = app.session.map().layer(layer).map_or_else(|| TRACKS.to_string(), |l| l.name.clone()); app.session.notify(i18n::fmt("Added the track to {layer}: {notes}.", &[("layer", &named), ("notes", ¬es)]), false); - left_out(app, track.poor); + if parts.len() > 1 { + let text = i18n::fmt( + "The track has breaks where this device's position was off: it is stored in {n} parts, not joined across them.", + &[("n", &parts.len().to_string())], + ); + app.session.notify(text, false); + } + left_out(app, &track, alone); Ok(()) } @@ -324,6 +378,45 @@ mod tests { assert_eq!(stamp(1_794_614_460_123).as_deref(), Some("2026-11-14 00:01Z")); } + #[test] + fn a_track_with_a_break_is_stored_in_parts_and_a_late_position_is_left_out() { + use rustgis_ui_egui::rustgis_engine::data::Geometry; + let mut app = RustGisApp::with_sample(); + let mut track = Track::default(); + track.push(fix(1.0, 1.0, None, Some(0))); + track.push(fix(1.1, 1.0, None, Some(2000))); + // Out of order: before the last kept. + track.push(fix(1.05, 1.0, None, Some(1000))); + // The position went off, then came back somewhere else. + track.broken = true; + track.push(fix(2.0, 1.0, None, Some(60_000))); + track.push(fix(2.1, 1.0, None, Some(61_000))); + // And off again, with one position before the end: too few for a line of its own. + track.broken = true; + track.push(fix(3.0, 1.0, None, Some(90_000))); + assert_eq!((track.points.len(), track.late, track.runs.clone()), (5, 1, vec![2, 4])); + assert_eq!(track.parts().iter().map(|p| p.len()).collect::>(), [2, 2, 1]); + let mark = app.session.notice_mark(); + assert!(finish(&mut app, track).is_ok()); + let tracks = app.session.map().layers.iter().find(|l| l.name == TRACKS).unwrap(); + match &tracks.dataset.features[0].geometry { + Some(Geometry::Line(parts)) => assert_eq!(parts.iter().map(Vec::len).collect::>(), [2, 2]), + other => panic!("{other:?}"), + } + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("stored in 2 parts")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("1 positions") && t.contains("after a later one")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("1 positions") && t.contains("alone between two breaks")), "{said:?}"); + // A track without breaks or late positions says none of it. + let mut clean = Track::default(); + clean.push(fix(1.0, 1.0, None, Some(0))); + clean.push(fix(1.1, 1.0, None, Some(1000))); + let mark = app.session.notice_mark(); + assert!(finish(&mut app, clean).is_ok()); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().all(|t| !t.contains("parts") && !t.contains("left out")), "{said:?}"); + } + #[test] fn a_finished_track_is_added_to_the_tracks_layer_and_what_was_left_out_is_said() { let mut app = RustGisApp::with_sample(); From 80d91cd33126b905858fc945f251d0ed27afe332 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 14 Nov 2026 10:33:50 -0500 Subject: [PATCH 18/18] Address review feedback - A track whose positions are each alone between breaks says that is why it wasn't added, and how many positions were left out, instead of "fewer than two positions"; tested. --- crates/ui-touch/src/track.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-touch/src/track.rs b/crates/ui-touch/src/track.rs index 2837fe6fce..1d77163d7c 100644 --- a/crates/ui-touch/src/track.rs +++ b/crates/ui-touch/src/track.rs @@ -225,8 +225,16 @@ pub(crate) fn finish(app: &mut RustGisApp, track: Track) -> Result<(), Track> { let parts: Vec<&[Fix]> = track.parts().into_iter().filter(|p| p.len() >= 2).collect(); let alone = track.points.len() - parts.iter().map(|p| p.len()).sum::(); if parts.is_empty() { - app.session.notify(tl!("The track wasn't added: it has fewer than two positions."), true); - left_out(app, &track, 0); + if track.points.len() < 2 { + app.session.notify(tl!("The track wasn't added: it has fewer than two positions."), true); + left_out(app, &track, 0); + } else { + app.session.notify( + tl!("The track wasn't added: this device's position was off between each of its positions, so no part of it has two."), + true, + ); + left_out(app, &track, alone); + } return Ok(()); } // Editing first: a Tracks layer isn't made for a track that then can't be added. @@ -407,6 +415,17 @@ mod tests { assert!(said.iter().any(|t| t.contains("stored in 2 parts")), "{said:?}"); assert!(said.iter().any(|t| t.starts_with("1 positions") && t.contains("after a later one")), "{said:?}"); assert!(said.iter().any(|t| t.starts_with("1 positions") && t.contains("alone between two breaks")), "{said:?}"); + // Every position alone between breaks: none is a line, and how many is said. + let mut scattered = Track::default(); + for (i, lon) in [1.0, 2.0, 3.0].into_iter().enumerate() { + scattered.broken = true; + scattered.push(fix(lon, 1.0, None, Some(i64::try_from(i).unwrap() * 1000))); + } + let mark = app.session.notice_mark(); + assert!(finish(&mut app, scattered).is_ok()); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("no part of it has two")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("3 positions") && t.contains("alone between two breaks")), "{said:?}"); // A track without breaks or late positions says none of it. let mut clean = Track::default(); clean.push(fix(1.0, 1.0, None, Some(0)));