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
51 changes: 38 additions & 13 deletions crates/ui-egui/src/layoutview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ mod actions;
mod format;
mod handles;
mod interact;
#[cfg(test)]
mod refused_tests;
mod section;
mod snap;
#[cfg(test)]
Expand Down Expand Up @@ -177,6 +179,9 @@ pub struct LayoutView {
/// 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>,
/// 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 @@ -224,16 +229,18 @@ impl LayoutView {
}
}

/// Forgets the selection, the text typed into its fields and the layouts' page views once another
/// project has replaced the one they were for: its elements and layouts may have the same ids and
/// names. Run after every command, after what agents and scripts sent, and before drafts are saved.
/// Forgets the selection, the text typed into its fields or kept after a refusal, and the
/// layouts' page views once another project has replaced the one they were for: its elements and
/// layouts may have the same ids and names. Run after every command, after what agents and scripts
/// sent, and before drafts are saved.
pub(crate) fn follow_project(app: &mut RustGisApp) {
let opened = app.session.opened;
if app.layout.project.is_some_and(|p| p != opened) {
app.layout.selected = None;
app.layout.formatted = None;
app.layout.drawn = None;
app.layout.typing.clear();
app.layout.sent.clear();
app.layout.viewed = None;
app.layout.text_warning = None;
app.layout.section_warning = None;
Expand All @@ -260,11 +267,12 @@ 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 typing = std::mem::take(&mut app.layout.typing);
app.layout.typing = typing
.into_iter()
.filter_map(|((l, id, field), text)| Some(((now.iter().position(|m| Some(m) == was.get(l))?, id, field), text)))
.collect();
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.
let sent = std::mem::take(&mut app.layout.sent);
app.layout.sent = sent.into_iter().filter_map(|(key, text)| Some((follow(key)?, text))).collect();
}
}

Expand Down Expand Up @@ -717,13 +725,24 @@ 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.
/// 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);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}

/// 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 Some(text) = app.layout.typing.remove(&key) else { continue };
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()),
Expand All @@ -734,17 +753,23 @@ pub(crate) fn save_drafts(app: &mut RustGisApp) {
("unitLabel", ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()),
_ => None,
});
if current.is_some_and(|c| c != text) {
// 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}));
}
}
}

/// Saves all text being typed, the field the Format pane shows included: for a command that
/// draws the page before the pane runs this frame (the ribbon is drawn first).
/// Saves the text being typed, the field the Format pane shows included, for a command that
/// draws the page before the pane runs this frame (the ribbon is drawn first). A section line's
/// name, a grid's CRS and a chart's automatic title have no value in [`save_typed`] and stay
/// being typed.
pub(crate) fn commit_drafts(app: &mut RustGisApp) {
app.layout.drawn = None;
save_drafts(app);
follow_project(app);
save_typed(app, None);
}
49 changes: 46 additions & 3 deletions crates/ui-egui/src/layoutview/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,51 @@ pub(super) fn orientation_row(ui: &mut Ui, current: Orientation) -> Option<&'sta
picked
}

/// 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,
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.
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 {
// 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);
}
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())
}

/// 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> {
// 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);
return None;
}
if app.layout.sent.get(&key).is_some_and(|s| s.was == current && s.text == text) {
return None;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
app.layout.sent.insert(key, Sent { was: current.to_string(), text: text.clone(), drawn: true });
Some(text)
}

/// A text field whose typing is kept in the view's state while it has focus. Returns the new text
/// when the field loses focus with a change.
/// when the field loses focus with a change; one the element doesn't take stays in the field.
pub(super) fn text_field(
app: &mut RustGisApp,
ui: &mut Ui,
Expand All @@ -71,7 +114,7 @@ pub(super) fn hinted_text_field(
hint: Option<&str>,
label_id: egui::Id,
) -> Option<String> {
let mut buf = app.layout.typing.remove(&key).unwrap_or_else(|| current.to_string());
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 @@ -82,7 +125,7 @@ pub(super) fn hinted_text_field(
}
let r = ui.add(edit).labelled_by(label_id);
if r.lost_focus() {
return (buf != current).then_some(buf);
return send(app, key, current, buf);
}
if r.has_focus() {
app.layout.typing.insert(key, buf);
Expand Down
71 changes: 50 additions & 21 deletions crates/ui-egui/src/layoutview/format/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,44 @@ use rustgis_engine::map::layout::{
};
use serde_json::{Value, json};

/// Each section line's name box in [`LayoutView`]'s typing, by its place among the frame's.
pub(super) const SECTION_NAMES: [&str; MAX_SECTIONS] = [
"section A",
"section B",
"section C",
"section D",
"section E",
"section F",
"section G",
"section H",
"section I",
"section J",
"section K",
"section L",
"section M",
"section N",
"section O",
"section P",
"section Q",
"section R",
"section S",
"section T",
"section U",
"section V",
"section W",
"section X",
"section Y",
"section Z",
];

/// A map frame's section lines (#2863), each with its name, direction, place and look, why it isn't
/// drawn when it isn't, and Remove; below them, the buttons that add one, whose direction is given
/// back when one is clicked. `update` sends a change.
fn section_rows(
app: &mut RustGisApp,
ui: &mut Ui,
layout: &Layout,
li: usize,
id: u32,
sections: &[Section],
update: &dyn Fn(&mut RustGisApp, Value),
Expand All @@ -30,17 +61,16 @@ fn section_rows(
ui.push_id(("section", id, i), |ui| {
egui::Grid::new("section_place").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| {
let label = ui.label(tl!("Name"));
// Typing is kept with the view until the field is left.
let key = egui::Id::unique(("section_name", id, i));
let mut name = ui.data_mut(|d| d.get_temp::<String>(key)).unwrap_or_else(|| s.name.clone());
// 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 r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(60.0)).labelled_by(label.id);
if r.has_focus() {
ui.data_mut(|d| d.insert_temp(key, name));
} else {
ui.data_mut(|d| d.remove::<String>(key));
if r.lost_focus() && name.trim() != s.name {
if r.lost_focus() {
if let Some(name) = send(app, key, &s.name, name) {
set(app, json!({"section": {"newName": name}}));
}
} else if r.has_focus() {
app.layout.typing.insert(key, name);
}
ui.end_row();
let label = ui.label(tl!("Direction"));
Expand Down Expand Up @@ -108,7 +138,7 @@ fn section_rows(
}

/// A map frame's grid options; `set` sends the changed ones (`false` removes the grid).
fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) {
fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, li: usize, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) {
let mut on = grid.is_some();
if ui.checkbox(&mut on, tl!("Show grid")).changed() {
set(app, json!(on));
Expand All @@ -133,7 +163,7 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u
.labelled_by(input_label.id);
ui.end_row();
if measured {
crs_row(app, ui, g, id, set);
crs_row(app, ui, g, li, id, set);
}
let input_label = ui.label(tl!("Interval"));
let mut step = g.step;
Expand Down Expand Up @@ -323,11 +353,11 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u

/// A measured grid's coordinate system, typed (EPSG:25832, WKT or a PROJ string) and set when the
/// 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, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) {
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 = egui::Id::unique(("grid_crs", id));
let key = (li, id, "crs");
let current = g.crs.clone().unwrap_or_default();
let mut buf = ui.data(|d| d.get_temp::<String>(key)).unwrap_or_else(|| current.clone());
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 @@ -343,13 +373,12 @@ fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, id: u32, set: &dyn Fn(&m
};
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.has_focus() {
ui.data_mut(|d| d.insert_temp(key, buf));
} else {
ui.data_mut(|d| d.remove::<String>(key));
if r.lost_focus() && buf.trim() != current {
set(app, json!({"crs": buf.trim()}));
if r.lost_focus() {
if let Some(crs) = send(app, key, &current, buf.trim().to_string()) {
set(app, json!({"crs": crs}));
}
} else if r.has_focus() {
app.layout.typing.insert(key, buf);
}
ui.end_row();
}
Expand Down Expand Up @@ -421,15 +450,15 @@ pub(super) fn frame_sections(
if let ElementKind::MapFrame { grid, .. } = &e.kind {
ui.add_space(4.0);
egui::CollapsingHeader::new(tl!("Grid")).id_salt(("frame_grid", id)).default_open(grid.is_some()).show(ui, |ui| {
grid_properties(app, ui, grid.as_ref(), id, &|app, g| update(app, json!({"grid": g})));
grid_properties(app, ui, grid.as_ref(), li, id, &|app, g| update(app, json!({"grid": g})));
});
}
if let ElementKind::MapFrame { sections, .. } = &e.kind {
ui.add_space(4.0);
egui::CollapsingHeader::new(tl!("Section Lines")).id_salt(("frame_sections", id)).default_open(!sections.is_empty()).show(
ui,
|ui| {
if let Some(direction) = section_rows(app, ui, layout, id, sections, &update) {
if let Some(direction) = section_rows(app, ui, layout, li, id, sections, &update) {
let _ = app.run("layout.addElement", json!({"layout": li, "kind": "section", "frame": id, "direction": direction}));
}
},
Expand Down
17 changes: 12 additions & 5 deletions crates/ui-egui/src/layoutview/format/scalebar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::RustGisApp;
use crate::widgets::Dragged;
use egui::Ui;
use rustgis_engine::map::layout::{
Element, ElementKind, Layout, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, ScaleBarFit,
ScaleBarStyle, ScaleLabelPosition, ScaleUnits, UnitLabelPosition,
Element, ElementKind, Layout, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS,
MAX_UNIT_LABEL_CHARS, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, UnitLabelPosition,
};
use serde_json::{Value, json};

Expand Down Expand Up @@ -155,16 +155,23 @@ pub(super) fn scale_bar_rows(
// gets this one's text; a renamed layout forgets it.
let kept = egui::Id::unique(("scale_unit_label_kept", app.session.opened, li, layout.name.as_str(), id));
// The label being typed is dropped, so the field losing its focus
// doesn't write it back; hidden, it is the text kept.
let draft = app.layout.typing.remove(&(li, id, "unitLabel"));
// doesn't write it back; hidden, it is the text kept, unless the command
// would refuse it: that one is sent, to say why (once).
let key = (li, id, "unitLabel");
let mut dropped = app.layout.typing.remove(&key);
if let Some(long) = dropped.take_if(|t| t.chars().count() > MAX_UNIT_LABEL_CHARS)
&& let Some(long) = send(app, key, unit_label.as_deref().unwrap_or(""), long)
{
update(app, json!({"unitLabel": long}));
}
if on {
// Read, not taken: a show that is undone can be shown again.
let typed = ui.ctx().data(|d| d.get_temp::<String>(kept)).filter(|t| !t.is_empty());
update(app, json!({"unitLabel": typed.map_or(Value::Null, Value::String)}));
} else {
// Every hide keeps the text hidden now, and forgets an older one
// once the label is back to the abbreviation.
match draft.or_else(|| unit_label.clone()).filter(|t| !t.is_empty()) {
match dropped.or_else(|| unit_label.clone()).filter(|t| !t.is_empty()) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Some(text) => {
ui.ctx().data_mut(|d| d.insert_temp(kept, text));
}
Expand Down
8 changes: 5 additions & 3 deletions crates/ui-egui/src/layoutview/format/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub(super) fn text_section(
} = &e.kind
{
let key = (li, id, "text");
let mut buf = app.layout.typing.remove(&key).unwrap_or_else(|| text.clone());
let mut buf = draft(app, key, text);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let (mut sz, mut c, mut bb) = (*size, crate::theme::c32(*color), *bold);
let (mut it, mut al, mut ls, mut fam, mut named) = (*italic, *align, *letter_spacing, *font, font_name.clone());
let (mut wr, mut va, mut line_sp, mut cs) = (*wrap, valign.kept(), *line_spacing, case.kept());
Expand Down Expand Up @@ -99,8 +99,10 @@ pub(super) fn text_section(
.unwrap_or_default();
if settled.typing {
app.layout.typing.insert(key, buf);
} else if settled.text && buf != *text {
update(app, json!({"text": buf}));
} else if settled.text
&& let Some(new_text) = send(app, key, text, buf)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
update(app, json!({"text": new_text}));
}
if settled.size {
update(app, json!({"size": sz}));
Expand Down
Loading
Loading