diff --git a/crates/map/src/layout/section.rs b/crates/map/src/layout/section.rs index f44b3d9a27..75db613344 100644 --- a/crates/map/src/layout/section.rs +++ b/crates/map/src/layout/section.rs @@ -57,6 +57,14 @@ impl SectionLine { _ => None, } } + + /// Its direction's name in commands. + pub fn code(self) -> &'static str { + match self { + SectionLine::Horizontal(_) => "horizontal", + SectionLine::Vertical(_) => "vertical", + } + } } impl Section { diff --git a/crates/render/src/layout/section.rs b/crates/render/src/layout/section.rs index 5abb87ea93..fa6675da6e 100644 --- a/crates/render/src/layout/section.rs +++ b/crates/render/src/layout/section.rs @@ -6,6 +6,69 @@ use super::*; /// A section line's ends in its frame's points, from its left or top. pub type SectionEnds = [(f64, f64); 2]; +/// The globe a frame `w` × `h` points shows, if its map is on one. +fn section_globe(map: &Map, cam: &rustgis_map::Camera, (w, h): (f64, f64)) -> Option { + map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(cam, w, h)) +} + +/// Where the place `at` is on a frame `w` × `h` points, in its points; on a map whose world +/// repeats, the copy nearest the frame's middle. `None` where the frame's map can't show it. +fn section_px( + map: &Map, + cam: &rustgis_map::Camera, + globe: Option<&rustgis_map::globe::Globe>, + (w, h): (f64, f64), + mut at: Coord, +) -> Option<(f64, f64)> { + if let Some(mid) = map.to_lonlat(cam.center).filter(|c| c.x.is_finite()) { + at.x += 360.0 * ((mid.x - at.x) / 360.0).round(); + } + match globe { + Some(g) => g.forward(at), + // A projection that holds a place to its reach (Web Mercator past 85.05°) gives another + // place, back: that one isn't the frame's to show. + None => { + map.to_map(at).filter(|&m| map.to_lonlat(m).is_none_or(|back| same_place(back, at))).and_then(|m| cam.try_to_screen(m, w, h)) + } + } + .filter(|(x, y)| x.is_finite() && y.is_finite()) +} + +/// `line` moved `by` points across itself (down, or right for a vertical one) on a frame drawn as +/// for [`section_ends`], and its ends there. Its place keeps where it is along the line; where that +/// isn't in the frame's shape there, it goes to `along` points from the frame's left (or top). +/// `None` where the frame would not draw the line there. +pub fn section_moved( + map: &Map, + cam: &rustgis_map::Camera, + (w, h): (f64, f64), + shape: &FrameShape, + line: SectionLine, + by: f64, + along: f64, +) -> Option<(SectionLine, SectionEnds)> { + let globe = section_globe(map, cam, (w, h)); + let vertical = matches!(line, SectionLine::Vertical(_)); + let swap = |(x, y): (f64, f64)| if vertical { (y, x) } else { (x, y) }; + let (own, across) = swap(section_px(map, cam, globe.as_ref(), (w, h), line.at())?); + let to = across + by; + [own, along].into_iter().find_map(|along| { + let (x, y) = swap((along, to)); + let at = match &globe { + Some(g) => g.inverse(x, y), + None => cam.try_to_map(x, y, w, h).and_then(|m| map.to_lonlat(m)), + }?; + let at = Coord::new((at.x + 180.0).rem_euclid(360.0) - 180.0, at.y); + if !at.x.is_finite() || !(-90.0..=90.0).contains(&at.y) { + return None; + } + let moved = line.through(at); + let ends = section_ends(map, cam, (w, h), shape, moved).ok()?; + // Where the projection has no such place, its inverse can give one that is drawn elsewhere. + ((swap(ends[0]).1 - to).abs() < 0.5).then_some((moved, ends)) + }) +} + /// Where `line` is drawn on a frame `w` × `h` points showing `map` through `cam`, within its /// `shape`: its ends, the outermost of where it meets the shape's outline (#2863). It is straight /// on the page whatever the frame's projection or bearing. On a tilted frame or the globe it runs @@ -21,22 +84,8 @@ pub fn section_ends( line: SectionLine, ) -> Result { const NOT_SHOWN: &str = "its place isn't one the frame's map shows"; - let globe = map.projection.is_globe().then(|| rustgis_map::globe::Globe::new(cam, w, h)); - let mut at = line.at(); - // On a map whose world repeats, the copy of the place nearest the frame's middle. - if let Some(mid) = map.to_lonlat(cam.center).filter(|c| c.x.is_finite()) { - at.x += 360.0 * ((mid.x - at.x) / 360.0).round(); - } - let (px, py) = match &globe { - Some(g) => g.forward(at), - // A projection that holds a place to its reach (Web Mercator past 85.05°) gives another - // place, back: that one isn't the frame's to show. - None => { - map.to_map(at).filter(|&m| map.to_lonlat(m).is_none_or(|back| same_place(back, at))).and_then(|m| cam.try_to_screen(m, w, h)) - } - } - .filter(|(x, y)| x.is_finite() && y.is_finite()) - .ok_or(NOT_SHOWN)?; + let globe = section_globe(map, cam, (w, h)); + let (px, py) = section_px(map, cam, globe.as_ref(), (w, h), line.at()).ok_or(NOT_SHOWN)?; // Along the line and across it: a vertical line is worked out with the axes swapped. let vertical = matches!(line, SectionLine::Vertical(_)); let swap = |(x, y): (f64, f64)| if vertical { (y, x) } else { (x, y) }; diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1d86fdd957..5987cf4aad 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -7993,6 +7993,60 @@ fn a_section_line_past_mercators_reach_is_not_drawn() { assert!(end(85.0).is_ok(), "{:?}", end(85.0)); } +/// A section line moved across itself is drawn where it was moved to, its place kept along it +/// whatever the frame's projection or bearing; in a round frame its place goes where the pointer +/// is when the shape leaves it out. Off the frame, its ground or its projection, it isn't moved. +#[test] +fn a_section_line_moves_across_its_frame() { + use rustgis_map::Projection; + let (w, h) = (400.0, 200.0); + let at = Coord::new(-44.66, -22.38); + let moved = |map: &Map, (c, scale, bearing, pitch): (Coord, f64, f64, f64), shape: &FrameShape, line, by, along| { + section_moved(map, &frame_camera(map, c, scale, bearing, pitch), (w, h), shape, line, by, along) + }; + let rect = FrameShape::Rectangle; + let mut albers = Map::new("albers"); + albers.projection = Projection::Custom("EPSG:10857".into()); + for (map, bearing) in [(Map::new("m"), 0.0), (Map::new("m"), 40.0), (albers, -30.0)] { + let view = (Coord::new(at.x - 0.1, at.y + 0.05), 1e6, bearing, 0.0); + let cam = frame_camera(&map, view.0, view.1, view.2, view.3); + let px = |at: Coord| cam.try_to_screen(map.to_map(at).unwrap(), w, h).unwrap(); + let (x, y) = px(at); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 0.01 && (a.1 - b.1).abs() < 0.01; + let (line, ends) = moved(&map, view, &rect, SectionLine::Horizontal(at), -20.0, 7.0).unwrap(); + assert!(near(px(line.at()), (x, y - 20.0)) && matches!(line, SectionLine::Horizontal(_)), "{line:?}"); + assert!(near(ends[0], (0.0, y - 20.0)) && near(ends[1], (w, y - 20.0)), "{ends:?}"); + let (line, ends) = moved(&map, view, &rect, SectionLine::Vertical(at), 25.0, 7.0).unwrap(); + assert!(near(px(line.at()), (x + 25.0, y)) && matches!(line, SectionLine::Vertical(_)), "{line:?}"); + assert!(near(ends[0], (x + 25.0, 0.0)) && near(ends[1], (x + 25.0, h)), "{ends:?}"); + assert_eq!(moved(&map, view, &rect, SectionLine::Horizontal(at), h, 7.0), None, "below the frame"); + assert_eq!(moved(&map, view, &rect, SectionLine::Vertical(at), -w, 7.0), None, "left of the frame"); + } + // A place by a round frame's edge, moved up: the shape is narrower there, so it goes to the + // pointer, and there is no line where the pointer is off the shape too. + let map = Map::new("m"); + let here = (at, 1e6, 0.0, 0.0); + let cam = frame_camera(&map, at, 1e6, 0.0, 0.0); + let edge = SectionLine::Horizontal(map.to_lonlat(cam.to_map(110.0, h / 2.0, w, h)).unwrap()); + let (line, _) = moved(&map, here, &FrameShape::Circle, edge, -80.0, 210.0).unwrap(); + let (x, y) = cam.try_to_screen(map.to_map(line.at()).unwrap(), w, h).unwrap(); + assert!((x - 210.0).abs() < 0.01 && (y - 20.0).abs() < 0.01, "{x} {y}"); + assert_eq!(moved(&map, here, &FrameShape::Circle, edge, -80.0, 110.0), None); + // Across 180°, the place keeps within the longitudes a command takes. + let line = SectionLine::Vertical(Coord::new(179.5, 0.0)); + let (line, _) = moved(&map, (Coord::new(179.5, 0.0), 1e7, 0.0, 0.0), &rect, line, 60.0, 100.0).unwrap(); + assert!((-180.0..-175.0).contains(&line.at().x), "{line:?}"); + // Not over the horizon, nor off the globe. + let tilted = (at, 5e4, 0.0, 80.0); + assert!(moved(&map, tilted, &rect, SectionLine::Horizontal(at), 20.0, 200.0).is_some()); + assert_eq!(moved(&map, tilted, &rect, SectionLine::Horizontal(at), -99.0, 200.0), None); + let mut globe = Map::new("g"); + globe.projection = Projection::Globe; + let whole = (at, 5e8, 0.0, 0.0); + assert!(moved(&globe, whole, &rect, SectionLine::Vertical(at), 20.0, 100.0).is_some()); + assert_eq!(moved(&globe, whole, &rect, SectionLine::Vertical(at), 190.0, 100.0), None); +} + /// A frame's section lines are drawn over its map in their colour, dashed, with their names at /// both ends, clipped to its shape, as pixels and as vectors in a layer of their own; a frame /// without one draws the same page as before. diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index c104b97f8b..fa0c974c9c 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -14,6 +14,7 @@ mod actions; mod format; mod handles; mod interact; +mod section; mod snap; #[cfg(test)] mod tests; @@ -25,6 +26,7 @@ pub use format::format; use format::*; use handles::*; use interact::*; +use section::*; use snap::*; /// Width of the rulers along the view's top and left edges (points). @@ -569,6 +571,14 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let top = [rt, rb, lb].into_iter().fold(lt, |a, p| if p.y < a.y - 0.5 { p } else { a }); painter.text(top + vec2(0.0, -4.0), Align2::LEFT_BOTTOM, &e.name, regular(11.0), accent); } + // A section line being dragged: where it will be, and its place. + if let (Some(Drag::Section(id, i, line, start)), Some(p)) = (app.layout.drag, pointer) + && let Some((e, name, at, ends)) = section_landing(app, &layout, (id, i, line, start), to_mm(page, s, p)) + { + painter.line_segment(section_on_screen(e, page, s, ends), Stroke::new(2.0, accent)); + let label = format!("{name}: {:.4}°, {:.4}°", at.x, at.y); + painter.text(p + vec2(12.0, 12.0), Align2::LEFT_TOP, label, semibold(12.0), accent); + } // A line being turned: where it will point, and its angle. if let (Some(Drag::Rotate(id, a0, from)), Some(p)) = (app.layout.drag, pointer) && let Some(e) = layout.element(id) diff --git a/crates/ui-egui/src/layoutview/format/frame.rs b/crates/ui-egui/src/layoutview/format/frame.rs index fcd0b2508d..123ec66c6f 100644 --- a/crates/ui-egui/src/layoutview/format/frame.rs +++ b/crates/ui-egui/src/layoutview/format/frame.rs @@ -5,11 +5,108 @@ use crate::RustGisApp; use crate::widgets::Dragged; use egui::{Ui, vec2}; use rustgis_engine::map::layout::{ - CoordFormat, Element, ElementKind, Grid, GridKind, GridStyle, Layout, MAX_FRAME_SCALE, MAX_GRID_WIDTH, MAX_TICK_MM, MIN_FRAME_SCALE, - Orientation, + CoordFormat, Element, ElementKind, Grid, GridKind, GridStyle, Layout, MAX_FRAME_SCALE, MAX_GRID_WIDTH, MAX_SECTIONS, MAX_TICK_MM, + MIN_FRAME_SCALE, Orientation, Section, SectionLine, }; use serde_json::{Value, json}; +/// A map frame's section lines (#2863), each with its name, direction, place and look, why it isn't +/// drawn when it isn't, and Remove; below them, the buttons that add one, whose direction is given +/// back when one is clicked. `update` sends a change. +fn section_rows( + app: &mut RustGisApp, + ui: &mut Ui, + layout: &Layout, + id: u32, + sections: &[Section], + update: &dyn Fn(&mut RustGisApp, Value), +) -> Option<&'static str> { + let gaps = rustgis_engine::render::layout::sections_not_drawn(layout, &app.session.project.maps); + for (i, s) in sections.iter().enumerate() { + let set = |app: &mut RustGisApp, mut p: Value| { + p["section"]["name"] = json!(s.name); + update(app, p); + }; + ui.push_id(("section", id, i), |ui| { + egui::Grid::new("section_place").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { + let label = ui.label(tl!("Name")); + // Typing is kept with the view until the field is left. + let key = egui::Id::unique(("section_name", id, i)); + let mut name = ui.data_mut(|d| d.get_temp::(key)).unwrap_or_else(|| s.name.clone()); + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(60.0)).labelled_by(label.id); + if r.has_focus() { + ui.data_mut(|d| d.insert_temp(key, name)); + } else { + ui.data_mut(|d| d.remove::(key)); + if r.lost_focus() && name.trim() != s.name { + set(app, json!({"section": {"newName": name}})); + } + } + ui.end_row(); + let label = ui.label(tl!("Direction")); + let shown = |line: SectionLine| match line { + SectionLine::Horizontal(_) => tl!("Horizontal"), + SectionLine::Vertical(_) => tl!("Vertical"), + }; + let at = s.line.at(); + let items = [SectionLine::Horizontal(at), SectionLine::Vertical(at)] + .map(|l| (shown(l).to_string(), l == s.line, json!({"section": {"direction": l.code()}}))); + if let Some(p) = choice(ui, ("section_direction", id), label.id, shown(s.line), &items) { + set(app, p); + } + ui.end_row(); + for (text, axis, current, most) in [("Longitude", 0, at.x, 180.0), ("Latitude", 1, at.y, 90.0)] { + let label = ui.label(tl!(text)); + let mut v = current; + let drag = Dragged::lend(ui, egui::Id::unique(("section_drag", id, i, text)), &mut v); + let field = egui::DragValue::new(&mut v).update_while_editing(false).range(-most..=most).speed(0.01).max_decimals(5); + let r = ui.add(field.suffix("°")).labelled_by(label.id); + if drag.settled(ui, &r, &mut v) && (v - current).abs() > 1e-9 { + let mut to = [at.x, at.y]; + to[axis] = v; + set(app, json!({"section": {"at": to}})); + } + ui.end_row(); + } + let label = ui.label(tl!("Dash")); + if let Some(dash) = dash_picked(ui, ("section_dash", id), s.dash, s.width, label.id) { + set(app, json!({"section": {"dash": dash}})); + } + ui.end_row(); + }); + let (least, most) = rustgis_engine::map::layout::SECTION_WIDTHS; + let line = Outline { + key: "section", + drag: egui::Id::unique(("section_drag", id, i, "width")), + color: s.color, + width: s.width, + range: least..=most, + }; + outline_rows(app, ui, "section_look", line, None, &set); + if let Some(gap) = gaps.iter().find(|g| g.frame == id && g.section == s.name) { + let why = crate::i18n::fmt("Not drawn: {why}", &[("why", tl_raw!(gap.why))]); + ui.label(egui::RichText::new(why).size(11.5).color(ui.visuals().warn_fg_color)); + } + if ui.button(tl!("Remove Section Line")).clicked() { + set(app, json!({"section": {"remove": true}})); + } + }); + ui.separator(); + } + let mut add = None; + ui.add_enabled_ui(sections.len() < MAX_SECTIONS, |ui| { + ui.horizontal_wrapped(|ui| { + for (text, direction) in [("Add Horizontal", "horizontal"), ("Add Vertical", "vertical")] { + let hint = tl!("A line across the frame through its centre's place, named at both ends."); + if ui.button(tl!(text)).on_hover_text(hint).clicked() { + add = Some(direction); + } + } + }); + }); + add +} + /// A map frame's grid options; `set` sends the changed ones (`false` removes the grid). fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) { let mut on = grid.is_some(); @@ -327,6 +424,17 @@ pub(super) fn frame_sections( grid_properties(app, ui, grid.as_ref(), id, &|app, g| update(app, json!({"grid": g}))); }); } + if let ElementKind::MapFrame { sections, .. } = &e.kind { + ui.add_space(4.0); + egui::CollapsingHeader::new(tl!("Section Lines")).id_salt(("frame_sections", id)).default_open(!sections.is_empty()).show( + ui, + |ui| { + if let Some(direction) = section_rows(app, ui, layout, id, sections, &update) { + let _ = app.run("layout.addElement", json!({"layout": li, "kind": "section", "frame": id, "direction": direction})); + } + }, + ); + } // The extent indicator this frame draws (another frame's extent): its colour and width. if let ElementKind::MapFrame { extent_of: Some(of), extent_color, extent_width, .. } = &e.kind { let other = layout.element(*of).map_or_else(|| of.to_string(), |o| o.name.clone()); diff --git a/crates/ui-egui/src/layoutview/interact.rs b/crates/ui-egui/src/layoutview/interact.rs index f628903334..c3add9210b 100644 --- a/crates/ui-egui/src/layoutview/interact.rs +++ b/crates/ui-egui/src/layoutview/interact.rs @@ -22,6 +22,10 @@ pub(super) enum Drag { NewGuide(bool), /// Moving a guide: vertical or horizontal, and its index. Guide(bool, usize), + /// Moving a map frame's section line across itself: the frame, the line's index and the line + /// as it was when taken, its place and name (a command that changes the frame's lines meanwhile + /// lets it go), and the pointer's page position (mm) at the start. + Section(u32, usize, Taken, (f64, f64)), /// Turning a line or arrow by its rotation handle: its id, its angle at the start, and the /// pointer's angle about its centre then (degrees). Rotate(u32, f64, f64), @@ -102,6 +106,7 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, Some(Drag::Move(id, p)) => Some(Drag::Move(id, rebase(p))), Some(Drag::Resize(id, h, p)) => Some(Drag::Resize(id, h, rebase(p))), Some(Drag::PanFrame(id, p)) => Some(Drag::PanFrame(id, rebase(p))), + Some(Drag::Section(id, i, line, p)) => Some(Drag::Section(id, i, line, rebase(p))), d => d, }; } @@ -157,6 +162,18 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, }; let rotating = matches!(app.layout.drag, Some(Drag::Rotate(..))); let knob = app.layout.drag.is_none() && rotate_at(app, layout, page, s, p).is_some(); + // A section line shows which way it can be dragged, and where it can't be put. + let section = match app.layout.drag { + Some(Drag::Section(id, i, line, start)) => { + let lands = section_landing(app, layout, (id, i, line, start), to_mm(page, s, p)).is_some(); + Some(if lands { section_cursor(section_vertical(layout, id, i)) } else { CursorIcon::NotAllowed }) + } + None if !knob => { + let pans = ui.input(|i| i.modifiers.shift) || app.layout.navigate; + section_at(app, layout, page, s, p, pans).map(|(.., vertical)| section_cursor(vertical)) + } + _ => None, + }; match (vertical, handle) { _ if rotating => ui.ctx().set_cursor_icon(CursorIcon::Grabbing), _ if knob => ui.ctx().set_cursor_icon(CursorIcon::Grab), @@ -166,6 +183,7 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, } (Some(true), _) => ui.ctx().set_cursor_icon(CursorIcon::ResizeHorizontal), (Some(false), _) => ui.ctx().set_cursor_icon(CursorIcon::ResizeVertical), + _ if section.is_some() => ui.ctx().set_cursor_icon(section.unwrap_or_default()), _ if matches!(app.layout.drag, Some(Drag::PanFrame(..))) => ui.ctx().set_cursor_icon(CursorIcon::Grabbing), _ if navigating => ui.ctx().set_cursor_icon(CursorIcon::Grab), _ if matches!(app.layout.drag, Some(Drag::Move(..))) => ui.ctx().set_cursor_icon(CursorIcon::Move), @@ -234,6 +252,7 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, let handle = handle_at(app, layout, page, s, origin); let ruler = ruler_at(&app.layout, resp.rect, origin); let guide = guide_at(layout, page, s, origin); + let section = section_at(app, layout, page, s, origin, shift); // A line's rotation knob, outside its box, comes before anything under it. let rotate = ruler.is_none().then(|| rotate_at(app, layout, page, s, origin)).flatten(); app.layout.drag = if let Some((id, c)) = rotate { @@ -243,6 +262,10 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, (Some(vertical), ..) => Some(Drag::NewGuide(vertical)), (None, Some((id, h)), ..) => Some(Drag::Resize(id, h, p)), (None, None, Some((vertical, i)), _) => Some(Drag::Guide(vertical, i)), + // The selected frame's section line, over its map. + (None, None, None, Some(_)) if section.is_some() => { + section.and_then(|(id, i, _)| section_line(layout, id, i)).map(|(id, i, line)| Drag::Section(id, i, line, p)) + } // A locked element is selected and stays put, its map too. (None, None, None, Some(id)) if locked(layout, id) => { app.layout.selected = Some(id); @@ -289,6 +312,15 @@ pub(super) fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, let at = ui.input(|i| i.pointer.latest_pos()); drop_guide(app, layout, li, page, s, resp.rect, v, Some(i), at); } + (Some(Drag::Section(id, i, line, start)), Some(end)) => { + // A press that hardly moved is a click; dropped where it isn't drawn, the line stays. + if ((end.0 - start.0).abs() > 0.2 || (end.1 - start.1).abs() > 0.2) + && let Some((_, name, at, _)) = section_landing(app, layout, (id, i, line, start), end) + { + let section = json!({"name": name, "at": [at.x, at.y]}); + let _ = app.run("layout.update", json!({"layout": li, "element": id, "section": section})); + } + } (Some(Drag::PanFrame(id, start)), Some(end)) => pan_frame(app, layout, li, id, end.0 - start.0, end.1 - start.1), (Some(Drag::Rotate(id, a0, from)), _) => { if let (Some(at), Some(e)) = (ui.input(|i| i.pointer.latest_pos()), layout.element(id)) { diff --git a/crates/ui-egui/src/layoutview/section.rs b/crates/ui-egui/src/layoutview/section.rs new file mode 100644 index 0000000000..3cce7ab5da --- /dev/null +++ b/crates/ui-egui/src/layoutview/section.rs @@ -0,0 +1,124 @@ +//! A map frame's section lines on the page (#2863): where each is drawn, which one the pointer is +//! on, and where a dragged one lands. + +use super::*; +use egui::{CursorIcon, Pos2, Rect}; +use rustgis_engine::geom::Coord; +use rustgis_engine::map::layout::{Element, FrameShape, Layout, Section, SectionLine}; +use rustgis_engine::map::{Camera, Map}; +use rustgis_engine::render::layout::{SectionEnds, section_ends, section_moved}; + +/// The map a frame shows and the camera it is drawn through, when the project has it. +pub(super) fn frame_map<'a>(app: &'a RustGisApp, e: &Element) -> Option<(&'a Map, Camera)> { + let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &e.kind else { return None }; + let m = app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map))?; + Some((m, frame_camera(m, *center, *scale, *bearing, *pitch))) +} + +/// A section line's ends (points of its frame `e`) on screen. +pub(super) fn section_on_screen(e: &Element, page: Rect, s: f32, ends: SectionEnds) -> [Pos2; 2] { + ends.map(|(x, y)| to_screen(page, s, (e.x + x / PT_PER_MM, e.y + y / PT_PER_MM))) +} + +/// The section line (#2863) of the selected map frame under a screen point, when it can be dragged: +/// the frame, the line's index and whether it is vertical. Not one of a locked frame, nor one under +/// another element, nor when a drag pans (map frames being navigated, or Shift held). +pub(super) fn section_at(app: &RustGisApp, layout: &Layout, page: Rect, s: f32, pos: Pos2, pans: bool) -> Option<(u32, usize, bool)> { + let e = app.layout.selected.and_then(|id| layout.element(id)).filter(|e| !e.locked && !pans)?; + let ElementKind::MapFrame { shape, sections, .. } = &e.kind else { return None }; + let at = to_mm(page, s, pos); + if sections.is_empty() || layout.hit(at.0, at.1) != Some(e.id) { + return None; + } + let (map, cam) = frame_map(app, e)?; + let size = (e.w * PT_PER_MM, e.h * PT_PER_MM); + let under = |(i, l): (usize, &Section)| { + let ends = section_ends(map, &cam, size, shape, l.line).ok()?; + let [a, b] = section_on_screen(e, page, s, ends); + let reach = GUIDE_PICK.max((l.width / PT_PER_MM) as f32 * s / 2.0); + let d = Rect::from_two_pos(a, b).distance_to_pos(pos); + (d < reach).then_some((d, i, matches!(l.line, SectionLine::Vertical(_)))) + }; + // The nearest; the one drawn last where two cross. + sections.iter().enumerate().rev().filter_map(under).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, i, vertical)| (e.id, i, vertical)) +} + +/// A section line as a drag takes it: its place, and a key of its name (a frame's only one of that +/// name), so that one put at the same place meanwhile isn't taken for it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Taken { + line: SectionLine, + name: u64, +} + +impl Taken { + fn of(l: &Section) -> Self { + use std::hash::{DefaultHasher, Hash, Hasher}; + let mut h = DefaultHasher::new(); + l.name.trim().to_lowercase().hash(&mut h); + Taken { line: l.line, name: h.finish() } + } +} + +/// Section line `i` of frame `id`, with them, as a drag takes it. +pub(super) fn section_line(layout: &Layout, id: u32, i: usize) -> Option<(u32, usize, Taken)> { + let ElementKind::MapFrame { sections, .. } = &layout.element(id)?.kind else { return None }; + Some((id, i, Taken::of(sections.get(i)?))) +} + +/// Whether section line `i` of frame `id` is vertical. +pub(super) fn section_vertical(layout: &Layout, id: u32, i: usize) -> bool { + matches!(layout.element(id).map(|e| &e.kind), Some(ElementKind::MapFrame { sections, .. }) + if sections.get(i).is_some_and(|l| matches!(l.line, SectionLine::Vertical(_)))) +} + +/// The cursor over a section line that can be dragged. +pub(super) fn section_cursor(vertical: bool) -> CursorIcon { + if vertical { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical } +} + +/// Whether page point `at` (mm) is on frame `e`, within its `shape` (a circle as wide as the +/// shorter side, as it is drawn), counted as the shape is filled: by its winding number. +fn in_shape(e: &Element, shape: &FrameShape, at: (f64, f64)) -> bool { + let (x, y) = e.unturned(at.0, at.1); + let (x, y) = (x - e.x, y - e.y); + let side = e.w.min(e.h); + let (bw, bh) = if *shape == FrameShape::Circle { (side, side) } else { (e.w, e.h) }; + let outline: Vec<(f64, f64)> = + shape.outline().into_iter().map(|(u, v)| ((e.w - bw) / 2.0 + u * bw, (e.h - bh) / 2.0 + v * bh)).collect(); + let winding: i32 = outline + .iter() + .zip(outline.iter().cycle().skip(1)) + .filter(|(a, b)| (a.1 <= y) != (b.1 <= y) && a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0) <= x) + .map(|(a, _)| if a.1 <= y { 1 } else { -1 }) + .sum(); + winding != 0 +} + +/// Where a section line being dragged (its frame, its index, the line taken and the drag's start) +/// lands with the pointer at `at` (mm): the frame, the line's name, its place, and its ends in the +/// frame's points; `None` off the frame, or where the frame would not draw it. +pub(super) fn section_landing<'a>( + app: &RustGisApp, + layout: &'a Layout, + (id, i, taken, start): (u32, usize, Taken, (f64, f64)), + at: (f64, f64), +) -> Option<(&'a Element, &'a str, Coord, SectionEnds)> { + let e = layout.element(id)?; + let ElementKind::MapFrame { shape, sections, .. } = &e.kind else { return None }; + // The line taken, still at its index: one removed, moved, renamed or replaced meanwhile isn't + // moved. Dropped off the frame or outside its shape, it stays. + let l = sections.get(i).filter(|l| Taken::of(l) == taken)?; + if !in_shape(e, shape, at) { + return None; + } + let (map, cam) = frame_map(app, e)?; + let size = (e.w * PT_PER_MM, e.h * PT_PER_MM); + let (by, along) = match l.line { + SectionLine::Horizontal(_) => (at.1 - start.1, at.0 - e.x), + SectionLine::Vertical(_) => (at.0 - start.0, at.1 - e.y), + }; + let (by, along) = (by * PT_PER_MM, along * PT_PER_MM); + let (line, ends) = section_moved(map, &cam, size, shape, l.line, by, along)?; + Some((e, &l.name, line.at(), ends)) +} diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index e56de03380..7e39ebd89f 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -473,6 +473,177 @@ fn a_panned_frame_shows_map_beyond_its_edges() { assert_ne!(center(&h.state().session.project.layouts[li]), before, "the pan moved the frame's map"); } +/// Dragging a section line of the selected frame (#2863) moves its place across it in one undo +/// step, and the frame stays; dropped off the frame, or in a frame that is locked, isn't +/// selected or is being panned, the line stays. +#[test] +fn a_selected_frames_section_line_is_dragged() { + use egui::CursorIcon; + use rustgis_engine::map::layout::ElementKind; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Sections"})).unwrap(); + app.layout.no_snap = true; + let li = app.session.active_layout.unwrap(); + let frame = app.session.project.layouts[li].first_frame().unwrap(); + app.run("layout.update", json!({"element": frame, "center": [10, 50], "scale": 1e7})).unwrap(); + for (name, direction) in [("A", "horizontal"), ("B", "vertical")] { + let add = json!({"kind": "section", "frame": frame, "name": name, "direction": direction, "at": [10, 50]}); + app.run("layout.addElement", add).unwrap(); + } + app.layout.selected = Some(frame); + let area = Rc::new(Cell::new(Rect::NOTHING)); + let shown = area.clone(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 760.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + shown.set(ui.available_rect_before_wrap()); + super::show(app, ui); + }, + app, + ); + h.run_steps(3); + let held = |app: &RustGisApp| { + let e = app.session.project.layouts[li].element(frame).unwrap().clone(); + let ElementKind::MapFrame { sections, .. } = &e.kind else { panic!("a map frame") }; + let at = |i: usize| sections[i].line.at(); + (at(0), at(1), (e.x, e.y)) + }; + let button = |pos: Pos2, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // From a share of the frame's width and height, by screen points: the cursor before and during. + let drag = |h: &mut egui_kittest::Harness, (u, v): (f64, f64), by: egui::Vec2| { + let layout = h.state().session.project.layouts[li].clone(); + let e = layout.element(frame).unwrap(); + let (page, s) = page_rect(&h.state().layout, area.get(), &layout); + let from = to_screen(page, s, (e.x + e.w * u, e.y + e.h * v)); + h.event(Event::PointerMoved(from)); + h.step(); + let over = h.output().platform_output.cursor_icon; + h.event(button(from, true)); + h.step(); + for i in 1..=3 { + h.event(Event::PointerMoved(from + by * i as f32 / 3.0)); + h.step(); + } + let dragged = h.output().platform_output.cursor_icon; + h.event(button(from + by, false)); + h.step(); + h.run_steps(2); + (over, dragged) + }; + let before = held(h.state()); + assert_eq!(drag(&mut h, (0.25, 0.5), vec2(5.0, 40.0)), (CursorIcon::ResizeVertical, CursorIcon::ResizeVertical)); + let after = held(h.state()); + assert!(after.0.y < before.0.y - 0.1 && (after.0.x - before.0.x).abs() < 1e-6, "{before:?} → {after:?}"); + assert_eq!((after.1, after.2), (before.1, before.2), "only that line"); + // One undo step, the other line across the other way. + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(held(h.state()), before); + h.run_steps(2); + assert_eq!(drag(&mut h, (0.5, 0.25), vec2(-40.0, 5.0)).0, CursorIcon::ResizeHorizontal); + let after = held(h.state()); + assert!(after.1.x < before.1.x - 0.1 && (after.1.y - before.1.y).abs() < 1e-6, "{before:?} → {after:?}"); + assert_eq!((after.0, after.2), (before.0, before.2)); + // Dropped off the frame, it stays. + let layout = h.state().session.project.layouts[li].clone(); + let half = layout.element(frame).unwrap().h as f32 * page_rect(&h.state().layout, area.get(), &layout).1 / 2.0; + assert_eq!(drag(&mut h, (0.25, 0.5), vec2(0.0, -half - 5.0)).1, CursorIcon::NotAllowed); + assert_eq!(held(h.state()), after); + // A line removed by a command while it is dragged: the drop moves no other line in its place. + let layout = h.state().session.project.layouts[li].clone(); + let e = layout.element(frame).unwrap(); + let (page, s) = page_rect(&h.state().layout, area.get(), &layout); + let from = to_screen(page, s, (e.x + e.w * 0.25, e.y + e.h * 0.5)); + h.event(Event::PointerMoved(from)); + h.step(); + h.event(button(from, true)); + h.step(); + h.event(Event::PointerMoved(from + vec2(20.0, 20.0))); + h.step(); + h.state_mut().run("layout.update", json!({"element": frame, "section": {"name": "A", "remove": true}})).unwrap(); + h.event(Event::PointerMoved(from + vec2(20.0, 40.0))); + h.step(); + h.event(button(from + vec2(20.0, 40.0), false)); + h.step(); + h.run_steps(2); + let e = h.state().session.project.layouts[li].element(frame).unwrap().clone(); + let ElementKind::MapFrame { sections, .. } = &e.kind else { panic!("a map frame") }; + assert!(sections.len() == 1 && sections[0].name == "B" && sections[0].line.at() == after.1, "{sections:?}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(held(h.state()), after); + h.run_steps(2); + // Replaced meanwhile by another line of the same direction at the same place, at the same + // index: the drop doesn't move that one either. + let layout = h.state().session.project.layouts[li].clone(); + let e = layout.element(frame).unwrap(); + let (page, s) = page_rect(&h.state().layout, area.get(), &layout); + let from = to_screen(page, s, (e.x + e.w * 0.25, e.y + e.h * 0.5)); + h.event(Event::PointerMoved(from)); + h.step(); + h.event(button(from, true)); + h.step(); + h.event(Event::PointerMoved(from + vec2(20.0, 20.0))); + h.step(); + h.state_mut().run("layout.update", json!({"element": frame, "section": {"name": "B", "remove": true}})).unwrap(); + h.state_mut().run("layout.update", json!({"element": frame, "section": {"name": "A", "remove": true}})).unwrap(); + let add = json!({"kind": "section", "frame": frame, "name": "Z", "direction": "horizontal", "at": [after.0.x, after.0.y]}); + h.state_mut().run("layout.addElement", add).unwrap(); + h.event(Event::PointerMoved(from + vec2(20.0, 40.0))); + h.step(); + h.event(button(from + vec2(20.0, 40.0), false)); + h.step(); + h.run_steps(2); + let e = h.state().session.project.layouts[li].element(frame).unwrap().clone(); + let ElementKind::MapFrame { sections, .. } = &e.kind else { panic!("a map frame") }; + assert!(sections.len() == 1 && sections[0].name == "Z" && sections[0].line.at() == after.0, "{sections:?}"); + for _ in 0..3 { + h.state_mut().run("edit.undo", json!({})).unwrap(); + } + assert_eq!(held(h.state()), after); + h.run_steps(2); + // Dropped beside the frame, at a height inside it: off the frame, it stays. + let layout = h.state().session.project.layouts[li].clone(); + let quarter = layout.element(frame).unwrap().w as f32 * page_rect(&h.state().layout, area.get(), &layout).1 / 4.0; + assert_eq!(drag(&mut h, (0.75, 0.5), vec2(quarter + 10.0, 10.0)).1, CursorIcon::NotAllowed); + assert_eq!(held(h.state()), after); + // An ellipse's frame: dropped in a corner of its box, outside the ellipse, it stays too. + let shaped = |h: &mut egui_kittest::Harness, to: rustgis_engine::map::layout::FrameShape| { + let e = h.state_mut().session.project.layouts[li].elements.iter_mut().find(|e| e.id == frame).unwrap(); + let ElementKind::MapFrame { shape, .. } = &mut e.kind else { panic!("a map frame") }; + *shape = to; + h.state_mut().session.revision += 1; + }; + shaped(&mut h, rustgis_engine::map::layout::FrameShape::Ellipse); + h.run_steps(2); + let layout = h.state().session.project.layouts[li].clone(); + let e = layout.element(frame).unwrap(); + let s = page_rect(&h.state().layout, area.get(), &layout).1; + let corner = vec2(-0.2 * e.w as f32 * s, -0.4 * e.h as f32 * s); + assert_eq!(drag(&mut h, (0.25, 0.5), corner).1, CursorIcon::NotAllowed); + assert_eq!(held(h.state()), after); + shaped(&mut h, rustgis_engine::map::layout::FrameShape::Rectangle); + h.run_steps(2); + // Map frames being navigated, a drag on the line pans the frame's map. + h.state_mut().layout.navigate = true; + drag(&mut h, (0.25, 0.5), vec2(0.0, 30.0)); + assert_eq!(held(h.state()), after); + h.state_mut().layout.navigate = false; + h.state_mut().run("edit.undo", json!({})).unwrap(); + // Locked, nothing moves; not selected, the drag moves the frame. + h.state_mut().run("layout.update", json!({"element": frame, "locked": true})).unwrap(); + drag(&mut h, (0.25, 0.5), vec2(0.0, 30.0)); + assert_eq!(held(h.state()), after); + h.state_mut().run("layout.update", json!({"element": frame, "locked": false})).unwrap(); + h.state_mut().layout.selected = None; + drag(&mut h, (0.25, 0.5), vec2(0.0, 30.0)); + let last = held(h.state()); + assert!((last.0, last.1) == (after.0, after.1) && last.2.1 > after.2.1 + 1.0, "{after:?} → {last:?}"); +} + /// Pressing a corner handle and dragging away fast resizes the element, though by the time /// egui starts the drag the pointer is already off the handle; it used to move the element. #[test] @@ -1778,6 +1949,81 @@ fn an_overview_frame_shows_its_extent_indicator() { assert!(h.query_by_label("Remove Extent Indicator").is_none(), "and its section with it"); } +/// A frame's Section Lines section (#2863) adds one each way, renames it, says one isn't drawn +/// when its place is outside the frame, and removes it. +#[test] +fn a_frame_adds_names_and_removes_section_lines() { + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Sections"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let frame = app.session.project.layouts[li].first_frame().unwrap(); + app.run("layout.update", json!({"element": frame, "center": [10, 50], "scale": 1e7})).unwrap(); + app.layout.selected = Some(frame); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 1800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + with_format(app, ui); + }, + app, + ); + let held = |app: &RustGisApp| match &app.session.project.layouts[li].element(frame).unwrap().kind { + rustgis_engine::map::layout::ElementKind::MapFrame { sections, .. } => { + sections.iter().map(|s| (s.name.clone(), s.line.code())).collect::>() + } + _ => panic!("a map frame"), + }; + h.run_steps(3); + h.get_by_label("Section Lines").click(); + h.run_steps(12); + h.get_by_label("Add Vertical").click(); + h.run_steps(3); + assert_eq!(held(h.state()), [("A".to_string(), "vertical")]); + assert!(h.query_by_label_contains("Not drawn").is_none()); + // Renamed when the field is left. + let name = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("A")).unwrap(); + name.focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.event(egui::Event::Text("Serra".into())); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(held(h.state()), [("Serra".to_string(), "vertical")]); + // A name another line has is refused, and that is said. + h.get_by_label("Add Vertical").click(); + h.run_steps(3); + let said = h.state().session.notices.len(); + let name = h.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("A")).unwrap(); + name.focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.event(egui::Event::Text("serra".into())); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(held(h.state()), [("Serra".to_string(), "vertical"), ("A".to_string(), "vertical")]); + let notices = &h.state().session.notices; + assert!(notices.len() > said && notices.iter().skip(said).any(|n| n.text.contains("Serra")), "{notices:?}"); + h.state_mut().run("layout.update", json!({"element": frame, "section": {"name": "A", "remove": true}})).unwrap(); + h.run_steps(3); + // Moved off the frame, it says so. + h.state_mut().run("layout.update", json!({"element": frame, "section": {"name": "Serra", "at": [-150, 0]}})).unwrap(); + h.run_steps(3); + assert!(h.query_by_label("Not drawn: its place is outside the frame").is_some()); + h.get_by_label("Remove Section Line").click(); + h.run_steps(3); + assert!(held(h.state()).is_empty()); + assert!(h.query_by_label("Remove Section Line").is_none()); +} + /// A frame's Border section (#2557): Default Border shows only for a border of its own, and /// gives the frame the default one back. #[test] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index dc66a3d538..61707e150d 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -244,7 +244,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu from the whole world down to site plans at 1:20, finds at 1:1 and 2:1 (a scale of 1:0.5). A frame can be turned and tilted like the map view: a new frame, or one matched to the view, takes the view's bearing and pitch, and **Bearing** and **Pitch** in its properties (or - `layout.update` with `bearing` and `pitch`) set them. Its north arrows turn with it. **Grid** draws a labelled graticule over a frame; **Extent Indicator** outlines another frame's + `layout.update` with `bearing` and `pitch`) set them. Its north arrows turn with it. **Grid** draws a labelled graticule over a frame; **Section Lines** draws the traces of cross-sections; **Extent Indicator** outlines another frame's extent (an overview map). - **Frame borders**: the **Border** section of a frame's properties sets the line drawn round it, along its shape for a round or polygon frame: its **Color** and **Line width** (dark grey and @@ -280,20 +280,23 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu `"grid": {…}` (`false` removes the grid). On a map on the globe the lines are drawn on the globe, and stop at its horizon. A frame that shows the whole globe has nothing beyond its rim, and so no labels along its edges. -- **Section lines**: a frame can draw the traces of cross-sections over its map, up to 26 of them: +- **Section lines**: the **Section Lines** section of a frame's properties draws the traces of + cross-sections over its map, up to 26 a frame. **Add Horizontal** and **Add Vertical** add one + across the whole frame, straight on the page, through the place at the frame's centre, its name in + a box at both ends (A and A'); its **Name**, **Direction**, place (**Longitude** and + **Latitude**), **Dash**, **Color** and **Line width** are below. With the frame selected, a line + can also be dragged across its map, up or down, or sideways for a vertical one. The place is what + is kept, so the line follows it when the frame is moved, turned or rescaled, and on each page of a + map series; the line runs to the frame's edge, or to the outline of a round or polygon frame. A + line whose place is outside the frame, or that the frame's map can't show, isn't drawn: its + properties, the layout view and exports say which and why (for a map series' PDF, on how many of + its pages). On a tilted frame or one on the globe, the line runs through the place as the grid + puts it there, only as far as there is ground along it; it is straight on the page there, and not + a straight section of the ground. From a command: `layout.addElement={"kind":"section","frame":1,"name":"A","direction":"horizontal","at":[-44.66,-22.38]}` - draws one across the whole frame, straight on the page (`"direction"` is `"horizontal"` or - `"vertical"`), through a place, with its name in a box at both ends (A and A'). The name defaults - to the first free letter and the place to the frame's centre; `color`, `width` and `dash` set its - look. `layout.update={"element":1,"section":{"name":"A","at":[-44.7,-22.4],"color":"#1F5C84"}}` - changes one by its name, the keys not given keeping theirs (`"newName"` renames it, and - `"remove": true` removes it). The place is what is kept, so the line follows it when the frame is - moved, turned or rescaled, and on each page of a map series; the line runs to the frame's - edge, or to the outline of a round or polygon frame. A line whose place is outside the frame, or - that the frame's map can't show, isn't drawn: these commands, the layout view and exports say which - and why (for a map series' PDF, on how many of its pages). On a tilted frame or one on the globe, - the line runs through the place as the grid puts it there, only as far as there is ground along - it; it is straight on the page there, and not a straight section of the ground. + (the name defaults to the first free letter, the place to the frame's centre), then + `layout.update={"element":1,"section":{"name":"A","at":[-44.7,-22.4],"color":"#1F5C84"}}` + (`"newName"` renames it, and `"remove": true` removes it). - **Measured grids**: a grid's **Type** is a **Graticule** (latitudes and longitudes, as above) or a **Measured grid**, as ArcGIS Pro has them: eastings and northings in a projected coordinate system, for maps read with UTM or national grid coordinates (a hiking map at 1:25,000 with a