diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 547b6a24a4..4204383beb 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -134,12 +134,17 @@ pub fn commands() -> Vec { ), C::new("layout.removeElement", "Delete Element", "Publish › Element", |s, p| { let id = element_id(p)?; + let named = maps_layouts_name(&s.project); let l = active(s, p)?; // A frame's surrounds go with it: a locked one keeps the frame too. if let Some(locked) = l.locked_in_removal(id).map(|e| e.id) { unlocked(l, locked)?; } - if l.remove(id) { Ok(Value::Null) } else { Err(format!("no element {id}")) } + if !l.remove(id) { + return Err(format!("no element {id}")); + } + say_map_texts(s, &named); + Ok(Value::Null) }).inputs(object_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layout"?, "element": id}"#), C::new("layout.frameZoom", "Zoom Frame", "Publish › Map Frame", frame_zoom).inputs(frame_zoom_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( @@ -222,6 +227,7 @@ fn element_id(p: &Value) -> Result { fn arrange(s: &mut Session, p: &Value) -> CmdResult { let id = element_id(p)?; let to = ps(p, "to").and_then(Arrange::from_name).ok_or("to is front, forward, backward or back")?; + let named = maps_layouts_name(&s.project); let l = active(s, p)?; if l.element(id).is_none() { return Err(format!("no element {id}")); @@ -234,6 +240,8 @@ fn arrange(s: &mut Session, p: &Value) -> CmdResult { if before == Some(index) { s.request_only = true; } + // The first map frame is the lowest: sending a frame back, or another forward, can change it. + say_map_texts(s, &named); Ok(json!({"element": id, "index": index, "of": of})) } @@ -335,7 +343,9 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { let frame = l.add("Map Frame", (m, m + 16.0, fw, fh), frame_kind(s, &map, fw, FrameShape::Rectangle)); let side = m + fw + 6.0; let sw = w - side - m; - l.add("Title", (m, m, w - 2.0 * m, 14.0), ElementKind::text(map.clone(), 22.0, Rgba::rgb(0x1F, 0x29, 0x37), true)); + // The token, not the map's name as typed text: the title follows a rename of the map in + // the first map frame, as the layout draws it. + l.add("Title", (m, m, w - 2.0 * m, 14.0), ElementKind::text("{map}", 22.0, Rgba::rgb(0x1F, 0x29, 0x37), true)); l.add( "Legend", (side, m + 16.0, sw, fh * 0.6), @@ -574,15 +584,33 @@ pub(crate) fn capitals(t: &str) -> String { out } +/// A publication text broken to its box's width. +#[derive(Default)] +pub(crate) struct Broken { + /// What its element holds. + text: String, + /// The lines it is drawn in, which size its box. + lines: Vec, + /// Whether the element wraps to its box as it is drawn. + wrap: bool, +} + +impl From> for Broken { + /// Lines the element holds as they are drawn. + fn from(lines: Vec) -> Self { + Self { text: lines.join("\n"), lines, wrap: false } + } +} + /// A text element in a publication layout's style: upright, sans, in `align`. -fn pub_text(text: String, size: f64, color: Rgba, bold: bool, align: TextAlign) -> ElementKind { +fn pub_text(text: Broken, size: f64, color: Rgba, bold: bool, align: TextAlign) -> ElementKind { pub_text_in(text, size, color, bold, align, FontFamily::Sans) } /// [`pub_text`] in `font`. -fn pub_text_in(text: String, size: f64, color: Rgba, bold: bool, align: TextAlign, font: FontFamily) -> ElementKind { +fn pub_text_in(broken: Broken, size: f64, color: Rgba, bold: bool, align: TextAlign, font: FontFamily) -> ElementKind { ElementKind::Text { - text, + text: broken.text, size, color, bold, @@ -592,7 +620,7 @@ fn pub_text_in(text: String, size: f64, color: Rgba, bold: bool, align: TextAlig font, font_name: None, rotation: 0.0, - wrap: false, + wrap: broken.wrap, } } @@ -1355,9 +1383,24 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { .iter() .fold(t.to_string(), |t, (token, like)| t.replace(token, like)) }; - let wrap_as = |t: &str, w: f64, pt: f64, bold: bool| { - crate::render::report::wrap_with(&fill(t), w.max(1.0), |x| crate::render::report::width_mm(&drawn(x), pt as f32, bold)) + // A text breaks at spaces, but `{map}` is one word as wide as the map's name. Where a line + // holding it is wider than the box with the name in it, the text is stored as it is and its + // element wraps to the box when drawn, so it still follows a rename of the map; its box is + // sized by the lines the page draws it in, which measures a line's ink. + let broken = |t: &str, w: f64, pt: f64, bold: bool, align: TextAlign, font: FontFamily| { + let (t, w) = (fill(t), w.max(1.0)); + let width = |x: &str| match font { + FontFamily::Serif => crate::render::report::serif_width_mm(&drawn(x), pt as f32, bold), + FontFamily::Sans => crate::render::report::width_mm(&drawn(x), pt as f32, bold), + }; + if t.lines().any(|l| l.contains("{map}") && width(l) > w) { + let lines = crate::render::layout::wrapped_lines(&drawn(&t), w, pt, bold, font, align); + Broken { text: t, lines, wrap: true } + } else { + Broken::from(crate::render::report::wrap_with(&t, w, width)) + } }; + let wrap_as = |t: &str, w: f64, pt: f64, bold: bool| broken(t, w, pt, bold, TextAlign::Left, FontFamily::Sans); let wrap = |t: &str, w: f64, pt: f64| wrap_as(t, w, pt, false); let pitch = crate::render::layout::line_pitch_mm; let ink = Rgba::rgb(0x2B, 0x26, 0x20); @@ -1388,7 +1431,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // The sources and the reference that have something in them, each its heading in `head_pt` and // lines in `body_pt`, `tw` wide. Each one's elements keep their names (`Sources`, `Reference`) // whatever its heading reads, the heading filled and wrapped like the rest. - let sections = |tw: f64, head_pt: f64, body_pt: f64| -> Vec<(&'static str, Vec, Vec)> { + let sections = |tw: f64, head_pt: f64, body_pt: f64| -> Vec<(&'static str, Broken, Broken)> { [("Sources", heading(0, "Sources"), &sources), ("Reference", heading(1, "Cartographic reference"), &reference)] .into_iter() .filter(|(.., texts)| !texts.is_empty()) @@ -1396,7 +1439,17 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // Filled first, so `{projection}` reads in capitals too; the live tokens left keep // their case (wrap_as fills again, which then finds nothing). let head = wrap_as(&capitals(&fill(&head)), tw, head_pt, true); - (name, head, texts.iter().flat_map(|t| wrap(t, tw, body_pt)).collect::>()) + let parts: Vec = texts.iter().map(|t| wrap(t, tw, body_pt)).filter(|b| !b.lines.is_empty()).collect(); + let text = parts.iter().map(|b| b.text.as_str()).collect::>().join("\n"); + // One of them wrapping as drawn wraps their element, so all are measured so. + let body = if parts.iter().any(|b| b.wrap) { + let (font, align) = (FontFamily::Sans, TextAlign::Left); + let lines = crate::render::layout::wrapped_lines(&drawn(&text), tw.max(1.0), body_pt, false, font, align); + Broken { text, lines, wrap: true } + } else { + Broken { text, lines: parts.into_iter().flat_map(|b| b.lines).collect(), wrap: false } + }; + (name, head, body) }) .collect() }; @@ -1432,26 +1485,23 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { type Around = Vec<(String, (f64, f64, f64, f64), ElementKind)>; let footer = |around: &mut Around, look: &Look, note_here: bool, boxes_here: bool| -> f64 { let bottom = page_h - m - pad; - let author_lines = author.as_deref().map(|t| wrap(t, iw, small_pt)).unwrap_or_default(); - let author_h = author_lines.len() as f64 * pitch(small_pt); + let author_lines = + author.as_deref().map(|t| broken(t, iw, small_pt, false, TextAlign::Right, FontFamily::Sans)).unwrap_or_default(); + let author_h = author_lines.lines.len() as f64 * pitch(small_pt); let author_y = bottom - author_h; - if !author_lines.is_empty() { + if !author_lines.lines.is_empty() { around.push(( "Author".into(), (x0, author_y, iw, author_h), - pub_text(author_lines.join("\n"), small_pt, look.small, false, TextAlign::Right), + pub_text(author_lines, small_pt, look.small, false, TextAlign::Right), )); } let mut foot = author_y; let note_lines = note.as_deref().filter(|_| note_here).map(|t| wrap(t, iw, body_pt)).unwrap_or_default(); - if !note_lines.is_empty() { - let nh = note_lines.len() as f64 * pitch(body_pt); + if !note_lines.lines.is_empty() { + let nh = note_lines.lines.len() as f64 * pitch(body_pt); foot -= nh + 1.5 * k; - around.push(( - "Note".into(), - (x0, foot, iw, nh), - pub_text(note_lines.join("\n"), body_pt, look.small, false, TextAlign::Left), - )); + around.push(("Note".into(), (x0, foot, iw, nh), pub_text(note_lines, body_pt, look.small, false, TextAlign::Left))); } if !boxes_here { return foot; @@ -1462,8 +1512,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let cw = (iw - gap * (n - 1.0)) / n; let tw = cw - 2.0 * inner; let columns = sections(tw, head_pt, body_pt); - let heads = columns.iter().map(|(_, h, _)| h.len()).max().unwrap_or(1); - let rows = columns.iter().map(|(.., l)| l.len()).max().unwrap_or(0); + let heads = columns.iter().map(|(_, h, _)| h.lines.len()).max().unwrap_or(1); + let rows = columns.iter().map(|(.., l)| l.lines.len()).max().unwrap_or(0); if rows > 0 { let head_h = heads as f64 * pitch(head_pt); let bh = 2.0 * inner + head_h + rows as f64 * pitch(body_pt); @@ -1478,16 +1528,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let tx = bx + inner; around.push(( format!("{name} Heading"), - (tx, foot + inner, tw, head.len() as f64 * pitch(head_pt)), - pub_text(head.join("\n"), head_pt, look.head, true, TextAlign::Left), + (tx, foot + inner, tw, head.lines.len() as f64 * pitch(head_pt)), + pub_text(head, head_pt, look.head, true, TextAlign::Left), )); - if !lines.is_empty() { - let body = (tx, foot + inner + head_h, tw, lines.len() as f64 * pitch(body_pt)); - around.push(( - name.to_string(), - body, - pub_text(lines.join("\n"), body_pt, look.body, false, TextAlign::Left), - )); + if !lines.lines.is_empty() { + let body = (tx, foot + inner + head_h, tw, lines.lines.len() as f64 * pitch(body_pt)); + around.push((name.to_string(), body, pub_text(lines, body_pt, look.body, false, TextAlign::Left))); } } } @@ -1517,23 +1563,15 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { Style::Classic => { let mut top = m + pad; if let Some(t) = &title { - let lines = wrap_as(t, iw, title_pt, true); - let th = lines.len() as f64 * pitch(title_pt) + 1.5 * k; - around.push(( - "Title".into(), - (x0, top, iw, th), - pub_text(lines.join("\n"), title_pt, ink, true, TextAlign::Center), - )); + let lines = broken(t, iw, title_pt, true, TextAlign::Center, FontFamily::Sans); + let th = lines.lines.len() as f64 * pitch(title_pt) + 1.5 * k; + around.push(("Title".into(), (x0, top, iw, th), pub_text(lines, title_pt, ink, true, TextAlign::Center))); top += th; } if let Some(t) = &subtitle { - let lines = wrap(t, iw, sub_pt); - let sh = lines.len() as f64 * pitch(sub_pt) + 1.0 * k; - around.push(( - "Subtitle".into(), - (x0, top, iw, sh), - pub_text(lines.join("\n"), sub_pt, soft, false, TextAlign::Center), - )); + let lines = broken(t, iw, sub_pt, false, TextAlign::Center, FontFamily::Sans); + let sh = lines.lines.len() as f64 * pitch(sub_pt) + 1.0 * k; + around.push(("Subtitle".into(), (x0, top, iw, sh), pub_text(lines, sub_pt, soft, false, TextAlign::Center))); top += sh; } let foot = footer(&mut around, &plain, true, true); @@ -1552,31 +1590,37 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if title.is_some() || subtitle.is_some() { let big = title_pt * 1.2; let t_max = if subtitle.is_some() { 0.42 * iw } else { iw }; - let t_lines = title.as_deref().map(|t| wrap_as(t, t_max, big, true)).unwrap_or_default(); + let mut t_lines = title.as_deref().map(|t| wrap_as(t, t_max, big, true)).unwrap_or_default(); let t_w = t_lines + .lines .iter() .map(|x| crate::render::report::width_mm(&drawn(x), big as f32, true)) .fold(0.0, f64::max) .min(t_max) .ceil(); - let rule = if t_lines.is_empty() { 0.0 } else { 6.0 * k }; + // A title that wraps as it is drawn is measured again at the box it got. + if let Some(t) = title.as_deref().filter(|_| t_lines.wrap) { + t_lines = wrap_as(t, t_w, big, true); + } + let rule = if t_lines.lines.is_empty() { 0.0 } else { 6.0 * k }; let s_x = x0 + t_w + rule; let s_w = (x0 + iw - s_x).max(20.0 * k); let s_lines = subtitle.as_deref().map(|t| wrap(t, s_w, sub_pt)).unwrap_or_default(); - let (t_h, s_h) = (t_lines.len() as f64 * pitch(big), s_lines.len() as f64 * pitch(sub_pt)); + let (t_h, s_h) = (t_lines.lines.len() as f64 * pitch(big), s_lines.lines.len() as f64 * pitch(sub_pt)); + let (titled, subtitled) = (!t_lines.lines.is_empty(), !s_lines.lines.is_empty()); let band_h = t_h.max(s_h) + 2.0 * pad; let mid = m + band_h / 2.0; if !poster { around.push(("Banner".into(), (m, m, page_w - 2.0 * m, band_h), pub_box(accent, clear, 0.0))); } - if !t_lines.is_empty() { + if titled { around.push(( "Title".into(), (x0, mid - t_h / 2.0, t_w, t_h), - pub_text(t_lines.join("\n"), big, white, true, TextAlign::Left), + pub_text(t_lines, big, white, true, TextAlign::Left), )); } - if !t_lines.is_empty() && !s_lines.is_empty() { + if titled && subtitled { around.push(( "Banner Rule".into(), (x0 + t_w + rule / 2.0 - 0.5, mid - t_h.max(s_h) / 2.0, 1.0, t_h.max(s_h)), @@ -1589,11 +1633,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { }, )); } - if !s_lines.is_empty() { + if subtitled { around.push(( "Subtitle".into(), (s_x, mid - s_h / 2.0, s_w, s_h), - pub_text(s_lines.join("\n"), sub_pt, Rgba::rgb(0xF2, 0xEE, 0xE6), false, TextAlign::Left), + pub_text(s_lines, sub_pt, Rgba::rgb(0xF2, 0xEE, 0xE6), false, TextAlign::Left), )); } top = m + band_h; @@ -1633,18 +1677,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if let Some(t) = &title { let big = title_pt * 1.3; let lines = wrap_as(t, tw, big, true); - let th = lines.len() as f64 * pitch(big); - around.push(("Title".into(), (x0, y, tw, th), pub_text(lines.join("\n"), big, ink, true, TextAlign::Left))); + let th = lines.lines.len() as f64 * pitch(big); + around.push(("Title".into(), (x0, y, tw, th), pub_text(lines, big, ink, true, TextAlign::Left))); y += th; } if let Some(t) = &subtitle { let lines = wrap(t, tw, sub_pt); - let sh = lines.len() as f64 * pitch(sub_pt); - around.push(( - "Subtitle".into(), - (x0, y, tw, sh), - pub_text(lines.join("\n"), sub_pt, soft, false, TextAlign::Left), - )); + let sh = lines.lines.len() as f64 * pitch(sub_pt); + around.push(("Subtitle".into(), (x0, y, tw, sh), pub_text(lines, sub_pt, soft, false, TextAlign::Left))); y += sh; } if y > m + pad { @@ -1691,22 +1731,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let mut y = top + ip; if let Some(t) = &title { let lines = wrap_as(t, tw, title_pt, true); - let th = lines.len() as f64 * pitch(title_pt); - around.push(( - "Title".into(), - (ix, y, tw, th), - pub_text(lines.join("\n"), title_pt, ink, true, TextAlign::Left), - )); + let th = lines.lines.len() as f64 * pitch(title_pt); + around.push(("Title".into(), (ix, y, tw, th), pub_text(lines, title_pt, ink, true, TextAlign::Left))); y += th + 1.0 * k; } if let Some(t) = &subtitle { let lines = wrap(t, tw, sub_pt); - let sh = lines.len() as f64 * pitch(sub_pt); - around.push(( - "Subtitle".into(), - (ix, y, tw, sh), - pub_text(lines.join("\n"), sub_pt, soft, false, TextAlign::Left), - )); + let sh = lines.lines.len() as f64 * pitch(sub_pt); + around.push(("Subtitle".into(), (ix, y, tw, sh), pub_text(lines, sub_pt, soft, false, TextAlign::Left))); y += sh; } if y > top + ip { @@ -1720,18 +1752,18 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // The sources and the reference, stacked up from the panel's foot. let mut yb = panel_bottom - ip; for (name, head, lines) in sections(tw, head_pt, body_pt).into_iter().rev().filter(|_| !under) { - let (hh, bh) = (head.len() as f64 * pitch(head_pt), lines.len() as f64 * pitch(body_pt)); + let (hh, bh) = (head.lines.len() as f64 * pitch(head_pt), lines.lines.len() as f64 * pitch(body_pt)); yb -= hh + bh; around.push(( format!("{name} Heading"), (ix, yb, tw, hh), - pub_text(head.join("\n"), head_pt, accent, true, TextAlign::Left), + pub_text(head, head_pt, accent, true, TextAlign::Left), )); - if !lines.is_empty() { + if !lines.lines.is_empty() { around.push(( name.to_string(), (ix, yb + hh, tw, bh), - pub_text(lines.join("\n"), body_pt, soft, false, TextAlign::Left), + pub_text(lines, body_pt, soft, false, TextAlign::Left), )); } yb -= 3.0 * k; @@ -1758,30 +1790,26 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let gap = 6.0 * k; let cw = (0.3 * iw).max(45.0 * k).min(0.4 * iw); let (mw, cx) = (iw - cw - gap, x0 + iw - cw); - let serif_wrap = |t: &str, w: f64, pt: f64, bold: bool| { - crate::render::report::wrap_with(&fill(t), w.max(1.0), |x| { - crate::render::report::serif_width_mm(&drawn(x), pt as f32, bold) - }) - }; + let serif_wrap = |t: &str, w: f64, pt: f64, bold: bool| broken(t, w, pt, bold, TextAlign::Left, FontFamily::Serif); let (big, sub) = (30.0 * k, 13.0 * k); let mut y = m + pad; if let Some(t) = &title { let lines = serif_wrap(t, mw, big, true); - let th = lines.len() as f64 * pitch(big); + let th = lines.lines.len() as f64 * pitch(big); around.push(( "Title".into(), (x0, y, mw, th), - pub_text_in(lines.join("\n"), big, accent, true, TextAlign::Left, FontFamily::Serif), + pub_text_in(lines, big, accent, true, TextAlign::Left, FontFamily::Serif), )); y += th + 1.0 * k; } if let Some(t) = &subtitle { let lines = serif_wrap(t, mw, sub, false); - let sh = lines.len() as f64 * pitch(sub); + let sh = lines.lines.len() as f64 * pitch(sub); around.push(( "Subtitle".into(), (x0, y, mw, sh), - pub_text_in(lines.join("\n"), sub, soft, false, TextAlign::Left, FontFamily::Serif), + pub_text_in(lines, sub, soft, false, TextAlign::Left, FontFamily::Serif), )); y += sh; } @@ -1797,19 +1825,15 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if let Some(hd) = headings.get(2).filter(|h| !h.trim().is_empty()) { let pt = head_pt * 1.2; let lines = wrap_as(&capitals(&fill(hd)), cw, pt, true); - let hh = lines.len() as f64 * pitch(pt); - around.push(( - "Column Heading".into(), - (cx, cy, cw, hh), - pub_text(lines.join("\n"), pt, accent, true, TextAlign::Left), - )); + let hh = lines.lines.len() as f64 * pitch(pt); + around.push(("Column Heading".into(), (cx, cy, cw, hh), pub_text(lines, pt, accent, true, TextAlign::Left))); cy += hh + 2.0 * k; } if let Some(t) = ¬e { let pt = body_pt * 1.15; let lines = wrap(t, cw, pt); - let nh = lines.len() as f64 * pitch(pt); - around.push(("Note".into(), (cx, cy, cw, nh), pub_text(lines.join("\n"), pt, soft, false, TextAlign::Left))); + let nh = lines.lines.len() as f64 * pitch(pt); + around.push(("Note".into(), (cx, cy, cw, nh), pub_text(lines, pt, soft, false, TextAlign::Left))); cy += nh + 4.0 * k; } if fb - cy < 30.0 * k { @@ -1846,10 +1870,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let line = reference.iter().map(|t| fill(t)).collect::>().join(" · "); // A millimetre in from the paper's edges, which a journal may trim. let lines = wrap(&line, page_w - 2.0, FIGURE_PT); - if lines.len() > 1 { + if lines.lines.len() > 1 { warnings.push("the reference is wider than the figure: it wraps under the map".into()); } - let note_h = lines.len() as f64 * pitch(FIGURE_PT) + 1.0; + let note_h = lines.lines.len() as f64 * pitch(FIGURE_PT) + 1.0; let fh = if page_h > 0.0 { page_h - note_h } else { @@ -1866,7 +1890,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { around.push(( "Reference".into(), (1.0, fh + 1.0, page_w - 2.0, note_h - 1.0), - pub_text(lines.join("\n"), FIGURE_PT, ink, false, TextAlign::Left), + pub_text(lines, FIGURE_PT, ink, false, TextAlign::Left), )); (page_w, h, (0.0, 0.0, page_w, fh), None) }) @@ -2965,7 +2989,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { placed.push(("scale bar", (sx, sy, w, h))); l.add("Scale Box", (sx, sy, w, sh + nh), surround_box(paper)); l.add("Scale Bar", (sx, sy, w, sh), scale_bar); - l.add("Scale", (sx, sy + sh, w, nh), pub_text("{scale}".into(), small_pt, ink, false, TextAlign::Center)); + l.add("Scale", (sx, sy + sh, w, nh), pub_text(Broken::from(vec!["{scale}".to_string()]), small_pt, ink, false, TextAlign::Center)); } // What placing couldn't avoid: a surround over the map's drawing while a clearly freer corner // went to another (more surrounds than free corners), or two overlapping (a frame too small @@ -3096,6 +3120,67 @@ fn page(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"width": w, "height": h, "decimal": if l.decimal_comma { "," } else { "." }})) } +/// For each layout, the map its `{map}` texts name: the one its first map frame shows, as the +/// project names it; None when that frame or its map is gone. +pub(crate) fn maps_layouts_name(project: &crate::project::Project) -> Vec> { + let named = |l: &Layout| { + let frame = l.first_frame().and_then(|id| l.element(id))?; + let ElementKind::MapFrame { map, .. } = &frame.kind else { return None }; + crate::render::layout::map_index(&project.maps, map).and_then(|i| project.maps.get(i)).map(|m| m.name.clone()) + }; + project.layouts.iter().map(named).collect() +} + +/// Says which `{map}` texts a change (`before` it, [`maps_layouts_name`], layouts in the same +/// order) left naming another map or none: `{map}` follows the layout's first map frame, which +/// is the lowest in the drawing order, so removing or reordering frames can change it. One +/// notice for each, with the count. +pub(crate) fn say_map_texts(s: &mut Session, before: &[Option]) { + let after = maps_layouts_name(&s.project); + let (mut empty, mut moved) = (Vec::new(), Vec::new()); + for (l, (was, now)) in s.project.layouts.iter().zip(before.iter().zip(&after)) { + let Some(was) = was else { continue }; + let n = l.elements.iter().filter(|e| matches!(&e.kind, ElementKind::Text { text, .. } if text.contains("{map}"))).count(); + match now { + _ if n == 0 => {} + None => empty.push((l.name.as_str(), n)), + Some(now) if !now.eq_ignore_ascii_case(was) => moved.push((l.name.as_str(), n, now.as_str())), + Some(_) => {} + } + } + let texts = |n: usize| if n == 1 { format!("{n} text with {{map}}") } else { format!("{n} texts with {{map}}") }; + let n: usize = empty.iter().map(|(_, n)| n).sum(); + let notice = match empty.as_slice() { + [] => None, + [(name, _)] => Some(format!("Layout '{name}': {}", texts(n))), + more => Some(format!("{} layouts: {}", more.len(), texts(n))), + }; + let mut said = Vec::new(); + if let Some(whose) = notice { + let have = if n == 1 { "has" } else { "have" }; + said.push(format!("{whose} {have} no map frame showing a map to name, so {{map}} draws empty")); + } + let n: usize = moved.iter().map(|(_, n, _)| n).sum(); + let notice = match moved.as_slice() { + [] => None, + [(name, _, map)] => Some(format!( + "Layout '{name}': its first map frame, the lowest in the drawing order, now shows '{map}', so {} {} it", + texts(n), + if n == 1 { "names" } else { "name" } + )), + more => Some(format!( + "{} layouts: their first map frame, the lowest in the drawing order, now shows another map, so {} {} that one", + more.len(), + texts(n), + if n == 1 { "names" } else { "name" } + )), + }; + said.extend(notice); + for text in said { + s.notify(text, false); + } +} + /// A sheet's footer of two columns, its right one moved to start where a legend at the right of the /// frame (`frame` its left edge and width, page mm) does, when that is between 45 % and 70 % of the /// frame's width, so the two line up (#1379). Each column's heading and lines are wrapped again to @@ -3105,7 +3190,7 @@ pub(crate) fn align_footer( around: &mut [(String, Rect, ElementKind)], legend: Rect, (fx, fw): (f64, f64), - sections: &dyn Fn(f64, f64, f64) -> Vec<(&'static str, Vec, Vec)>, + sections: &dyn Fn(f64, f64, f64) -> Vec<(&'static str, Broken, Broken)>, ) { let at = (legend.0 - fx) / fw; if !(0.45..=0.70).contains(&at) || legend.0 + legend.2 < fx + 0.9 * fw { @@ -3129,8 +3214,8 @@ pub(crate) fn align_footer( let pitch = crate::render::layout::line_pitch_mm; let column = |w: f64, name: &str| sections(w - 2.0 * inner, head_pt, body_pt).into_iter().find(|(n, ..)| *n == name); let (Some((_, l_head, l_lines)), Some((_, r_head, r_lines))) = (column(lw, "Sources"), column(rw, "Reference")) else { return }; - let head_h = l_head.len().max(r_head.len()) as f64 * pitch(head_pt); - let rows = l_lines.len().max(r_lines.len()); + let head_h = l_head.lines.len().max(r_head.lines.len()) as f64 * pitch(head_pt); + let rows = l_lines.lines.len().max(r_lines.lines.len()); if 2.0 * inner + head_h + rows as f64 * pitch(body_pt) > left.3 + 1e-6 { return; } @@ -3138,17 +3223,13 @@ pub(crate) fn align_footer( let y = left.1; for (part, r, text) in [ (format!("{name} Box"), (x, y, w, left.3), None), - (format!("{name} Heading"), (x + inner, y + inner, w - 2.0 * inner, head.len() as f64 * pitch(head_pt)), Some(head.join("\n"))), - ( - name.to_string(), - (x + inner, y + inner + head_h, w - 2.0 * inner, lines.len() as f64 * pitch(body_pt)), - Some(lines.join("\n")), - ), + (format!("{name} Heading"), (x + inner, y + inner, w - 2.0 * inner, head.lines.len() as f64 * pitch(head_pt)), Some(head)), + (name.to_string(), (x + inner, y + inner + head_h, w - 2.0 * inner, lines.lines.len() as f64 * pitch(body_pt)), Some(lines)), ] { if let Some(e) = around.iter_mut().find(|(n, ..)| *n == part) { e.1 = r; - if let (Some(new), ElementKind::Text { text, .. }) = (text, &mut e.2) { - *text = new; + if let (Some(new), ElementKind::Text { text, wrap, .. }) = (text, &mut e.2) { + (*text, *wrap) = (new.text, new.wrap); } } } diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 7463431b39..4ca2478037 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -214,6 +214,7 @@ pub fn commands() -> Vec { 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; @@ -224,6 +225,7 @@ pub fn commands() -> Vec { 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}"#), diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 55222935d1..df68884e7e 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -284,6 +284,7 @@ pub fn commands() -> Vec { 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 @@ -312,6 +313,7 @@ pub fn commands() -> Vec { 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}"#), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d2bc6eec41..5da3a069f6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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; @@ -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(), @@ -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::>()) + } // 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. @@ -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, Vec)>; + 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 { diff --git a/crates/engine/src/tests/layout_title.rs b/crates/engine/src/tests/layout_title.rs new file mode 100644 index 0000000000..5b2dd87afc --- /dev/null +++ b/crates/engine/src/tests/layout_title.rs @@ -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 { + 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("").next().unwrap(); + let after_tag = |t: &str| t.split_once('>').unwrap().1.to_string(); + if text.contains("").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 { + let mark = s.notice_mark(); + s.run(command, ¶ms).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 = + 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::::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::::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::::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::::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::::new()); + assert_eq!(map_notices(&mut s, "layout.arrange", json!({"element": detail, "to": "front"})), Vec::::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"] + ); +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 25ed8b4b14..d5f86bd107 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4429,6 +4429,13 @@ pub(crate) fn wrapped(s: &str, width: f64, size: f64, style: TextStyle) -> Strin crate::report::wrap_lines(s, width * WRAP_PX_PER_MM, measure, 200).join("\n") } +/// The lines a wrapped text element (#2346), upright and without letter spacing or a named family, +/// is drawn in: `s`, its text with the dynamic text filled in, in a box `width` mm wide. For a +/// caller that sizes the box around the text. +pub fn wrapped_lines(s: &str, width: f64, size: f64, bold: bool, font: rustgis_map::layout::FontFamily, align: TextAlign) -> Vec { + wrapped(s, width, size, text_style(bold, false, font, None, align, 0.0)).lines().map(str::to_string).collect() +} + /// A colorbar's title's size in points; it is drawn bold. pub const COLORBAR_TITLE_PT: f64 = 9.0; diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 14c3aa8005..a5900ab61f 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1190,11 +1190,12 @@ fn map_labeling_group(app: &mut RustGisApp, ui: &mut Ui) { } /// Runs `layout.publication` for `profile` from the New Layout menu, in `style` on a sheet: a sheet -/// is titled with the map's name, a figure's title being its caption's. +/// is titled with the map's name as `{map}`, so the title follows a rename of the map, a figure's +/// title being its caption's. fn publication_layout(app: &mut RustGisApp, profile: &rustgis_engine::cmd::layout::PublicationProfile, style: Option<&str>) { let mut p = json!({"profile": profile.id}); if profile.sheet { - p["title"] = json!(app.session.map().name.clone()); + p["title"] = json!("{map}"); } if let Some(style) = style { p["style"] = json!(style); @@ -6890,10 +6891,9 @@ mod tests { let l = app.session.project.layouts.last().unwrap(); assert!(l.elements.iter().any(|e| e.name == "Panel Box"), "the panel style"); assert!((l.width, l.height) == (210.0, 297.0), "an A4 portrait sheet: {} × {}", l.width, l.height); - let title = app.session.map().name.clone(); assert!( - l.elements.iter().any(|e| matches!(&e.kind, rustgis_engine::map::layout::ElementKind::Text { text, .. } if *text == title)), - "titled with the map's name" + l.elements.iter().any(|e| matches!(&e.kind, rustgis_engine::map::layout::ElementKind::Text { text, .. } if text == "{map}")), + "titled with the map's name as {{map}}, so a rename of the map changes it" ); assert_eq!(app.ui.tab, "Publish"); assert!(h.query_by_label("Banner").is_none(), "the menu closed"); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2188dee782..d419563d25 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -8,7 +8,9 @@ Home › New Layout adds a page layout (Letter, Legal, Tabloid or A5 to A0, landscape or portrait) -with a map frame, title, legend, north arrow, scale bar and a dynamic credits line. The command +with a map frame, title, legend, north arrow, scale bar and a dynamic credits line. The title is +the dynamic text `{map}`, so it follows a rename of the map in the first map frame; replace it +with your own text for a title that stays. The command `layout.new` also accepts custom `width` and `height` in millimetres and `"template": "blank"`. Both `layout.new` and each layout in `info` include an `elements` array with each element's `element` ID, `name` and `kind`, ready to use in `layout.update` or `layout.removeElement`.