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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ pub fn commands() -> Vec<C> {
r##""valign"?: "top"|"middle"|"bottom" (text, dynamicText: where its block of lines sits down its box; default top; a block taller than its box is drawn from the top, its last lines left out, which a warning says; refused for other kinds), "##,
r##""lineSpacing"?: 0.5 to 3 (text, dynamicText: the distance between its lines, a multiple of the usual; default 1; refused outside that range, and for other kinds), "##,
r##""case"?: "none"|"upper"|"lower" (text, dynamicText: drawn in upper or lower case once its dynamic text is filled in, its text kept as typed; default none; refused for other kinds), "##,
r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##,
r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText, and a northArrow's N; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##,
r##""fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "##,
r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group); profile: written over its curve ("" for none; default its layer's name), "##,
r##""subtitle"?: text (legend: one line under its title, at the rows' text size, up to 200 characters; "" for none, the default; refused for other kinds), "##,
Expand Down Expand Up @@ -327,8 +327,8 @@ pub fn commands() -> Vec<C> {
r##""valign"?, "##,
r##""lineSpacing"?, "##,
r##""case"? (text, as in layout.addElement; null leaves each as it is; refused for other elements), "##,
r##""font"?: "sans"|"serif"|an installed font family's name, "##,
r##""fallback"?: "sans"|"serif" (text, as in layout.addElement; refused for other elements), "##,
r##""font"?: "sans"|"serif"|an installed font family's name (text, dynamicText, a northArrow's N), "##,
r##""fallback"?: "sans"|"serif" (text, dynamicText, a northArrow's N, as in layout.addElement; refused for other elements), "##,
r##""title"? (legend, colorbar; chart: its own title ("" for none; null giving it the title it is given again)), "##,
r##""subtitle"?: text (legend, as in layout.addElement; "" takes it away, null leaves it as it is), "##,
r##""allClasses"?: bool (legend), "##,
Expand Down
13 changes: 9 additions & 4 deletions crates/engine/src/cmd/layout/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu
}
// A family is a text's: refused elsewhere, as a legend's left-out layers are, so a script
// doesn't take it as applied.
if !matches!(kind, "text" | "dynamicText") && gives_font(p) {
if !matches!(kind, "text" | "dynamicText" | "northArrow") && gives_font(p) {
return Err(ONLY_TEXT_FONT.into());
}
if kind != "rectangle" && p.get("radius").is_some_and(|v| !v.is_null()) {
Expand Down Expand Up @@ -798,6 +798,10 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu
ElementKind::Text { font, font_name, bold, italic, .. } => {
font_warning(*font, font_name.as_deref(), p.get("fallback").is_some_and(|v| !v.is_null()), (*bold, *italic))
}
// Its `N` is bold; a call that gives no font is told nothing.
ElementKind::NorthArrow { font, font_name, .. } if gives_font(p) => {
font_warning(*font, font_name.as_deref(), p.get("fallback").is_some_and(|v| !v.is_null()), (true, false))
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
_ => None,
};
// A colorbar with nothing to show says why, as a notice the app shows.
Expand Down Expand Up @@ -1103,7 +1107,8 @@ pub fn add_element_reads_frame(kind: &str) -> bool {
}

/// Keys read by `layout.addElement` for a north arrow (#3074).
const ADD_NORTH_ARROW_KEYS: &[&str] = &["layout", "kind", "frame", "x", "y", "w", "h", "background", "style", "fill", "outline"];
const ADD_NORTH_ARROW_KEYS: &[&str] =
&["layout", "kind", "frame", "x", "y", "w", "h", "background", "style", "fill", "outline", "font", "fallback"];

/// Keys read by `layout.addElement` for a scale bar (#3074).
const ADD_SCALE_BAR_KEYS: &[&str] = &[
Expand Down Expand Up @@ -1593,7 +1598,7 @@ mod tests {
let err = s.run("layout.addElement", &json!({"kind": "northArrow", "bold": true})).unwrap_err();
assert_eq!(
err,
"layout.addElement: a north arrow takes no \"bold\" (it reads layout, kind, frame, x, y, w, h, background, style, fill, outline)"
"layout.addElement: a north arrow takes no \"bold\" (it reads layout, kind, frame, x, y, w, h, background, style, fill, outline, font, fallback)"
);

let err = s.run("layout.addElement", &json!({"kind": "rectangle", "angle": 30})).unwrap_err();
Expand Down Expand Up @@ -1661,7 +1666,7 @@ mod tests {

// Every key a kind reads, each given a value it takes.
let calls = [
json!({"kind": "northArrow", "layout": 0, "frame": frame, "x": 10, "y": 10, "w": 15, "h": 20, "style": "compass", "fill": "#112233", "outline": "#445566", "background": {"fill": "#FFFFFF"}}),
json!({"kind": "northArrow", "layout": 0, "frame": frame, "x": 10, "y": 10, "w": 15, "h": 20, "style": "compass", "fill": "#112233", "outline": "#445566", "font": "sans", "fallback": null, "background": {"fill": "#FFFFFF"}}),
json!({"kind": "scaleBar", "frame": frame, "x": 10, "y": 10, "w": 60, "h": 12, "style": "stepped", "units": "miles", "divisions": 3, "subdivisions": 2, "divisionsBeforeZero": 1, "labelPosition": "below", "unitLabel": "mi", "unitLabelPosition": "afterBar", "fit": "adjustWidth", "decimals": 1, "textSize": 9, "color": "#112233", "fill": "#FFFFFF"}),
json!({"kind": "legend", "frame": frame, "title": "T", "allClasses": true, "hideOther": true, "showNoData": true, "exclude": [], "layerOrder": [], "columns": 2, "labels": {}, "textSize": 8, "fit": "adjustSize", "showLayerNames": false, "showCounts": true, "sizes": "nested", "color": "#112233"}),
json!({"kind": "colorbar", "frame": frame, "title": "T", "orientation": "vertical", "ticks": 3, "tickSide": "left", "reverse": true, "color": "#112233"}),
Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/cmd/layout/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

use super::*;

/// What an export of a layout whose texts name installed families is told while the app is still
/// What an export of a layout whose texts or north arrows name installed families is told while the app is still
/// indexing the fonts (its first seconds; the app's exports don't wait for them): those texts
/// are drawn in their fallbacks. A script or the command line indexes them at once.
pub(in crate::cmd::layout) fn named_fonts_unread(layout: &Layout) -> Option<&'static str> {
let named = layout.elements.iter().any(|e| matches!(&e.kind, ElementKind::Text { font_name: Some(_), .. }));
let named = layout.elements.iter().any(|e| e.kind.named_font().is_some());
(named && rustgis_render::families::available().is_none()).then_some(
"the installed fonts are still being read, so texts in a named font family are drawn in their fallback: export again in a moment",
"the installed fonts are still being read, so texts and north arrows in a named font family are drawn in their fallback: export again in a moment",
)
}

Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/cmd/layout/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,10 +345,10 @@ pub(crate) fn text_block_settings(p: &Value, current: (TextVAlign, f64, TextCase
Ok((valign, spacing, case))
}

/// What a `font` given for an element that isn't a text is told.
pub(in crate::cmd::layout) const ONLY_TEXT_FONT: &str = "only text elements take a font or a fallback";
/// What a `font` given for an element that draws no text of a chosen family is told.
pub(in crate::cmd::layout) const ONLY_TEXT_FONT: &str = "only text elements and north arrows take a font or a fallback";

/// Whether `p` gives a `font` or a `fallback`, which only text elements take.
/// Whether `p` gives a `font` or a `fallback`, which only text elements and north arrows take.
pub(in crate::cmd::layout) fn gives_font(p: &Value) -> bool {
["font", "fallback"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()))
}
Expand Down
20 changes: 14 additions & 6 deletions crates/engine/src/cmd/layout/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,23 @@ fn changed_indicators(kind: &ElementKind, v: &Value) -> Result<Vec<ExtentIndicat
/// or when `p` has none. A bad value is an error, leaving nothing changed.
pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result<Option<ElementKind>, String> {
match kind {
ElementKind::NorthArrow { frame, style, fill, outline } => {
if ["style", "fill", "outline"].iter().all(|k| p.get(k).is_none()) {
ElementKind::NorthArrow { frame, style, fill, outline, font, font_name } => {
if ["style", "fill", "outline", "font", "fallback"].iter().all(|k| p.get(k).is_none()) {
return Ok(None);
}
let style = match given_name(p, "style", "classic, compass, triangle or star")? {
Some(v) => ArrowStyle::from_name(v)
.ok_or_else(|| format!("unknown north arrow style '{v}' (classic, compass, triangle or star)"))?,
None => *style,
};
let (font, font_name) = text_font(p, (*font, font_name.clone()))?;
Ok(Some(ElementKind::NorthArrow {
frame: *frame,
style,
fill: color(p, "fill", *fill)?,
outline: color(p, "outline", *outline)?,
font,
font_name,
}))
}
ElementKind::ScaleBar {
Expand Down Expand Up @@ -395,6 +398,8 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult {
Some(ElementKind::Text { italic, align, letter_spacing, font, font_name, .. }) => {
Some((text_style(p, *italic, *align, *letter_spacing)?, text_font(p, (*font, font_name.clone()))?))
}
// A north arrow's are read with its look, by `restyle`.
Some(ElementKind::NorthArrow { .. }) => None,
_ if gives_font(p) => return Err(ONLY_TEXT_FONT.into()),
_ => None,
};
Expand Down Expand Up @@ -423,12 +428,15 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult {
Some(ElementKind::Text { bold, .. }) => b(p, "bold").unwrap_or(*bold),
_ => false,
};
let font_told = match &new_text_style {
Some(((italic, _, _), (f, n))) if gives_font(p) => {
font_warning(*f, n.as_deref(), p.get("fallback").is_some_and(|v| !v.is_null()), (bold_now, *italic))
}
// The family asked for: a text's, or a north arrow's, whose `N` is bold.
let asked = match (&new_text_style, &restyled) {
(Some(((italic, _, _), (f, n))), _) => Some((*f, n.as_deref(), (bold_now, *italic))),
(None, Some(ElementKind::NorthArrow { font, font_name, .. })) => Some((*font, font_name.as_deref(), (true, false))),
_ => None,
};
let font_told = asked
.filter(|_| gives_font(p))
.and_then(|(f, n, style)| font_warning(f, n, p.get("fallback").is_some_and(|v| !v.is_null()), style));
if p.get("radius").is_some_and(|v| !v.is_null())
&& !matches!(s.project.layouts.get(li).and_then(|l| l.element(id)).map(|e| &e.kind), Some(ElementKind::Rectangle { .. }))
{
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ pub const CAPABILITIES: &[&str] = &[
"layout-chart-outline",
"layout-table-look",
"layout-colorbar-labels",
"layout-north-arrow-font",
"field-generation",
"field-package",
FIELD_CONFLICTS,
Expand Down
98 changes: 98 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("layout-chart-outline", command_uses_chart_outline),
("layout-table-look", command_uses_table_look),
("layout-colorbar-labels", command_uses_colorbar_labels),
("layout-north-arrow-font", command_uses_north_arrow_font),
("blank-paper", command_uses_blank_paper),
("layout-frame-border", command_uses_frame_border),
("layout-section", command_uses_section),
Expand Down Expand Up @@ -1233,6 +1234,38 @@ fn command_uses_colorbar_labels(id: &str, params: &Value) -> bool {
}
}

fn north_arrows_with_font(e: &rustgis_map::layout::Element) -> bool {
e.kind.north_arrow_uses_font()
}

/// A layout command that gives a north arrow a font (#3467). A saved `layout.update` isn't told
/// what kind of element it changes (a text takes a font too), so it requires nothing here on
/// purpose: a reader without this refuses a font on a north arrow when the step runs.
fn command_uses_north_arrow_font(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("northArrow"))
&& params
.get("font")
.and_then(Value::as_str)
.is_some_and(|f| rustgis_map::layout::FontFamily::from_name(f.trim()) != Some(rustgis_map::layout::FontFamily::Sans))
}
"layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"font"], north_arrows_with_font),
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
// It opens its `text` only, whatever else the step holds.
"project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_gives_north_arrow_font),
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_north_arrow_font)),
_ => false,
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// Whether a project's saved text requires `layout-north-arrow-font`, as one saved would: its
/// north arrows', its steps' and its notebooks'. Parsed only when the text may name a font, may
/// hide the key ([`may_hide_a_key`]) or holds a step's base64 `data` ([`names_data`]).
fn text_gives_north_arrow_font(text: &str) -> bool {
(text.contains("font") || may_hide_a_key(text) || names_data(text))
&& Project::from_json(text).is_ok_and(|p| p.required_capabilities().contains(&"layout-north-arrow-font"))
}

/// Whether a command carries its layout inline with an element `uses`, as `layout.import` and
/// `report.existingTemplate` do: an older reader reads it without the keys it doesn't know. One
/// read from a `"path"` is a layout file, whose own header requires what it uses (#2277). Every
Expand Down Expand Up @@ -1813,6 +1846,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static
(elements().any(charts_outlined), "layout-chart-outline"),
(elements().any(tables_with_a_look), "layout-table-look"),
(elements().any(colorbars_with_labels), "layout-colorbar-labels"),
(elements().any(north_arrows_with_font), "layout-north-arrow-font"),
(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.is_profile()), "layout-profile"),
Expand Down Expand Up @@ -2299,6 +2333,7 @@ mod tests {
(&[], "buffer", json!({"input": "Cities", "distance": 1})),
(&[], "layout.addElement", chart),
(&["layout-colorbar-labels"], "layout.addElement", json!({"kind": "colorbar", "decimals": 2})),
(&["layout-north-arrow-font"], "layout.addElement", json!({"kind": "northArrow", "font": "serif"})),
];
let mut covered = std::collections::BTreeSet::new();
for (capability, id, params) in samples {
Expand Down Expand Up @@ -2601,6 +2636,7 @@ mod tests {
"layout-chart-outline",
"layout-table-look",
"layout-colorbar-labels",
"layout-north-arrow-font",
"layout-frame-border",
"layout-text-size",
"layout-scale-bar-details",
Expand Down Expand Up @@ -3768,6 +3804,68 @@ mod tests {
}
}

/// A north arrow's font (#3467) requires `layout-north-arrow-font`, in a saved layout and in
/// a saved command.
#[test]
fn north_arrow_font_capability_follows_saved_layouts_and_commands() {
use rustgis_map::layout::{ElementKind, FontFamily};
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_north_arrow_font.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["layout-north-arrow-font"]));
let mut clean = fixture;
for e in &mut clean.layouts[0].elements {
if let ElementKind::NorthArrow { font, font_name, .. } = &mut e.kind {
(*font, *font_name) = (FontFamily::Sans, None);
}
}
let base = serde_json::to_value(&clean).unwrap();
assert!(base.get("requires").is_none(), "a plain north arrow needs nothing");
// Project texts a step opens: without the header an older reader would drop the font.
let mut headerless = saved.clone();
headerless.as_object_mut().unwrap().remove("requires");
let mut generic = headerless.clone();
generic["layouts"][0]["elements"][1]["kind"]["NorthArrow"].as_object_mut().unwrap().remove("font_name");
// Its key written with an escape, in a project whose name doesn't spell it.
let mut escaped = headerless.clone();
escaped["name"] = json!("Arrow");
let escaped = escaped.to_string().replace("\"font", "\"\\u0066ont");
let stepped = |params: Value| {
let mut p = base.clone();
p["tasks"] = json!([{"name": "Inner", "steps": [{"title": "Add", "command": "layout.addElement", "params": params}]}]);
p.to_string()
};
for (id, params, required) in [
("project.openText", json!({"text": headerless.to_string()}), true),
("project.openText", json!({"text": saved.to_string()}), true),
("project.openText", json!({"text": generic.to_string()}), true),
("project.openText", json!({"text": escaped}), true),
("project.openText", json!({"text": stepped(json!({"kind": "northArrow", "font": "serif"}))}), true),
("project.openText", json!({"text": stepped(json!({"kind": "text", "font": "serif"}))}), false),
("project.openText", json!({"text": base.to_string()}), false),
// Left out on purpose: it names no element kind, and a text takes a font too.
("layout.update", json!({"element": 2, "font": "serif"}), false),
("layout.addElement", json!({"kind": "northArrow", "font": "serif"}), true),
("layout.addElement", json!({"kind": "northArrow", "font": "DejaVu Serif"}), true),
("layout.addElement", json!({"kind": "northArrow", "font": "sans-serif"}), false),
("layout.addElement", json!({"kind": "northArrow", "font": null}), false),
("layout.addElement", json!({"kind": "text", "font": "serif"}), false),
("layout.import", json!({"text": saved["layouts"][0].to_string()}), true),
("layout.import", json!({"text": base["layouts"][0].to_string()}), false),
] {
let script = format!("{id} {params}");
for value in [
json!([{"name": "Task", "steps": [{"title": "Arrow", "command": id, "params": params}]}]),
json!([{"name": "Script", "steps": [{"title": "Arrow", "command": "script.run", "params": {"script": script}}]}]),
] {
let mut document = base.clone();
document["tasks"] = value;
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
let has = saved["requires"].as_array().is_some_and(|r| r.contains(&json!("layout-north-arrow-font")));
assert_eq!(has, required, "{id} {params}");
}
}
}

#[test]
fn field_identity_is_preserved_and_required_in_a_plain_saved_project() {
let project = Project::from_json(include_str!("../../../schema/fixtures/field_origin.rgis")).unwrap();
Expand Down
Loading
Loading