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
301 changes: 191 additions & 110 deletions crates/engine/src/cmd/layout.rs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ pub fn commands() -> Vec<C> {
return Err("a project keeps at least one map".into());
}
let i = required_map_at(s,p)?;
let named = super::layout::maps_layouts_name(&s.project);
s.project.maps.remove(i);
// Deleting another map keeps the one in view (a map tab's close button).
let active = s.project.active_map;
Expand All @@ -224,6 +225,7 @@ pub fn commands() -> Vec<C> {
s.active_layer = s.map().layers.first().map(|l| l.id);
s.table_layer = None;
}
super::layout::say_map_texts(s, &named);
Ok(Value::Null)
}).transition(unmodelled_transition).inputs(required_map_inputs).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name": string}"#),
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ pub fn commands() -> Vec<C> {
C::new("offline.remove", "Remove", "Data › Offline", |s, p| {
let n = ps(p, "name").ok_or("name is required")?;
let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?;
let named = super::layout::maps_layouts_name(&s.project);
let area = s.project.offline_areas.remove(ai);
let kept = offline_map_index(&s.project, &area);
// A copy kept as the only map is no longer the area's: neither its saved association
Expand Down Expand Up @@ -312,6 +313,7 @@ pub fn commands() -> Vec<C> {
super::navigate::follow_renamed_map(s, &old, &kept);
s.notify(format!("The offline area's map was the only one, so it was kept as '{kept}'"), false);
}
super::layout::say_map_texts(s, &named);
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name": offline area}"#),
Expand Down
19 changes: 11 additions & 8 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ mod elevation_tiles;
#[path = "tests/layout_files.rs"]
mod layout_files;

#[path = "tests/layout_title.rs"]
mod layout_title;

#[path = "tests/sde_connections.rs"]
mod sde_connections;

Expand Down Expand Up @@ -58204,7 +58207,7 @@ fn a_layer_read_from_a_file_says_whether_it_and_the_file_are_in_step() {
/// is for a legend elsewhere, or when the texts would need a taller box.
#[test]
fn the_footer_lines_up_with_a_legend_at_the_right() {
use crate::cmd::layout::align_footer;
use crate::cmd::layout::{Broken, align_footer};
use rustgis_map::layout::{ElementKind, FontFamily, TextAlign};
let text = |t: &str, size: f64| ElementKind::Text {
text: t.into(),
Expand Down Expand Up @@ -58237,19 +58240,19 @@ fn the_footer_lines_up_with_a_legend_at_the_right() {
("Reference".to_string(), (109.5, 255.5, 83.0, 3.0), text("UTM zone 24S", 7.0)),
]
};
fn column(lines: &[&str]) -> Broken {
Broken::from(lines.iter().map(|l| l.to_string()).collect::<Vec<_>>())
}
// One line each however wide; the reference in three under 70 mm.
let short = |_: f64, _: f64, _: f64| {
vec![
("Sources", vec!["SOURCES".to_string()], vec!["Boundaries: IBGE".to_string()]),
("Reference", vec!["REFERENCE".to_string()], vec!["UTM zone 24S".to_string()]),
("Sources", column(&["SOURCES"]), column(&["Boundaries: IBGE"])),
("Reference", column(&["REFERENCE"]), column(&["UTM zone 24S"])),
]
};
let long = |tw: f64, _: f64, _: f64| {
let n = if tw < 70.0 { 3 } else { 1 };
vec![
("Sources", vec!["SOURCES".to_string()], vec!["IBGE".to_string()]),
("Reference", vec!["REFERENCE".to_string()], vec!["UTM".to_string(); n]),
]
vec![("Sources", column(&["SOURCES"]), column(&["IBGE"])), ("Reference", column(&["REFERENCE"]), column(&vec!["UTM"; n]))]
};
let rect = |around: &[(String, (f64, f64, f64, f64), ElementKind)], name: &str| around.iter().find(|e| e.0 == name).unwrap().1;
// A legend from 60 % of the frame to its right edge: the right column starts there.
Expand All @@ -58260,7 +58263,7 @@ fn the_footer_lines_up_with_a_legend_at_the_right() {
assert_eq!(rect(&around, "Reference Heading").0, 125.5);
assert_eq!(rect(&around, "Reference").2, 67.0);
// Elsewhere: at 30 %, short of the right edge, or texts needing a taller box.
type Sections = dyn Fn(f64, f64, f64) -> Vec<(&'static str, Vec<String>, Vec<String>)>;
type Sections = dyn Fn(f64, f64, f64) -> Vec<(&'static str, Broken, Broken)>;
let cases: [((f64, f64, f64, f64), &Sections); 3] =
[((69.0, 200.0, 126.0, 40.0), &short), ((123.0, 200.0, 20.0, 40.0), &short), ((123.0, 200.0, 72.0, 40.0), &long)];
for (legend, sections) in cases {
Expand Down
299 changes: 299 additions & 0 deletions crates/engine/src/tests/layout_title.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
//! A layout made from New Layout is titled with the map's name as `{map}`, so renaming the map
//! changes the title.

use super::*;
use rustgis_map::layout::ElementKind;

/// What the layout `li`'s element `name` says as the page draws it: its text with the tokens
/// filled from the map in the layout's first map frame.
fn drawn(s: &Session, li: usize, name: &str) -> String {
let l = &s.project.layouts[li];
let ElementKind::Text { text, .. } = &l.elements.iter().find(|e| e.name == name).unwrap().kind else { panic!("{name} isn't text") };
let ElementKind::MapFrame { map, .. } = &l.element(l.first_frame().unwrap()).unwrap().kind else { panic!() };
let m = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)).unwrap();
let cam = rustgis_map::layout::frame_camera(m, rustgis_geom::Coord::new(0.0, 0.0), 1.0e7, 0.0, 0.0);
let info = crate::render::layout::PageInfo { page: 1, pages: 1, page_name: String::new() };
crate::render::layout::expand(text, l, &info, Some((m, cam)))
}

/// The text stored in the layout `li`'s element `name`.
fn stored(s: &Session, li: usize, name: &str) -> String {
match &s.project.layouts[li].elements.iter().find(|e| e.name == name).unwrap().kind {
ElementKind::Text { text, .. } => text.clone(),
k => panic!("{name}: {k:?}"),
}
}

#[test]
fn the_new_layout_title_follows_a_rename_of_the_map() {
let mut s = world();
s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
let before = s.map().name.clone();
assert_eq!(drawn(&s, 0, "Title"), before);
s.run("map.rename", &json!({"name": "Location map"})).unwrap();
assert_eq!(drawn(&s, 0, "Title"), "Location map");
assert_eq!(stored(&s, 0, "Title"), "{map}");
}

#[test]
fn a_publication_sheet_titled_with_the_map_token_follows_a_rename() {
let mut s = world();
s.run("layout.publication", &json!({"profile": "a4", "extent": [-46.8, -11.6, -38.5, -2.2], "title": "{map}"})).unwrap();
s.run("map.rename", &json!({"name": "Location map"})).unwrap();
assert_eq!(drawn(&s, 0, "Title"), "Location map");
}

/// The layout `li`'s elements as (name, x, y, w, h), so two layouts compare by their boxes.
fn boxes(s: &Session, li: usize) -> Vec<(String, f64, f64, f64, f64)> {
s.project.layouts[li].elements.iter().map(|e| (e.name.clone(), e.x, e.y, e.w, e.h)).collect()
}

#[test]
fn a_sheet_titled_with_the_map_token_is_laid_out_as_one_titled_with_the_name() {
let mut s = world();
let name = s.map().name.clone();
let extent = json!([-46.8, -11.6, -38.5, -2.2]);
s.run("layout.publication", &json!({"profile": "a4", "extent": extent, "title": name})).unwrap();
s.run("layout.publication", &json!({"profile": "a4", "extent": extent, "title": "{map}"})).unwrap();
assert_eq!(boxes(&s, 0), boxes(&s, 1));
assert_eq!(drawn(&s, 0, "Title"), drawn(&s, 1, "Title"));
}

#[test]
fn a_title_typed_over_the_token_stays_as_typed_after_a_rename() {
let mut s = world();
s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
let title = s.project.layouts[0].elements.iter().find(|e| e.name == "Title").unwrap().id;
s.run("layout.update", &json!({"layout": 0, "element": title, "text": "Flood risk"})).unwrap();
s.run("map.rename", &json!({"name": "Location map"})).unwrap();
assert_eq!(drawn(&s, 0, "Title"), "Flood risk");
assert_eq!(stored(&s, 0, "Title"), "Flood risk");
}

/// The layout `li`'s element `name`.
fn element<'a>(s: &'a Session, li: usize, name: &str) -> &'a rustgis_map::layout::Element {
s.project.layouts[li].elements.iter().find(|e| e.name == name).unwrap()
}

/// The lines the page draws the layout `li`'s text element `name` in, read from its SVG export.
fn drawn_lines(s: &Session, li: usize, name: &str) -> Vec<String> {
let mut l = s.project.layouts[li].clone();
let id = element(s, li, name).id;
for e in &mut l.elements {
e.visible = e.id == id;
}
let info = crate::render::layout::PageInfo { page: 1, pages: 1, page_name: String::new() };
let svg = crate::render::svg::layout_svg(&l, &mut s.project.maps.clone(), 96.0, &info).unwrap().0;
let text = svg.split("<text ").nth(1).unwrap().split("</text>").next().unwrap();
let after_tag = |t: &str| t.split_once('>').unwrap().1.to_string();
if text.contains("<tspan") {
text.split("<tspan ").skip(1).map(|t| after_tag(t.split("</tspan>").next().unwrap())).collect()
} else {
vec![after_tag(text)]
}
}

/// How many lines the box of the text element `name` was sized for, `pad` mm of it not text.
fn sized_lines(s: &Session, li: usize, name: &str, pad: f64) -> usize {
let e = element(s, li, name);
let ElementKind::Text { size, .. } = &e.kind else { panic!("{name} isn't text") };
let lines = (e.h - pad) / crate::render::layout::line_pitch_mm(*size);
assert!((lines - lines.round()).abs() < 1e-6, "{name}: {lines} lines");
lines.round() as usize
}

fn wraps(s: &Session, li: usize, name: &str) -> bool {
matches!(element(s, li, name).kind, ElementKind::Text { wrap: true, .. })
}

const LONG: &str = "A very long map name that goes on and on past the width of the title box on a sheet of paper";

/// A name wider than the title's box can't be a `{map}` broken into lines in the stored text: the
/// title wraps to its box as it is drawn, in a box sized for those lines.
#[test]
fn a_map_name_wider_than_the_title_wraps_as_drawn_and_follows_a_rename() {
let mut s = world();
s.run("map.rename", &json!({"name": LONG})).unwrap();
let extent = json!([-46.8, -11.6, -38.5, -2.2]);
for (li, style) in ["classic", "banner", "panel", "editorial", "modular", "poster"].into_iter().enumerate() {
let r =
s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "title": "{map}", "style": style})).unwrap();
assert_eq!(stored(&s, li, "Title"), "{map}", "{style}");
assert!(wraps(&s, li, "Title"), "{style}");
let lines = drawn_lines(&s, li, "Title");
assert!(lines.len() > 1, "{style}: {lines:?}");
assert_eq!(lines.join(" "), LONG, "{style}");
// The classic title's box has 1.5 mm under its text on A4.
let pad = if style == "classic" { 1.5 } else { 0.0 };
assert_eq!(sized_lines(&s, li, "Title", pad), lines.len(), "{style}: {lines:?}");
assert!(!r["warnings"].to_string().contains("{map}"), "{r}");
}
s.run("map.rename", &json!({"name": "Location map"})).unwrap();
assert_eq!(drawn_lines(&s, 0, "Title"), ["Location map"]);
// A name that fits needs no wrapping.
s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "title": "{map}"})).unwrap();
assert_eq!(stored(&s, 6, "Title"), "{map}");
assert!(!wraps(&s, 6, "Title"));
}

/// The box is sized by the lines drawn, not by the line breaking the sheet uses for other texts,
/// which measures a line's advance rather than its ink: names the two count differently in the
/// Linux interface fonts and serif.
#[test]
fn a_wrapped_map_title_is_sized_for_its_drawn_lines() {
let mut s = world();
let extent = json!([-46.8, -11.6, -38.5, -2.2]);
// Each style, what its title's box holds besides the text (1.5 mm for a classic one on A4), and
// the name.
let cases = [
("classic", 1.5, "parcels by flood in flood use zoning roads valley T."),
("banner", 0.0, "AV off in water district T. WAVY off river if roads county district and water and map"),
(
"panel",
0.0,
"use use by fully survey valley river fully of WAVY survey WAVY map of AV in zoning water in north use county zoning district valley if T.",
),
("editorial", 0.0, "north valley off north in map district zoning T. AV land county by flood use if north valley"),
];
for (li, (style, pad, name)) in cases.into_iter().enumerate() {
s.run("map.rename", &json!({"name": name})).unwrap();
s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "title": "{map}", "style": style})).unwrap();
assert!(wraps(&s, li, "Title"), "{style}");
let lines = drawn_lines(&s, li, "Title");
assert_eq!(sized_lines(&s, li, "Title", pad), lines.len(), "{style}: {lines:?}");
}
}

/// A column of sources is one element: one `{map}` source too wide for it wraps the element, the
/// others keeping their own lines.
#[test]
fn a_map_token_among_several_sources_wraps_with_them() {
let mut s = world();
s.run("map.rename", &json!({"name": LONG})).unwrap();
let extent = json!([-46.8, -11.6, -38.5, -2.2]);
let sources = ["Parcels of {map}", "Census 2020"];
s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "sources": sources})).unwrap();
assert_eq!(stored(&s, 0, "Sources"), "Parcels of {map}\nCensus 2020");
assert!(wraps(&s, 0, "Sources"));
let lines = drawn_lines(&s, 0, "Sources");
assert_eq!(lines.last().unwrap(), "Census 2020");
assert_eq!(lines[..lines.len() - 1].join(" "), format!("Parcels of {LONG}"));
assert_eq!(sized_lines(&s, 0, "Sources", 0.0), lines.len(), "{lines:?}");
}

/// The notices `run` gives about `{map}`.
fn map_notices(s: &mut Session, command: &str, params: Value) -> Vec<String> {
let mark = s.notice_mark();
s.run(command, &params).unwrap();
s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("{map}")).collect()
}

/// The id of the layout `li`'s element `name`.
fn id(s: &Session, li: usize, name: &str) -> u32 {
element(s, li, name).id
}

#[test]
fn removing_the_last_map_frame_says_how_many_map_texts_draw_empty() {
let mut s = world();
s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap();
s.run("layout.addElement", &json!({"kind": "text", "text": "Map of {map}"})).unwrap();
s.run("layout.addFrame", &json!({})).unwrap();
let frames: Vec<u32> =
s.project.layouts[0].elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).map(|e| e.id).collect();
assert_eq!(frames.len(), 2);
// A frame is left to name the map: nothing to say.
assert_eq!(map_notices(&mut s, "layout.removeElement", json!({"element": frames[0]})), Vec::<String>::new());
assert_eq!(
map_notices(&mut s, "layout.removeElement", json!({"element": frames[1]})),
["Layout 'Sheet': 2 texts with {map} have no map frame showing a map to name, so {map} draws empty"]
);
// Said when it happens, not again.
let title = id(&s, 0, "Title");
assert_eq!(map_notices(&mut s, "layout.removeElement", json!({"element": title})), Vec::<String>::new());
}

#[test]
fn removing_the_last_map_frame_of_a_layout_without_map_texts_says_nothing() {
let mut s = world();
s.run("layout.new", &json!({"page": "a4", "template": "blank"})).unwrap();
s.run("layout.addElement", &json!({"kind": "text", "text": "Flood risk"})).unwrap();
let frame = s.run("layout.addFrame", &json!({})).unwrap()["element"].clone();
assert_eq!(map_notices(&mut s, "layout.removeElement", json!({"element": frame})), Vec::<String>::new());
}

#[test]
fn removing_the_map_a_layout_names_says_its_map_texts_draw_empty() {
let mut s = world();
let first = s.map().name.clone();
s.run("map.new", &json!({"name": "Detail"})).unwrap();
s.run("map.new", &json!({"name": "Spare"})).unwrap();
s.run("map.activate", &json!({"name": "Detail"})).unwrap();
s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap();
// A map no frame names, then the one this layout's frame shows.
assert_eq!(map_notices(&mut s, "map.remove", json!({"name": "Spare"})), Vec::<String>::new());
assert_eq!(
map_notices(&mut s, "map.remove", json!({"name": "Detail"})),
["Layout 'Sheet': 1 text with {map} has no map frame showing a map to name, so {map} draws empty"]
);
assert_eq!(drawn_lines(&s, 0, "Title"), [""]);
assert_eq!(s.map().name, first);
}

#[test]
fn removing_a_map_two_layouts_name_says_so_once() {
let mut s = world();
s.run("map.new", &json!({"name": "Detail"})).unwrap();
s.run("map.activate", &json!({"name": "Detail"})).unwrap();
s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
assert_eq!(
map_notices(&mut s, "map.remove", json!({"name": "Detail"})),
["2 layouts: 2 texts with {map} have no map frame showing a map to name, so {map} draws empty"]
);
}

#[test]
fn removing_an_offline_area_and_its_map_says_the_map_texts_draw_empty() {
let mut s = world();
let first = s.map().name.clone();
s.run("map.new", &json!({"name": "Crew (offline)"})).unwrap();
s.run("map.activate", &json!({"name": "Crew (offline)"})).unwrap();
s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap();
let extent = rustgis_geom::Extent::new(0.0, 0.0, 1.0, 1.0);
let area = json!({"name": "Crew", "map": first, "extent": extent, "created": 0.0, "data": s.project.maps[0]});
s.project.offline_areas.push(serde_json::from_value(area).unwrap());
assert_eq!(
map_notices(&mut s, "offline.remove", json!({"name": "Crew"})),
["Layout 'Sheet': 1 text with {map} has no map frame showing a map to name, so {map} draws empty"]
);
}

/// `{map}` names the first map frame's map, and the first is the lowest in the drawing order:
/// sending another frame to the back, or deleting the first, changes the map it names, and says
/// so. Moves that leave the first frame's map as it was say nothing.
#[test]
fn reordering_or_removing_frames_says_when_map_texts_name_another_map() {
let mut s = world();
let first = s.map().name.clone();
s.run("map.new", &json!({"name": "Detail"})).unwrap();
s.run("map.activate", &json!({"name": &first})).unwrap();
s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap();
let detail =
s.run("layout.addFrame", &json!({"map": "Detail", "x": 10, "y": 10, "w": 40, "h": 30})).unwrap()["element"].as_u64().unwrap();
let title = id(&s, 0, "Title");
// Neither changes the first frame.
assert_eq!(map_notices(&mut s, "layout.arrange", json!({"element": title, "to": "front"})), Vec::<String>::new());
assert_eq!(map_notices(&mut s, "layout.arrange", json!({"element": detail, "to": "front"})), Vec::<String>::new());
assert_eq!(
map_notices(&mut s, "layout.arrange", json!({"element": detail, "to": "back"})),
["Layout 'Sheet': its first map frame, the lowest in the drawing order, now shows 'Detail', so 1 text with {map} names it"]
);
// Undone, the title names the first map again; the next change is said again.
s.run("edit.undo", &json!({})).unwrap();
let world_frame = s.project.layouts[0].first_frame().unwrap();
assert_eq!(
map_notices(&mut s, "layout.removeElement", json!({"element": world_frame})),
["Layout 'Sheet': its first map frame, the lowest in the drawing order, now shows 'Detail', so 1 text with {map} names it"]
);
}
Loading
Loading