Skip to content
17 changes: 0 additions & 17 deletions crates/render/src/layout/legend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -982,23 +982,6 @@ pub fn class_row_labels(l: &rustgis_map::Layer) -> Vec<String> {
entries.into_iter().map(|e| e.label).collect()
}

/// Whether [`class_row_labels`] lists any row for a layer, without making a classed layer's rows:
/// asked for every row of a legend's Layers section on every frame (#3306), where making a Unique
/// Values layer's would sort and merge all its classes. A raster's are made, few and from kept
/// statistics.
pub fn has_class_rows(l: &rustgis_map::Layer) -> bool {
if !legend_lists(l) {
return false;
}
if l.is_raster() {
return !every_class(l).is_empty();
}
// Every renderer but a single symbol lists a row, even with no class: Unique Values its
// fallback, Proportional its sizes, Graduated Colors its "No data".
let classed = !matches!(l.renderer, rustgis_map::Renderer::Single(_));
classed || !l.with_size_legend(Vec::new()).is_empty() || l.diagram.as_ref().is_some_and(|d| !d.categories.is_empty())
}

/// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the
/// frame draws: only the layers listed there, with their classes. Without, every class of every
/// visible layer. `opts` leaves out `<all other values>` and the layers it names, either way, and
Expand Down
7 changes: 1 addition & 6 deletions crates/render/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8780,9 +8780,6 @@ fn a_legend_labels_a_layers_classes_itself() {
};
assert_eq!(labels_of(&legend_rows(&map, None, &opts(&listed, false))), ["c0", "c1", "c99"]);
assert_eq!(class_row_labels(&map.layers[0]), ["c0", "c1", "c99"]);
for l in &map.layers {
assert_eq!(has_class_rows(l), !class_row_labels(l).is_empty(), "{}", l.name);
}
// Graduated Colors with no class, as an imported style can bring: its "No data" row is one.
let mut empty = rows_map(1);
let l = &mut empty.layers[0];
Expand All @@ -8799,10 +8796,9 @@ fn a_legend_labels_a_layers_classes_itself() {
class_fills: Default::default(),
};
assert_eq!(class_row_labels(l), ["No data"]);
assert!(has_class_rows(l));
// One symbol: no row of its own until a diagram brings its categories.
l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Point, 0));
assert!(class_row_labels(l).is_empty() && !has_class_rows(l));
assert!(class_row_labels(l).is_empty());
l.diagram = Some(rustgis_map::DiagramSettings {
kind: rustgis_map::DiagramKind::Pie,
categories: vec![rustgis_map::DiagramCategory { field: "g".into(), colour: Rgba::rgb(255, 0, 0) }],
Expand All @@ -8814,7 +8810,6 @@ fn a_legend_labels_a_layers_classes_itself() {
labels: rustgis_map::DiagramLabel::None,
});
assert_eq!(class_row_labels(l), ["g"]);
assert!(has_class_rows(l));
let mut own = ClassLabels::default();
own.by_layer.insert(
"PTS".into(),
Expand Down
78 changes: 56 additions & 22 deletions crates/ui-egui/src/layoutview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::RustGisApp;
use crate::theme::{Tokens, regular, semibold};
use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};
use rustgis_engine::map::layout::{ElementKind, Layout, PT_PER_MM, frame_camera, line_length};
use serde_json::{Value, json};
use serde_json::json;

mod actions;
mod format;
Expand Down Expand Up @@ -175,13 +175,13 @@ pub struct LayoutView {
sketch: Vec<(f64, f64)>,
/// Text being typed into the element properties, by (layout, element, field): kept here so
/// keystrokes survive the frame, and saved when the field loses focus or stops being shown.
typing: std::collections::HashMap<(usize, u32, &'static str), String>,
typing: std::collections::HashMap<format::DraftKey, String>,
/// The layouts (their [`Layout::instance_id`]), in their order, when `typing` last followed
/// them ([`follow_project`]).
typing_order: Vec<u64>,
/// Text a field sent to its element, by the same key: shown while the element still has the
/// value it was typed over, so a refused text stays to be corrected (#3348).
sent: std::collections::HashMap<(usize, u32, &'static str), format::Sent>,
sent: std::collections::HashMap<format::DraftKey, format::Sent>,
/// The layout shown, shared between frames until the project changes (layouts can hold
/// megabytes of pictures, too much to copy every frame), keyed by layout and revision.
shown: Option<(usize, u64, std::rc::Rc<Layout>)>,
Expand Down Expand Up @@ -267,7 +267,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) {
if !app.layout.typing_order.iter().copied().eq(layouts.iter().map(Layout::instance_id)) {
let was = std::mem::replace(&mut app.layout.typing_order, layouts.iter().map(Layout::instance_id).collect());
let now = &app.layout.typing_order;
let follow = |(l, id, field): (usize, u32, &'static str)| Some((now.iter().position(|m| Some(m) == was.get(l))?, id, field));
let follow = |(l, id, field): format::DraftKey| Some((now.iter().position(|m| Some(m) == was.get(l))?, id, field));
let typing = std::mem::take(&mut app.layout.typing);
app.layout.typing = typing.into_iter().filter_map(|(key, text)| Some((follow(key)?, text))).collect();
// What a field sent goes with it, so a refused text isn't sent as new.
Expand Down Expand Up @@ -725,42 +725,76 @@ pub fn page_info(app: &mut RustGisApp, li: usize) -> rustgis_engine::render::lay

/// Saves the text typed into fields the Format pane didn't draw this frame: the selection or the
/// layout changed, or the pane was closed or hidden, before the field could notice it lost focus.
/// A text kept after a refusal is dropped with its field.
/// A text kept after a refusal is dropped with its field. A legend's label box goes only with its
/// legend, as its row can be closed or filtered out while the legend stays shown, and its text is
/// kept while the legend's is still the one it was typed over, so an accepted one isn't (#3436).
/// Runs once a frame, after the panes and the view.
pub(crate) fn save_drafts(app: &mut RustGisApp) {
follow_project(app);
let shown = app.layout.drawn.take();
save_typed(app, shown);
// What save_typed has no value for goes with an element no longer shown.
app.layout.typing.retain(|(l, id, _), _| Some((*l, *id)) == shown);
// A refused text goes with the field that showed it: not drawn this frame (another element,
// mode or pane), it is dropped, never sent again, one just saved for such an element too.
app.layout.sent.retain(|(l, id, _), sent| std::mem::take(&mut sent.drawn) && Some((*l, *id)) == shown);
// A refused text goes with the field that showed it, a legend label's with its legend: then it
// is dropped, never sent again, one just saved for such an element too.
let layouts = &app.session.project.layouts;
app.layout.sent.retain(|(l, id, field), sent| {
let drawn = std::mem::take(&mut sent.drawn);
let kept = match field {
format::Field::Own(_) => drawn,
format::Field::Label { layer, class } => layouts
.get(*l)
.and_then(|x| x.element(*id))
.is_some_and(|e| format::legend_text(&e.kind, layer, class.as_deref()) == sent.was),
};
kept && Some((*l, *id)) == shown
});
}

/// Saves the text typed into the fields of every element but `shown` (all of them when `shown` is
/// `None`), as far as their values are known here.
fn save_typed(app: &mut RustGisApp, shown: Option<(usize, u32)>) {
let stale: Vec<_> = app.layout.typing.keys().filter(|(l, id, _)| Some((*l, *id)) != shown).copied().collect();
for key in stale {
let (l, id, field) = key;
let current = app.session.project.layouts.get(l).and_then(|x| x.element(id)).and_then(|e| match (field, &e.kind) {
("name", _) => Some(e.name.clone()),
("text", ElementKind::Text { text, .. }) => Some(text.clone()),
("title", ElementKind::Legend { title, .. } | ElementKind::Colorbar { title, .. }) => Some(title.clone()),
("subtitle", ElementKind::Legend { subtitle, .. }) => Some(subtitle.clone()),
("title", ElementKind::Chart { title, .. }) => title.clone(),
("unitLabel", ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()),
let stale = app.layout.typing.keys().filter(|(l, id, _)| Some((*l, *id)) != shown).cloned().collect();
save_fields(app, stale);
}

/// Saves the text typed into the label boxes of legend `id` that aren't in `drawn`: a row closed
/// or filtered out takes its boxes while the legend stays shown (#3436).
fn save_hidden_labels(app: &mut RustGisApp, li: usize, id: u32, drawn: &std::collections::HashSet<format::Field>) {
let hidden = app
.layout
.typing
.keys()
.filter(|(l, i, field)| (*l, *i) == (li, id) && matches!(field, format::Field::Label { .. }) && !drawn.contains(field))
.cloned()
.collect();
save_fields(app, hidden);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Saves the text typed into the fields `keys`, as far as their values are known here.
fn save_fields(app: &mut RustGisApp, keys: Vec<format::DraftKey>) {
use format::Field;
for key in keys {
let (l, id, field) = &key;
let current = app.session.project.layouts.get(*l).and_then(|x| x.element(*id)).and_then(|e| match (field, &e.kind) {
(Field::Own("name"), _) => Some(e.name.clone()),
(Field::Own("text"), ElementKind::Text { text, .. }) => Some(text.clone()),
(Field::Own("title"), ElementKind::Legend { title, .. } | ElementKind::Colorbar { title, .. }) => Some(title.clone()),
(Field::Own("subtitle"), ElementKind::Legend { subtitle, .. }) => Some(subtitle.clone()),
(Field::Own("title"), ElementKind::Chart { title, .. }) => title.clone(),
(Field::Own("unitLabel"), ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()),
(Field::Label { layer, class }, kind @ ElementKind::Legend { .. }) => Some(format::legend_text(kind, layer, class.as_deref())),
_ => None,
});
// A field with no value here (a section line's name, a grid's CRS, a chart's automatic
// title) stays being typed.
let Some(current) = current else { continue };
let Some(text) = app.layout.typing.remove(&key) else { continue };
if let Some(text) = format::send(app, key, &current, text) {
// An emptied unit label gives the unit's abbreviation back, as the field does.
let value = if field == "unitLabel" && text.is_empty() { Value::Null } else { json!(text) };
let _ = app.run("layout.update", json!({"layout": l, "element": id, field: value}));
if let Some(text) = format::send(app, &key, &current, text) {
let mut p = format::field_change(&key.2, text);
p["layout"] = json!(key.0);
p["element"] = json!(key.1);
let _ = app.run("layout.update", p);
}
}
}
Expand Down
82 changes: 65 additions & 17 deletions crates/ui-egui/src/layoutview/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use rustgis_engine::map::symbology::Dash;
use scalebar::*;
use serde_json::{Value, json};
use shapes::*;
use std::sync::Arc;
use table::*;
use text::*;

Expand All @@ -48,46 +49,92 @@ pub(super) fn orientation_row(ui: &mut Ui, current: Orientation) -> Option<&'sta
picked
}

/// A field text is typed into.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(super) enum Field {
/// One of the element's own, by its command key.
Own(&'static str),
/// A legend's own text for a layer, or for one of that layer's classes (#3436).
Label { layer: Arc<str>, class: Option<Arc<str>> },
}

impl From<&'static str> for Field {
fn from(key: &'static str) -> Self {
Field::Own(key)
}
}

/// A field's text, by the layout's place, the element and the field.
pub(super) type DraftKey = (usize, u32, Field);

/// The text a legend has of its own for a layer or a class of it; empty without one, or on any
/// other element.
pub(super) fn legend_text(kind: &ElementKind, layer: &str, class: Option<&str>) -> String {
let ElementKind::Legend { labels, class_labels, .. } = kind else { return String::new() };
let text = match class {
Some(class) => class_labels.of(layer).and_then(|own| own.get(class)),
// By its name in any case, as the legend draws it.
None => labels.get(layer).or_else(|| labels.iter().find(|(n, _)| n.eq_ignore_ascii_case(layer)).map(|(_, l)| l)),
};
text.cloned().unwrap_or_default()
}

/// The `layout.update` parameters giving `field` the text `text`.
pub(super) fn field_change(field: &Field, text: String) -> Value {
match field {
// An emptied unit label gives the unit's abbreviation back.
Field::Own("unitLabel") if text.is_empty() => json!({"unitLabel": Value::Null}),
Field::Own(key) => json!({*key: text}),
Field::Label { layer, class: None } => json!({"labels": {&**layer: text}}),
Field::Label { layer, class: Some(class) } => json!({"classLabels": {&**layer: {&**class: text}}}),
}
}

/// A text a field sent to its element ([`send`]).
pub(super) struct Sent {
/// The value the element had: another one drops the text.
was: String,
pub(super) was: String,
text: String,
/// Set when its field was drawn or saved this frame; [`super::save_drafts`] keeps the text
/// only for a drawn field of the element shown.
/// Set when its field was drawn or saved this frame. [`super::save_drafts`] keeps the text of
/// the element shown: an own field's while drawn, a legend label's while its value is `was`.
pub(super) drawn: bool,
}

/// What a text field holding `current` shows: the text being typed, else the one it sent while the
/// element still has the value it was typed over (so the command refused it, #3348), else `current`.
pub(super) fn draft(app: &mut RustGisApp, key: (usize, u32, &'static str), current: &str) -> String {
pub(super) fn draft(app: &mut RustGisApp, key: &DraftKey, current: &str) -> String {
// A value set since, by this text or from elsewhere, drops what was sent.
if app.layout.sent.get(&key).is_some_and(|s| s.was != current) {
app.layout.sent.remove(&key);
if app.layout.sent.get(key).is_some_and(|s| s.was != current) {
app.layout.sent.remove(key);
}
let kept = app.layout.sent.get_mut(&key).map(|s| {
let kept = app.layout.sent.get_mut(key).map(|s| {
s.drawn = true;
s.text.clone()
});
app.layout.typing.remove(&key).or(kept).unwrap_or_else(|| current.to_string())
app.layout.typing.remove(key).or(kept).unwrap_or_else(|| current.to_string())
}

/// What a text field gives its element on losing focus: `text`, when it differs from `current`
/// and wasn't sent already, kept for [`draft`] in case it is refused. A field is left more than
/// once with the same refused text (egui says so again, the user clicks in and out): it is said
/// once.
pub(super) fn send(app: &mut RustGisApp, key: (usize, u32, &'static str), current: &str, text: String) -> Option<String> {
pub(super) fn send(app: &mut RustGisApp, key: &DraftKey, current: &str, text: String) -> Option<String> {
// A name is trimmed by its command: spaces alone around it change nothing. A blank element
// name is ignored without a word, so it isn't kept either.
let name = key.2 == "name" || SECTION_NAMES.contains(&key.2);
if text == current || (name && text.trim() == current) || (key.2 == "name" && text.trim().is_empty()) {
app.layout.sent.remove(&key);
// A blank label where the legend has none of its own changes nothing either.
let unchanged = match &key.2 {
Field::Own("name") => text.trim() == current || text.trim().is_empty(),
Field::Own(f) => SECTION_NAMES.contains(f) && text.trim() == current,
Field::Label { .. } => current.is_empty() && text.trim().is_empty(),
};
if text == current || unchanged {
app.layout.sent.remove(key);
return None;
}
if app.layout.sent.get(&key).is_some_and(|s| s.was == current && s.text == text) {
if app.layout.sent.get(key).is_some_and(|s| s.was == current && s.text == text) {
return None;
}
app.layout.sent.insert(key, Sent { was: current.to_string(), text: text.clone(), drawn: true });
app.layout.sent.insert(key.clone(), Sent { was: current.to_string(), text: text.clone(), drawn: true });
Some(text)
}

Expand All @@ -114,7 +161,8 @@ pub(super) fn hinted_text_field(
hint: Option<&str>,
label_id: egui::Id,
) -> Option<String> {
let mut buf = draft(app, key, current);
let key = (key.0, key.1, Field::Own(key.2));
let mut buf = draft(app, &key, current);
let mut edit = if multiline {
egui::TextEdit::multiline(&mut buf).desired_rows(3).desired_width(240.0)
} else {
Expand All @@ -125,7 +173,7 @@ pub(super) fn hinted_text_field(
}
let r = ui.add(edit).labelled_by(label_id);
if r.lost_focus() {
return send(app, key, current, buf);
return send(app, &key, current, buf);
}
if r.has_focus() {
app.layout.typing.insert(key, buf);
Expand Down Expand Up @@ -315,7 +363,7 @@ pub(super) fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li:
);
});
text_section(app, ui, layout, li, &e, &update);
legend_layers(app, ui, layout, &e, &update);
legend_layers(app, ui, layout, li, &e, &update);
frame_sections(app, ui, layout, li, &e, &update);
// Its background (#2257): a box behind its content, which a map frame, drawing its own paper,
// doesn't take.
Expand Down
2 changes: 1 addition & 1 deletion crates/ui-egui/src/layoutview/format/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ pub(super) fn chart_rows(
};
// Its own title being typed is dropped, so the field losing its
// focus, now or with the selection, doesn't bring it back.
app.layout.typing.remove(&(li, id, "title"));
app.layout.typing.remove(&(li, id, Field::Own("title")));
update(app, json!({"title": value}));
}
}
Expand Down
12 changes: 6 additions & 6 deletions crates/ui-egui/src/layoutview/format/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ fn section_rows(
egui::Grid::new("section_place").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| {
let label = ui.label(tl!("Name"));
// Sections are capped at MAX_SECTIONS on load and on add: the clamp only guards the index.
let key = (li, id, SECTION_NAMES[i.min(MAX_SECTIONS - 1)]);
let mut name = draft(app, key, &s.name);
let key = (li, id, Field::Own(SECTION_NAMES[i.min(MAX_SECTIONS - 1)]));
let mut name = draft(app, &key, &s.name);
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(60.0)).labelled_by(label.id);
if r.lost_focus() {
if let Some(name) = send(app, key, &s.name, name) {
if let Some(name) = send(app, &key, &s.name, name) {
set(app, json!({"section": {"newName": name}}));
}
} else if r.has_focus() {
Expand Down Expand Up @@ -355,9 +355,9 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, li: u
/// field is left; empty is the map's when projected, else the UTM zone at the frame's centre.
fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, li: usize, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) {
let input_label = ui.label(tl!("Coordinate system"));
let key = (li, id, "crs");
let key = (li, id, Field::Own("crs"));
let current = g.crs.clone().unwrap_or_default();
let mut buf = draft(app, key, &current);
let mut buf = draft(app, &key, &current);
let (hint, help) = if g.mgrs {
(
tl!("The map's UTM zone, else the frame's"),
Expand All @@ -374,7 +374,7 @@ fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, li: usize, id: u32, set:
let r =
ui.add(egui::TextEdit::singleline(&mut buf).hint_text(hint).desired_width(150.0)).labelled_by(input_label.id).on_hover_text(help);
if r.lost_focus() {
if let Some(crs) = send(app, key, &current, buf.trim().to_string()) {
if let Some(crs) = send(app, &key, &current, buf.trim().to_string()) {
set(app, json!({"crs": crs}));
}
} else if r.has_focus() {
Expand Down
Loading
Loading