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
2 changes: 2 additions & 0 deletions crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ miniz_oxide = { workspace = true }
# Writing sample GeoPackages.
rusqlite = { workspace = true }
rustgis-plugins = { workspace = true, features = ["testing"] }
# Test rasters to draw layouts from.
rustgis-render = { workspace = true, features = ["testing"] }
# Cancelling a command at each of its checks in turn.
rustgis-analysis = { workspace = true, features = ["testing"] }
tiny-skia = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,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? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? showCounts? 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?
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? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? showCounts? 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? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? 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?
Expand Down
10 changes: 6 additions & 4 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7570,6 +7570,7 @@ fn references_follow_layer(s: &mut Session, old: &str, new: &str) {
replace(layer)
}
ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => replace(layer),
ElementKind::Profile(p) if frames.contains(&p.frame) => replace(&mut p.layer),
ElementKind::Text { text, .. } if texts_read_this_map => {
match renamed_statistics(text, rustgis_map::layout::MAX_TEXT_CHARS, braces, &mut replace) {
Renamed::To(renamed) => *text = renamed,
Expand Down Expand Up @@ -7731,10 +7732,10 @@ fn removed_notice(keys: [&'static str; 2], count: usize, named: &[&str]) -> Opti
Some(crate::notice_text::NoticeText::format(key, [("count", count.to_string().into()), ("names", names.into())]))
}

/// After layers called `names` are removed: a table's, chart's or colorbar's layer, and a text's
/// layer statistics (#2853), keep the name, so a layer of that name brings them back, and are drawn
/// without it meanwhile: how many elements, said once. Which elements read the active map is as for
/// a rename (`references_follow_layer`).
/// After layers called `names` are removed: a table's, chart's, colorbar's or profile's layer, and a
/// text's layer statistics (#2853), keep the name, so a layer of that name brings them back, and are
/// drawn without it meanwhile: how many elements, said once. Which elements read the active map is
/// as for a rename (`references_follow_layer`).
fn layouts_follow_removal(s: &mut Session, names: &[String]) {
use rustgis_map::layout::ElementKind;

Expand All @@ -7752,6 +7753,7 @@ fn layouts_follow_removal(s: &mut Session, names: &[String]) {
vec![layer]
}
ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => vec![layer],
ElementKind::Profile(p) if frames.contains(&p.frame) => vec![&p.layer],
ElementKind::Text { text, .. } if texts_read_this_map => {
rustgis_map::layout::stat_tokens(text).iter().map(|t| t.layer).collect()
}
Expand Down
13 changes: 11 additions & 2 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ pub fn commands() -> Vec<C> {
r##""locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "##,
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"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##,
r##""color"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart, profile: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##,
r##""bold"?, "##,
r##""italic"?, "##,
r##""align"?, "##,
Expand Down Expand Up @@ -374,7 +374,16 @@ pub fn commands() -> Vec<C> {
r##""classes"?: bool, "##,
r##""labelAlign"?: "left"|"right", "##,
r##""mirror"?: bool, "##,
r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again), "##,
r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again; profile: a number, or null for its samples' own), "##,
r##""band"?, "##,
r##""side"?, "##,
r##""gap"?, "##,
r##""thickness"?, "##,
r##""unit"?, "##,
r##""lineColor"?, "##,
r##""lineWidth"?, "##,
r##""min"?, "##,
r##""guides"? (profile, as in layout.addElement: "section" its line's name, "layer" its raster, "fill", "min" and "max" null for none or its samples' own, "color" its ink; its x, y, w and h set its gap and thickness, along its frame it keeping the frame's), "##,
r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##,
r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##,
r##""rows"?, "##,
Expand Down
7 changes: 7 additions & 0 deletions crates/engine/src/cmd/layout/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,12 @@ pub(in crate::cmd::layout) fn update_inputs(input: &crate::cmd::InputContext<'_>
inputs.extend(crate::cmd::Inputs::named(frame_map(input, l, *frame)?, [name.as_str()])?);
}
}
// A profile's new raster (#2863 part 2).
Some(ElementKind::Profile(profile)) if ps(p, "layer").is_some_and(|n| !n.trim().is_empty()) => {
let map = frame_map(input, l, profile.frame)?;
let name = added_profile_layer(map, p)?;
inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?);
}
Some(ElementKind::Legend { frame, .. }) => {
let (names, labels) = (legend_exclude(input, l, *frame, p)?, legend_labels(input, l, *frame, p)?);
let classes = legend_class_labels(input, l, *frame, p)?;
Expand Down Expand Up @@ -302,6 +308,7 @@ pub(in crate::cmd::layout) fn element_selectors(kind: &ElementKind) -> Option<Va
json!({"frame":frame,"exclude":exclude,"layerOrder":layer_order,"labels":labels,"classLabels":class_labels})
}
ElementKind::Colorbar { frame, layer, .. } => json!({"frame":frame,"layer":layer}),
ElementKind::Profile(p) => json!({"frame":p.frame,"layer":p.layer,"section":p.section}),
ElementKind::NorthArrow { frame, .. } | ElementKind::ScaleBar { frame, .. } => json!({"frame":frame}),
_ => return None,
})
Expand Down
109 changes: 107 additions & 2 deletions crates/engine/src/cmd/layout/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rustgis_map::layout::{

use super::*;

/// The keys of a profile's own, which `layout.addElement` reads.
/// The keys of a profile's own, which `layout.addElement` and `layout.update` read.
const PROFILE_KEYS: &[&str] = &[
"section",
"layer",
Expand All @@ -28,6 +28,18 @@ const PROFILE_KEYS: &[&str] = &[
];
/// What `layout.addElement` reads for a profile, besides [`PROFILE_KEYS`].
const ADD_PROFILE_KEYS: &[&str] = &["layout", "kind", "frame", "background"];
/// What `layout.update` reads for a profile, besides [`PROFILE_KEYS`]: `x`, `y`, `w` and `h` as its
/// gap and thickness ([`Profile::take_rect`]).
const UPDATE_PROFILE_KEYS: &[&str] = &["layout", "element", "name", "visible", "locked", "background", "x", "y", "w", "h"];

/// A profile's keys that null gives back their default: no fill, the samples' own ends, the dark
/// grey ink.
const PROFILE_NULL_KEYS: &[&str] = &["fill", "min", "max", "color", "background"];

/// Whether element `id` of layout `li` is a profile.
pub(in crate::cmd::layout) fn is_profile(s: &Session, li: usize, id: u32) -> bool {
s.project.layouts.get(li).and_then(|l| l.element(id)).is_some_and(|e| e.kind.is_profile())
}

/// A frame's map, its section lines and its box (x, y, w, h in mm).
fn frame_parts<'a>(s: &'a Session, l: &'a Layout, frame: u32) -> Result<(&'a Map, &'a [Section], (f64, f64, f64, f64)), String> {
Expand Down Expand Up @@ -118,7 +130,8 @@ fn profile_params(s: &Session, l: &Layout, p: &Value, mut base: Profile) -> Resu
}
base.band = v as u32;
}
if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n) {
// Only a band or layer given is checked: one left on a band its raster lost still takes the rest.
if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n && (gives(p, "band") || gives(p, "layer"))) {
return Err(format!("'{}' has {n} band(s): band is 1 to {n}", base.layer));
}
let mut mm = |k: &str, range: (f64, f64), v: &mut f64| -> Result<(), String> {
Expand Down Expand Up @@ -219,6 +232,85 @@ pub(in crate::cmd::layout) fn add_profile(s: &mut Session, p: &Value) -> CmdResu
Ok(json!({"element": id}))
}

/// `layout.update` for a profile: its own options, its name, visibility, lock and background, and
/// `x`, `y`, `w` and `h` read as its gap and thickness, along its frame it keeping the frame's.
pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usize, id: u32) -> CmdResult {
let keys: Vec<&str> = UPDATE_PROFILE_KEYS.iter().chain(PROFILE_KEYS).copied().collect();
if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !keys.contains(&k.as_str()) && gives(p, k))) {
let shown: String = k.chars().take(40).map(|c| if c.is_control() { '?' } else { c }).collect();
return Err(format!("layout.update: a profile takes no \"{shown}\" (it reads {})", keys.join(", ")));
}
let l = s.project.layouts.get(li).ok_or("no layout")?;
let e = l.element(id).ok_or_else(|| format!("no element {id}"))?;
let ElementKind::Profile(current) = &e.kind else { return Err(format!("element {id} isn't a profile")) };
let changes = p.as_object().is_some_and(|o| {
o.iter().any(|(k, v)| {
(!v.is_null() || PROFILE_NULL_KEYS.contains(&k.as_str())) && !matches!(k.as_str(), "layout" | "element" | "locked")
})
});
if changes && b(p, "locked") != Some(false) {
unlocked(l, id)?;
}
let new_name = crate::cmd::name_given(p, "an element's name", 200)?;
let new_background = match element_background(p, e.background)? {
BackgroundParam::Set(b) => Some(Some(b)),
BackgroundParam::Remove => Some(None),
BackgroundParam::Absent => None,
};
let boxed = ["x", "y", "w", "h"].iter().any(|k| gives(p, k));
if boxed && (gives(p, "gap") || gives(p, "thickness")) {
return Err("give a profile a gap and thickness, or x, y, w and h, not both".into());
}
// Only its name, visibility, lock or background: its frame and map aren't read, so one whose
// map was deleted can still be unlocked, renamed or shown.
let (new, held) = if boxed || PROFILE_KEYS.iter().any(|k| p.get(*k).is_some()) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let (mut new, mut held) = profile_params(s, l, p, current.clone())?;
let (_, _, frame_box) = frame_parts(s, l, new.frame)?;
if boxed {
// What isn't given is where it would sit now, on its side after this change.
let (x, y, w, h) = new.rect(frame_box);
let at = |k: &str, now: f64| given_num(p, k, "a number of mm").map(|v| v.unwrap_or(now));
let rect = (at("x", x)?, at("y", y)?, at("w", w)?, at("h", h)?);
if new.take_rect(frame_box, rect) {
let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES);
held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
// Along its frame it keeps the frame's: what was given there and isn't that, said.
let along = if new.side.is_horizontal() { [("x", x), ("w", w)] } else { [("y", y), ("h", h)] };
for (k, kept) in along {
if let Some(v) = f(p, k).filter(|v| (v - kept).abs() > 1e-9) {
held.push(format!("{k} {v} not used: along its frame a profile keeps the frame's ({kept})"));
}
}
}
(new, held)
} else {
(current.clone(), Vec::new())
};
let reread = ["section", "layer", "band", "side"].iter().any(|k| gives(p, k));
let l = s.project.layouts.get_mut(li).ok_or("no layout")?;
let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?;
e.kind = ElementKind::Profile(new);
if let Some(n) = new_name {
e.name = n;
}
if let Some(v) = b(p, "visible") {
e.visible = v;
}
if let Some(v) = b(p, "locked") {
e.locked = v;
}
if let Some(v) = new_background {
e.background = v;
}
l.fit_profiles();
say_held(s, "Element Properties", held);
if reread {
say_profile_drawn(s, li, id);
}
Ok(Value::Null)
}

/// Says that profile `id` of layout `li` isn't drawn, and why, or that it is read at fewer samples
/// than its raster's cells along its section line, when it is.
pub(in crate::cmd::layout) fn say_profile_drawn(s: &mut Session, li: usize, id: u32) {
Expand All @@ -230,6 +322,19 @@ pub(in crate::cmd::layout) fn say_profile_drawn(s: &mut Session, li: usize, id:
}
}

/// The profiles of section line `old` of frame `frame` named `new` instead, after the line was
/// renamed: they follow it.
pub(in crate::cmd::layout) fn profiles_follow_section(l: &mut Layout, frame: u32, old: &str, new: &str) {
for e in &mut l.elements {
if let ElementKind::Profile(p) = &mut e.kind
&& p.frame == frame
&& p.section.eq_ignore_ascii_case(old)
{
p.section = new.to_string();
}
}
}

/// The raster layer `layout.addElement` reads for a profile, for its inputs: the one given, else the
/// top one its frame's map shows that it can read.
pub(in crate::cmd::layout) fn added_profile_layer(map: &Map, p: &Value) -> Result<String, String> {
Expand Down
19 changes: 11 additions & 8 deletions crates/engine/src/cmd/layout/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,12 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result<O

pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult {
let id = element_id(p)?;
// A profile reads its own keys (#2863 part 2), several of them other kinds' too.
if let Ok(li) = index(s, p)
&& is_profile(s, li, id)
{
return update_profile(s, p, li, id);
}
// The first frame's map as it is, to say what the texts lose only when it changes (#2853).
let map_before = index(s, p).ok().and_then(|li| first_frame_map(s, li));
// Checked before anything changes, so a bad value leaves the element as it was.
Expand Down Expand Up @@ -860,17 +866,14 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult {
if let Some((_, Some(name))) = &new_sections {
say_section_not_drawn(s, li, id, name);
}
// A frame moved or resized takes its profiles with it (#2863); a profile's own box is its frame's.
let profile = s.project.layouts.get(li).and_then(|l| l.element(id)).filter(|e| e.kind.is_profile()).map(|e| e.name.clone());
// A frame moved or resized takes its profiles with it, and a section line renamed its
// profiles (#2863).
if let Some(l) = s.project.layouts.get_mut(li) {
if let (Some((_, Some(new))), Some(old)) = (&new_sections, p.get("section").and_then(|v| ps(v, "name"))) {
profiles_follow_section(l, id, old.trim(), new);
}
l.fit_profiles();
}
if let Some(name) = profile.filter(|_| given(&["x", "y", "w", "h"])) {
s.notify(
format!("Element Properties: the profile '{name}' keeps beside its frame, whose side is its box: x, y, w and h are not used"),
false,
);
}
say_held(s, "Element Properties", held);
if let Some(w) = font_told {
return Ok(json!({"warning": w}));
Expand Down
15 changes: 12 additions & 3 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,12 +578,20 @@ fn command_uses_section(id: &str, params: &Value) -> bool {
}
}

/// A layout command that adds a profile beside a map frame or brings one in (#2863 part 2): an
/// older reader refuses the kind `profile` of `layout.addElement` and the kind `Profile` of a
/// layout file.
/// The keys of `layout.update` only a profile reads (#2863 part 2), besides a `section` given as a
/// name, which a map frame takes as an object.
const PROFILE_ONLY_KEYS: &[&str] = &["band", "side", "gap", "thickness", "unit", "lineColor", "lineWidth", "guides", "min"];

/// A layout command that adds, changes or brings in a profile beside a map frame (#2863 part 2): an
/// older reader refuses the kind `profile` of `layout.addElement`, the keys of `layout.update` only
/// a profile reads, and the kind `Profile` of a layout file.
fn command_uses_profile(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("profile")),
"layout.update" => {
PROFILE_ONLY_KEYS.iter().any(|k| params.get(*k).is_some_and(|v| !v.is_null()))
|| params.get("section").is_some_and(Value::is_string)
}
// A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does.
"layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"Profile\""], |e| e.kind.is_profile()),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_profile)),
Expand Down Expand Up @@ -1775,6 +1783,7 @@ mod tests {
(&["layout-section"], "layout.update", json!({"element": 1, "section": {"name": "A", "y": 0}})),
(&["layout-profile"], "layout.import", json!({"text": profile_layout})),
(&["layout-profile"], "layout.addElement", json!({"kind": "profile"})),
(&["layout-profile"], "layout.update", json!({"element": 2, "thickness": 20})),
(&["layout-text-size"], "layout.update", json!({"element": 1, "textSize": 12})),
(&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})),
(&["layout-legend-class-labels"], "layout.update", json!({"element": 1, "classLabels": {"a": {"x": "X"}}})),
Expand Down
Loading
Loading