Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) {
let live = app.map.pointer_lonlat.is_some();
let resp = ui.add(
egui::Label::new(
egui::RichText::new(format.readout(kept, earth)).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }),
egui::RichText::new(format.readout(kept, earth, crate::coordreadout::MapSystem::of(app.session.map()).as_ref())).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MapSystem::of now runs on every frame of the status bar, whatever the format. It takes a thread-local cache lookup that lowercases the projection code, and system_name calls Projection::label() (a lookup) and allocates a name string. Only the Map format uses the result, so the work is wasted in the other five formats. The added cost is small, since line 487 already calls label() per frame for custom projections, but it is easy to avoid by computing the system only for Map:

Suggested change
egui::RichText::new(format.readout(kept, earth, crate::coordreadout::MapSystem::of(app.session.map()).as_ref())).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }),
egui::RichText::new(format.readout(kept, earth, (format == crate::CoordReadout::Map).then(|| crate::coordreadout::MapSystem::of(app.session.map())).flatten().as_ref())).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }),

Category: performance

)
.sense(Sense::click()),
);
Expand Down
211 changes: 176 additions & 35 deletions crates/ui-egui/src/coordreadout.rs

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ use serde_json::{Value, json};
pub use autosave::FolderStore;
pub use autosave::{Recovery, RecoveryStore};
pub use chrome::{DoubleClick, TitlebarMetrics};
pub use coordreadout::CoordReadout;
pub use coordreadout::{CoordReadout, MapSystem};
pub use rustgis_assistant;
pub use rustgis_engine;
pub use widgets::big_split_menu;
Expand Down Expand Up @@ -1926,15 +1926,15 @@ impl RustGisApp {
.unwrap_or_else(|| "Meters".into());
self.ui.measurement_imperial =
self.services.load_pref.as_ref().and_then(|load| load("measurement_units")).as_deref() == Some("imperial");
// The pointer's coordinate format; a missing one reads as decimal degrees. One this
// version doesn't know (a newer RustGIS may have saved it) is said and read as decimal
// degrees too. It stays saved until the user picks a format (`ui.coordinateFormat`).
// The pointer's coordinate format; a missing one reads in the map's coordinates. One this
// version doesn't know (a newer RustGIS may have saved it) is said and read in the map's
// coordinates too. It stays saved until the user picks a format (`ui.coordinateFormat`).
if let Some(code) = self.services.load_pref.as_ref().and_then(|load| load(coordreadout::PREF)) {
match CoordReadout::from_code(&code) {
Some(format) => self.map.coord_format = format,
None => {
self.session
.notify(tl!("The saved coordinate format isn't known to this version, so decimal degrees are shown."), false);
.notify(tl!("The saved coordinate format isn't known to this version, so map coordinates are shown."), false);
}
}
}
Expand Down Expand Up @@ -4315,8 +4315,8 @@ impl RustGisApp {
let format = match p.get("format") {
None | Some(Value::Null) => self.map.coord_format.next(),
Some(Value::String(v)) => CoordReadout::from_code(v)
.ok_or_else(|| tl!("The coordinate format must be decimal, dms, utm or mgrs").to_string())?,
_ => return Err(tl!("The coordinate format must be decimal, dms, utm or mgrs").into()),
.ok_or_else(|| tl!("The coordinate format must be map, decimal, dms, utm or mgrs").to_string())?,
_ => return Err(tl!("The coordinate format must be map, decimal, dms, utm or mgrs").into()),
};
self.map.coord_format = format;
self.save_pref(coordreadout::PREF, format.code());
Expand Down
58 changes: 42 additions & 16 deletions crates/ui-egui/src/mapmenu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use egui::Ui;
use rustgis_engine::geom::Coord;
use serde_json::json;

use crate::coordreadout::MapSystem;
use crate::widgets::{menu_row, submenu_row};
use crate::{CoordReadout, RustGisApp, i18n};

Expand Down Expand Up @@ -54,11 +55,18 @@ fn lat_lon(c: Coord) -> String {
/// The coordinate row: the text it shows and copies, in the readout's format, and whether it fell
/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N and south of 80° S
/// UTM and MGRS give UPS (`north …`, `Z …`); on another body's map (`earth` false) they fall back
/// to latitude and longitude (and the row's hover text says why).
fn coordinate_row(c: Coord, f: CoordReadout, earth: bool) -> (String, bool) {
match f {
CoordReadout::Decimal => (lat_lon(c), false),
_ => match f.format(c, earth) {
/// to latitude and longitude (and the row's hover text says why). Map coordinates are the map's
/// own system's (`map`), followed by its name so the copy says which system they are in
/// (`2600173 mE 1200272 mN EPSG:2056`); without one (the globe, another body) they are latitude
/// and longitude, and where the system doesn't reach they fall back to them.
fn coordinate_row(c: Coord, f: CoordReadout, earth: bool, map: Option<&MapSystem>) -> (String, bool) {
match (f, map) {
(CoordReadout::Decimal, _) | (CoordReadout::Map, None) => (lat_lon(c), false),
(CoordReadout::Map, Some(m)) => match f.format(c, earth, map) {
Some(text) => (format!("{text} {}", m.name()), false),
None => (lat_lon(c), true),
},
_ => match f.format(c, earth, map) {
Some(text) => (text, false),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the map format, this arm copies text like 2600173 mE 1200272 mN with no name of the coordinate system. Pasted elsewhere, the numbers are ambiguous: the status bar names the system beside the readout, but the clipboard does not. The search box also can't read this text back, unlike the UTM and MGRS rows, which the tests round-trip. Consider copying the system's name with the numbers, or stating in the row's hover text that the copy has no system.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 00228ff. In map coordinates the row now copies the system's name after the numbers, 2600173 mE 1200272 mN EPSG:2056. The name is one map.projection reads back: the EPSG or ESRI code, Web Mercator, or else the map's projection code (robinson +lon_0=150, local:7.4386,46.9511) rather than a preset's or a local view's rounded display name. A test checks that this name gives the same projection back.

Reading the copy back in the search box is a separate feature: the search box would need to parse a system and its coordinates. I've left that out of this PR.

None => (lat_lon(c), true),
},
Expand Down Expand Up @@ -124,8 +132,12 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) {
crate::shapeconvert::menu(app, ui);
let format = app.map.coord_format;
let earth = app.session.map().body().is_earth();
let (coords, fell_back) = coordinate_row(c, format, earth);
let hover = if fell_back && !earth {
let system = MapSystem::of(app.session.map());
let (coords, fell_back) = coordinate_row(c, format, earth, system.as_ref());
let hover = if fell_back && format == CoordReadout::Map {
tl!("Copy coordinates to the clipboard. The map's coordinate system doesn't reach here, so latitude and longitude are copied")
.to_string()
} else if fell_back && !earth {
i18n::fmt(
"Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied",
&[("format", format.label())],
Expand Down Expand Up @@ -289,14 +301,14 @@ mod tests {
#[test]
fn the_coordinate_row_copies_the_chosen_format() {
let p = Coord::new(44.4, 33.3);
assert_eq!(coordinate_row(p, CoordReadout::Decimal, true), ("33.300000, 44.400000".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Dms, true), ("44°24′00.0″ E 33°18′00.0″ N".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Utm, true), ("38north 444141 3684706".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true), ("38S MB 44140 84706".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Decimal, true, None), ("33.300000, 44.400000".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Dms, true, None), ("44°24′00.0″ E 33°18′00.0″ N".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Utm, true, None), ("38north 444141 3684706".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true, None), ("38S MB 44140 84706".into(), false));
// What is copied as UTM or MGRS is found again by the search box, in both hemispheres.
for q in [p, Coord::new(-58.4, -34.6), Coord::new(151.2, -33.87), Coord::new(3.0, -1e-7), Coord::new(-21.9, 64.15)] {
for f in [CoordReadout::Utm, CoordReadout::Mgrs] {
let (text, fell_back) = coordinate_row(q, f, true);
let (text, fell_back) = coordinate_row(q, f, true, None);
assert!(!fell_back, "{text}");
let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
assert!((at.x - q.x).abs() < 1e-4 && (at.y - q.y).abs() < 1e-4, "{text} {at:?}");
Expand All @@ -305,15 +317,29 @@ mod tests {
// Where UTM has no zone, the row gives UPS (`north …`, `Z …`), which reads back too.
let pole = Coord::new(10.0, 86.0);
for f in [CoordReadout::Utm, CoordReadout::Mgrs] {
let (text, fell_back) = coordinate_row(pole, f, true);
let (text, fell_back) = coordinate_row(pole, f, true, None);
assert!(!fell_back && (text.starts_with("north ") || text.starts_with("Z ")), "{f:?}: {text}");
let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
assert!((at.x - pole.x).abs() < 1e-3 && (at.y - pole.y).abs() < 1e-4, "{text} {at:?}");
// On another body's map the row falls back to latitude and longitude (and says so):
// UTM, MGRS and UPS are the Earth's grids.
assert_eq!(coordinate_row(p, f, false), ("33.300000, 44.400000".into(), true), "{f:?}");
assert_eq!(coordinate_row(p, f, false, None), ("33.300000, 44.400000".into(), true), "{f:?}");
}
assert!(!coordinate_row(pole, CoordReadout::Dms, true).1);
assert_eq!(coordinate_row(p, CoordReadout::Dms, false), coordinate_row(p, CoordReadout::Dms, true));
assert!(!coordinate_row(pole, CoordReadout::Dms, true, None).1);
assert_eq!(coordinate_row(p, CoordReadout::Dms, false, None), coordinate_row(p, CoordReadout::Dms, true, None));
// Map coordinates: the map's own system's, and latitude and longitude without one (the
// globe, another body) or where the system doesn't reach (said in the row's hover text).
let merc = MapSystem::new(rustgis_engine::map::projection::Flat::Mercator, 1000.0, "Web Mercator");
assert_eq!(coordinate_row(Coord::new(0.0, 0.0), CoordReadout::Map, true, Some(&merc)), ("0 mE 0 mN Web Mercator".into(), false));
assert_eq!(coordinate_row(p, CoordReadout::Map, true, None), ("33.300000, 44.400000".into(), false));
let lv95 = MapSystem::new(
rustgis_engine::map::projection::Flat::of(&rustgis_engine::map::Projection::Custom("EPSG:2056".into())),
1.0,
"EPSG:2056",
);
let (bern, _) = coordinate_row(Coord::new(7.4386, 46.9511), CoordReadout::Map, true, Some(&lv95));
assert!(bern.starts_with("2599") && bern.ends_with(" mN EPSG:2056"), "{bern}");
let far = Coord::new(-150.0, -60.0);
assert_eq!(coordinate_row(far, CoordReadout::Map, true, Some(&lv95)), ("-60.000000, -150.000000".into(), true));
}
}
2 changes: 1 addition & 1 deletion crates/ui-egui/src/mapview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ impl Default for MapView {
kept_lonlat: None,
menu_lonlat: None,
menu_text: None,
coord_format: crate::CoordReadout::Decimal,
coord_format: crate::CoordReadout::default(),
render_ms: 0,
notices_seen: 0,
toasts: Vec::new(),
Expand Down
72 changes: 57 additions & 15 deletions crates/ui-egui/tests/integration/coordinate_readout.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! The status bar's coordinate readout: a click steps decimal → DMS → UTM → MGRS, the choice is
//! remembered as a preference, and the readout shows the pointer in it.
//! The status bar's coordinate readout: a click steps map → decimal → DMS → UTM → MGRS, the choice
//! is remembered as a preference, and the readout shows the pointer in it.

use std::sync::{Arc, Mutex};

use egui_kittest::kittest::Queryable;
use rustgis_ui_egui::{CoordReadout, RustGisApp, Services};
use rustgis_ui_egui::{CoordReadout, MapSystem, RustGisApp, Services};
use serde_json::{Value, json};

fn harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> {
Expand All @@ -26,23 +26,25 @@ fn the_format_cycles_persists_and_is_restored() {
save_pref: Some(Box::new(move |k, v| writes.lock().unwrap_or_else(|e| e.into_inner()).push((k.to_string(), v.to_string())))),
..Services::default()
});
assert_eq!(app.map.coord_format, CoordReadout::Decimal);
assert_eq!(app.map.coord_format, CoordReadout::Map);
let mut seen = Vec::new();
for _ in 0..4 {
for _ in 0..5 {
app.run("ui.coordinateFormat", Value::Null).unwrap();
seen.push(app.map.coord_format.code());
}
assert_eq!(seen, ["dms", "utm", "mgrs", "decimal"]);
assert_eq!(seen, ["decimal", "dms", "utm", "mgrs", "map"]);
let writes: Vec<String> = saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect();
assert_eq!(writes, ["dms", "utm", "mgrs", "decimal"]);
assert_eq!(writes, ["decimal", "dms", "utm", "mgrs", "map"]);
app.run("ui.coordinateFormat", json!({"format": "MGRS"})).unwrap();
assert_eq!(app.map.coord_format, CoordReadout::Mgrs);
for bad in [json!({"format": "ups"}), json!({"format": 3}), json!({"format": ""})] {
assert!(app.run("ui.coordinateFormat", bad.clone()).is_err(), "{bad}");
assert_eq!(app.map.coord_format, CoordReadout::Mgrs, "{bad}");
}
// A saved choice comes back, with nothing to say.
for (pref, want) in [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs)] {
for (pref, want) in
[("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs), ("decimal", CoordReadout::Decimal), ("map", CoordReadout::Map)]
{
let restored = RustGisApp::with_sample().with_services(Services {
load_pref: Some(Box::new(move |k| (k == "coordinate_format").then(|| pref.to_string()))),
..Services::default()
Expand All @@ -67,8 +69,8 @@ fn an_unknown_saved_format_is_said_and_kept_until_the_user_picks_one() {
});
let format_writes =
|| saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect::<Vec<_>>();
// Read as decimal degrees, and said once.
assert_eq!(app.map.coord_format, CoordReadout::Decimal);
// Read in the map's coordinates, and said once.
assert_eq!(app.map.coord_format, CoordReadout::Map);
assert_eq!(app.session.notices.iter().filter(|n| n.text.contains("saved coordinate format isn't known")).count(), 1);
// Frames drawn and another setting saved leave the stored format alone.
let mut h = harness(app);
Expand All @@ -78,11 +80,18 @@ fn an_unknown_saved_format_is_said_and_kept_until_the_user_picks_one() {
assert!(saved.lock().unwrap().iter().any(|(k, _)| k == "measurement_units"));
assert!(format_writes().is_empty(), "{:?}", format_writes());
// A click on the readout is the user's choice: it is saved.
let decimal = rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the map"));
h.get_by_label(&decimal).click();
let shown = map_readout(&h);
h.get_by_label(&shown).click();
hover_map(&mut h);
assert_eq!(h.state().map.coord_format, CoordReadout::Dms);
assert_eq!(format_writes(), ["dms"]);
assert_eq!(h.state().map.coord_format, CoordReadout::Decimal);
assert_eq!(format_writes(), ["decimal"]);
}

/// The readout in the map's coordinates of where the pointer is.
fn map_readout(h: &egui_kittest::Harness<'_, RustGisApp>) -> String {
let app = h.state();
let at = app.map.pointer_lonlat.expect("the pointer is over the map");
CoordReadout::Map.readout(Some(at), true, MapSystem::of(app.session.map()).as_ref())
}

/// Points the mouse at the middle of the window, over the map, for a few frames.
Expand All @@ -101,6 +110,13 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches()
hover_map(&mut h);
let at = h.state().map.pointer_lonlat.expect("the pointer is over the map");
assert!((at.x - 44.4).abs() < 0.05 && (at.y - 33.3).abs() < 0.05, "{at:?}");
// First in the map's own coordinates: Web Mercator's metres, about 4.94 million east.
let shown = map_readout(&h);
assert!(shown.starts_with("494") && shown.ends_with(" mN"), "{shown}");
h.get_by_label(&shown).click();
hover_map(&mut h);
assert_eq!(h.state().map.coord_format, CoordReadout::Decimal);
let at = h.state().map.pointer_lonlat.expect("the pointer is over the map");
let decimal = rustgis_engine::geom::format_lonlat(at);
h.get_by_label(&decimal).click();
hover_map(&mut h);
Expand All @@ -119,7 +135,7 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches()
assert!(mgrs.starts_with("38S MB 4"), "{mgrs}");
h.get_by_label(&mgrs).click();
hover_map(&mut h);
assert_eq!(h.state().map.coord_format, CoordReadout::Decimal);
assert_eq!(h.state().map.coord_format, CoordReadout::Map);
// Where UTM has no zone the readout gives the polar grid, UPS (MGRS without a zone number).
h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap();
h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap();
Expand All @@ -138,6 +154,31 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches()
h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap();
hover_map(&mut h);
h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.unwrap()));
// There the map's coordinates, which its projection would give on the Earth's figure, read
// as degrees.
h.state_mut().run("ui.coordinateFormat", json!({"format": "map"})).unwrap();
hover_map(&mut h);
h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.unwrap()));
}

/// A map in the Swiss grid (LV95) reads the pointer in its eastings and northings, in metres, as
/// does the right-click menu's first row; the globe reads degrees.
#[test]
fn a_map_in_lv95_reads_eastings_and_northings() {
let mut h = harness(RustGisApp::with_sample());
h.state_mut().run("map.projection", json!({"type": "EPSG:2056"})).unwrap();
h.state_mut().run("map.goToXY", json!({"lon": 7.4386, "lat": 46.9511, "scale": 10000})).unwrap();
hover_map(&mut h);
let shown = map_readout(&h);
let (e, n) = shown.split_once(" ").expect("an easting and a northing");
let e: f64 = e.strip_suffix(" mE").and_then(|v| v.parse().ok()).expect("metres east");
let n: f64 = n.strip_suffix(" mN").and_then(|v| v.parse().ok()).expect("metres north");
assert!((e - 2_600_000.0).abs() < 2_000.0 && (n - 1_200_000.0).abs() < 2_000.0, "{shown}");
h.get_by_label(&shown);
h.state_mut().run("map.projection", json!({"type": "globe"})).unwrap();
h.state_mut().run("map.goToXY", json!({"lon": 7.4386, "lat": 46.9511, "scale": 10000})).unwrap();
hover_map(&mut h);
h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the globe")));
}

/// Moves the mouse onto the status bar, off the map, for a few frames.
Expand All @@ -149,6 +190,7 @@ fn hover_status_bar(h: &mut egui_kittest::Harness<'_, RustGisApp>) {
}

fn readout_at_center(h: &mut egui_kittest::Harness<'_, RustGisApp>) -> String {
h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap();
h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap();
hover_map(h);
rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the map"))
Expand Down
4 changes: 4 additions & 0 deletions crates/ui-egui/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3535,6 +3535,8 @@ fn save_project_dialog_needs_downloads() {
#[test]
fn map_context_menu_copies_the_clicked_coordinates() {
let mut h = harness();
// In decimal degrees (the default reads in the map's own coordinates).
h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap();
for _ in 0..4 {
h.step();
}
Expand Down Expand Up @@ -4134,6 +4136,8 @@ fn plugin_picks_take_a_place_on_the_map() {
rp::load(rp::Package::from_zip(&rp::testing::pick_package("ui-pick")).unwrap(), "test").unwrap();
let _unload = Unload("ui-pick");
let mut h = harness();
// The status bar in decimal degrees, as the pane shows the place.
h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap();
h.state_mut().run("ui.pane.plugin", json!({"id": "ui-pick"})).unwrap();
h.run_steps(3);
let place = |h: &egui_kittest::Harness<'_, RustGisApp>, id: &str| h.state().session.plugin_panels["ui-pick"].values[id].clone();
Expand Down
Loading
Loading