diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 100e326e79..bf26b1ad9f 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 d4c513f8f8..1d9cf9651d 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 3a02959d1d..bb666f1965 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -154,7 +154,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 012186e8e7..aa931c702c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1114,6 +1114,23 @@ 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_dropped += 1; + } + self.fixes.push_back(fix); + } +} + pub struct RustGisApp { pub session: Session, pub ui: UiState, @@ -1145,6 +1162,14 @@ 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, + /// 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). @@ -1414,6 +1439,8 @@ impl RustGisApp { chrome: None, 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 dc8f9a13f9..b89b730849 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; @@ -35,10 +36,15 @@ 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. 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 +72,44 @@ 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); + // 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)); + // 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); + 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 +124,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 + usize::from(app.locate), + // 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, }; @@ -109,6 +162,33 @@ 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); + // 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()]; + 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(_), _) => {} + (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 { @@ -133,6 +213,30 @@ 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. 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); + 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. 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 }; @@ -461,7 +565,8 @@ fn capture_rows(app: &RustGisApp, ctx: &egui::Context) -> usize { } _ => 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 @@ -780,81 +885,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. - if app.locate && action(ui, t, tl!("Go to My Position"), width, false, app.position.is_some()) { - go_to_position(app); - } - // 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| { @@ -1015,6 +1131,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(std::sync::Arc::default()); + } + }); + } + 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 }); @@ -1129,21 +1284,43 @@ 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")) { set_sheet(ui.ctx(), Sheet::None); - 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); + } } }); } @@ -1468,14 +1645,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); } @@ -1667,6 +1844,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 a_picked_vertex_an_undo_moved_or_took_away_is_let_go() { use rustgis_ui_egui::rustgis_engine::data::{Coord, Geometry}; @@ -1704,6 +1895,64 @@ 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)); + // 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); + // With positioning off, the next position starts a run of its own. + assert!(track::field(&ctx).track.is_some_and(|t| t.broken)); + } + + #[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; + 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 new file mode 100644 index 0000000000..1d77163d7c --- /dev/null +++ b/crates/ui-touch/src/track.rs @@ -0,0 +1,480 @@ +//! 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}; +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. +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. + /// 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. + 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 { + /// 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`] 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; + 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. + pub fn minutes(&self) -> Option { + let first = self.points.first()?.time?; + let last = self.points.last()?.time?; + Some(last.saturating_sub(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; + } + // 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); + } + 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, 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()); + 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) { + 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. +/// `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. 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, 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", &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); + } + }; + 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() { + 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. + if !super::edit::ensure_editing(app) { + return Err(track); + } + let Some(layer) = tracks_layer(app) else { + 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)]) }; + let kept = (track.points.len() - alone).to_string(); + let notes = match track.minutes() { + Some(m) => i18n::fmt("{n} positions over {m} min", &[("n", &kept), ("m", &m.to_string())]), + None => i18n::fmt("{n} positions", &[("n", &kept)]), + }; + 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); + 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(()) +} + +/// 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::{FieldType, GeometryType}; + let has = |l: &rustgis_ui_egui::rustgis_engine::map::Layer, name: &str| { + // 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 + .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; + } + 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()) +} + +/// 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; + 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 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(); + 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:?}"); + // 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:?}"); + } + + #[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).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(); + 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(); + 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)); + // 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")); + } + + #[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:?}"); + // 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))); + 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(); + 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(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))); + } + 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(|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()).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()).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()).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).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() }).is_ok()); + assert!(app.session.notices_since(mark).iter().any(|n| n.error)); + } +}