From 56f415366be2da6f67406af7c5d106fc4e170cc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 17:15:05 -0500 Subject: [PATCH 1/6] fix: keep right-to-left display text in logical order when it leaves the screen --- crates/data/src/display_marks.rs | 63 ++++++++ crates/data/src/lib.rs | 1 + crates/engine/src/lib.rs | 5 +- crates/ui-egui/src/chrome.rs | 17 +- crates/ui-egui/src/diagnosticlog.rs | 2 +- crates/ui-egui/src/filedialog.rs | 50 +++++- crates/ui-egui/src/i18n/boundary_tests.rs | 187 ++++++++++++++++++++++ crates/ui-egui/src/i18n/mod.rs | 56 +++++++ crates/ui-egui/src/i18n/rtl.rs | 63 +++++--- crates/ui-egui/src/lib.rs | 9 +- 10 files changed, 426 insertions(+), 27 deletions(-) create mode 100644 crates/data/src/display_marks.rs create mode 100644 crates/ui-egui/src/i18n/boundary_tests.rs diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs new file mode 100644 index 0000000000..6a4044c7b2 --- /dev/null +++ b/crates/data/src/display_marks.rs @@ -0,0 +1,63 @@ +//! The marks right-to-left display text carries. An interface that lays a line out back to +//! front rewrites it for painting (`ui-egui`'s `i18n::rtl`) and marks what it rewrote, so that +//! text leaving the screen (a command's parameters, a notice, a file name) can be put back in +//! logical order. + +/// Around a rewritten line. Invisible, of no width and no direction. +pub const LINE: char = '\u{2063}'; +/// Around each run of characters reversed within a rewritten line. +pub const RUN: char = '\u{2064}'; + +/// The mirrored glyph of a bracket, which the shaper mirrors back on a back-to-front line. +#[must_use] +pub fn mirror(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '«' => '»', + '»' => '«', + '‹' => '›', + '›' => '‹', + c => c, + } +} + +/// `shown` with what was rewritten for display put back in logical order, and its marks gone; +/// `None` when nothing in it carries a mark. Text around a marked line stays as it is. +#[must_use] +pub fn logical(shown: &str) -> Option { + if !shown.contains([LINE, RUN]) { + return None; + } + let mut out = String::with_capacity(shown.len()); + let mut run: Vec = Vec::new(); + let (mut in_line, mut in_run) = (false, false); + for c in shown.chars() { + match c { + LINE => { + out.extend(run.drain(..).rev()); + in_line = !in_line; + in_run = false; + } + RUN => { + out.extend(run.drain(..).rev()); + in_run = !in_run; + } + '\n' => { + out.extend(run.drain(..).rev()); + (in_line, in_run) = (false, false); + out.push(c); + } + c if in_run => run.push(mirror(c)), + c if in_line => out.push(mirror(c)), + c => out.push(c), + } + } + // A mark cut off the end leaves its run open. + out.extend(run.drain(..).rev()); + Some(out) +} diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 8f2258725f..1d03d72c27 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -15,6 +15,7 @@ pub mod date_format; mod dbf; pub mod diagnostics; pub mod dirs; +pub mod display_marks; pub mod dxf; pub mod esripbf; pub mod export; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 65f0fe9178..48ca2d29ca 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3704,7 +3704,10 @@ impl Session { /// redacted: what a notice or history record may show. Login values are known only here, so /// a failure redacted by [`Session::notify_redacted`]'s callers goes through this first. pub fn redacted(text: &str) -> rustgis_data::diagnostics::Redacted { - rustgis_data::diagnostics::Redacted::new(&durable::generated_text(text)) + // Right-to-left text a front end shaped for painting is kept in logical order, and + // first, so that a secret in it is recognised. + let logical = rustgis_data::display_marks::logical(text); + rustgis_data::diagnostics::Redacted::new(&durable::generated_text(logical.as_deref().unwrap_or(text))) } /// [`Session::notify`] for text already scrubbed and redacted by [`Session::redacted`] (a diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 87828a7884..049f97bafa 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -2237,7 +2237,7 @@ fn notice_text(notice: &rustgis_engine::Notice) -> String { .translated(crate::i18n::fmt_raw) .map(|message| crate::i18n::fmt("{message}", &[("message", &message)])) .or_else(|| crate::i18n::file_size_error(¬ice.text, crate::i18n::fmt)) - .unwrap_or_else(|| notice.text.clone()) + .unwrap_or_else(|| crate::i18n::display(¬ice.text)) } /// A deferred message stays in logical order until the complete tooltip is shaped, including @@ -2479,6 +2479,21 @@ mod tests { assert!(super::search_disabled(&RustGisApp::with_sample(), "raster.mosaic").is_none()); } + /// A Persian notice is kept in logical order and shown in display form, as before. + #[test] + fn a_right_to_left_notice_is_painted_in_display_form() { + crate::i18n::set_current(crate::i18n::Lang::from_code("fa").unwrap()); + let args = &[("names", "GeoPackage 42")]; + let (shown, text) = (crate::i18n::fmt("Added: {names}", args), crate::i18n::fmt_raw("Added: {names}", args)); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.session.notify(shown.clone(), false); + let notice = app.session.notices.last().unwrap(); + let (stored, painted) = (notice.text.clone(), notice_text(notice)); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(stored, text); + assert_eq!(painted, shown); + } + /// Past the 200 notices the session keeps, each new notice it holds still makes one toast (#1755). #[test] fn each_kept_notice_makes_one_toast_past_the_200th() { diff --git a/crates/ui-egui/src/diagnosticlog.rs b/crates/ui-egui/src/diagnosticlog.rs index 6da2e98b1c..001ab33a83 100644 --- a/crates/ui-egui/src/diagnosticlog.rs +++ b/crates/ui-egui/src/diagnosticlog.rs @@ -178,7 +178,7 @@ fn entry(ui: &mut Ui, record: &Record, t: &Tokens, standalone: bool, open_url: & ui.label(RichText::new(source).small().color(t.text_dim)); } }); - ui.add(egui::Label::new(&record.message).wrap().selectable(true)); + ui.add(egui::Label::new(crate::i18n::display(&record.message)).wrap().selectable(true)); if let Some(code) = record.loss { let spec = code.spec(); // What the code means and what to do, in a quiet inset under the message. diff --git a/crates/ui-egui/src/filedialog.rs b/crates/ui-egui/src/filedialog.rs index 3f9cbe24ef..bc75b78820 100644 --- a/crates/ui-egui/src/filedialog.rs +++ b/crates/ui-egui/src/filedialog.rs @@ -8,11 +8,59 @@ //! front end what to tell the user. #[cfg(not(any(target_os = "android", target_os = "ios")))] -pub use rfd::FileDialog; +pub use desktop::FileDialog; #[cfg(any(target_os = "android", target_os = "ios"))] pub use phone::{FileDialog, take_refused}; +#[cfg(not(any(target_os = "android", target_os = "ios")))] +mod desktop { + use std::path::PathBuf; + + use crate::i18n::outgoing; + + /// `rfd::FileDialog`, as far as this crate uses it. The system shapes text itself, so what + /// it is given is in logical order. + pub struct FileDialog(rfd::FileDialog); + + impl FileDialog { + pub fn new() -> Self { + Self(rfd::FileDialog::new()) + } + + pub fn add_filter(self, name: impl Into, extensions: &[impl ToString]) -> Self { + Self(self.0.add_filter(&*outgoing(&name.into()), extensions)) + } + + pub fn set_title(self, title: impl Into) -> Self { + Self(self.0.set_title(&*outgoing(&title.into()))) + } + + #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + pub fn set_file_name(self, name: impl Into) -> Self { + Self(self.0.set_file_name(&*outgoing(&name.into()))) + } + + pub fn pick_file(self) -> Option { + self.0.pick_file() + } + + #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + pub fn pick_files(self) -> Option> { + self.0.pick_files() + } + + pub fn pick_folder(self) -> Option { + self.0.pick_folder() + } + + #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + pub fn save_file(self) -> Option { + self.0.save_file() + } + } +} + #[cfg(any(target_os = "android", target_os = "ios"))] mod phone { use std::path::PathBuf; diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs new file mode 100644 index 0000000000..4a8e9ebbab --- /dev/null +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -0,0 +1,187 @@ +//! Right-to-left display text paints rewritten, and leaves the screen in logical order. + +use egui::OutputCommand; +use rustgis_engine::data::display_marks::{LINE, RUN, logical}; +use serde_json::json; + +use super::*; +use crate::{RustGisApp, Services}; + +const TEMPLATE: &str = "Added: {names}"; +const NAME: &str = "GeoPackage 42"; + +fn fa() -> Lang { + Lang::from_code("fa").unwrap() +} + +/// The sample project with the interface in Persian. +fn persian() -> RustGisApp { + let mut app = RustGisApp::with_sample(); + app.run("ui.language", json!({"code": "fa"})).unwrap(); + set_current(fa()); + app +} + +/// A message as painted, and as it must leave the screen. +fn message() -> (String, String) { + let args = &[("names", NAME)]; + let (shown, text) = (fmt(TEMPLATE, args), fmt_raw(TEMPLATE, args)); + assert_ne!(shown, text, "the fixture must be rewritten for display"); + (shown, text) +} + +fn marked(s: &str) -> bool { + s.contains([LINE, RUN]) +} + +#[test] +fn every_persian_text_comes_back_from_its_display_form() { + let mut rewritten = 0; + for text in fa().0.catalog().values().flat_map(|entries| entries.values()) { + let shown = rtl::visual(text); + if shown == *text { + assert_eq!(logical(&shown), None); + continue; + } + rewritten += 1; + assert_eq!(logical(&shown).as_ref(), Some(text)); + } + assert!(rewritten > 0); +} + +#[test] +fn data_without_marks_is_left_alone() { + for data in ["Cities", "رودخانه GeoPackage (2)", "پنل ygolobmyS", ""] { + assert_eq!(logical(data), None, "{data:?}"); + } +} + +#[test] +fn only_the_marked_part_of_a_composed_string_is_put_back() { + set_current(fa()); + let (shown, text) = message(); + set_current(Lang::EN); + let composed = format!("roads (a) · {shown} · (b) رود 12"); + assert_eq!(logical(&composed), Some(format!("roads (a) · {text} · (b) رود 12"))); +} + +#[test] +fn a_display_form_cut_anywhere_leaves_no_mark() { + set_current(fa()); + let (shown, _) = message(); + set_current(Lang::EN); + for (at, _) in shown.char_indices() { + for piece in [&shown[..at], &shown[at..]] { + let back = logical(piece).unwrap_or_else(|| piece.to_owned()); + assert!(!marked(&back), "{piece:?} gave {back:?}"); + } + } +} + +#[test] +fn english_text_takes_no_marks() { + set_current(Lang::EN); + let shown = fmt(TEMPLATE, &[("names", NAME)]); + assert!(!marked(&shown), "{shown:?}"); + assert_eq!(logical(&shown), None); +} + +#[test] +fn a_layer_buffered_from_the_map_menu_is_named_in_logical_order() { + let mut app = persian(); + let args = &[("distance", "500 m")]; + let (shown, text) = (fmt("Buffer {distance}", args), fmt_raw("Buffer {distance}", args)); + assert_ne!(shown, text); + app.run("gp.bufferPoint", json!({"lon": 8.5, "lat": 47.4, "distance": 500.0, "units": "Meters", "name": shown})).unwrap(); + assert!(app.session.map().layers.iter().any(|l| l.name == text), "no layer named {text:?}"); + let saved = serde_json::to_string(&app.session.project).unwrap(); + set_current(Lang::EN); + assert!(!marked(&saved), "the saved project holds a display mark"); +} + +#[test] +fn a_notice_is_kept_in_logical_order() { + let mut app = persian(); + let (shown, text) = message(); + app.session.notify(shown.clone(), false); + assert_eq!(app.session.notices.last().unwrap().text, text); + app.session.notify_redacted(rustgis_engine::Session::redacted(&shown), true); + assert_eq!(app.session.notices.last().unwrap().text, text); + let report = app.session.diagnostics.report(rustgis_engine::data::diagnostics::Filter::All); + set_current(Lang::EN); + assert!(report.contains(&text) && !marked(&report), "{report}"); +} + +#[test] +fn a_download_is_offered_under_its_logical_name() { + let offered = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = offered.clone(); + let mut app = persian().with_services(Services { + download: Some(Box::new(move |name, _| { + seen.borrow_mut().push(name.to_owned()); + Ok(()) + })), + ..Default::default() + }); + let (shown, text) = message(); + assert!(app.download_bytes(&format!("{shown}.csv"), Vec::new())); + app.save_download(&shown).unwrap(); + set_current(Lang::EN); + assert_eq!(*offered.borrow(), [format!("{text}.csv"), format!("{text}.rgis")]); + assert_eq!(app.session.project.name, text); +} + +#[test] +fn the_clipboard_and_the_window_title_get_logical_order() { + let mut app = persian(); + set_current(fa()); + let (shown, text) = message(); + // No Persian font is needed to read what leaves the window. + let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + // Set once the harness's first frames are done: only this test's frames are read. + h.state_mut().session.project.name = shown.clone(); + h.state_mut().ui.copy_out = Some(shown); + let mut copied = Vec::new(); + let mut titles = Vec::new(); + for _ in 0..3 { + h.step(); + let output = h.output(); + for command in &output.platform_output.commands { + if let OutputCommand::CopyText(s) = command { + copied.push(s.clone()); + } + } + for command in output.viewport_output.values().flat_map(|v| &v.commands) { + if let egui::ViewportCommand::Title(s) = command { + titles.push(s.clone()); + } + } + } + set_current(Lang::EN); + assert_eq!(copied, std::slice::from_ref(&text)); + assert!(!titles.is_empty() && titles.iter().all(|t| t.starts_with(&text) && !marked(t)), "{titles:?}"); +} + +#[test] +fn the_marks_do_not_change_what_is_painted() { + set_current(fa()); + let (shown, _) = message(); + set_current(Lang::EN); + let plain = shown.replace([LINE, RUN], ""); + assert_ne!(plain, shown, "the display form carries marks"); + let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().build_ui(move |ui| { + let width = |s: &str| { + let galley = ui.painter().layout_no_wrap(s.to_owned(), egui::FontId::proportional(14.0), egui::Color32::WHITE); + galley.rect.size() + }; + assert_eq!(width(&shown), width(&plain)); + }); + h.step(); +} diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 2372491ece..f480147d6d 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -24,10 +24,13 @@ //! # Adding a language //! Add `xx.tsv` (copy the keys of another catalog) and one row to [`LANGUAGES`]. +use std::borrow::Cow; use std::cell::Cell; use std::collections::HashMap; use std::sync::OnceLock; +use rustgis_engine::data::display_marks::logical; + mod rtl; /// The preference value that follows the system. @@ -535,6 +538,57 @@ pub(crate) fn display(logical: &str) -> String { rtl::visual(logical) } +/// `s` as it leaves the screen: what a display form in it rewrote is put back in logical +/// order, and its marks are gone. +pub(crate) fn outgoing(s: &str) -> Cow<'_, str> { + logical(s).map_or(Cow::Borrowed(s), Cow::Owned) +} + +/// [`outgoing`] for every string of a command's parameters. +pub(crate) fn outgoing_params(value: &mut serde_json::Value) { + use serde_json::Value; + match value { + Value::String(s) => { + if let Some(text) = logical(s) { + *s = text; + } + } + Value::Array(items) => items.iter_mut().for_each(outgoing_params), + Value::Object(fields) => fields.values_mut().for_each(outgoing_params), + _ => {} + } +} + +/// Puts what egui itself sends out of the window (the clipboard, the window title) in logical +/// order. +#[derive(Default)] +pub(crate) struct LogicalOutput; + +impl egui::Plugin for LogicalOutput { + fn debug_name(&self) -> &'static str { + "rustgis_logical_output" + } + + fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) { + use egui::{OutputCommand, ViewportCommand}; + let restore = |s: &mut String| { + if let Some(text) = logical(s) { + *s = text; + } + }; + for command in &mut output.platform_output.commands { + if let OutputCommand::CopyText(s) | OutputCommand::TextSelectionSettled(s) = command { + restore(s); + } + } + for command in output.viewport_output.values_mut().flat_map(|v| &mut v.commands) { + if let ViewportCommand::Title(s) = command { + restore(s); + } + } + } +} + /// [`fmt`] in logical order, without the display form: for a message shown with /// [`paragraph`], which fits a right-to-left message to its rows and puts each row in /// display form itself. @@ -677,5 +731,7 @@ macro_rules! tl_raw { }; } +#[cfg(test)] +mod boundary_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/i18n/rtl.rs b/crates/ui-egui/src/i18n/rtl.rs index f68cc15cad..65db4a1840 100644 --- a/crates/ui-egui/src/i18n/rtl.rs +++ b/crates/ui-egui/src/i18n/rtl.rs @@ -30,6 +30,11 @@ //! The run rules are the Unicode bidirectional algorithm's, kept to what one //! line needs: a neutral joins a run when left-to-right text is on both sides //! of it (N1), and a bracket when it opens or closes onto a Latin letter (N0). +//! +//! What is rewritten is marked ([`rustgis_engine::data::display_marks`]), so text that leaves +//! the screen can be put back in logical order. + +use rustgis_engine::data::display_marks::{LINE, RUN, mirror}; /// A character of a script written right to left (Arabic, Persian, Hebrew). Digits /// read left to right, and the comma, semicolon and question mark take the line's @@ -80,23 +85,6 @@ fn strong(c: char) -> Option { } } -/// The mirrored glyph of a bracket, which the shaper mirrors back on a back-to-front line. -fn mirror(c: char) -> char { - match c { - '(' => ')', - ')' => '(', - '[' => ']', - ']' => '[', - '{' => '}', - '}' => '{', - '«' => '»', - '»' => '«', - '‹' => '›', - '›' => '‹', - c => c, - } -} - fn opening(c: char) -> bool { matches!(c, '(' | '[' | '{' | '«' | '‹') } @@ -229,16 +217,26 @@ fn visual_line(line: &str) -> String { }; let mut out = String::with_capacity(line.len()); let mut run: Vec = Vec::new(); + // A run of one character reads the same either way: it takes no marks. + let flush = |out: &mut String, run: &mut Vec| { + let marked = run.len() > 1; + out.extend(marked.then_some(RUN)); + out.extend(run.drain(..).rev().map(mirror)); + out.extend(marked.then_some(RUN)); + }; for (i, c) in chars.iter().enumerate() { if in_run(i) { run.push(*c); } else { - out.extend(run.drain(..).rev().map(mirror)); + flush(&mut out, &mut run); out.push(mirror(*c)); } } - out.extend(run.drain(..).rev().map(mirror)); - out + flush(&mut out, &mut run); + if out == line { + return out; + } + format!("{LINE}{out}{LINE}") } /// `s` broken into lines whose display form is no wider than `max_width`, so the @@ -292,8 +290,29 @@ fn fit_line(line: &str, max_width: f32, width: &dyn Fn(&str) -> f32, rows: &mut #[cfg(test)] mod tests { - use super::{fit, visual}; - use crate::i18n::{Lang, fmt, set_current, tr}; + use crate::i18n::{Lang, set_current}; + use rustgis_engine::data::display_marks::{LINE, RUN}; + + /// What is painted: the display form without its marks. + fn painted(s: &str) -> String { + s.replace([LINE, RUN], "") + } + + fn visual(s: &str) -> String { + painted(&super::visual(s)) + } + + fn fit(s: &str, max_width: f32, width: &dyn Fn(&str) -> f32) -> String { + painted(&super::fit(s, max_width, &|row| width(&painted(row)))) + } + + fn tr(lang: Lang, s: &'static str) -> String { + painted(crate::i18n::tr(lang, s)) + } + + fn fmt(template: &str, args: &[(&str, &str)]) -> String { + painted(&crate::i18n::fmt(template, args)) + } #[test] fn text_without_latin_runs_is_untouched() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c795fb356f..6d0a7e8c34 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2936,6 +2936,7 @@ impl RustGisApp { /// unsaved, and a rename makes a clean project unsaved: the browser doesn't say whether /// it wrote the file (the save prompt can be cancelled, the download blocked). pub(crate) fn save_download(&mut self, file: &str) -> Result<(), String> { + let file = i18n::outgoing(file); let file = file.trim(); let stem = if file.to_ascii_lowercase().ends_with(".rgis") { file.get(..file.len() - 5).unwrap_or(file) } else { file }.trim(); if stem.is_empty() || stem.contains(['/', '\\']) { @@ -2985,6 +2986,7 @@ impl RustGisApp { /// Offers bytes as a download (web) and reports whether a download hook exists. fn download(&mut self, name: &str, bytes: Vec) -> bool { + let name = &*i18n::outgoing(name); match &self.services.download { Some(d) => { if let Err(e) = d(name, Arc::new(bytes)) { @@ -3558,7 +3560,9 @@ impl RustGisApp { } /// Runs a command by id: `ui.*` here, everything else in the engine. - pub fn run(&mut self, id: &str, params: Value) -> Result { + pub fn run(&mut self, id: &str, mut params: Value) -> Result { + // Names and values made from interface text are data from here on. + i18n::outgoing_params(&mut params); #[cfg(not(target_arch = "wasm32"))] self.session.statistics_need_read_ahead(self.reads_off_frame); #[cfg(not(target_arch = "wasm32"))] @@ -7347,6 +7351,9 @@ impl RustGisApp { /// Per-frame work that doesn't draw (theme, fonts, files that arrived). pub fn logic(&mut self, ctx: &egui::Context) { + if ctx.plugin_opt::().is_none() { + ctx.add_plugin(i18n::LogicalOutput); + } annotation::sync(self); #[cfg(not(target_arch = "wasm32"))] self.session.statistics_need_read_ahead(self.reads_off_frame); From 96ee099fb153cdf7c775756f88fb2b5f2c90b481 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 17:39:17 -0500 Subject: [PATCH 2/6] fix(ui): tidy the display helper and its output test --- crates/ui-egui/src/i18n/boundary_tests.rs | 2 +- crates/ui-egui/src/i18n/mod.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs index 4a8e9ebbab..9b7e994b96 100644 --- a/crates/ui-egui/src/i18n/boundary_tests.rs +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -133,7 +133,7 @@ fn a_download_is_offered_under_its_logical_name() { #[test] fn the_clipboard_and_the_window_title_get_logical_order() { - let mut app = persian(); + let app = persian(); set_current(fa()); let (shown, text) = message(); // No Persian font is needed to read what leaves the window. diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index f480147d6d..8daa185eb0 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -531,11 +531,11 @@ pub fn note_raw(n: &rustgis_assistant::provider::Note) -> String { fmt_raw(n.template, &args) } -/// `logical`, a message made in logical order (of parts from [`fmt_raw`] and [`t_raw`]), in +/// `message`, made in logical order (of parts from [`fmt_raw`] and [`t_raw`]), in /// display form, as [`fmt`] gives its message: for a message put together from parts, which /// is put in display form once, as a whole. -pub(crate) fn display(logical: &str) -> String { - rtl::visual(logical) +pub(crate) fn display(message: &str) -> String { + rtl::visual(message) } /// `s` as it leaves the screen: what a display form in it rewrote is put back in logical From 51bb0068c8f167919b5eefeb73abf60b0e26d79f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 20:06:57 -0500 Subject: [PATCH 3/6] fix(ui): paint data kept in logical order, and reorder only paired marks --- crates/data/src/display_marks.rs | 81 ++++++++++++++-------- crates/ui-egui/src/filedialog.rs | 6 +- crates/ui-egui/src/i18n/boundary_tests.rs | 83 ++++++++++++++++++++++- crates/ui-egui/src/i18n/mod.rs | 83 ++++++++++++++++++++++- crates/ui-egui/src/i18n/rtl.rs | 14 ++-- 5 files changed, 222 insertions(+), 45 deletions(-) diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs index 6a4044c7b2..da04d45e98 100644 --- a/crates/data/src/display_marks.rs +++ b/crates/data/src/display_marks.rs @@ -3,10 +3,19 @@ //! text leaving the screen (a command's parameters, a notice, a file name) can be put back in //! logical order. -/// Around a rewritten line. Invisible, of no width and no direction. -pub const LINE: char = '\u{2063}'; -/// Around each run of characters reversed within a rewritten line. -pub const RUN: char = '\u{2064}'; +// Invisible, of no width and no direction. A start and an end differ, so that a mark whose +// partner was cut off is told apart and reorders nothing. + +/// Before a rewritten line. +pub const LINE_START: char = '\u{2063}'; +/// After a rewritten line. +pub const LINE_END: char = '\u{2062}'; +/// Before a run of characters reversed within a rewritten line. +pub const RUN_START: char = '\u{2064}'; +/// After such a run. +pub const RUN_END: char = '\u{2061}'; +/// Every mark. +pub const MARKS: [char; 4] = [LINE_START, LINE_END, RUN_START, RUN_END]; /// The mirrored glyph of a bracket, which the shaper mirrors back on a back-to-front line. #[must_use] @@ -27,37 +36,51 @@ pub fn mirror(c: char) -> char { } /// `shown` with what was rewritten for display put back in logical order, and its marks gone; -/// `None` when nothing in it carries a mark. Text around a marked line stays as it is. +/// `None` when nothing in it carries a mark. Only what stands between a start mark and its end +/// on the same line is reordered; text around it, and what a cut left without a partner, stays +/// as it is. #[must_use] pub fn logical(shown: &str) -> Option { - if !shown.contains([LINE, RUN]) { + if !shown.contains(MARKS) { return None; } - let mut out = String::with_capacity(shown.len()); + Some(shown.split('\n').map(logical_line).collect::>().join("\n")) +} + +/// One line of [`logical`]. +fn logical_line(line: &str) -> String { + let chars: Vec = line.chars().collect(); + let in_line = between(&chars, LINE_START, LINE_END); + let in_run = between(&chars, RUN_START, RUN_END); + let mut out = String::with_capacity(line.len()); let mut run: Vec = Vec::new(); - let (mut in_line, mut in_run) = (false, false); - for c in shown.chars() { - match c { - LINE => { - out.extend(run.drain(..).rev()); - in_line = !in_line; - in_run = false; - } - RUN => { - out.extend(run.drain(..).rev()); - in_run = !in_run; - } - '\n' => { - out.extend(run.drain(..).rev()); - (in_line, in_run) = (false, false); - out.push(c); - } - c if in_run => run.push(mirror(c)), - c if in_line => out.push(mirror(c)), - c => out.push(c), + for ((c, in_line), in_run) in chars.into_iter().zip(in_line).zip(in_run) { + if in_run && !MARKS.contains(&c) { + run.push(mirror(c)); + continue; + } + out.extend(run.drain(..).rev()); + if !MARKS.contains(&c) { + out.push(if in_line { mirror(c) } else { c }); } } - // A mark cut off the end leaves its run open. out.extend(run.drain(..).rev()); - Some(out) + out +} + +/// For each character, whether it stands between a `start` and the `end` that closes it. +fn between(chars: &[char], start: char, end: char) -> Vec { + let mut inside = vec![false; chars.len()]; + let mut open = None; + for (i, c) in chars.iter().enumerate() { + if *c == start { + open = Some(i); + } else if *c == end + && let Some(from) = open.take() + && let Some(span) = inside.get_mut(from..=i) + { + span.fill(true); + } + } + inside } diff --git a/crates/ui-egui/src/filedialog.rs b/crates/ui-egui/src/filedialog.rs index bc75b78820..53daf72d7a 100644 --- a/crates/ui-egui/src/filedialog.rs +++ b/crates/ui-egui/src/filedialog.rs @@ -36,7 +36,7 @@ mod desktop { Self(self.0.set_title(&*outgoing(&title.into()))) } - #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + #[cfg_attr(test, expect(dead_code, reason = "unit tests stand in for `dialogs::pick_save` and the picture picker"))] pub fn set_file_name(self, name: impl Into) -> Self { Self(self.0.set_file_name(&*outgoing(&name.into()))) } @@ -45,7 +45,7 @@ mod desktop { self.0.pick_file() } - #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + #[cfg_attr(test, expect(dead_code, reason = "unit tests stand in for `dialogs::pick_save` and the picture picker"))] pub fn pick_files(self) -> Option> { self.0.pick_files() } @@ -54,7 +54,7 @@ mod desktop { self.0.pick_folder() } - #[cfg_attr(test, expect(dead_code, reason = "unit tests answer the pickers that use it"))] + #[cfg_attr(test, expect(dead_code, reason = "unit tests stand in for `dialogs::pick_save` and the picture picker"))] pub fn save_file(self) -> Option { self.0.save_file() } diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs index 9b7e994b96..f6634ca43e 100644 --- a/crates/ui-egui/src/i18n/boundary_tests.rs +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -1,7 +1,7 @@ //! Right-to-left display text paints rewritten, and leaves the screen in logical order. use egui::OutputCommand; -use rustgis_engine::data::display_marks::{LINE, RUN, logical}; +use rustgis_engine::data::display_marks::{MARKS, RUN_END, logical}; use serde_json::json; use super::*; @@ -31,7 +31,7 @@ fn message() -> (String, String) { } fn marked(s: &str) -> bool { - s.contains([LINE, RUN]) + s.contains(MARKS) } #[test] @@ -174,7 +174,7 @@ fn the_marks_do_not_change_what_is_painted() { set_current(fa()); let (shown, _) = message(); set_current(Lang::EN); - let plain = shown.replace([LINE, RUN], ""); + let plain = shown.replace(MARKS, ""); assert_ne!(plain, shown, "the display form carries marks"); let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().build_ui(move |ui| { let width = |s: &str| { @@ -185,3 +185,80 @@ fn the_marks_do_not_change_what_is_painted() { }); h.step(); } + +/// The strings of the text shapes the last frame paints. +fn painted_texts(h: &egui_kittest::Harness<'_, S>) -> Vec { + fn collect(shape: &egui::Shape, into: &mut Vec) { + match shape { + egui::Shape::Text(text) => into.push(text.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, into)), + _ => {} + } + } + let mut texts = Vec::new(); + h.output().shapes.iter().for_each(|s| collect(&s.shape, &mut texts)); + texts +} + +/// Data is kept in logical order and painted like interface text, wherever it is painted; a +/// display form is painted as it is. +#[test] +fn data_in_logical_order_is_painted_in_display_form() { + set_current(fa()); + let (shown, _) = message(); + set_current(Lang::EN); + let data = "رود GeoPackage 42"; + let expected = rtl::visual(data).replace(MARKS, ""); + assert_ne!(expected, data, "the fixture must need rewriting to paint"); + let marked_label = shown.clone(); + let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().build_ui(move |ui| { + if ui.ctx().plugin_opt::().is_none() { + ui.ctx().add_plugin(LogicalOutput); + } + ui.label(data); + ui.label(&marked_label); + ui.label("Cities"); + egui::Area::new(egui::Id::unique("over")).show(ui.ctx(), |ui| ui.label(data)); + }); + h.step(); + let texts = painted_texts(&h); + assert_eq!(texts.iter().filter(|t| **t == expected).count(), 2, "{texts:?}"); + assert!(!texts.iter().any(|t| t == data), "{texts:?}"); + assert!(texts.contains(&shown) && texts.iter().any(|t| t == "Cities"), "{texts:?}"); +} + +#[test] +fn a_mark_with_no_partner_reorders_nothing() { + set_current(fa()); + let (shown, _) = message(); + set_current(Lang::EN); + for mark in MARKS { + let cut = format!("abc (d){mark} def"); + assert_eq!(logical(&cut).as_deref(), Some("abc (d) def"), "{mark:?}"); + } + // A run whose end was cut off stays as it is painted. + let end = shown.rfind(RUN_END).unwrap(); + assert_eq!(logical(&shown[..end]), Some(shown[..end].replace(MARKS, ""))); +} + +#[test] +fn a_layer_named_in_logical_order_is_painted_in_display_form_in_the_app() { + let mut app = persian(); + set_current(fa()); + let data = "رود GeoPackage 42"; + let expected = rtl::visual(data).replace(MARKS, ""); + app.run("layer.rename", json!({"layer": "Cities", "name": data})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).allow_missing_glyphs().build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.step(); + let texts = painted_texts(&h); + set_current(Lang::EN); + assert!(texts.contains(&expected), "{texts:?}"); + assert!(!texts.iter().any(|t| t == data), "{texts:?}"); +} diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 8daa185eb0..9f60d2a734 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -29,7 +29,7 @@ use std::cell::Cell; use std::collections::HashMap; use std::sync::OnceLock; -use rustgis_engine::data::display_marks::logical; +use rustgis_engine::data::display_marks::{MARKS, logical}; mod rtl; @@ -559,8 +559,46 @@ pub(crate) fn outgoing_params(value: &mut serde_json::Value) { } } -/// Puts what egui itself sends out of the window (the clipboard, the window title) in logical -/// order. +/// The display form of data painted as it is kept, in logical order: each right-to-left line +/// that carries no mark, rewritten. `None` when `text` paints as it should already. Without the +/// marks, so it takes the room and the byte count of `text`. +fn painted(text: &str) -> Option { + if !rtl::has_rtl(text) { + return None; + } + let lines: Vec = + text.split('\n').map(|line| if line.contains(MARKS) { line.to_owned() } else { rtl::visual(line).replace(MARKS, "") }).collect(); + Some(lines.join("\n")).filter(|painted| painted != text) +} + +/// Calls `f` on each text shape in `shape`. +fn for_each_text(shape: &mut egui::Shape, f: &mut impl FnMut(&mut egui::epaint::TextShape)) { + match shape { + egui::Shape::Text(text) => f(text), + egui::Shape::Vec(shapes) => shapes.iter_mut().for_each(|shape| for_each_text(shape, f)), + _ => {} + } +} + +/// `galley` laid out again in display form, when it shows data kept in logical order. One whose +/// mesh something else changed (a selection painted into it) is left as it is, as is text of +/// several formats, whose ranges a reordering would not keep. +fn repainted(ctx: &egui::Context, galley: &egui::Galley) -> Option> { + if galley.job.sections.len() != 1 { + return None; + } + let text = painted(&galley.job.text)?; + let mut job = (*galley.job).clone(); + if ctx.fonts_mut(|fonts| fonts.layout_job(job.clone())).num_vertices != galley.num_vertices { + return None; + } + job.text = text; + Some(ctx.fonts_mut(|fonts| fonts.layout_job(job))) +} + +/// Where the interface's text meets what is outside its logical order: data is painted in +/// display form, and what egui sends out of the window (the clipboard, the window title) is put +/// back in logical order. #[derive(Default)] pub(crate) struct LogicalOutput; @@ -569,6 +607,45 @@ impl egui::Plugin for LogicalOutput { "rustgis_logical_output" } + /// Painted here, inside the pass, so that glyphs this lays out reach the texture with it. + /// It reaches the background and every area; a layer only a painter draws on is not listed. + fn on_end_pass(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx(); + let mut layers: Vec = ctx.memory(|memory| memory.layer_ids().collect()); + if !layers.contains(&egui::LayerId::background()) { + layers.push(egui::LayerId::background()); + } + for layer in layers { + let mut shapes: Vec<(usize, egui::Shape)> = ctx.graphics(|graphics| { + let entries = graphics.get(layer).into_iter().flat_map(|list| list.all_entries().enumerate()); + entries + .filter(|(_, entry)| matches!(entry.shape, egui::Shape::Text(_) | egui::Shape::Vec(_))) + .map(|(i, entry)| (i, entry.shape.clone())) + .collect() + }); + // Laid out outside the lock `graphics` holds. + shapes.retain_mut(|(_, shape)| { + let mut changed = false; + for_each_text(shape, &mut |text| { + if let Some(galley) = repainted(ctx, &text.galley) { + text.galley = galley; + changed = true; + } + }); + changed + }); + if shapes.is_empty() { + continue; + } + ctx.graphics_mut(|graphics| { + let list = graphics.entry(layer); + for (i, shape) in shapes { + list.mutate_shape(egui::layers::ShapeIdx(i), |entry| entry.shape = shape); + } + }); + } + } + fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) { use egui::{OutputCommand, ViewportCommand}; let restore = |s: &mut String| { diff --git a/crates/ui-egui/src/i18n/rtl.rs b/crates/ui-egui/src/i18n/rtl.rs index 65db4a1840..ee92b0e748 100644 --- a/crates/ui-egui/src/i18n/rtl.rs +++ b/crates/ui-egui/src/i18n/rtl.rs @@ -34,7 +34,7 @@ //! What is rewritten is marked ([`rustgis_engine::data::display_marks`]), so text that leaves //! the screen can be put back in logical order. -use rustgis_engine::data::display_marks::{LINE, RUN, mirror}; +use rustgis_engine::data::display_marks::{LINE_END, LINE_START, RUN_END, RUN_START, mirror}; /// A character of a script written right to left (Arabic, Persian, Hebrew). Digits /// read left to right, and the comma, semicolon and question mark take the line's @@ -220,9 +220,9 @@ fn visual_line(line: &str) -> String { // A run of one character reads the same either way: it takes no marks. let flush = |out: &mut String, run: &mut Vec| { let marked = run.len() > 1; - out.extend(marked.then_some(RUN)); + out.extend(marked.then_some(RUN_START)); out.extend(run.drain(..).rev().map(mirror)); - out.extend(marked.then_some(RUN)); + out.extend(marked.then_some(RUN_END)); }; for (i, c) in chars.iter().enumerate() { if in_run(i) { @@ -236,7 +236,7 @@ fn visual_line(line: &str) -> String { if out == line { return out; } - format!("{LINE}{out}{LINE}") + format!("{LINE_START}{out}{LINE_END}") } /// `s` broken into lines whose display form is no wider than `max_width`, so the @@ -246,7 +246,7 @@ fn visual_line(line: &str) -> String { /// is laid out front to back, and the right-to-left words in it would read /// backwards, so it ends before the first word with right-to-left text; a row with /// no right-to-left text at all reads correctly front to back on its own. `width` -/// measures a line's display form. Strings with no right-to-left text come back +/// measures a line's display form, marks included (they have no width). Strings with no right-to-left text come back /// unchanged. #[must_use] pub fn fit(s: &str, max_width: f32, width: &dyn Fn(&str) -> f32) -> String { @@ -291,11 +291,11 @@ fn fit_line(line: &str, max_width: f32, width: &dyn Fn(&str) -> f32, rows: &mut #[cfg(test)] mod tests { use crate::i18n::{Lang, set_current}; - use rustgis_engine::data::display_marks::{LINE, RUN}; + use rustgis_engine::data::display_marks::MARKS; /// What is painted: the display form without its marks. fn painted(s: &str) -> String { - s.replace([LINE, RUN], "") + s.replace(MARKS, "") } fn visual(s: &str) -> String { From 388a44267e8c297976afb24b44652c4551533b96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 20:42:35 -0500 Subject: [PATCH 4/6] fix(ui): leave text fields and unpaired marks as they are in the paint pass --- crates/data/src/display_marks.rs | 66 ++++++++++++++--------- crates/ui-egui/src/i18n/boundary_tests.rs | 49 ++++++++++++++--- crates/ui-egui/src/i18n/mod.rs | 40 +++++++++----- crates/ui-egui/src/scriptcolor.rs | 3 ++ 4 files changed, 113 insertions(+), 45 deletions(-) diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs index da04d45e98..d7e9fb35cf 100644 --- a/crates/data/src/display_marks.rs +++ b/crates/data/src/display_marks.rs @@ -3,8 +3,8 @@ //! text leaving the screen (a command's parameters, a notice, a file name) can be put back in //! logical order. -// Invisible, of no width and no direction. A start and an end differ, so that a mark whose -// partner was cut off is told apart and reorders nothing. +// Invisible, of no width and no direction. A start and an end differ, so that a mark with no +// partner, cut from its pair or part of the data, is told apart and left where it is. /// Before a rewritten line. pub const LINE_START: char = '\u{2063}'; @@ -35,32 +35,33 @@ pub fn mirror(c: char) -> char { } } -/// `shown` with what was rewritten for display put back in logical order, and its marks gone; -/// `None` when nothing in it carries a mark. Only what stands between a start mark and its end -/// on the same line is reordered; text around it, and what a cut left without a partner, stays -/// as it is. +/// `shown` with what was rewritten for display put back in logical order, and the marks +/// around it gone; `None` when no line holds a start mark and its end. Only what stands between +/// the two is reordered; text around it, and a mark with no partner, stay as they are. #[must_use] pub fn logical(shown: &str) -> Option { if !shown.contains(MARKS) { return None; } - Some(shown.split('\n').map(logical_line).collect::>().join("\n")) + let text = shown.split('\n').map(logical_line).collect::>().join("\n"); + (text != shown).then_some(text) } /// One line of [`logical`]. fn logical_line(line: &str) -> String { let chars: Vec = line.chars().collect(); - let in_line = between(&chars, LINE_START, LINE_END); - let in_run = between(&chars, RUN_START, RUN_END); + let lines = Pairs::of(&chars, LINE_START, LINE_END); + let runs = Pairs::of(&chars, RUN_START, RUN_END); let mut out = String::with_capacity(line.len()); let mut run: Vec = Vec::new(); - for ((c, in_line), in_run) in chars.into_iter().zip(in_line).zip(in_run) { - if in_run && !MARKS.contains(&c) { + let marks = lines.mark.into_iter().zip(runs.mark).map(|(a, b)| a || b); + for (((c, mark), in_line), in_run) in chars.into_iter().zip(marks).zip(lines.inside).zip(runs.inside) { + if in_run && !mark { run.push(mirror(c)); continue; } out.extend(run.drain(..).rev()); - if !MARKS.contains(&c) { + if !mark { out.push(if in_line { mirror(c) } else { c }); } } @@ -68,19 +69,34 @@ fn logical_line(line: &str) -> String { out } -/// For each character, whether it stands between a `start` and the `end` that closes it. -fn between(chars: &[char], start: char, end: char) -> Vec { - let mut inside = vec![false; chars.len()]; - let mut open = None; - for (i, c) in chars.iter().enumerate() { - if *c == start { - open = Some(i); - } else if *c == end - && let Some(from) = open.take() - && let Some(span) = inside.get_mut(from..=i) - { - span.fill(true); +/// Where the complete pairs of one start and end mark are in a line, character by character. +struct Pairs { + /// Whether it stands between a start and the end that closes it, both included. + inside: Vec, + /// Whether it is one of those two marks. + mark: Vec, +} + +impl Pairs { + fn of(chars: &[char], start: char, end: char) -> Self { + let mut pairs = Self { inside: vec![false; chars.len()], mark: vec![false; chars.len()] }; + let mut open = None; + for (i, c) in chars.iter().enumerate() { + if *c == start { + open = Some(i); + } else if *c == end + && let Some(from) = open.take() + { + if let Some(span) = pairs.inside.get_mut(from..=i) { + span.fill(true); + } + for at in [from, i] { + if let Some(mark) = pairs.mark.get_mut(at) { + *mark = true; + } + } + } } + pairs } - inside } diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs index f6634ca43e..d736ac14e3 100644 --- a/crates/ui-egui/src/i18n/boundary_tests.rs +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -66,14 +66,15 @@ fn only_the_marked_part_of_a_composed_string_is_put_back() { } #[test] -fn a_display_form_cut_anywhere_leaves_no_mark() { +fn a_display_form_cut_anywhere_keeps_its_text() { set_current(fa()); let (shown, _) = message(); set_current(Lang::EN); + let letters = |s: &str| s.chars().filter(|c| !MARKS.contains(c)).count(); for (at, _) in shown.char_indices() { for piece in [&shown[..at], &shown[at..]] { let back = logical(piece).unwrap_or_else(|| piece.to_owned()); - assert!(!marked(&back), "{piece:?} gave {back:?}"); + assert_eq!(letters(&back), letters(piece), "{piece:?} gave {back:?}"); } } } @@ -227,18 +228,18 @@ fn data_in_logical_order_is_painted_in_display_form() { assert!(texts.contains(&shown) && texts.iter().any(|t| t == "Cities"), "{texts:?}"); } +/// A mark with no partner, as data may hold, is neither removed nor reorders anything. #[test] -fn a_mark_with_no_partner_reorders_nothing() { +fn a_mark_with_no_partner_is_left_where_it_is() { set_current(fa()); let (shown, _) = message(); set_current(Lang::EN); for mark in MARKS { - let cut = format!("abc (d){mark} def"); - assert_eq!(logical(&cut).as_deref(), Some("abc (d) def"), "{mark:?}"); + assert_eq!(logical(&format!("abc (d){mark} def")), None, "{mark:?}"); } - // A run whose end was cut off stays as it is painted. + // A run and a line whose ends were cut off stay as they are painted. let end = shown.rfind(RUN_END).unwrap(); - assert_eq!(logical(&shown[..end]), Some(shown[..end].replace(MARKS, ""))); + assert_eq!(logical(&shown[..end]), None); } #[test] @@ -262,3 +263,37 @@ fn a_layer_named_in_logical_order_is_painted_in_display_form_in_the_app() { assert!(texts.contains(&expected), "{texts:?}"); assert!(!texts.iter().any(|t| t == data), "{texts:?}"); } + +/// A text field places its caret and clicks by what it laid out, so that is what it paints. +#[test] +fn a_text_field_paints_what_it_edits() { + let mut value = String::from("رود GeoPackage 42"); + let data = value.clone(); + let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().with_accessibility_check(false).build_ui(move |ui| { + if ui.ctx().plugin_opt::().is_none() { + ui.ctx().add_plugin(LogicalOutput); + } + ui.text_edit_singleline(&mut value); + ui.text_edit_multiline(&mut value); + }); + h.step(); + let texts = painted_texts(&h); + assert_eq!(texts.iter().filter(|t| **t == data).count(), 2, "{texts:?}"); +} + +/// The Script box lays its own text out, and paints it as it edits it too. +#[test] +fn the_script_box_paints_what_it_edits() { + let data = "# رود GeoPackage 42"; + let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().with_accessibility_check(false).build_ui(move |ui| { + if ui.ctx().plugin_opt::().is_none() { + ui.ctx().add_plugin(LogicalOutput); + } + let palette = crate::scriptcolor::Palette::of(&crate::theme::Tokens::light()); + let galley = crate::scriptcolor::layout(ui, data, &[], palette, 600.0); + ui.painter().galley(egui::pos2(8.0, 8.0), galley, egui::Color32::WHITE); + }); + h.step(); + let texts = painted_texts(&h); + assert!(texts.iter().any(|t| t == data), "{texts:?}"); +} diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 9f60d2a734..e4c81a86a7 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -560,14 +560,15 @@ pub(crate) fn outgoing_params(value: &mut serde_json::Value) { } /// The display form of data painted as it is kept, in logical order: each right-to-left line -/// that carries no mark, rewritten. `None` when `text` paints as it should already. Without the -/// marks, so it takes the room and the byte count of `text`. +/// that is no display form already, rewritten. `None` when `text` paints as it should. For +/// painting only, so no mark is kept: they take no room. fn painted(text: &str) -> Option { if !rtl::has_rtl(text) { return None; } + // A line with a pair of marks is a display form already. let lines: Vec = - text.split('\n').map(|line| if line.contains(MARKS) { line.to_owned() } else { rtl::visual(line).replace(MARKS, "") }).collect(); + text.split('\n').map(|line| if logical(line).is_some() { line.to_owned() } else { rtl::visual(line).replace(MARKS, "") }).collect(); Some(lines.join("\n")).filter(|painted| painted != text) } @@ -580,14 +581,30 @@ fn for_each_text(shape: &mut egui::Shape, f: &mut impl FnMut(&mut egui::epaint:: } } -/// `galley` laid out again in display form, when it shows data kept in logical order. One whose -/// mesh something else changed (a selection painted into it) is left as it is, as is text of -/// several formats, whose ranges a reordering would not keep. -fn repainted(ctx: &egui::Context, galley: &egui::Galley) -> Option> { - if galley.job.sections.len() != 1 { +/// The text to lay `galley` out again with, when it shows data kept in logical order. None for +/// a text field's (the only galleys egui keeps trailing whitespace in), whose caret and clicks +/// follow what it laid out, nor for text of several formats, whose ranges a reordering would not +/// keep. +fn repaint_text(galley: &egui::Galley) -> Option { + if galley.job.keep_trailing_whitespace || galley.job.sections.len() != 1 { return None; } - let text = painted(&galley.job.text)?; + painted(&galley.job.text) +} + +/// Whether any text in `shape` is to be laid out again, told without copying it. +fn needs_repaint(shape: &egui::Shape) -> bool { + match shape { + egui::Shape::Text(text) => repaint_text(&text.galley).is_some(), + egui::Shape::Vec(shapes) => shapes.iter().any(needs_repaint), + _ => false, + } +} + +/// `galley` laid out again in display form ([`repaint_text`]). One whose mesh something else +/// changed (a selection painted into it) is left as it is. +fn repainted(ctx: &egui::Context, galley: &egui::Galley) -> Option> { + let text = repaint_text(galley)?; let mut job = (*galley.job).clone(); if ctx.fonts_mut(|fonts| fonts.layout_job(job.clone())).num_vertices != galley.num_vertices { return None; @@ -618,10 +635,7 @@ impl egui::Plugin for LogicalOutput { for layer in layers { let mut shapes: Vec<(usize, egui::Shape)> = ctx.graphics(|graphics| { let entries = graphics.get(layer).into_iter().flat_map(|list| list.all_entries().enumerate()); - entries - .filter(|(_, entry)| matches!(entry.shape, egui::Shape::Text(_) | egui::Shape::Vec(_))) - .map(|(i, entry)| (i, entry.shape.clone())) - .collect() + entries.filter(|(_, entry)| needs_repaint(&entry.shape)).map(|(i, entry)| (i, entry.shape.clone())).collect() }); // Laid out outside the lock `graphics` holds. shapes.retain_mut(|(_, shape)| { diff --git a/crates/ui-egui/src/scriptcolor.rs b/crates/ui-egui/src/scriptcolor.rs index b33478cab1..63df7567fc 100644 --- a/crates/ui-egui/src/scriptcolor.rs +++ b/crates/ui-egui/src/scriptcolor.rs @@ -387,6 +387,9 @@ pub fn layout(ui: &egui::Ui, script: &str, unknown: &[String], palette: Palette, let font = egui::TextStyle::Monospace.resolve(ui.style()); let mut job = ui.memory_mut(|m| m.caches.cache::().get((script, unknown, palette, &font)).clone()); job.wrap.max_width = wrap; + // As egui's own fields: it keeps what is typed in view, and says this galley is a field's, + // which the paint pass leaves as it was laid out. + job.keep_trailing_whitespace = true; ui.fonts_mut(|f| f.layout_job(job)) } From efc9946f55b65dffb7f3e76d090e467d3563704d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 05:14:45 -0500 Subject: [PATCH 5/6] fix(ui): keep command data as painted, and drop the paint pass --- crates/data/src/display_marks.rs | 27 +++-- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/diagnosticlog.rs | 2 +- crates/ui-egui/src/i18n/boundary_tests.rs | 124 ++++++---------------- crates/ui-egui/src/i18n/mod.rs | 119 ++++----------------- crates/ui-egui/src/lib.rs | 11 +- crates/ui-egui/src/plugindialog.rs | 4 +- crates/ui-egui/src/scriptcolor.rs | 3 - 8 files changed, 81 insertions(+), 211 deletions(-) diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs index d7e9fb35cf..a14d032153 100644 --- a/crates/data/src/display_marks.rs +++ b/crates/data/src/display_marks.rs @@ -1,7 +1,8 @@ //! The marks right-to-left display text carries. An interface that lays a line out back to //! front rewrites it for painting (`ui-egui`'s `i18n::rtl`) and marks what it rewrote, so that -//! text leaving the screen (a command's parameters, a notice, a file name) can be put back in -//! logical order. +//! text leaving the screen (a notice, a file name, the clipboard) can be put back in logical +//! order ([`logical`]), and text kept to be painted as it is (a command's parameters) can lose +//! the marks alone ([`unmarked`]). // Invisible, of no width and no direction. A start and an end differ, so that a mark with no // partner, cut from its pair or part of the data, is told apart and left where it is. @@ -40,15 +41,27 @@ pub fn mirror(c: char) -> char { /// the two is reordered; text around it, and a mark with no partner, stay as they are. #[must_use] pub fn logical(shown: &str) -> Option { + unmark(shown, true) +} + +/// `shown` without the marks [`logical`] would read, its characters left where they are: a +/// display form kept as data that is painted as it is. `None` when no line holds a pair. +#[must_use] +pub fn unmarked(shown: &str) -> Option { + unmark(shown, false) +} + +/// [`logical`] when `reorder`, else [`unmarked`]. +fn unmark(shown: &str, reorder: bool) -> Option { if !shown.contains(MARKS) { return None; } - let text = shown.split('\n').map(logical_line).collect::>().join("\n"); + let text = shown.split('\n').map(|line| unmark_line(line, reorder)).collect::>().join("\n"); (text != shown).then_some(text) } -/// One line of [`logical`]. -fn logical_line(line: &str) -> String { +/// One line of [`unmark`]. +fn unmark_line(line: &str, reorder: bool) -> String { let chars: Vec = line.chars().collect(); let lines = Pairs::of(&chars, LINE_START, LINE_END); let runs = Pairs::of(&chars, RUN_START, RUN_END); @@ -56,13 +69,13 @@ fn logical_line(line: &str) -> String { let mut run: Vec = Vec::new(); let marks = lines.mark.into_iter().zip(runs.mark).map(|(a, b)| a || b); for (((c, mark), in_line), in_run) in chars.into_iter().zip(marks).zip(lines.inside).zip(runs.inside) { - if in_run && !mark { + if reorder && in_run && !mark { run.push(mirror(c)); continue; } out.extend(run.drain(..).rev()); if !mark { - out.push(if in_line { mirror(c) } else { c }); + out.push(if reorder && in_line { mirror(c) } else { c }); } } out.extend(run.drain(..).rev()); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 049f97bafa..dd459f433b 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -2237,7 +2237,7 @@ fn notice_text(notice: &rustgis_engine::Notice) -> String { .translated(crate::i18n::fmt_raw) .map(|message| crate::i18n::fmt("{message}", &[("message", &message)])) .or_else(|| crate::i18n::file_size_error(¬ice.text, crate::i18n::fmt)) - .unwrap_or_else(|| crate::i18n::display(¬ice.text)) + .unwrap_or_else(|| crate::i18n::shaped(¬ice.text)) } /// A deferred message stays in logical order until the complete tooltip is shaped, including diff --git a/crates/ui-egui/src/diagnosticlog.rs b/crates/ui-egui/src/diagnosticlog.rs index 001ab33a83..3f1ae9cc3e 100644 --- a/crates/ui-egui/src/diagnosticlog.rs +++ b/crates/ui-egui/src/diagnosticlog.rs @@ -178,7 +178,7 @@ fn entry(ui: &mut Ui, record: &Record, t: &Tokens, standalone: bool, open_url: & ui.label(RichText::new(source).small().color(t.text_dim)); } }); - ui.add(egui::Label::new(crate::i18n::display(&record.message)).wrap().selectable(true)); + ui.add(egui::Label::new(crate::i18n::shaped(&record.message)).wrap().selectable(true)); if let Some(code) = record.loss { let spec = code.spec(); // What the code means and what to do, in a quiet inset under the message. diff --git a/crates/ui-egui/src/i18n/boundary_tests.rs b/crates/ui-egui/src/i18n/boundary_tests.rs index d736ac14e3..0cd022342e 100644 --- a/crates/ui-egui/src/i18n/boundary_tests.rs +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -88,13 +88,15 @@ fn english_text_takes_no_marks() { } #[test] -fn a_layer_buffered_from_the_map_menu_is_named_in_logical_order() { +fn a_layer_buffered_from_the_map_menu_is_named_without_marks() { let mut app = persian(); let args = &[("distance", "500 m")]; - let (shown, text) = (fmt("Buffer {distance}", args), fmt_raw("Buffer {distance}", args)); - assert_ne!(shown, text); + let shown = fmt("Buffer {distance}", args); + assert!(marked(&shown), "{shown:?}"); app.run("gp.bufferPoint", json!({"lon": 8.5, "lat": 47.4, "distance": 500.0, "units": "Meters", "name": shown})).unwrap(); - assert!(app.session.map().layers.iter().any(|l| l.name == text), "no layer named {text:?}"); + // As painted, so that every pane shows it as before. + let kept = shown.replace(MARKS, ""); + assert!(app.session.map().layers.iter().any(|l| l.name == kept), "no layer named {kept:?}"); let saved = serde_json::to_string(&app.session.project).unwrap(); set_current(Lang::EN); assert!(!marked(&saved), "the saved project holds a display mark"); @@ -126,10 +128,11 @@ fn a_download_is_offered_under_its_logical_name() { }); let (shown, text) = message(); assert!(app.download_bytes(&format!("{shown}.csv"), Vec::new())); + let shown_name = shown.replace(MARKS, ""); app.save_download(&shown).unwrap(); set_current(Lang::EN); assert_eq!(*offered.borrow(), [format!("{text}.csv"), format!("{text}.rgis")]); - assert_eq!(app.session.project.name, text); + assert_eq!(app.session.project.name, shown_name); } #[test] @@ -187,47 +190,6 @@ fn the_marks_do_not_change_what_is_painted() { h.step(); } -/// The strings of the text shapes the last frame paints. -fn painted_texts(h: &egui_kittest::Harness<'_, S>) -> Vec { - fn collect(shape: &egui::Shape, into: &mut Vec) { - match shape { - egui::Shape::Text(text) => into.push(text.galley.job.text.clone()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, into)), - _ => {} - } - } - let mut texts = Vec::new(); - h.output().shapes.iter().for_each(|s| collect(&s.shape, &mut texts)); - texts -} - -/// Data is kept in logical order and painted like interface text, wherever it is painted; a -/// display form is painted as it is. -#[test] -fn data_in_logical_order_is_painted_in_display_form() { - set_current(fa()); - let (shown, _) = message(); - set_current(Lang::EN); - let data = "رود GeoPackage 42"; - let expected = rtl::visual(data).replace(MARKS, ""); - assert_ne!(expected, data, "the fixture must need rewriting to paint"); - let marked_label = shown.clone(); - let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().build_ui(move |ui| { - if ui.ctx().plugin_opt::().is_none() { - ui.ctx().add_plugin(LogicalOutput); - } - ui.label(data); - ui.label(&marked_label); - ui.label("Cities"); - egui::Area::new(egui::Id::unique("over")).show(ui.ctx(), |ui| ui.label(data)); - }); - h.step(); - let texts = painted_texts(&h); - assert_eq!(texts.iter().filter(|t| **t == expected).count(), 2, "{texts:?}"); - assert!(!texts.iter().any(|t| t == data), "{texts:?}"); - assert!(texts.contains(&shown) && texts.iter().any(|t| t == "Cities"), "{texts:?}"); -} - /// A mark with no partner, as data may hold, is neither removed nor reorders anything. #[test] fn a_mark_with_no_partner_is_left_where_it_is() { @@ -242,58 +204,32 @@ fn a_mark_with_no_partner_is_left_where_it_is() { assert_eq!(logical(&shown[..end]), None); } +/// Text the session keeps in logical order is shaped for painting in a right-to-left interface +/// only; in another one data already reads in order. #[test] -fn a_layer_named_in_logical_order_is_painted_in_display_form_in_the_app() { - let mut app = persian(); - set_current(fa()); +fn kept_text_is_shaped_only_in_a_right_to_left_interface() { let data = "رود GeoPackage 42"; - let expected = rtl::visual(data).replace(MARKS, ""); - app.run("layer.rename", json!({"layer": "Cities", "name": data})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).allow_missing_glyphs().build_ui_state( - |ui, app: &mut RustGisApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - app, - ); - h.step(); - let texts = painted_texts(&h); set_current(Lang::EN); - assert!(texts.contains(&expected), "{texts:?}"); - assert!(!texts.iter().any(|t| t == data), "{texts:?}"); -} - -/// A text field places its caret and clicks by what it laid out, so that is what it paints. -#[test] -fn a_text_field_paints_what_it_edits() { - let mut value = String::from("رود GeoPackage 42"); - let data = value.clone(); - let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().with_accessibility_check(false).build_ui(move |ui| { - if ui.ctx().plugin_opt::().is_none() { - ui.ctx().add_plugin(LogicalOutput); - } - ui.text_edit_singleline(&mut value); - ui.text_edit_multiline(&mut value); - }); - h.step(); - let texts = painted_texts(&h); - assert_eq!(texts.iter().filter(|t| **t == data).count(), 2, "{texts:?}"); + assert_eq!(shaped(data), data); + set_current(fa()); + let (shown, text) = message(); + let (from_data, from_text, from_shown) = (shaped(data), shaped(&text), shaped(&shown)); + set_current(Lang::EN); + assert_ne!(from_data, data); + assert_eq!(from_text, shown); + assert_eq!(from_shown, shown, "a display form is not shaped twice"); } -/// The Script box lays its own text out, and paints it as it edits it too. +/// An error a dialog shows is redacted, which keeps it in logical order, and painted as before. #[test] -fn the_script_box_paints_what_it_edits() { - let data = "# رود GeoPackage 42"; - let mut h = egui_kittest::Harness::builder().allow_missing_glyphs().with_accessibility_check(false).build_ui(move |ui| { - if ui.ctx().plugin_opt::().is_none() { - ui.ctx().add_plugin(LogicalOutput); - } - let palette = crate::scriptcolor::Palette::of(&crate::theme::Tokens::light()); - let galley = crate::scriptcolor::layout(ui, data, &[], palette, 600.0); - ui.painter().galley(egui::pos2(8.0, 8.0), galley, egui::Color32::WHITE); - }); - h.step(); - let texts = painted_texts(&h); - assert!(texts.iter().any(|t| t == data), "{texts:?}"); +fn a_dialog_error_is_painted_in_display_form() { + let mut app = persian(); + set_current(fa()); + let (shown, _) = message(); + app.dialogs.info = Some(crate::serviceui::downloading("x")); + app.landed_in_dialog(&json!({"name": "x"}), Err(&shown)); + let (service, plugin) = (app.dialogs.error.clone(), crate::plugindialog::error_shown(&shown)); + set_current(Lang::EN); + assert_eq!(service.as_deref(), Some(shown.as_str())); + assert_eq!(plugin, shown); } diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 54c45c5074..35704e1230 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -29,7 +29,7 @@ use std::cell::Cell; use std::collections::HashMap; use std::sync::OnceLock; -use rustgis_engine::data::display_marks::{MARKS, logical}; +use rustgis_engine::data::display_marks::{logical, unmarked}; mod rtl; @@ -538,84 +538,41 @@ pub fn display(message: &str) -> String { rtl::visual(message) } +/// Text the session keeps in logical order (a notice, a redacted error), as it is painted. +/// Only a right-to-left interface lays such a line out back to front with one face, and a +/// display form already there (a translated message around the kept text) is left as it is. +pub(crate) fn shaped(text: &str) -> String { + if current().script() != Script::Arabic || logical(text).is_some() { + return text.to_owned(); + } + display(text) +} + /// `s` as it leaves the screen: what a display form in it rewrote is put back in logical /// order, and its marks are gone. pub(crate) fn outgoing(s: &str) -> Cow<'_, str> { logical(s).map_or(Cow::Borrowed(s), Cow::Owned) } -/// [`outgoing`] for every string of a command's parameters. -pub(crate) fn outgoing_params(value: &mut serde_json::Value) { +/// Takes the display marks out of every string of a command's parameters. What a command keeps +/// (a layer's name) is painted as data, which nothing shapes again, so it stays as it was +/// painted. +pub(crate) fn unmark_params(value: &mut serde_json::Value) { use serde_json::Value; match value { Value::String(s) => { - if let Some(text) = logical(s) { + if let Some(text) = unmarked(s) { *s = text; } } - Value::Array(items) => items.iter_mut().for_each(outgoing_params), - Value::Object(fields) => fields.values_mut().for_each(outgoing_params), - _ => {} - } -} - -/// The display form of data painted as it is kept, in logical order: each right-to-left line -/// that is no display form already, rewritten. `None` when `text` paints as it should. For -/// painting only, so no mark is kept: they take no room. -fn painted(text: &str) -> Option { - if !rtl::has_rtl(text) { - return None; - } - // A line with a pair of marks is a display form already. - let lines: Vec = - text.split('\n').map(|line| if logical(line).is_some() { line.to_owned() } else { rtl::visual(line).replace(MARKS, "") }).collect(); - Some(lines.join("\n")).filter(|painted| painted != text) -} - -/// Calls `f` on each text shape in `shape`. -fn for_each_text(shape: &mut egui::Shape, f: &mut impl FnMut(&mut egui::epaint::TextShape)) { - match shape { - egui::Shape::Text(text) => f(text), - egui::Shape::Vec(shapes) => shapes.iter_mut().for_each(|shape| for_each_text(shape, f)), + Value::Array(items) => items.iter_mut().for_each(unmark_params), + Value::Object(fields) => fields.values_mut().for_each(unmark_params), _ => {} } } -/// The text to lay `galley` out again with, when it shows data kept in logical order. None for -/// a text field's (the only galleys egui keeps trailing whitespace in), whose caret and clicks -/// follow what it laid out, nor for text of several formats, whose ranges a reordering would not -/// keep. -fn repaint_text(galley: &egui::Galley) -> Option { - if galley.job.keep_trailing_whitespace || galley.job.sections.len() != 1 { - return None; - } - painted(&galley.job.text) -} - -/// Whether any text in `shape` is to be laid out again, told without copying it. -fn needs_repaint(shape: &egui::Shape) -> bool { - match shape { - egui::Shape::Text(text) => repaint_text(&text.galley).is_some(), - egui::Shape::Vec(shapes) => shapes.iter().any(needs_repaint), - _ => false, - } -} - -/// `galley` laid out again in display form ([`repaint_text`]). One whose mesh something else -/// changed (a selection painted into it) is left as it is. -fn repainted(ctx: &egui::Context, galley: &egui::Galley) -> Option> { - let text = repaint_text(galley)?; - let mut job = (*galley.job).clone(); - if ctx.fonts_mut(|fonts| fonts.layout_job(job.clone())).num_vertices != galley.num_vertices { - return None; - } - job.text = text; - Some(ctx.fonts_mut(|fonts| fonts.layout_job(job))) -} - -/// Where the interface's text meets what is outside its logical order: data is painted in -/// display form, and what egui sends out of the window (the clipboard, the window title) is put -/// back in logical order. +/// Puts what egui itself sends out of the window (the clipboard, the window title) in logical +/// order. #[derive(Default)] pub(crate) struct LogicalOutput; @@ -624,42 +581,6 @@ impl egui::Plugin for LogicalOutput { "rustgis_logical_output" } - /// Painted here, inside the pass, so that glyphs this lays out reach the texture with it. - /// It reaches the background and every area; a layer only a painter draws on is not listed. - fn on_end_pass(&mut self, ui: &mut egui::Ui) { - let ctx = ui.ctx(); - let mut layers: Vec = ctx.memory(|memory| memory.layer_ids().collect()); - if !layers.contains(&egui::LayerId::background()) { - layers.push(egui::LayerId::background()); - } - for layer in layers { - let mut shapes: Vec<(usize, egui::Shape)> = ctx.graphics(|graphics| { - let entries = graphics.get(layer).into_iter().flat_map(|list| list.all_entries().enumerate()); - entries.filter(|(_, entry)| needs_repaint(&entry.shape)).map(|(i, entry)| (i, entry.shape.clone())).collect() - }); - // Laid out outside the lock `graphics` holds. - shapes.retain_mut(|(_, shape)| { - let mut changed = false; - for_each_text(shape, &mut |text| { - if let Some(galley) = repainted(ctx, &text.galley) { - text.galley = galley; - changed = true; - } - }); - changed - }); - if shapes.is_empty() { - continue; - } - ctx.graphics_mut(|graphics| { - let list = graphics.entry(layer); - for (i, shape) in shapes { - list.mutate_shape(egui::layers::ShapeIdx(i), |entry| entry.shape = shape); - } - }); - } - } - fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) { use egui::{OutputCommand, ViewportCommand}; let restore = |s: &mut String| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 28b0cf05e5..f93350ca29 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3009,7 +3009,6 @@ impl RustGisApp { /// unsaved, and a rename makes a clean project unsaved: the browser doesn't say whether /// it wrote the file (the save prompt can be cancelled, the download blocked). pub(crate) fn save_download(&mut self, file: &str) -> Result<(), String> { - let file = i18n::outgoing(file); let file = file.trim(); let stem = if file.to_ascii_lowercase().ends_with(".rgis") { file.get(..file.len() - 5).unwrap_or(file) } else { file }.trim(); if stem.is_empty() || stem.contains(['/', '\\']) { @@ -3018,6 +3017,9 @@ impl RustGisApp { if self.services.download.is_none() { return Err(tl!("this build saves projects with Save As").into()); } + // The file is offered in logical order; the project keeps its name as it is painted. + let offered = i18n::outgoing(stem).chars().take(200).collect::(); + let stem = rustgis_engine::data::display_marks::unmarked(stem).unwrap_or_else(|| stem.to_owned()); let stem: String = stem.chars().take(200).collect(); // Not an undoable edit: saving names the project, as `project.saveAs` does. The name // stays set while the download is offered, and goes back if the download fails. @@ -3031,7 +3033,8 @@ impl RustGisApp { } }; let file = format!("{stem}.rgis"); - if let Err(e) = self.services.download.as_ref().ok_or(tl!("no download service"))?(&file, Arc::new(text.into_bytes())) { + let offered = format!("{offered}.rgis"); + if let Err(e) = self.services.download.as_ref().ok_or(tl!("no download service"))?(&offered, Arc::new(text.into_bytes())) { self.session.project.name = old; return Err(e); } @@ -3656,7 +3659,7 @@ impl RustGisApp { /// Runs a command by id: `ui.*` here, everything else in the engine. pub fn run(&mut self, id: &str, mut params: Value) -> Result { // Names and values made from interface text are data from here on. - i18n::outgoing_params(&mut params); + i18n::unmark_params(&mut params); #[cfg(not(target_arch = "wasm32"))] self.session.statistics_need_read_ahead(self.reads_off_frame); #[cfg(not(target_arch = "wasm32"))] @@ -7152,7 +7155,7 @@ impl RustGisApp { } Err(e) => { self.dialogs.info = None; - self.dialogs.error = Some(connectionui::translated(rustgis_engine::Session::redacted(e).as_str())); + self.dialogs.error = Some(i18n::shaped(&connectionui::translated(rustgis_engine::Session::redacted(e).as_str()))); } } } diff --git a/crates/ui-egui/src/plugindialog.rs b/crates/ui-egui/src/plugindialog.rs index 3c6e0cbda2..1c419302b0 100644 --- a/crates/ui-egui/src/plugindialog.rs +++ b/crates/ui-egui/src/plugindialog.rs @@ -138,8 +138,8 @@ fn keep(values: &Map, form: &[ParamDecl]) -> Map { /// A command's error as the dialog shows it: redacted as its notice is (an address's password or /// token left out), and cut like an answer. -fn error_shown(e: &str) -> String { - shown(rustgis_engine::Session::redacted(e).into_string()) +pub(crate) fn error_shown(e: &str) -> String { + crate::i18n::shaped(&shown(rustgis_engine::Session::redacted(e).into_string())) } /// The most of an answer the dialog shows, in bytes: a longer one would hold the window (in a diff --git a/crates/ui-egui/src/scriptcolor.rs b/crates/ui-egui/src/scriptcolor.rs index 63df7567fc..b33478cab1 100644 --- a/crates/ui-egui/src/scriptcolor.rs +++ b/crates/ui-egui/src/scriptcolor.rs @@ -387,9 +387,6 @@ pub fn layout(ui: &egui::Ui, script: &str, unknown: &[String], palette: Palette, let font = egui::TextStyle::Monospace.resolve(ui.style()); let mut job = ui.memory_mut(|m| m.caches.cache::().get((script, unknown, palette, &font)).clone()); job.wrap.max_width = wrap; - // As egui's own fields: it keeps what is typed in view, and says this galley is a field's, - // which the paint pass leaves as it was laid out. - job.keep_trailing_whitespace = true; ui.fonts_mut(|f| f.layout_job(job)) } From 568b8e0408211081d99e83e950862c73ee99f6d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 29 Nov 2026 06:14:41 -0500 Subject: [PATCH 6/6] fix(ui): take the display marks out of a queued plugin command --- crates/ui-egui/src/lib.rs | 4 +++- crates/ui-egui/src/pluginstart.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e93aaf55b2..6862eed518 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3606,7 +3606,9 @@ impl RustGisApp { /// Asks for plugin command `id`, which may wait for a server: the window says so first /// (#1319). Errors before it starts are notices too. - pub(crate) fn ask_plugin(&mut self, id: &str, params: Value) -> Result<(), String> { + pub(crate) fn ask_plugin(&mut self, id: &str, mut params: Value) -> Result<(), String> { + // Kept and run later, past `run`: its parameters lose the marks here. + i18n::unmark_params(&mut params); let notice_mark = self.session.notice_mark(); pluginstart::ask(self, id, params).inspect_err(|e| self.command_failed(id, e, notice_mark)) } diff --git a/crates/ui-egui/src/pluginstart.rs b/crates/ui-egui/src/pluginstart.rs index 9e7a5368c4..efc0a43ceb 100644 --- a/crates/ui-egui/src/pluginstart.rs +++ b/crates/ui-egui/src/pluginstart.rs @@ -274,6 +274,18 @@ mod tests { plugins::unload("ui-queued-url"); } + /// A queued plugin command's parameters lose the display marks, as any command's do. + #[test] + fn a_queued_command_keeps_no_display_mark() { + use rustgis_engine::data::display_marks::{LINE_END, LINE_START}; + let mut h = launch("ui-pinned-marks"); + let shown = format!("{LINE_START}Streams{LINE_END}"); + h.state_mut().run_by_user("plugin:ui-pinned-marks/f", rename("Rivers", &shown)).unwrap(); + h.run(); + assert!(h.state().session.map().layer_by_name("Streams").is_some()); + plugins::unload("ui-pinned-marks"); + } + /// The delay never transfers an admitted command to another load with the same plugin id. #[test] fn a_queued_command_refuses_a_replacement_plugin_load() {