diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d0a77aac3a..6f7a5cc6ec 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -282,7 +282,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? @@ -304,7 +304,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index ed9e60be24..0bf6547e7e 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -11,9 +11,9 @@ use rustgis_map::layout::{ FrameShape, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, Guides, LAYOUT_TEXT_SIZE, LINE_SPACING, LayerNames, Layout, LegendFit, LineDir, LineHead, MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, MAX_COLORBAR_TICKS, MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_LINE_SPACING, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, - MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_TICK_MM, MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, MIN_LINE_SPACING, MapSeries, - Orientation, PAGES, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, - TickSide, UnitLabelPosition, fit_scale, line_angle, line_at_angle, line_length, + MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_SECTIONS, MAX_TICK_MM, MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, MIN_LINE_SPACING, + MapSeries, Orientation, PAGES, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, Section, SectionLine, + TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, fit_scale, line_angle, line_at_angle, line_length, }; use rustgis_map::report::StatKind; use rustgis_map::symbology::{Dash, MAX_DASH_STEP, MAX_DASH_STEPS}; @@ -180,12 +180,12 @@ pub fn commands() -> Vec { C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( concat!( r##"{"layout"?, "##, - r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "##, + r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name), "##, r##""frame"?: element id (default: the first map frame), "##, r##""of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "##, r##""text"? (a text's words; {count:Layer}, {sum:Layer:field}, {mean:Layer:field}, {min:Layer:field} and {max:Layer:field} show the layer's figure, as {scale} shows the scale: of the first map frame's map, over the features the layer's definition query keeps, with the layout's decimal mark; one with no figure shows as written and says why), "##, r##""size"?, "##, - r##""color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, + r##""color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; section, default #A8431F; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, r##""bold"?: bool (text), "##, r##""italic"?: bool, "##, r##""align"?: "left"|"center"|"right", "##, @@ -210,9 +210,9 @@ pub fn commands() -> Vec { r##""tickSide"?: "below"|"above"|"right"|"left" (colorbar), "##, r##""reverse"?: bool (colorbar: high values first), "##, r##""fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "##, - r##""width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "##, + r##""width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid; section, 0.1 to 20, default 1.5), "##, r##""radius"?: mm, 0 to 50 (rectangle: rounded corners), "##, - r##""dash"?: [points, …] (line, arrow, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "##, + r##""dash"?: [points, …] (line, arrow, section, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "##, r##""dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "##, r##""head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "##, r##""angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "##, @@ -252,6 +252,9 @@ pub fn commands() -> Vec { r##""labelOrientation"?: "horizontal"|"vertical", "##, r##""labelSize"?: points, 4 to 100 (its labels, their room from the frame's edge and MGRS squares' names following; default 8; null gives it back; refused outside that range, and for other kinds unless null), "##, r##""off"?: bool (grid; options not given keep the grid's), "##, + r##""name"?: a section's name, up to 20 characters, its frame's only one of that name (section, default the first free letter; a grid and an extent indicator refuse it, other kinds say they ignore it), "##, + r##""direction"?: "horizontal" (the default)|"vertical" (section: across the whole frame, straight on the page, named at its left and right ends or its top and bottom ones; refused for other kinds), "##, + r##""at"?: [longitude, latitude] (section: the place the line runs through and keeps to when the frame is moved, turned or rescaled, default the frame's centre; a line whose place is outside the frame isn't drawn, which a notice and exports say; refused for other kinds), "##, r##""outline"?: "#RRGGBB" (northArrow, or a rectangle's, ellipse's or circle's outline instead of color; refused for other kinds), "##, r##""units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "##, r##""divisions"?: 1..10, at most 10 with divisionsBeforeZero together, more refused (scaleBar, whose "color" is its lines, dark divisions and labels, default #222222), "##, @@ -265,7 +268,7 @@ pub fn commands() -> Vec { r##""y"?, "##, r##""w"?, "##, r##""h"?: mm, "##, - r##""background"?: {"fill"?: "#RRGGBB"|"#RRGGBBAA" (default white), "outline"?: colour (default #222222), "width"?: the outline's points (default 0, none), "radius"?: mm, its corners (0 to 50), "padding"?: mm it reaches past the box on every side (0 to 50)} | null (a box drawn behind the element, turned with a turned text; none by default; a map frame takes none, so it is refused for grid and extentIndicator)}"##, + r##""background"?: {"fill"?: "#RRGGBB"|"#RRGGBBAA" (default white), "outline"?: colour (default #222222), "width"?: the outline's points (default 0, none), "radius"?: mm, its corners (0 to 50), "padding"?: mm it reaches past the box on every side (0 to 50)} | null (a box drawn behind the element, turned with a turned text; none by default; a map frame takes none, so it is refused for grid, extentIndicator and section)}"##, ), ), C::new("layout.update", "Element Properties", "Publish › Element", update).inputs(update_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( @@ -332,6 +335,7 @@ pub fn commands() -> Vec { r##""grid"?: {grid options as in layout.addElement} | false (map frame; a grid's "labelSize" goes in it, and is refused outside it unless null), "##, r##""extentIndicator"?: {"color"?, "width"?: points} | false (map frame: its extent indicator's style, or removes it), "##, r##""border"?: {"color"?: "#RRGGBB"|"#RRGGBBAA", "width"?: points, 0 to 20, 0 for none} | null (map frame: the outline along its shape, default #303030 and 0.8, the keys not given keeping theirs; null gives the default back; refused for other elements), "##, + r##""section"?: {"name": the section line it changes, "newName"?, "direction"?, "at"?, "color"?, "width"?, "dash"? ([] or null for solid), as in layout.addElement, the keys not given keeping theirs, "remove"?: true to remove it} (map frame; refused for other elements), "##, r##""layer"?: (colorbar: "" for the top visible raster with a colour scale, not drawn by classes), "##, r##""field"?, "##, r##""label"?, "##, @@ -546,6 +550,7 @@ fn frame_kind(s: &Session, map: &str, w: f64, shape: FrameShape) -> ElementKind scale, shape, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index f41912d0c9..0cdcdd3fcf 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -75,9 +75,10 @@ pub(in crate::cmd::layout) fn place(p: &Value, l: &Layout, (dx, dy, dw, dh): (f6 /// Said when a map frame is given a background: it draws its map and its paper itself. pub(in crate::cmd::layout) const NO_FRAME_BACKGROUND: &str = "a map frame takes no background: it draws its map and the paper behind it"; -/// Said when a grid or an extent indicator is added with a background: they go on a map frame. +/// Said when a grid, an extent indicator or a section is added with a background: they go on a map +/// frame. pub(in crate::cmd::layout) const NO_OVERLAY_BACKGROUND: &str = - "a grid or an extent indicator goes on a map frame, which takes no background"; + "a grid, an extent indicator or a section goes on a map frame, which takes no background"; /// What an element's `background` object takes. pub(in crate::cmd::layout) const BACKGROUND_KEYS: [&str; 5] = ["fill", "outline", "width", "radius", "padding"]; @@ -275,7 +276,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu return Err(ONLY_RECTANGLE_RADIUS.into()); } // `null` too: on a line it means solid, so elsewhere it is refused rather than ignored. - if !matches!(kind, "line" | "arrow" | "rectangle" | "ellipse" | "circle") && p.get("dash").is_some() { + if !matches!(kind, "line" | "arrow" | "section" | "rectangle" | "ellipse" | "circle") && p.get("dash").is_some() { return Err(ONLY_DASH.into()); } if !matches!(kind, "text" | "dynamicText") && gives(p, "rotation") { @@ -290,6 +291,9 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if kind != "chart" && gives_chart_options_to(p, kind == "scaleBar") { return Err(ONLY_CHART_OPTIONS.into()); } + if kind != "section" && (gives(p, "direction") || gives(p, "at")) { + return Err(ONLY_SECTION.into()); + } // "unitLabel": null too, as layout.update refuses it, since it means something on a scale bar. if kind != "scaleBar" && (gives_scale_bar_details(p) || p.get("unitLabel").is_some()) { return Err(ONLY_SCALE_BAR_DETAILS.into()); @@ -305,6 +309,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu | "arrow" | "extentIndicator" | "grid" + | "section" | "scaleBar" | "legend" | "colorbar" @@ -324,10 +329,10 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if gives(p, "outline") && !shape { return Err(ONLY_OUTLINE.into()); } - // The box the new element sits on (#2257). A grid or an extent indicator goes on a map frame, - // which has none: refused rather than dropped. + // The box the new element sits on (#2257). A grid, an extent indicator or a section goes on a + // map frame, which has none: refused rather than dropped. let background = match element_background(p, None)? { - BackgroundParam::Set(_) if matches!(kind, "grid" | "extentIndicator") => return Err(NO_OVERLAY_BACKGROUND.into()), + BackgroundParam::Set(_) if matches!(kind, "grid" | "extentIndicator" | "section") => return Err(NO_OVERLAY_BACKGROUND.into()), BackgroundParam::Set(b) => Some(b), BackgroundParam::Absent | BackgroundParam::Remove => None, }; @@ -602,6 +607,33 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu } return Ok(json!({"element": frame})); } + "section" => { + // The frame's box is its own, and a line has no text: refused rather than dropped. + let given = p.as_object().and_then(|o| o.keys().find(|k| !ADDED_SECTION_KEYS.contains(&k.as_str()) && gives(p, k))); + if let Some(k) = given { + return Err(format!("a section takes no \"{k}\" (it reads {})", ADDED_SECTION_KEYS.join(", "))); + } + let frame = frame_of(l, p)?; + unlocked(l, frame)?; + let Some(ElementKind::MapFrame { sections, center, .. }) = l.element(frame).map(|e| &e.kind) else { + return Err(format!("element {frame} isn't a map frame")); + }; + if sections.len() >= MAX_SECTIONS { + return Err(format!("a map frame holds at most {MAX_SECTIONS} section lines")); + } + // The options given, over a horizontal line through the frame's middle. + let name = if gives(p, "name") { section_name(p, "name")? } else { Section::free_name(sections).unwrap_or_default() }; + let turn = if center.x.abs() > 180.0 { 360.0 * (center.x / 360.0).round() } else { 0.0 }; + let middle = Coord::new(center.x - turn, center.y); + let new = section_params(p, Section::new(name.clone(), SectionLine::Horizontal(middle)), sections, None)?; + let l = active(s, p)?; + if let Some(ElementKind::MapFrame { sections, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { + sections.push(new); + } + say_held(s, "Add Element", held_width(p, "section width", rustgis_map::layout::SECTION_WIDTHS).into_iter().collect()); + say_section_not_drawn(s, i, frame, &name); + return Ok(json!({"element": frame, "section": name})); + } o => return Err(format!("unknown element kind '{o}'")), }; let warning = match &k { @@ -635,6 +667,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu s.warn(said); } say_held(s, "Add Element", held_to_limits(p, Shape::of_name(kind))); + say_name_ignored(s, p, kind); let mut out = json!({"element": id}); if let Some(w) = warning { out["warning"] = json!(w); @@ -687,6 +720,91 @@ pub(in crate::cmd::layout) fn border_style(p: &Value, kind: &ElementKind) -> Res outline_style(p, current, (0.0, rustgis_map::layout::MAX_FRAME_BORDER_WIDTH)) } +/// Says that a `name` given for an element that isn't a section is ignored, as it always was. +fn say_name_ignored(s: &mut Session, p: &Value, kind: &str) { + if gives(p, "name") { + s.notify(format!("Add Element ignores \"name\" for a {kind}: only a section takes one (layout.update names an element)"), false); + } +} + +/// What a `direction` or an `at` given for an element that isn't a section is told. +const ONLY_SECTION: &str = "only sections take a direction and a place (at)"; +/// What `layout.addElement` takes for a section. +const ADDED_SECTION_KEYS: [&str; 9] = ["layout", "kind", "frame", "name", "direction", "at", "color", "width", "dash"]; +/// What a map frame's `"section"` object takes in `layout.update`. +const SECTION_KEYS: [&str; 8] = ["name", "newName", "direction", "at", "color", "width", "dash", "remove"]; + +/// The section name `p` gives as `key`, trimmed: refused blank or too long. +fn section_name(p: &Value, key: &str) -> Result { + let name = ps(p, key).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| format!("{key} must be a section line's name"))?; + crate::cmd::within(key, "a section line's name", name, rustgis_map::layout::MAX_SECTION_NAME) +} + +/// A section line with the options in `p` over `base`'s, its name one no other of its frame's +/// `sections` has (`own` is its own index there); a bad value is an error, leaving nothing changed. +fn section_params(p: &Value, base: Section, sections: &[Section], own: Option) -> Result { + let mut new = base; + if let Some(other) = Section::find(sections, &new.name).filter(|i| Some(*i) != own).and_then(|i| sections.get(i)) { + return Err(format!("the frame already has a section line '{}'", other.name)); + } + if let Some(v) = p.get("at").filter(|v| !v.is_null()) { + let place = v.as_array().filter(|a| a.len() == 2).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))); + let (x, y) = place + .filter(|(x, y)| (-180.0..=180.0).contains(x) && (-90.0..=90.0).contains(y)) + .ok_or("at is [longitude, latitude], within ±180 and ±90")?; + new.line = new.line.through(Coord::new(x, y)); + } + if gives(p, "direction") { + new.line = + ps(p, "direction").and_then(|d| SectionLine::from_name(d, new.line.at())).ok_or("direction is horizontal or vertical")?; + } + (new.color, new.width) = outline_style(p, (new.color, new.width), rustgis_map::layout::SECTION_WIDTHS)?; + new.dash = element_dash(p)?.unwrap_or(new.dash); + Ok(new) +} + +/// A map frame's section lines with the `"section"` object `v` of a `layout.update` applied, and +/// the one changed (`None` when it is removed). +pub(in crate::cmd::layout) fn sections_updated(v: &Value, sections: &[Section]) -> Result<(Vec
, Option), String> { + let o = v.as_object().ok_or("section is an object: the \"name\" of a section line and what changes of it")?; + if let Some(k) = o.keys().find(|k| !SECTION_KEYS.contains(&k.as_str())) { + return Err(format!("section takes no \"{k}\" (it reads {})", SECTION_KEYS.join(", "))); + } + let named = section_name(v, "name")?; + let i = Section::find(sections, &named).ok_or_else(|| format!("the frame has no section line '{named}'"))?; + let mut out = sections.to_vec(); + if let Some(remove) = v.get("remove").filter(|v| !v.is_null()) + && crate::cmd::bool_value(remove).ok_or("remove must be true or false")? + { + if let Some(k) = SECTION_KEYS.iter().find(|k| !matches!(**k, "name" | "remove") && gives(v, k)) { + return Err(format!("a removed section line takes no \"{k}\"")); + } + out.remove(i); + return Ok((out, None)); + } + let mut base = out.get(i).cloned().ok_or("no such section line")?; + if gives(v, "newName") { + base.name = section_name(v, "newName")?; + } + let new = section_params(v, base, sections, Some(i))?; + let name = new.name.clone(); + if let Some(slot) = out.get_mut(i) { + *slot = new; + } + Ok((out, Some(name))) +} + +/// Says that section line `name` of frame `frame` of layout `li` isn't drawn, when it isn't, and +/// why. A hidden frame's isn't said: nothing of it is drawn. +pub(in crate::cmd::layout) fn say_section_not_drawn(s: &mut Session, li: usize, frame: u32, name: &str) { + let Some(l) = s.project.layouts.get(li) else { return }; + let gaps = rustgis_render::layout::sections_not_drawn(l, &s.project.maps); + let gap = gaps.into_iter().filter(|g| g.frame == frame && g.section == name).map(|g| (g, 1)).collect(); + if let Some(note) = rustgis_render::layout::sections_notice(&gap, 1) { + s.warn(note); + } +} + /// An outline's colour and width (points, kept within `range`) from `color` and `width` in `p`, /// each keeping `current`'s when not given. pub(in crate::cmd::layout) fn outline_style(p: &Value, (c, w): (Rgba, f64), range: (f64, f64)) -> Result<(Rgba, f64), String> { @@ -703,7 +821,7 @@ pub(in crate::cmd::layout) fn outline_style(p: &Value, (c, w): (Rgba, f64), rang } /// What a `dash` given for an element that draws no line or outline is told. -pub(in crate::cmd::layout) const ONLY_DASH: &str = "only lines, arrows, rectangles, ellipses and circles take a dash"; +pub(in crate::cmd::layout) const ONLY_DASH: &str = "only lines, arrows, sections, rectangles, ellipses and circles take a dash"; /// A line's or an outline's `dash` when given, read as a line layer's stroke reads it /// (`layer.lineStrokes`): `Some(None)` for solid (`null` or `[]`), `Some(Some(_))` for a pattern, @@ -734,8 +852,8 @@ pub(in crate::cmd::layout) const ONLY_RECTANGLE_RADIUS: &str = "only a rectangle /// take them as applied: "color" is a text's, a line's, an arrow's, a scale bar's or a shape's /// outline (a rectangle's or an ellipse's), a legend's, colorbar's, table's or chart's ink (#2257), /// and, when adding, also an extent indicator's or a grid's. -pub(in crate::cmd::layout) const ONLY_COLOR_ADDED: &str = "only text, lines, arrows, rectangles, ellipses, circles, extent indicators, grids, scale bars, \ -legends, colorbars, tables and charts take a color"; +pub(in crate::cmd::layout) const ONLY_COLOR_ADDED: &str = "only text, lines, arrows, rectangles, ellipses, circles, extent indicators, grids, sections, \ +scale bars, legends, colorbars, tables and charts take a color"; pub(in crate::cmd::layout) const ONLY_COLOR_UPDATED: &str = "only text, lines, arrows, rectangles, ellipses, circles, scale bars, legends, colorbars, tables and charts take a color"; pub(in crate::cmd::layout) const ONLY_FILL: &str = "only north arrows, rectangles, ellipses, circles and scale bars take a fill"; diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 3e14839938..d48463674a 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -62,6 +62,10 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { clipped.retain(|(id, _)| layout.element(*id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } + let mut gaps: SectionGaps = rustgis_render::layout::sections_not_drawn(&layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); + if let Some(r) = region { + gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); + } let (img, mut unfitted) = rustgis_render::layout::unfitted_legends(|| { crate::cmd::share::saying_shadows(s, "The layout", |s| match region { Some(r) => rustgis_render::layout::render_region(&layout, &mut s.project.maps, dpi, &info, r), @@ -76,9 +80,15 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> s.warn(note); } say_unfitted_legends(s, &unfitted); + if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { + s.warn(note); + } img.encode_png().map_err(|e| e.to_string()) } +/// The section lines an export doesn't draw, each with the pages it is missing from. +type SectionGaps = BTreeMap; + /// What `view_map` draws when it is given a `layout`: the layout's frames' maps and their tiles, /// as exporting it reads them, rather than the active map's. `None` without a `layout`. pub(crate) fn view_inputs(input: &crate::cmd::InputContext<'_>, p: &Value) -> Option> { @@ -135,6 +145,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( // each with the page (from 1) it is on. let (mut left_out, mut by_corners): (Vec<(usize, u32, String, &'static str)>, Vec<(usize, u32, String)>) = (Vec::new(), Vec::new()); let mut clipped = BTreeMap::new(); + let mut gaps = SectionGaps::new(); let render_pages = || -> Result<(Vec, Option>), String> { let mut out = Vec::new(); let mut png = None; @@ -157,6 +168,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( }, }; clipped.extend(rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info)); + for gap in rustgis_render::layout::sections_not_drawn(layout, &s.project.maps) { + *gaps.entry(gap).or_default() += 1; + } // Each page is kept as vectors (its pictures compressed) as soon as it's drawn, within // a memory budget. if pdf { @@ -214,6 +228,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( if let Some(note) = rustgis_render::layout::clipped_text_notice(&saved, &clipped.into_iter().collect::>()) { s.warn(note); } + if let Some(note) = rustgis_render::layout::sections_notice(&gaps, pages.len()) { + s.warn(note); + } say_unfitted_legends(s, &unfitted); pictured_notices(s, &frames_pictured, &pages_pictured); georeference_notices(s, &left_out, &by_corners, pages.len()); @@ -437,10 +454,11 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - let layout = s.project.layouts.get(li).ok_or("no layout")?; let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info); let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); + let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); let (drawn, unfitted) = rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)); let (text, pictured) = drawn?; - if let Some(note) = note { + for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } say_unfitted_legends(s, &unfitted); diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index d9764ebf84..8c23837a49 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -83,7 +83,7 @@ pub(in crate::cmd::layout) fn element_inputs(input: &crate::cmd::InputContext<'_ let kind = ps(p, "kind").ok_or("kind is required")?; if !matches!(kind, "table" | "chart" | "colorbar" | "legend") { let mut inputs = object_inputs(input, p)?; - if matches!(kind, "northArrow" | "scaleBar" | "extentIndicator" | "grid") { + if matches!(kind, "northArrow" | "scaleBar" | "extentIndicator" | "grid" | "section") { let layout = s.project.layouts.get(index(input, p)?).ok_or("no layout")?; inputs.state["frame"] = json!(frame_of(layout, p)?); } diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index c778f9126d..bde53494ad 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -886,6 +886,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu scale, shape: FrameShape::Rectangle, grid: grid.clone(), + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -1794,6 +1795,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu scale: *locator_scale, shape: shape.clone(), grid: None, + sections: Vec::new(), extent_of: Some(frame), extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 8b9ce318bc..918ef9e35b 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -221,7 +221,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { // `true` adds the default one, an object changes the options it names, and null (not set) // leaves it as it is. let held; - let (restyled, new_grid, new_indicator, new_border) = { + let (restyled, new_grid, new_indicator, new_border, new_sections) = { let l = s.project.layouts.get(li).ok_or("no layout")?; let kind = &l.element(id).ok_or_else(|| format!("no element {id}"))?.kind; // `"extentIndicator": false` takes the frame's indicator away; an object restyles it. @@ -258,7 +258,15 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { (_, Some(_)) => return Err("only map frames have a grid".into()), _ => None, }; + let sections = match (kind, p.get("section").filter(|v| !v.is_null())) { + (ElementKind::MapFrame { sections, .. }, Some(v)) => Some(sections_updated(v, sections)?), + (_, Some(_)) => return Err("only map frames have section lines".into()), + _ => None, + }; let mut said = held_to_limits(p, Shape::of_kind(kind)); + if let (Some((_, Some(_))), Some(v)) = (§ions, p.get("section")) { + said.extend(held_width(v, "section width", rustgis_map::layout::SECTION_WIDTHS)); + } if let (ElementKind::MapFrame { .. }, Some(Some(_))) = (kind, &indicator) && let Some(v) = p.get("extentIndicator") { @@ -269,7 +277,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { said.extend(held_width(v, "border width", (0.0, rustgis_map::layout::MAX_FRAME_BORDER_WIDTH))); } held = said; - (restyle(kind, p)?, grid, indicator, border) + (restyle(kind, p)?, grid, indicator, border, sections) }; // A line turned to an "angle" or made a "length" long, about its centre: its new box, // direction and heads. @@ -626,8 +634,12 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { extent_width, border_color, border_width, + sections, .. } => { + if let Some((new, _)) = &new_sections { + sections.clone_from(new); + } match new_indicator { Some(None) => *extent_of = None, Some(Some((c, w))) => (*extent_color, *extent_width) = (c, w), @@ -790,6 +802,9 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { s.notify(said, false); } } + if let Some((_, Some(name))) = &new_sections { + say_section_not_drawn(s, li, id, name); + } say_held(s, "Element Properties", held); if let Some(w) = font_told { return Ok(json!({"warning": w})); diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 219cbf2763..083fa2a31c 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -408,6 +408,7 @@ pub fn page_layout(s: &Session, pres: &Presentation, page: &Page) -> Layout { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 6d2472b83b..1f5f869d84 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1184,6 +1184,7 @@ fn report_pages_bytes( let (img, ..) = drawn?; keep_unfitted(&mut unfitted, page_layout, listed); say_report_unfitted(s, &unfitted); + say_sections_not_drawn(s, pages, 1); return Ok((img.encode_png().map_err(|e| e.to_string())?, pages.len())); } let (drawn, listed) = rustgis_render::layout::unfitted_legends(|| { @@ -1211,9 +1212,33 @@ fn report_pages_bytes( } say_report_unfitted(s, &unfitted); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); + say_sections_not_drawn(s, pages, n); Ok((rustgis_render::pdf::write(&out, &doc.title), pages.len())) } +/// Says the section lines (#2863) the layouts of the first `n` of `pages` don't draw, as the +/// layout's own export says them: in one notice however many layouts leave one out, each line named +/// with its layout, and a layout on several pages counted once. +fn say_sections_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize) { + let mut seen = Vec::new(); + let mut gaps = std::collections::BTreeMap::new(); + for page in pages.iter().take(n) { + let rustgis_render::report::Page::Layout(li) = page else { continue }; + if seen.contains(li) { + continue; + } + seen.push(*li); + let Some(layout) = s.project.layouts.get(*li) else { continue }; + for mut gap in rustgis_render::layout::sections_not_drawn(layout, &s.project.maps) { + gap.frame_name = format!("{} in layout '{}'", gap.frame_name, layout.name); + gaps.insert(gap, 1); + } + } + if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { + s.warn(format!("The report: {note}")); + } +} + /// Keeps the legends `listed` as cut on a page that draws the layout `layout` (by its index), each /// with that layout: the ids are a layout's own, so two layouts' legends sharing one are two. Only /// an exact repeat (the same legend of the same layout, cut the same way) is dropped: the page diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 27179ae2e0..21cfbf715f 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -112,6 +112,7 @@ pub const CAPABILITIES: &[&str] = &[ "zarr-window", "blank-paper", "layout-frame-border", + "layout-section", NATIVE_COORDINATES, "layout-text-size", "layout-legend-fit", @@ -2792,7 +2793,7 @@ pub(crate) fn layout_notices( let cut = total(|r| r.elements_cut); if cut > 0 { notices.push(format!( - "{name}: {cut} layout element(s) with a name, text, polygon points, legend exclusions, scale bar unit labels or legend labels cut to their limits {when} (in {})", + "{name}: {cut} layout element(s) with a name, text, polygon points, section lines, legend exclusions, scale bar unit labels or legend labels cut to their limits {when} (in {})", layout_names(repairs, |r| r.elements_cut) )); } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 8003aa1b04..52e0b26cd8 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -174,6 +174,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-chart-outline", command_uses_chart_outline), ("blank-paper", command_uses_blank_paper), ("layout-frame-border", command_uses_frame_border), + ("layout-section", command_uses_section), ("layout-text-size", command_uses_text_size), ("layout-legend-fit", command_uses_legend_fit), ("layout-scale-bar-details", command_uses_scale_bar_details), @@ -431,6 +432,19 @@ fn command_uses_frame_border(id: &str, params: &Value) -> bool { } } +/// A layout command that adds or changes a map frame's section lines (#2863): an older reader +/// refuses the kind `section`, and warns that it ignores a frame's `section`, drawing none. +fn command_uses_section(id: &str, params: &Value) -> bool { + match id { + "layout.addElement" => params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("section")), + "layout.update" => params.get("section").is_some_and(|v| !v.is_null()), + // A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does. + "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"sections\""], |e| e.kind.has_sections()), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_section)), + _ => false, + } +} + /// A `layout.page` command that gives the page a colour other than white (#2855), read as the /// command reads it: an older reader ignores `color` and opens the page white. A `layout.import` /// whose layout has one needs it too. @@ -1124,6 +1138,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(charts_facing), "layout-chart-facing"), (elements().any(charts_outlined), "layout-chart-outline"), (elements().any(|e| e.kind.has_custom_border()), "layout-frame-border"), + (elements().any(|e| e.kind.has_sections()), "layout-section"), (elements().any(|e| e.kind.has_custom_text_size()), "layout-text-size"), (elements().any(legends_fitting), "layout-legend-fit"), (elements().any(bar_details), "layout-scale-bar-details"), @@ -1420,6 +1435,7 @@ mod tests { (&["layout-scale-bar-details"], "layout.update", json!({"element": 1, "subdivisions": 2})), (&["blank-paper"], "map.basemap", json!({"name": "blank", "color": "#112233"})), (&["layout-frame-border"], "layout.update", json!({"element": 1, "border": {}})), + (&["layout-section"], "layout.update", json!({"element": 1, "section": {"name": "A", "y": 0}})), (&["layout-text-size"], "layout.update", json!({"element": 1, "textSize": 12})), (&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})), (&["dggs-system"], "a5Grid", json!({"system": "H3"})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ffe4835be..4911583cda 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -99,6 +99,8 @@ mod elevation_tiles; #[path = "tests/layout_files.rs"] mod layout_files; +#[path = "tests/layout_sections.rs"] +mod layout_sections; #[path = "tests/layout_title.rs"] mod layout_title; diff --git a/crates/engine/src/tests/archive_render_revision.rs b/crates/engine/src/tests/archive_render_revision.rs index c0ba41c700..2bc9e89072 100644 --- a/crates/engine/src/tests/archive_render_revision.rs +++ b/crates/engine/src/tests/archive_render_revision.rs @@ -144,6 +144,7 @@ fn page(map: &Map) -> map::layout::Layout { scale: 300_000_000.0, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: map::Rgba::rgb(0, 0, 0), extent_width: 1.0, diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index cf2eb00851..90dea2eb91 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -124,6 +124,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same() ("facing", include_str!("../../../../schema/fixtures/layout_chart_facing.rgis")), ("outline", include_str!("../../../../schema/fixtures/layout_chart_outline.rgis")), ("border", include_str!("../../../../schema/fixtures/layout_frame_border.rgis")), + ("section", include_str!("../../../../schema/fixtures/layout_section.rgis")), ("legend-text", include_str!("../../../../schema/fixtures/layout_legend_text.rgis")), ("legend-fit", include_str!("../../../../schema/fixtures/layout_legend_fit.rgis")), ("scale-grid-text", include_str!("../../../../schema/fixtures/layout_scale_grid_text.rgis")), diff --git a/crates/engine/src/tests/layout_sections.rs b/crates/engine/src/tests/layout_sections.rs new file mode 100644 index 0000000000..e5d2e5883c --- /dev/null +++ b/crates/engine/src/tests/layout_sections.rs @@ -0,0 +1,296 @@ +//! Section lines on a layout's map frame (#2863): the commands, what they say, and the capability +//! their layouts and commands require. + +use crate::{Project, Session, sample}; +use rustgis_geom::Coord; +use rustgis_map::layout::{ElementKind, MAX_SECTIONS, SECTION_COLOR, SECTION_WIDTH, SECTION_WIDTHS, Section, SectionLine}; +use serde_json::{Value, json}; + +/// A layout with a frame of the sample's map round (10, 50), and the frame's id. +fn with_frame() -> (Session, u64) { + let mut s = Session::new(sample::world_project()); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let frame = u64::from(s.project.layouts[0].first_frame().unwrap()); + s.run("layout.update", &json!({"element": frame, "center": [10, 50], "scale": 1e7})).unwrap(); + (s, frame) +} + +fn sections(s: &Session, frame: u64) -> Vec
{ + match s.project.layouts[0].element(frame as u32).map(|e| &e.kind) { + Some(ElementKind::MapFrame { sections, .. }) => sections.clone(), + _ => panic!("a map frame"), + } +} + +fn said(s: &Session, mark: u64) -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +#[test] +fn section_lines_are_added_changed_removed_and_undone() { + let (mut s, frame) = with_frame(); + let mark = s.notice_mark(); + let r = s.run("layout.addElement", &json!({"kind": "section"})).unwrap(); + assert_eq!(r, json!({"element": frame, "section": "A"})); + let middle = Coord::new(10.0, 50.0); + assert_eq!(sections(&s, frame), vec![Section::new("A".into(), SectionLine::Horizontal(middle))]); + let r = s + .run( + "layout.addElement", + &json!({"kind": "section", "frame": frame, "name": "a2", "direction": "vertical", "at": [11, 49], "color": "#1F5C84", "width": 1, "dash": [6, 3], "layout": 0, "text": null}), + ) + .unwrap(); + assert_eq!(r["section"], json!("a2")); + s.run("layout.addElement", &json!({"kind": "section"})).unwrap(); + assert_eq!(sections(&s, frame).iter().map(|x| x.name.clone()).collect::>(), ["A", "a2", "B"]); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + // Changed by name (any case), the keys not given keeping theirs. + s.run("layout.update", &json!({"element": frame, "section": {"name": "A2", "newName": "Serra", "at": [9, 51]}})).unwrap(); + let serra = §ions(&s, frame)[1]; + assert_eq!((serra.name.as_str(), serra.line), ("Serra", SectionLine::Vertical(Coord::new(9.0, 51.0)))); + assert_eq!((serra.color.hex(), serra.width, serra.dash.is_some()), ("#1F5C84".to_string(), 1.0, true)); + s.run("layout.update", &json!({"element": frame, "section": {"name": "serra", "direction": "horizontal", "dash": null}})).unwrap(); + assert_eq!(sections(&s, frame)[1].line, SectionLine::Horizontal(Coord::new(9.0, 51.0)), "the place kept"); + assert!(sections(&s, frame)[1].dash.is_none()); + // A copy of the frame has its own; removed, and undone in one step. + let copy = s.run("layout.duplicateElement", &json!({"element": frame})).unwrap()["element"].as_u64().unwrap(); + s.run("layout.update", &json!({"element": frame, "section": {"name": "Serra", "remove": true}})).unwrap(); + assert_eq!((sections(&s, frame).len(), sections(&s, copy).len()), (2, 3)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(sections(&s, frame).len(), 3); + // A bad value is refused, changing nothing else either; so is a change to a locked frame. + let before = s.project.layouts[0].clone(); + for (bad, key) in [ + (json!({"name": "A", "at": [200, 0]}), "at is"), + (json!({"name": "A", "at": "here"}), "at is"), + (json!({"name": "A", "direction": "line"}), "direction is"), + (json!({"name": "A", "color": 3}), "color"), + (json!({"name": "A", "width": "thin"}), "width"), + (json!({"name": "A", "dash": "dotted"}), "dash"), + (json!({"name": "A", "newName": "b"}), "already has a section line 'B'"), + (json!({"name": "A", "newName": " "}), "newName"), + (json!({"name": "A", "newName": "n".repeat(21)}), "at most 20"), + (json!({"name": "A", "rows": 3}), "rows"), + (json!({"name": "A", "remove": "x"}), "remove"), + // A line being removed has no place or width to change: refused rather than dropped. + (json!({"name": "A", "remove": true, "at": [1, 2]}), "a removed section line takes no \"at\""), + (json!({"name": "A", "width": 3, "remove": true}), "a removed section line takes no \"width\""), + (json!({"name": "Z"}), "no section line 'Z'"), + (json!({"at": [0, 0]}), "name"), + (json!(false), "section is an object"), + ] { + let err = s.run("layout.update", &json!({"element": frame, "x": 3, "section": bad})).unwrap_err(); + assert!(err.contains(key), "{bad}: {err}"); + } + for (bad, key) in [ + (json!({"name": "b"}), "already has"), + (json!({"name": 5}), "name"), + (json!({"direction": "line"}), "direction is"), + (json!({"at": [0]}), "at is"), + (json!({"background": {}}), "takes no background"), + // What it doesn't read, a box or a text's, is refused rather than dropped. + (json!({"x": 10}), "a section takes no \"x\""), + (json!({"text": "hi"}), "a section takes no \"text\""), + (json!({"angle": 30}), "a section takes no \"angle\""), + (json!({"newName": "b"}), "a section takes no \"newName\""), + ] { + let mut p = bad.clone(); + p["kind"] = json!("section"); + assert!(s.run("layout.addElement", &p).unwrap_err().contains(key), "{bad}"); + } + assert_eq!(s.project.layouts[0], before); + s.run("layout.update", &json!({"element": frame, "locked": true})).unwrap(); + assert!(s.run("layout.addElement", &json!({"kind": "section", "frame": frame})).is_err()); + assert!(s.run("layout.update", &json!({"element": frame, "section": {"name": "A", "remove": true}})).is_err()); + s.run("layout.update", &json!({"element": frame, "locked": false})).unwrap(); + // Only a section has a direction and a place, and only a map frame holds one; a name given for + // another kind is ignored, and said so, as it was before sections took one. + for key in ["direction", "at"] { + let mut p = json!({"kind": "rectangle"}); + p[key] = json!("x"); + assert!(s.run("layout.addElement", &p).unwrap_err().contains("only sections"), "{key}"); + } + let mark = s.notice_mark(); + s.run("layout.addElement", &json!({"kind": "rectangle", "name": "x"})).unwrap(); + assert!(said(&s, mark)[0].contains("ignores \"name\""), "{:?}", said(&s, mark)); + // A grid and an extent indicator refuse any key they don't read (#2890). + for kind in ["grid", "extentIndicator"] { + let e = s.run("layout.addElement", &json!({"kind": kind, "name": "x"})).unwrap_err(); + assert!(e.contains("takes no \"name\""), "{e}"); + } + let rect = s.run("layout.addElement", &json!({"kind": "rectangle"})).unwrap()["element"].clone(); + let err = s.run("layout.update", &json!({"element": rect, "section": {"name": "A"}})).unwrap_err(); + assert!(err.contains("only map frames"), "{err}"); + // A width out of range is held to it, and said; the most a frame holds, refused past it. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": frame, "section": {"name": "A", "width": 99}})).unwrap(); + assert_eq!(sections(&s, frame)[0].width, SECTION_WIDTHS.1); + assert!(said(&s, mark)[0].contains("section width 99 held to 20"), "{:?}", said(&s, mark)); + for _ in sections(&s, frame).len()..MAX_SECTIONS { + s.run("layout.addElement", &json!({"kind": "section"})).unwrap(); + } + let err = s.run("layout.addElement", &json!({"kind": "section"})).unwrap_err(); + assert!(err.contains("at most 26"), "{err}"); + assert_eq!((sections(&s, frame)[2].color, sections(&s, frame)[2].width), (SECTION_COLOR, SECTION_WIDTH)); +} + +/// A section line whose place its frame doesn't show isn't drawn, which adding it, changing it and +/// every export say, a series' PDF with the pages; one drawn says nothing. +#[test] +fn a_section_line_not_drawn_is_said() { + let (mut s, frame) = with_frame(); + let said_of = |s: &mut Session, run: &mut dyn FnMut(&mut Session)| { + let mark = s.notice_mark(); + run(s); + said(s, mark).into_iter().filter(|t| t.contains("section line(s)")).collect::>() + }; + let drawn: Vec<(&str, Box)> = vec![ + ("png", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, false, 96.0, false).unwrap()))), + ("pdf", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, true, 96.0, true).unwrap()))), + ("view", Box::new(|s| drop(crate::cmd::layout::layout_png(s, 0, 96.0, None).unwrap()))), + ]; + let one = |s: &mut Session, p: Value| s.run("layout.addElement", &p).map(drop).unwrap(); + assert!(said_of(&mut s, &mut |s| one(s, json!({"kind": "section"}))).is_empty()); + for (how, export) in &drawn { + assert!(said_of(&mut s, &mut |s| export(s)).is_empty(), "{how}"); + } + let note = said_of(&mut s, &mut |s| one(s, json!({"kind": "section", "at": [-150, 0]}))); + assert_eq!(note.len(), 1, "{note:?}"); + assert!(note[0].starts_with("1 section line(s) not drawn: 'B' of ") && note[0].ends_with("its place is outside the frame"), "{note:?}"); + for (how, export) in &drawn { + assert_eq!(said_of(&mut s, &mut |s| export(s)), note, "{how}"); + } + let change = |s: &mut Session, p: Value| s.run("layout.update", &json!({"element": frame, "section": p})).map(drop).unwrap(); + assert!(said_of(&mut s, &mut |s| change(s, json!({"name": "B", "at": [10, 50]}))).is_empty(), "brought into the frame"); + assert_eq!(said_of(&mut s, &mut |s| change(s, json!({"name": "B", "at": [-150, 0]}))), note); + assert!(said_of(&mut s, &mut |s| change(s, json!({"name": "B", "remove": true}))).is_empty()); + // On a hidden frame nothing is drawn, so nothing is missing. + one(&mut s, json!({"kind": "section", "at": [-150, 0]})); + s.run("layout.update", &json!({"element": frame, "visible": false})).unwrap(); + assert!(said_of(&mut s, &mut |s| drop(crate::cmd::layout::layout_bytes(s, 0, false, 96.0, false).unwrap())).is_empty()); + s.run("layout.update", &json!({"element": frame, "visible": true})).unwrap(); + // A series moves the frame, and the line stays at its place: the PDF says how many pages lack + // it, and the layout is left as it was. + change(&mut s, json!({"name": "B", "remove": true})); + s.run("layout.series", &json!({"layer": "Lakes"})).unwrap(); + let before = s.project.layouts[0].clone(); + let note = said_of(&mut s, &mut |s| drop(crate::cmd::layout::layout_bytes(s, 0, true, 36.0, true).unwrap())); + assert!(note.len() == 1 && note[0].contains("'A' of ") && note[0].contains(" pages: its place"), "{note:?}"); + assert_eq!(s.project.layouts[0], before); + // On the globe some pages are too far round for its place, others only beside it: one line all + // the same, each reason with its pages. + s.project.maps[0].projection = rustgis_map::Projection::Globe; + let note = said_of(&mut s, &mut |s| drop(crate::cmd::layout::layout_bytes(s, 0, true, 36.0, true).unwrap())); + assert_eq!(note.len(), 1, "{note:?}"); + assert!(note[0].starts_with("1 section line(s) not drawn: 'A' of ") && note[0].matches("'A' of ").count() == 1, "{note:?}"); + for why in [" pages: its place is outside the frame", " pages: its place isn't one the frame's map shows"] { + assert!(note[0].contains(why), "{note:?}"); + } +} + +/// A report's layout page is drawn as the layout's own export is, and says the same of a section +/// line it can't draw, once a layout, as an image as in a PDF. +#[test] +fn a_report_says_a_section_line_its_layout_page_does_not_draw() { + let (mut s, _) = with_frame(); + s.run("layout.addElement", &json!({"kind": "section", "at": [-150, 0]})).unwrap(); + let layout = s.project.layouts[0].name.clone(); + s.run("report.new", &json!({"layer": "Countries", "name": "R", "fields": ["name"], "where": "name LIKE 'F%'"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": layout})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": layout, "end": true})).unwrap(); + /// Removed however the test ends. + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } + } + let dir = Dir(std::env::temp_dir().join(format!("rustgis-report-sections-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + for file in ["r.pdf", "r.png"] { + let mark = s.notice_mark(); + s.run("report.export", &json!({"report": "R", "path": dir.0.join(file).display().to_string(), "dpi": 36})).unwrap(); + let note: Vec<_> = said(&s, mark).into_iter().filter(|t| t.contains("section line(s)")).collect(); + assert_eq!(note.len(), 1, "{file}: {note:?}"); + assert!( + note[0].contains(&format!("'{layout}'")) && note[0].contains("'A' of ") && note[0].ends_with("its place is outside the frame"), + "{note:?}" + ); + } + // Two layouts that each leave one out: one notice counting both, each named with its layout. + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let second = s.project.layouts[1].name.clone(); + let other = u64::from(s.project.layouts[1].first_frame().unwrap()); + s.run("layout.update", &json!({"layout": 1, "element": other, "center": [10, 50], "scale": 1e7})).unwrap(); + s.run("layout.addElement", &json!({"layout": 1, "kind": "section", "at": [-150, 0]})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": second})).unwrap(); + let mark = s.notice_mark(); + s.run("report.export", &json!({"report": "R", "path": dir.0.join("r.pdf").display().to_string(), "dpi": 36})).unwrap(); + let note: Vec<_> = said(&s, mark).into_iter().filter(|t| t.contains("section line(s)")).collect(); + assert_eq!(note.len(), 1, "{note:?}"); + assert!( + note[0].contains("2 section line(s) not drawn") + && note[0].contains(&format!("'{layout}'")) + && note[0].contains(&format!("'{second}'")), + "{note:?}" + ); + s.run("layout.update", &json!({"layout": 1, "element": other, "section": {"name": "A", "remove": true}})).unwrap(); + // Brought into the frame, nothing is said. + let frame = u64::from(s.project.layouts[0].first_frame().unwrap()); + s.run("layout.update", &json!({"layout": 0, "element": frame, "section": {"name": "A", "at": [10, 50]}})).unwrap(); + let mark = s.notice_mark(); + s.run("report.export", &json!({"report": "R", "path": dir.0.join("r.pdf").display().to_string(), "dpi": 36})).unwrap(); + assert!(!said(&s, mark).iter().any(|t| t.contains("section line(s)"))); +} + +/// Section lines are required where they are saved, so an older reader refuses the project instead +/// of drawing its frames without them and saving it so. A layout without one needs nothing. +#[test] +fn section_capability_follows_saved_layouts_and_commands() { + let fixture = Project::from_json(include_str!("../../../../schema/fixtures/layout_section.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["layout-section"])); + let frames = &saved["layouts"][0]["elements"]; + assert!(frames[0]["kind"]["MapFrame"].get("sections").is_none()); + let file: Value = serde_json::from_str(include_str!("../../../../schema/fixtures/layout_section.rgis")).unwrap(); + assert_eq!( + frames[1]["kind"]["MapFrame"]["sections"][1]["name"], + file["layouts"][0]["elements"][1]["kind"]["MapFrame"]["sections"][1]["name"] + ); + assert_eq!(Project::from_json(&saved.to_string()).unwrap().layouts, fixture.layouts); + let mut clean = fixture; + for e in &mut clean.layouts[0].elements { + if let ElementKind::MapFrame { sections, .. } = &mut e.kind { + sections.clear(); + } + } + let base = serde_json::to_value(&clean).unwrap(); + assert!(base.get("requires").is_none(), "no section lines need nothing"); + let layout = |v: &Value| json!({"text": v["layouts"][0].to_string()}); + for (command, params, required) in [ + ("layout.addElement", json!({"kind": "section", "name": "A"}), true), + ("layout.addElement", json!({"kind": "grid"}), false), + ("layout.update", json!({"element": 2, "section": {"name": "A", "width": 2}}), true), + ("layout.update", json!({"element": 2, "section": null}), false), + ("layout.import", layout(&saved), true), + ("layout.import", layout(&base), false), + // A report's template is a layout file read as `layout.import` reads it. + ("report.existingTemplate", layout(&saved), true), + ("report.existingTemplate", layout(&base), false), + ] { + let script = format!("{command} {params}"); + for step in [ + json!({"title": "S", "command": command, "params": params}), + json!({"title": "S", "command": "script.run", "params": {"script": script}}), + ] { + let mut document = base.clone(); + document["tasks"] = json!([{"name": "Task", "steps": [step]}]); + let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap(); + let expected = if required { json!(["layout-section"]) } else { Value::Null }; + assert_eq!(saved.get("requires").cloned().unwrap_or_default(), expected, "{command} {params}"); + } + } + let mut unknown = saved; + unknown["requires"] = json!(["layout-section", "future-section"]); + assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-section")); +} diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 592c71c9eb..4bdaef3f04 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -23,6 +23,7 @@ mod legend; mod lines; mod north; mod scale_bar; +mod section; mod stats; mod text; @@ -35,6 +36,7 @@ pub use legend::*; pub use lines::*; pub use north::*; pub use scale_bar::*; +pub use section::*; pub use stats::*; pub use text::*; @@ -535,7 +537,7 @@ impl Layout { let mut cut = e.name.chars().nth(200).is_some(); e.name = e.name.chars().take(200).collect(); match &mut e.kind { - ElementKind::MapFrame { center, scale, shape, grid, bearing, pitch, extent_width, border_width, .. } => { + ElementKind::MapFrame { center, scale, shape, grid, sections, bearing, pitch, extent_width, border_width, .. } => { *scale = finite_or(*scale, 50_000_000.0).clamp(MIN_FRAME_SCALE, MAX_FRAME_SCALE); *extent_width = finite_or(*extent_width, INDICATOR_WIDTH).clamp(MIN_INDICATOR_WIDTH, MAX_INDICATOR_WIDTH); *border_width = finite_or(*border_width, FRAME_BORDER_WIDTH).clamp(0.0, MAX_FRAME_BORDER_WIDTH); @@ -583,6 +585,7 @@ impl Layout { g.width = finite_or(g.width, grid_width()).clamp(0.0, MAX_GRID_WIDTH); g.label_size = layout_text_in_range(g.label_size, GRID_LABEL_PT); } + cut |= Section::clamp_all(sections); } ElementKind::Legend { exclude, columns, labels, text_size, fit, show_layer_names, .. } => { *text_size = layout_text_in_range(*text_size, LEGEND_TEXT_PT); @@ -721,8 +724,8 @@ pub struct LayoutRepairs { /// Elements kept with a value brought into range, a new id, a reference cleared, or a unit /// label's line breaks replaced. pub elements_adjusted: usize, - /// Elements with a name, text, polygon points, legend exclusions, scale bar unit labels or - /// legend labels cut to their limits (the same element may count as adjusted too). + /// Elements with a name, text, polygon points, section lines, legend exclusions, scale bar unit + /// labels or legend labels cut to their limits (the same element may count as adjusted too). pub elements_cut: usize, /// Elements removed: beyond the 500 a layout holds, or tied to a map frame it doesn't have. pub elements_removed: usize, diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 143b5817e5..4cfaca88c9 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -15,6 +15,10 @@ pub enum ElementKind { shape: FrameShape, #[serde(default)] grid: Option, + /// The section lines drawn over the frame (#2863). Left out with none, so layouts saved + /// before keep their bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + sections: Vec
, /// Another frame whose extent this one outlines (an extent indicator). #[serde(default)] extent_of: Option, @@ -556,6 +560,11 @@ impl ElementKind { if !is_frame_border_color(border_color) || !is_frame_border_width(border_width)) } + /// Whether it is a map frame with section lines (#2863). + pub fn has_sections(&self) -> bool { + matches!(self, ElementKind::MapFrame { sections, .. } if !sections.is_empty()) + } + /// The map frame this element belongs to. pub fn frame(&self) -> Option { match self { diff --git a/crates/map/src/layout/section.rs b/crates/map/src/layout/section.rs new file mode 100644 index 0000000000..f44b3d9a27 --- /dev/null +++ b/crates/map/src/layout/section.rs @@ -0,0 +1,106 @@ +//! A map frame's section lines (#2863): where each runs, its name at both ends and its look. + +use super::*; + +/// A section line over a map frame (#2863): the trace of a cross-section, its name at both ends +/// (A and A'). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Section { + /// 1 to [`MAX_SECTION_NAME`] characters, its frame's only one of that name (any case). + pub name: String, + pub line: SectionLine, + pub color: Rgba, + /// Points. + pub width: f64, + /// Dashed: the pattern along the line, in points ([`Dash`]); `None` is solid. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::symbology::de_dash")] + pub dash: Option, +} + +/// Where a section line runs: across the frame, straight on the page, through a place +/// (longitude/latitude) it keeps to when the frame is moved or rescaled. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub enum SectionLine { + Horizontal(Coord), + Vertical(Coord), +} + +/// The section lines a map frame holds at most (one a letter), and their longest name (characters). +pub const MAX_SECTIONS: usize = 26; +pub const MAX_SECTION_NAME: usize = 20; +/// A new section line's colour and width (points), and the least and most its width may be. +pub const SECTION_COLOR: Rgba = Rgba::rgb(0xA8, 0x43, 0x1F); +pub const SECTION_WIDTH: f64 = 1.5; +pub const SECTION_WIDTHS: (f64, f64) = (MIN_INDICATOR_WIDTH, MAX_INDICATOR_WIDTH); + +impl SectionLine { + /// The place it runs through. + pub fn at(self) -> Coord { + match self { + SectionLine::Horizontal(at) | SectionLine::Vertical(at) => at, + } + } + + /// The same line through another place. + pub fn through(self, at: Coord) -> SectionLine { + match self { + SectionLine::Horizontal(_) => SectionLine::Horizontal(at), + SectionLine::Vertical(_) => SectionLine::Vertical(at), + } + } + + /// A line through `at` by its direction's name, `horizontal` or `vertical`. + pub fn from_name(direction: &str, at: Coord) -> Option { + match direction.trim().to_ascii_lowercase().as_str() { + "horizontal" => Some(SectionLine::Horizontal(at)), + "vertical" => Some(SectionLine::Vertical(at)), + _ => None, + } + } +} + +impl Section { + /// A section line named `name`, in the default look. + pub fn new(name: String, line: SectionLine) -> Section { + Section { name, line, color: SECTION_COLOR, width: SECTION_WIDTH, dash: None } + } + + /// The first letter from A to Z that no section of `sections` is named, or `None` when all 26 are. + pub fn free_name(sections: &[Section]) -> Option { + ('A'..='Z').map(String::from).find(|n| Section::find(sections, n).is_none()) + } + + /// The index of the section of `sections` named `name` (any case). + pub fn find(sections: &[Section], name: &str) -> Option { + let name = name.trim().to_lowercase(); + sections.iter().position(|s| s.name.to_lowercase() == name) + } + + /// `sections` brought into range (a layout file is hostile input): places and widths in range, + /// a blank or repeated name given a free letter. Whether any was cut: a name past its limit, or + /// the sections past theirs. + pub(super) fn clamp_all(sections: &mut Vec
) -> bool { + let mut cut = sections.len() > MAX_SECTIONS; + sections.truncate(MAX_SECTIONS); + for s in sections.iter_mut() { + cut |= s.name.trim().chars().nth(MAX_SECTION_NAME).is_some(); + s.name = s.name.trim().chars().take(MAX_SECTION_NAME).collect::().trim_end().to_string(); + s.width = finite_or(s.width, SECTION_WIDTH).clamp(SECTION_WIDTHS.0, SECTION_WIDTHS.1); + let at = s.line.at(); + let x = finite_or(at.x, 0.0).clamp(-540.0, 540.0); + // (A longitude past ±180° is the same place a turn nearer.) + let x = if x.abs() > 180.0 { (x + 180.0).rem_euclid(360.0) - 180.0 } else { x }; + s.line = s.line.through(Coord::new(x, finite_or(at.y, 0.0).clamp(-90.0, 90.0))); + } + for i in 0..sections.len() { + let free = Section::free_name(sections); + let (before, rest) = sections.split_at_mut(i); + if let (Some(s), Some(free)) = (rest.first_mut(), free) + && (s.name.is_empty() || Section::find(before, &s.name).is_some()) + { + s.name = free; + } + } + cut + } +} diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 23e96ad4fd..25481a8566 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -844,6 +844,7 @@ fn elements_add_hit_and_remove_with_surrounds() { scale: 1e8, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -1297,6 +1298,7 @@ fn mgrs_labels_need_a_wgs84_utm_zone() { scale: 25_000.0, shape: FrameShape::Rectangle, grid: Some(Grid { crs: crs.map(Into::into), kind, ..g.clone() }), + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -1654,6 +1656,49 @@ fn inks_are_saved_and_read_back() { assert!(!text.takes_ink() && text.ink_mut().is_none(), "a text's colour is its own option"); } +/// A frame's section lines (#2863): not written when none, read back as saved, and a hostile +/// file's brought into range, a blank or repeated name given a free letter, with what was cut +/// counted; a repaired frame needs nothing more. +#[test] +fn section_lines_are_saved_and_repaired() { + let frame = |sections: &str| -> Layout { + let text = format!( + r#"{{"name":"x","width":100,"height":100,"elements":[{{"id":1,"name":"f","x":0,"y":0,"w":50,"h":50, + "kind":{{"MapFrame":{{"map":"M","center":{{"x":0,"y":0}},"scale":1000000{sections}}}}}}}]}}"# + ); + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}")) + }; + let held = |l: &Layout| match &l.elements[0].kind { + ElementKind::MapFrame { sections, .. } => sections.clone(), + _ => panic!("a map frame"), + }; + let mut l = frame(""); + assert!(!serde_json::to_string(&l).unwrap().contains("sections"), "none is not written"); + assert!(l.clamp().is_empty() && !l.elements[0].kind.has_sections()); + let one = + |name: &str| format!(r#"{{"name":"{name}","line":{{"Vertical":{{"x":1,"y":2}}}},"color":[1,2,3,255],"width":2,"dash":[4,2]}}"#); + let mut l = frame(&format!(r#","sections":[{}]"#, one("B"))); + assert!(l.clamp().is_empty() && l.elements[0].kind.has_sections()); + assert_eq!(held(&l)[0].line, SectionLine::Vertical(Coord::new(1.0, 2.0))); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&l).unwrap()).unwrap(), l); + // Spaces round a name are trimmed, which adjusts the frame; nothing of the name is cut. + let padded = format!(" {} ", "n".repeat(MAX_SECTION_NAME)); + let mut l = frame(&format!(r#","sections":[{}]"#, one(&padded))); + let repairs = l.clamp(); + assert_eq!((repairs.elements_adjusted, repairs.elements_cut, held(&l)[0].name.as_str()), (1, 0, padded.trim())); + let hostile = r#"{"name":" a ","line":{"Horizontal":{"x":1e300,"y":-200}},"color":[0,0,0,255],"width":1e9}"#; + let long = "n".repeat(50); + let list = [hostile.to_string(), one("A"), one(""), one(&long)].into_iter().chain((0..40).map(|i| one(&format!("s{i}")))); + let mut l = frame(&format!(r#","sections":[{}]"#, list.collect::>().join(","))); + let repairs = l.clamp(); + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (1, 1)); + let s = held(&l); + assert_eq!(s.len(), MAX_SECTIONS); + assert_eq!((s[0].name.as_str(), s[0].line.at(), s[0].width), ("a", Coord::new(-180.0, -90.0), SECTION_WIDTHS.1)); + assert_eq!((s[1].name.as_str(), s[2].name.as_str(), s[3].name.len()), ("B", "C", MAX_SECTION_NAME), "the first A keeps its name"); + assert!(l.clamp().is_empty(), "a repaired frame needs nothing more"); +} + /// A text's block alignment, line spacing and case: left out of the file at their defaults, so a /// text saved before saves byte for byte; written and read back when set; and a hand-edited value /// out of range, of the wrong kind or not a name loads, brought into range and counted. diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index dc4b7b6d60..1212e657e3 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -10,8 +10,8 @@ use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ ArrowStyle, ChartLook, ColorScale, ElementKind, FrameShape, GRID_LABEL_PT, Grid, GridKind, INK, LAYOUT_TEXT_SIZE, LEGEND_TEXT_PT, Layout, LegendFit, LineHead, MAX_LEGEND_COLUMNS, Orientation, PT_PER_MM, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, - ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, frame_camera, layout_text_in_range, - layout_text_scale, legend_columns_in_range, + ScaleLabelPosition, ScaleUnits, Section, SectionLine, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, frame_camera, + layout_text_in_range, layout_text_scale, legend_columns_in_range, }; use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; @@ -29,6 +29,7 @@ mod legend; mod losses; mod north; mod scale_bar; +mod section; mod swatch; mod table; mod textbox; @@ -43,6 +44,7 @@ pub use legend::*; pub use losses::*; use north::*; pub use scale_bar::*; +pub use section::*; use swatch::*; use table::*; pub use textbox::*; @@ -404,7 +406,7 @@ fn draw_page( ((e.x * k - f64::from(bounds.x())) as f32, (e.y * k - f64::from(bounds.y())) as f32, (e.w * k) as f32, (e.h * k) as f32); let Some(r) = Rect::from_xywh(x, y, ew.max(1.0), eh.max(1.0)) else { continue }; match &e.kind { - ElementKind::MapFrame { shape, grid, extent_of, extent_color, extent_width, border_color, border_width, .. } => { + ElementKind::MapFrame { shape, grid, sections, extent_of, extent_color, extent_width, border_color, border_width, .. } => { let Some(&(_, mi, cam, fw, fh)) = frame(e.id) else { placeholder(&mut pm, r, "Missing map", ppp); continue; @@ -416,8 +418,11 @@ fn draw_page( // The grid is drawn with the frame's map, before its attribution, which keeps // clear of the grid's labels. let grid = grid.as_ref().map(|g| (g, layout.decimal_comma)); + let sections: Vec<_> = + sections.iter().filter_map(|s| Some((s, section_ends(map, &cam, (fw, fh), shape, s.line).ok()?))).collect(); + let over = FrameOver { grid, sections: §ions }; let mut failed_source = None; - let Some(mut frame_pm) = frame_canvas(map, &view, pm.is_recording(), &mut pending.frames, grid, &mut failed_source, env) + let Some(mut frame_pm) = frame_canvas(map, &view, pm.is_recording(), &mut pending.frames, over, &mut failed_source, env) else { if frame_requires_complete(map, &view) { *source_error = failed_source_error(map, failed_source); @@ -432,7 +437,7 @@ fn draw_page( frame_pm.overflowed() || pm.recorded_cost().saturating_add(frame_pm.recorded_cost()) > crate::vector::max_cost(); if frame_pm.is_recording() && too_large - && let Some(pixels) = frame_canvas(map, &view, false, &mut pending.frames, grid, &mut None, env) + && let Some(pixels) = frame_canvas(map, &view, false, &mut pending.frames, over, &mut None, env) { frame_pm = pixels; if let Some(list) = record.as_deref_mut() { diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 0b650842e1..54089e52af 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -9,13 +9,23 @@ pub fn frame_map(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp let revisions = crate::archive_revisions([&*map]); let mut failed_source = None; let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - let result = frame_canvas(map, &view, false, &mut false, None, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); + let over = FrameOver::default(); + let result = frame_canvas(map, &view, false, &mut false, over, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); revisions.finish(map, failed_source, result, "could not draw the map frame") } +/// What a page draws over a map frame's map, under its attribution. +#[derive(Clone, Copy, Default)] +pub(super) struct FrameOver<'a> { + /// The grid, and whether the layout writes a decimal comma. + pub(super) grid: Option<(&'a Grid, bool)>, + /// The section lines drawn, each with its ends ([`section_ends`]). + pub(super) sections: &'a [(&'a Section, SectionEnds)], +} + /// [`frame_map`] on a canvas: one that records (see [`crate::canvas`]) when `record` and the /// frame can be kept as vectors (flat, north up, without view effects), else its pixels; with -/// `grid` (and whether the layout writes a decimal comma) drawn on it under the attribution. +/// what goes `over` it drawn on it under the attribution. /// `pending` is set when some of its tiles, or a read of its streamed layers or rasters, were /// still on their way (in the browser, which doesn't wait for them). pub(super) fn frame_canvas( @@ -23,7 +33,7 @@ pub(super) fn frame_canvas( view: &View, record: bool, pending: &mut bool, - grid: Option<(&Grid, bool)>, + over: FrameOver, failed_source: &mut Option, env: &Env, ) -> Option { @@ -32,7 +42,8 @@ pub(super) fn frame_canvas( let (img, shadows) = crate::frame_with_shadows_to_come(|| crate::complete(map, view, record, failed_source, env)); let img = img?; *pending |= img.tiles_pending || img.data_pending || shadows; - Some(finish_frame(img, view.pixels_per_point, grid.map(|(g, comma)| (&*map, view, g, comma)))) + let grid = over.grid.map(|(g, comma)| (&*map, view, g, comma)); + Some(finish_frame(img, view.pixels_per_point, grid, over.sections)) } /// [`frame_map`] without waiting for tiles still on their way, for a preview drawn while the @@ -45,22 +56,31 @@ pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: /// Map preview during a layout pan, using the same expression context as its page. pub fn frame_map_preview_with(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64, env: &Env) -> Option { let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None).into_pixmap()) + crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None, &[]).into_pixmap()) } /// A rendered frame map with its labels, its `grid` (drawn on `map` in `view`, with a decimal -/// comma or not) and its attribution drawn on it: on its recording when it was recorded, else on -/// its pixels. The attribution keeps clear of the grid's labels. -pub(super) fn finish_frame(img: crate::Rendered, ppp: f64, grid: Option<(&Map, &View, &Grid, bool)>) -> Canvas { +/// comma or not), its section lines and its attribution drawn on it: on its recording when it was +/// recorded, else on its pixels. The attribution keeps clear of the grid's labels and the sections' +/// names. +pub(super) fn finish_frame( + img: crate::Rendered, + ppp: f64, + grid: Option<(&Map, &View, &Grid, bool)>, + sections: &[(&Section, SectionEnds)], +) -> Canvas { let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img; let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap)); crate::draw_labels(&mut pm, (&unplaced, &labels, &label_layers), ppp as f32); // The grid is a layer of its own (#1815). pm.layer(grid.is_some().then_some("Grid")); - let grid_labels = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); + let mut kept_clear = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); + // So are the section lines (#2863). + pm.layer((!sections.is_empty()).then_some("Section lines")); + kept_clear.extend(draw_sections(&mut pm, sections, ppp)); pm.layer(None); let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); - let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &grid_labels)); + let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &kept_clear)); crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); pm } diff --git a/crates/render/src/layout/section.rs b/crates/render/src/layout/section.rs new file mode 100644 index 0000000000..5abb87ea93 --- /dev/null +++ b/crates/render/src/layout/section.rs @@ -0,0 +1,203 @@ +//! A map frame's section lines (#2863): where each runs across its frame, what isn't drawn and +//! why, and the lines with their names. + +use super::*; + +/// A section line's ends in its frame's points, from its left or top. +pub type SectionEnds = [(f64, f64); 2]; + +/// 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 +/// through the place as the frame's grid puts it there (on the ground, without its relief), only as +/// far as there is ground along it, to the horizon or the globe's limb; what it crosses there is no +/// straight section of the ground. `Err` says why it isn't drawn: its place is outside the frame, +/// or one the frame's map can't show (behind the globe or the eye, or outside its projection). +pub fn section_ends( + map: &Map, + cam: &rustgis_map::Camera, + (w, h): (f64, f64), + shape: &FrameShape, + 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)?; + // 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) }; + let (along, across) = swap((px, py)); + // Where the line meets the shape's outline, and which way the outline crosses it there: the + // place is inside as the shape is filled, by its winding number. A circle is as wide as the + // shorter side ([`shape_path`]). + let (bw, bh) = if *shape == FrameShape::Circle { (w.min(h), w.min(h)) } else { (w, h) }; + let outline: Vec<(f64, f64)> = + shape.outline().into_iter().map(|(u, v)| swap(((w - bw) / 2.0 + u * bw, (h - bh) / 2.0 + v * bh))).collect(); + let mut meets: Vec<(f64, i32)> = Vec::new(); + for (a, b) in outline.iter().zip(outline.iter().cycle().skip(1)) { + if (a.1 <= across) != (b.1 <= across) { + meets.push((a.0 + (across - a.1) / (b.1 - a.1) * (b.0 - a.0), if a.1 <= across { 1 } else { -1 })); + } + } + let inside = meets.iter().filter(|m| m.0 <= along).map(|m| m.1).sum::() != 0; + let (from, to) = meets.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), m| (lo.min(m.0), hi.max(m.0))); + if !inside || from >= to { + return Err("its place is outside the frame"); + } + let ground = |along: f64| { + let (x, y) = swap((along, across)); + match &globe { + Some(g) => g.inverse(x, y).is_some(), + None => cam.pitch.abs() <= 1e-9 || cam.try_to_map(x, y, w, h).is_some(), + } + }; + // The ground along the line is in one piece, which holds the place: 24 halvings find its end. + let reach = |end: f64| { + let (mut on, mut off) = (along, end); + if ground(end) { + return end; + } + for _ in 0..24 { + let mid = (on + off) / 2.0; + *(if ground(mid) { &mut on } else { &mut off }) = mid; + } + on + }; + Ok([swap((reach(from), across)), swap((reach(to), across))]) +} + +/// Whether `back`, `at` taken there and back through a projection, is `at`: its longitude a +/// whole turn apart aside, and any at a pole. +fn same_place(back: Coord, at: Coord) -> bool { + let turns = ((back.x - at.x) / 360.0).round() * 360.0; + (back.y - at.y).abs() < 1e-6 && (at.y.abs() > 90.0 - 1e-6 || (back.x - turns - at.x).abs() < 1e-6) +} + +/// A section line its frame doesn't draw ([`section_ends`]). +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct SectionGap { + pub frame: u32, + pub frame_name: String, + pub section: String, + pub why: &'static str, +} + +/// The section lines of `layout`'s visible frames they don't draw, as the page is now: those +/// [`section_ends`] gives no ends for, and every one of a frame whose map is missing. +pub fn sections_not_drawn(layout: &Layout, maps: &[Map]) -> Vec { + let mut gaps = Vec::new(); + for e in layout.elements.iter().filter(|e| e.visible) { + let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, sections, .. } = &e.kind else { continue }; + let shown = map_index(maps, map).and_then(|i| maps.get(i)).map(|m| (m, frame_camera(m, *center, *scale, *bearing, *pitch))); + let size = (e.w * PT_PER_MM, e.h * PT_PER_MM); + gaps.extend(sections.iter().filter_map(|s| { + let why = match &shown { + Some((m, cam)) => section_ends(m, cam, size, shape, s.line).err()?, + None => "its frame's map is missing", + }; + Some(SectionGap { frame: e.id, frame_name: e.name.clone(), section: s.name.clone(), why }) + })); + } + gaps +} + +/// What an export of `pages` pages says of the section lines not drawn, each with the pages it is +/// missing from, by reason: one notice, the lines counted, the first ten named; `None` for none. +pub fn sections_notice(gaps: &BTreeMap, pages: usize) -> Option { + if gaps.is_empty() { + return None; + } + // A line can be missing for one reason on some pages and another on others: one line still. + let mut lines: BTreeMap<(u32, &str, &str), Vec> = BTreeMap::new(); + for (g, on) in gaps { + let on = if pages > 1 { format!(" on {on} of {pages} pages") } else { String::new() }; + lines.entry((g.frame, &g.frame_name, &g.section)).or_default().push(format!("{on}: {}", g.why)); + } + let named = lines.iter().take(10).map(|((frame, name, section), why)| format!("'{section}' of {name} ({frame}){}", why.join(","))); + let mut named = named.collect::>().join("; "); + if lines.len() > 10 { + named.push_str(&format!("; and {} more", lines.len() - 10)); + } + Some(format!("{} section line(s) not drawn: {named}", lines.len())) +} + +/// The size of a section's name at its ends, in points. +pub(super) const SECTION_NAME_PT: f32 = 8.0; +/// The least share of [`SECTION_NAME_PT`] a line too short for both its names draws them at. +const SECTION_NAME_LEAST: f32 = 0.4; + +/// A frame's section lines, each from end to end with its name in a box of its colour at both (A +/// and A'), just inside them and wholly in the frame; on a line too short for both at their size, +/// smaller (down to [`SECTION_NAME_LEAST`] of it), each clear of the other. Gives the names drawn, as [`draw_grid`] +/// gives its labels, each with the edge the credit treats it as: a vertical line's names and a +/// horizontal line's right one as right labels, which it goes left of (above, where it can't), and +/// a horizontal line's left one as a bottom label, which it goes above. +pub(super) fn draw_sections(pm: &mut Canvas, sections: &[(&Section, SectionEnds)], ppp: f64) -> Vec<(Edge, [f32; 4])> { + let k = ppp as f32; + let (fw, fh) = (pm.width() as f32, pm.height() as f32); + // A centre `c` of a box `half` across, inside `0..size` when the box fits there. + let inside = |c: f32, half: f32, size: f32| if size >= 2.0 * half { c.clamp(half, size - half) } else { c }; + let mut drawn = Vec::new(); + for (s, ends) in sections { + let [a, b] = ends.map(|(x, y)| (x as f32 * k, y as f32 * k)); + let mut pb = PathBuilder::new(); + pb.move_to(a.0, a.1); + pb.line_to(b.0, b.1); + if let Some(p) = pb.finish() { + let stroke = dashed(Stroke { width: s.width as f32 * k, ..Stroke::default() }, s.dash.as_ref(), ppp, &p); + pm.stroke_path(&p, &paint(s.color, 1.0), &stroke, Transform::identity(), None); + } + } + // The names over every line. + for (s, ends) in sections { + let [a, b] = ends.map(|(x, y)| (x as f32 * k, y as f32 * k)); + let vertical = matches!(s.line, SectionLine::Vertical(_)); + // Half a name's box along the line, its text `px` pixels. + let half_along = + |px: f32, name: &str| if vertical { px * 0.8 } else { (text::measure(name, px / 1.33, true) / 2.0 + px * 0.35).max(px * 0.8) }; + let names = [s.name.clone(), format!("{}'", s.name)]; + let length = (b.0 - a.0).max(b.1 - a.1); + // Each name takes a point at its end and its box's length: smaller where both don't fit. + let full = SECTION_NAME_PT * 1.33 * k; + let boxes_long = names.iter().map(|n| 2.0 * half_along(full, n)).sum::(); + let px = full * ((length - 2.0 * k) / boxes_long).clamp(SECTION_NAME_LEAST, 1.0); + // Dark on a light colour, or one the map shows through, else white. + let [r, g, b_, alpha] = s.color.0.map(f32::from); + let ink = if alpha < 128.0 || 0.299 * r + 0.587 * g + 0.114 * b_ > 150.0 { INK } else { Rgba::rgb(255, 255, 255) }; + let [first, second] = names; + let boxes = [(a, 1.0, first), (b, -1.0, second)]; + for ((x, y), inward, name) in boxes { + let hh = px * 0.8; + let hw = (text::measure(&name, px / 1.33, true) / 2.0 + px * 0.35).max(hh); + // Inside the end by a point, but never past the line's middle. + let inset = inward * (k + if vertical { hh } else { hw }).min(length / 2.0); + // Across the line, the whole box inside the frame too. + let (cx, cy) = if vertical { (inside(x, hw, fw), y + inset) } else { (x + inset, inside(y, hh, fh)) }; + if let Some(path) = Rect::from_ltrb(cx - hw, cy - hh, cx + hw, cy + hh).and_then(|r| rounded_rect(r, hh)) { + pm.fill_path(&path, &paint(s.color, 1.0), FillRule::Winding, Transform::identity(), None); + } + text::text_at(pm, &name, cx, cy, px, ink, true, text::Align::Center, false); + // Section names lie anywhere in the frame, not only along its edges as a grid's labels + // do, so the credit keeps clear of every one, whichever end it is. + // A vertical line's two names are one above the other: going left clears both, where + // going above one can meet the other. + let edge = if vertical || inward < 0.0 { Edge::Right } else { Edge::Bottom }; + drawn.push((edge, [(cx - hw) / k, (cy - hh) / k, (cx + hw) / k, (cy + hh) / k])); + } + } + drawn +} diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 5fe2217de9..1d86fdd957 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -2824,6 +2824,7 @@ fn colorbar_page(map: &Map, orientation: Orientation, reverse: bool, title: &str scale: 1e8, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -2919,6 +2920,7 @@ fn page_settles_with_suns(suns: &[f64]) { scale: 1e7, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -3076,6 +3078,7 @@ fn indicator_page(color: Rgba, width: f64) -> Pixmap { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: color, extent_width: width, @@ -4100,6 +4103,7 @@ fn a_map_frame_border_takes_its_colour_and_width_or_none() { scale: 1e7, shape, grid: None, + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4162,6 +4166,7 @@ fn an_extent_indicator_on_a_globe_lands_on_the_area() { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4211,6 +4216,7 @@ fn a_frame_on_the_globe_is_outlined_by_what_it_shows() { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4265,6 +4271,7 @@ fn a_frame_partly_off_the_globe_is_outlined_without_a_chord() { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4338,6 +4345,7 @@ fn a_globe_frame_across_the_antimeridian_is_outlined_in_one_piece() { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4382,6 +4390,7 @@ fn outline_on(map: Map, source: (Coord, f64, f64, f64), locator: Map, view: (Coo scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4581,6 +4590,7 @@ fn a_flat_frame_wider_than_the_world_is_outlined_where_it_is() { scale, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -4895,6 +4905,7 @@ fn colorbars_draw_the_raster_colour_scale() { scale: 1e8, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -5017,6 +5028,7 @@ fn grid_page(grid: rustgis_map::layout::Grid) -> Pixmap { scale: 2e8, shape: FrameShape::Rectangle, grid: Some(grid), + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -5058,6 +5070,7 @@ fn winterthur_page(grid: rustgis_map::layout::Grid, projection: rustgis_map::Pro scale: 25_000.0, shape: FrameShape::Rectangle, grid: Some(grid), + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -5314,6 +5327,7 @@ fn a_measured_grid_on_the_globe_seen_whole_is_drawn() { scale: 2e8, shape: FrameShape::Rectangle, grid: Some(grid), + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -5348,6 +5362,7 @@ fn a_grid_on_the_globe_is_drawn_on_it() { scale: 2e8, shape: FrameShape::Rectangle, grid: Some(grid), + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -5515,7 +5530,7 @@ fn a_frames_attribution_keeps_clear_of_its_grid_labels() { recorded: None, label_layers: Vec::new(), }; - let framed = finish_frame(img, ppp, Some((&map, &view, &all, false))); + let framed = finish_frame(img, ppp, Some((&map, &view, &all, false)), &[]); let (a, b) = (labels_pm.pixmap(), framed.pixmap()); assert_ne!(a.data(), b.data(), "the credit is drawn"); for (_, [x0, y0, x1, y1]) in &labels { @@ -6258,6 +6273,7 @@ fn colour_test_page() -> (Vec, Layout, u32) { scale: 10_000_000.0, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -7846,3 +7862,235 @@ fn a_background_is_drawn_under_its_element_and_turns_with_it() { let (alone, _) = render_element(&l, id, &mut [], 96.0, (&PageInfo::default(), &Env::default()), &mut None).unwrap().unwrap(); assert!(alone.pixels().iter().all(|c| c.alpha() == 0 || c.green() > 0), "no red in the element's own picture"); } + +/// A section line (#2863) runs across its frame, straight on the page, through the place the +/// frame shows there whatever its projection, bearing or copy of the world, within the frame's +/// shape; on a tilted frame or the globe, only as far as there is ground. One whose place the +/// frame doesn't show says why. +#[test] +fn a_section_line_runs_across_its_frame_through_its_place() { + use rustgis_map::Projection; + let (w, h) = (400.0, 200.0); + let at = Coord::new(-44.66, -22.38); + let ends = |map: &Map, (c, scale, bearing, pitch): (Coord, f64, f64, f64), shape: &FrameShape, line| { + section_ends(map, &frame_camera(map, c, scale, bearing, pitch), (w, h), shape, line) + }; + let near = |a: f64, b: f64| (a - b).abs() < 0.6; + 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 (x, y) = cam.try_to_screen(map.to_map(at).unwrap(), w, h).unwrap(); + assert!((0.0..w).contains(&x) && (0.0..h).contains(&y), "{x} {y}"); + assert_eq!(ends(&map, view, &rect, SectionLine::Horizontal(at)), Ok([(0.0, y), (w, y)])); + assert_eq!(ends(&map, view, &rect, SectionLine::Vertical(at)), Ok([(x, 0.0), (x, h)])); + // Panned away, its place is outside the frame; the line elsewhere isn't drawn. + let away = (Coord::new(at.x + 5.0, at.y), 1e6, bearing, 0.0); + assert!(ends(&map, away, &rect, SectionLine::Horizontal(at)).unwrap_err().contains("outside the frame")); + } + // The copy of the place a frame across 180° shows, and one a turn away from the frame's own. + let map = Map::new("m"); + for (center, place) in [(179.5, -179.5), (-179.5, 179.5), (224.0, -136.0)] { + let got = ends(&map, (Coord::new(center, 0.0), 5e7, 0.0, 0.0), &rect, SectionLine::Vertical(Coord::new(place, 0.0))); + assert!(got.is_ok_and(|[a, _]| (a.0 - w / 2.0).abs() < w / 2.0), "{center} {got:?}"); + } + // Within its shape: a circle is as wide as the shorter side, and a polygon's outermost + // edges count, a place in its notch being outside the frame. + let here = (at, 1e6, 0.0, 0.0); + let [a, b] = ends(&map, here, &FrameShape::Circle, SectionLine::Horizontal(at)).unwrap(); + assert!(near(a.0, 100.0) && near(b.0, 300.0), "{a:?} {b:?}"); + let [a, b] = ends(&map, here, &FrameShape::Ellipse, SectionLine::Vertical(at)).unwrap(); + assert!(near(a.1, 0.0) && near(b.1, h), "{a:?} {b:?}"); + let notched = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.5, 0.25), (0.0, 1.0)]); + assert!(ends(&map, here, ¬ched, SectionLine::Horizontal(at)).is_err(), "in the notch"); + let left = map.to_lonlat(frame_camera(&map, at, 1e6, 0.0, 0.0).to_map(40.0, h / 2.0, w, h)).unwrap(); + let [a, b] = ends(&map, here, ¬ched, SectionLine::Horizontal(left)).unwrap(); + assert!(near(a.0, 0.0) && near(b.0, w), "{a:?} {b:?}"); + // Tilted to see the horizon, a vertical line stops there, its middle on the ground. + let tilted = (at, 5e4, 0.0, 80.0); + let cam = frame_camera(&map, at, 5e4, 0.0, 80.0); + let [a, b] = ends(&map, tilted, &rect, SectionLine::Vertical(at)).unwrap(); + assert!(a.1 > 1.0 && near(b.1, h), "{a:?} {b:?}"); + assert!(cam.try_to_map(a.0, a.1 + 1.0, w, h).is_some() && cam.try_to_map(a.0, a.1 - 1.0, w, h).is_none()); + // On the globe, it stops at the limb, and a place on the far side isn't shown. + let mut globe = Map::new("g"); + globe.projection = Projection::Globe; + let whole = (at, 5e8, 0.0, 0.0); + let [a, b] = ends(&globe, whole, &rect, SectionLine::Horizontal(at)).unwrap(); + assert!(a.0 > 1.0 && b.0 < w - 1.0 && near(a.0 + b.0, w), "{a:?} {b:?}"); + let far = SectionLine::Vertical(Coord::new(at.x + 180.0, -at.y)); + assert!(ends(&globe, whole, &rect, far).unwrap_err().contains("map shows")); +} + +/// A section's names stay in their frame across the line as along it, each clear of the other on +/// a short line, and the frame's credit keeps clear of every one of them and in the frame: the +/// left one too once it has gone left of the right one, and both of a vertical line's. +#[test] +fn section_names_stay_in_the_frame_and_clear_of_the_credit() { + let (w, h) = (200.0f32, 100.0f32); + let section = |line| Section::new("A".into(), line); + let at = Coord::new(0.0, 0.0); + let near_edges: [(Section, SectionEnds); 4] = [ + (section(SectionLine::Horizontal(at)), [(0.0, 1.0), (200.0, 1.0)]), + (section(SectionLine::Horizontal(at)), [(0.0, 99.0), (200.0, 99.0)]), + (section(SectionLine::Vertical(at)), [(1.0, 0.0), (1.0, 100.0)]), + (section(SectionLine::Vertical(at)), [(199.0, 0.0), (199.0, 100.0)]), + ]; + for (s, ends) in &near_edges { + let mut pm = Canvas::new(w as u32, h as u32).unwrap(); + for (_, b) in draw_sections(&mut pm, &[(s, *ends)], 1.0) { + assert!(b[0] >= 0.0 && b[1] >= 0.0 && b[2] <= w && b[3] <= h, "{ends:?}: {b:?}"); + } + } + // A credit 170 points wide goes left of the right name at the foot of the frame, and then + // not over the left one. + // A credit 100 points wide on a frame 37 points tall beside a vertical line near its right edge + // goes left of both its names, not above them out of the frame. + let credit_clear = |(w, h): (f32, f32), s: &Section, ends: SectionEnds, tw: f32| { + let mut pm = Canvas::new(w as u32, h as u32).unwrap(); + let names = draw_sections(&mut pm, &[(s, ends)], 1.0); + let (bottom, right) = attribution_inset((w, h), tw, &names); + let size = crate::ATTRIBUTION_SIZE; + let (cx, cy) = (crate::attribution_center(w, tw, right), h - bottom - size * 0.9); + let (x0, x1, y0, y1) = (cx - tw / 2.0, cx + tw / 2.0, cy - size * 0.8, cy + size * 0.8); + assert!(x0 >= 0.0 && y0 >= 0.0 && y1 <= h, "the credit {:?} leaves the frame", (x0, y0, x1, y1)); + for (_, b) in &names { + assert!(!(x0 < b[2] && b[0] < x1 && y0 < b[3] && b[1] < y1), "the credit {:?} covers {b:?}", (x0, y0, x1, y1)); + } + }; + let (s, ends) = &near_edges[1]; + credit_clear((w, h), s, *ends, 170.0); + credit_clear((200.0, 37.0), §ion(SectionLine::Vertical(at)), [(185.0, 0.0), (185.0, 37.0)], 100.0); + // On a line too short for both names at their size, they are drawn smaller, each clear of the + // other; on a long one, at their size. + for (length, smaller) in [(18.0, true), (30.0, true), (100.0, false)] { + for vertical in [true, false] { + let (line, ends) = if vertical { + (SectionLine::Vertical(at), [(100.0, 0.0), (100.0, length)]) + } else { + (SectionLine::Horizontal(at), [(0.0, 50.0), (length, 50.0)]) + }; + let mut pm = Canvas::new(w as u32, h as u32).unwrap(); + let names = draw_sections(&mut pm, &[(§ion(line), ends)], 1.0); + let [(_, a), (_, b)] = names[..] else { panic!("two names") }; + assert!(a[2] <= b[0] + 1e-3 || a[3] <= b[1] + 1e-3, "{length} {vertical}: {a:?} {b:?}"); + let tall = a[3] - a[1]; + assert_eq!(tall < SECTION_NAME_PT * 1.33 * 1.6 - 0.01, smaller, "{length} {vertical}: {tall}"); + } + } +} + +/// A place a flat Web Mercator frame can't show, nearer a pole than its 85.05°, isn't drawn at the +/// latitude it is held to, but said; one just inside is drawn. +#[test] +fn a_section_line_past_mercators_reach_is_not_drawn() { + let map = Map::new("m"); + let cam = frame_camera(&map, Coord::new(0.0, 84.9), 1e7, 0.0, 0.0); + let end = |lat: f64| section_ends(&map, &cam, (400.0, 200.0), &FrameShape::Rectangle, SectionLine::Horizontal(Coord::new(0.0, lat))); + assert_eq!(end(89.0), Err("its place isn't one the frame's map shows")); + assert!(end(85.0).is_ok(), "{:?}", end(85.0)); +} + +/// 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. +#[test] +fn section_lines_are_drawn_over_their_frame() { + use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH}; + let blue = Rgba::rgb(0, 0, 255); + let page = |shape: FrameShape, sections: Vec
| { + let mut map = Map::new("m"); + (map.basemap, map.graticule) = (rustgis_map::Basemap::Blank, false); + let mut l = Layout::new("Layout", 100.0, 100.0); + let kind = ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 1e7, + shape, + grid: None, + sections, + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: FRAME_BORDER_COLOR, + border_width: FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + l.add("Frame", (20.0, 20.0, 60.0, 60.0), kind); + (l, map) + }; + let section = |line| Section { color: blue, ..Section::new("A".into(), line) }; + let middle = Coord::new(0.0, 0.0); + let blues = |shape: FrameShape, sections: Vec
| { + let (l, map) = page(shape, sections); + let pm = render(&l, &mut [map], 254.0, &PageInfo::default()).unwrap(); + // Ten pixels a millimetre; the share of the row (or column) through the middle, between + // two millimetres, in blue. + move |vertical: bool, from: u32, to: u32| { + let blue = (from * 10..to * 10).filter(|&i| { + let (x, y) = if vertical { (500, i) } else { (i, 500) }; + let (r, g, b) = rgb(&pm, x, y); + b > 200 && r < 100 && g < 100 + }); + blue.count() as f64 / f64::from((to - from) * 10) + } + }; + let horizontal = blues(FrameShape::Rectangle, vec![section(SectionLine::Horizontal(middle))]); + assert!(horizontal(false, 30, 70) > 0.99 && horizontal(false, 0, 20) == 0.0 && horizontal(false, 81, 100) == 0.0); + assert!(horizontal(true, 21, 49) == 0.0, "no vertical one"); + let vertical = blues(FrameShape::Rectangle, vec![section(SectionLine::Vertical(middle))]); + assert!(vertical(true, 30, 70) > 0.99 && vertical(false, 30, 49) == 0.0); + let dashed = Section { dash: rustgis_map::symbology::Dash::new(&[6.0, 6.0]), ..section(SectionLine::Horizontal(middle)) }; + let share = blues(FrameShape::Rectangle, vec![dashed.clone()])(false, 30, 70); + assert!((0.4..0.6).contains(&share), "{share}"); + // A name is in a box of its colour at each end: pixels off the line there, none mid-way. + let (l, map) = page(FrameShape::Rectangle, vec![section(SectionLine::Horizontal(middle))]); + let pm = render(&l, &mut [map], 254.0, &PageInfo::default()).unwrap(); + let off = |x: u32| rgb(&pm, x, 512) == (0, 0, 255); + assert!((205..230).any(off) && (770..795).any(off) && !(300..700).any(off)); + // Clipped to a round frame, whose corners stay clear. + let off_centre = Coord::new(0.0, 2.2); + let (l, map) = page(FrameShape::Circle, vec![section(SectionLine::Horizontal(off_centre))]); + assert!(sections_not_drawn(&l, &[map]).is_empty()); + let round = blues(FrameShape::Circle, vec![section(SectionLine::Vertical(off_centre))]); + assert!(round(true, 30, 70) > 0.99 && round(true, 0, 20) == 0.0); + // As vectors, in a layer of their own; none without a section. + let layers = |sections| { + let (l, map) = page(FrameShape::Rectangle, sections); + let (drawing, pictured) = render_drawing(&l, &mut [map], 96.0, &PageInfo::default()).unwrap(); + assert!(pictured.is_empty()); + let page = crate::pdf::Page::drawing(drawing, l.width, l.height); + let (bytes, _) = crate::pdf::write_with(&[page], "p", crate::pdf::Options::default()); + String::from_utf8_lossy(&bytes).contains("(Section lines)") + }; + assert!(layers(vec![dashed]) && !layers(Vec::new())); + let plain = |sections| { + let (l, map) = page(FrameShape::Rectangle, sections); + render(&l, &mut [map], 96.0, &PageInfo::default()).unwrap().data().to_vec() + }; + // One whose place is outside the frame draws nothing, and is said, with its frame. + let away = section(SectionLine::Vertical(Coord::new(90.0, 0.0))); + assert_eq!(plain(vec![away.clone()]), plain(Vec::new())); + let (l, map) = page(FrameShape::Rectangle, vec![away, section(SectionLine::Horizontal(middle))]); + let gaps = sections_not_drawn(&l, &[map]); + assert_eq!(gaps.iter().map(|g| (g.frame, g.section.as_str())).collect::>(), vec![(1, "A")]); + let note = |pages| sections_notice(&gaps.iter().cloned().map(|g| (g, 2)).collect(), pages).unwrap(); + assert_eq!(note(1), "1 section line(s) not drawn: 'A' of Frame (1): its place is outside the frame"); + assert!(note(5).contains("'A' of Frame (1) on 2 of 5 pages: "), "{}", note(5)); + assert_eq!(sections_notice(&BTreeMap::new(), 5), None); + // A frame whose map is missing draws none of its own. + let gaps = sections_not_drawn(&l, &[]); + assert!(gaps.len() == 2 && gaps.iter().all(|g| g.why == "its frame's map is missing"), "{gaps:?}"); + // Its colour's transparency is its name boxes' too: blended with the white map, and clear. + let faded = |alpha| { + let (l, map) = + page(FrameShape::Rectangle, vec![Section { color: Rgba::new(0, 0, 255, alpha), ..section(SectionLine::Horizontal(middle)) }]); + let pm = render(&l, &mut [map], 254.0, &PageInfo::default()).unwrap(); + rgb(&pm, 209, 512) + }; + let (solid, half) = (faded(255), faded(128)); + assert!(solid == (0, 0, 255) && half.2 == 255 && (100..160).contains(&half.0), "{solid:?} {half:?}"); +} diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index ab09df9896..f933c0bf6f 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -536,6 +536,7 @@ fn layout_export_keeps_all_drawn_legend_classes() { scale: 300000.0, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, @@ -1312,6 +1313,7 @@ fn layout_export_rejects_unopened_local_shapefiles_and_required_masks() { scale: 300000.0, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 987eafcb38..9f3555cbd6 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -1956,6 +1956,7 @@ pub(crate) mod tests { scale: 500_000.0, shape: FrameShape::Rectangle, grid: None, + sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, extent_width: INDICATOR_WIDTH, diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 8c5bdb0242..c104b97f8b 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -115,6 +115,8 @@ pub struct LayoutView { page_wait: Option, /// The last clipping warning shown, cleared when the text fits or another layout opens. text_warning: Option, + /// The last notice of the section lines the page's frames don't draw. + section_warning: Option, /// The texts of the layout drawn (by its index) cut off on its page, with their lines left /// out of their box, as the Format pane tells them (#2346). text_losses: Option<(usize, Vec)>, @@ -207,6 +209,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.typing.clear(); app.layout.viewed = None; app.layout.text_warning = None; + app.layout.section_warning = None; app.layout.text_losses = None; app.layout.views.clear(); } @@ -283,6 +286,7 @@ impl LayoutView { return; } self.text_warning = None; + self.section_warning = None; self.text_losses = None; if let Some(old) = self.viewed.replace(name.to_string()) { self.views.insert(old, (self.zoom, self.pan)); @@ -415,6 +419,15 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } app.layout.text_warning = note; } + let gaps = rustgis_engine::render::layout::sections_not_drawn(&layout, &app.session.project.maps); + let note = rustgis_engine::render::layout::sections_notice(&gaps.into_iter().map(|g| (g, 1)).collect(), 1); + if note != app.layout.section_warning { + // (The command that added or moved one has just said so.) + if let Some(note) = note.as_ref().filter(|n| app.session.notices.last().is_none_or(|last| last.text != **n)) { + app.session.warn(note.clone()); + } + app.layout.section_warning = note; + } // The Format pane is drawn before the page: a count that changed shows on the next // frame, without waiting for an input event. let losses = Some((li, losses)); diff --git a/docs/maintaining.md b/docs/maintaining.md index d4c03b4e49..b08ba33105 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -279,6 +279,12 @@ without its own (#2557). A saved `layout.update` that gives a frame a `border` o too, since an older reader warns that it ignores the key; `"border": null` only gives the default back and needs nothing. A saved `layout.import` whose `text` has such a frame requires it as well. +Projects with section lines on a map frame (`sections`) require `layout-section`, so an older +reader refuses them instead of drawing the frame without them and saving it again so (#2863). A +saved `layout.addElement` of a section requires it too, and so does a `layout.update` with a +`section` object, which an older reader warns that it ignores. A saved `layout.import` whose `text` +has such a frame requires it as well. + Projects with a legend, a scale bar or a grid whose text isn't its default size (`text_size` on a legend, 9 points by default, or on a scale bar, 8; `label_size` on a frame's grid, 8) require `layout-text-size`, so an older reader refuses them instead of drawing that text at the default diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 27c18088ac..3a0bc2a323 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -274,6 +274,20 @@ 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: + `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. - **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 @@ -792,7 +806,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu Its page has layers (PDF optional content groups), which a vector editor that reads them opens as layers (VectorCraft, where it was checked), and PDF readers list in their layers panel: one for each element, named after it, and inside a map frame's, one for each map layer and one - for each layer's labels (`Labels: `), and one for the frame's grid. A map series' pages + for each layer's labels (`Labels: `), one for the frame's grid and one for its section lines. A map series' pages share them. `"pdf": {"layers": false}` on `layout.export` leaves them out. The map view's PDF (Publish › Print Map) has its map layers and labels as layers too. A PDF is also a GeoPDF: each map frame is georeferenced (an ISO 32000 geospatial viewport, the diff --git a/schema/fixtures/layout_section.rgis b/schema/fixtures/layout_section.rgis new file mode 100644 index 0000000000..56e27da433 --- /dev/null +++ b/schema/fixtures/layout_section.rgis @@ -0,0 +1,28 @@ +{ + "format": 2, + "name": "Section lines", + "requires": ["layout-section"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "layouts": [ + { + "name": "Sections", + "width": 200, + "height": 100, + "elements": [ + {"id": 1, "name": "None", "x": 5, "y": 5, "w": 60, "h": 90, "kind": {"MapFrame": {"map": "Map", "center": {"x": 0, "y": 0}, "scale": 1000000}}}, + {"id": 2, "name": "Two", "x": 70, "y": 5, "w": 60, "h": 90, "kind": {"MapFrame": {"map": "Map", "center": {"x": 0, "y": 0}, "scale": 1000000, "sections": [ + {"name": "A", "line": {"Horizontal": {"x": 0.05, "y": 0.1}}, "color": [168, 67, 31, 255], "width": 1.5}, + {"name": "B", "line": {"Vertical": {"x": -0.1, "y": 0}}, "color": [31, 92, 132, 255], "width": 1, "dash": [6, 3]} + ]}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 987e8deb7f..208b6e7b25 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1274,6 +1274,7 @@ "zarr-window", "blank-paper", "layout-frame-border", + "layout-section", "native-coordinates", "layout-text-size", "layout-legend-fit", @@ -1391,6 +1392,7 @@ "zarr-window", "blank-paper", "layout-frame-border", + "layout-section", "native-coordinates", "layout-text-size", "layout-legend-fit",