diff --git a/crates/data/src/display_marks.rs b/crates/data/src/display_marks.rs new file mode 100644 index 0000000000..a14d032153 --- /dev/null +++ b/crates/data/src/display_marks.rs @@ -0,0 +1,115 @@ +//! 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 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. + +/// 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] +pub fn mirror(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '«' => '»', + '»' => '«', + '‹' => '›', + '›' => '‹', + c => c, + } +} + +/// `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 { + 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(|line| unmark_line(line, reorder)).collect::>().join("\n"); + (text != shown).then_some(text) +} + +/// 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); + let mut out = String::with_capacity(line.len()); + 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 reorder && in_run && !mark { + run.push(mirror(c)); + continue; + } + out.extend(run.drain(..).rev()); + if !mark { + out.push(if reorder && in_line { mirror(c) } else { c }); + } + } + out.extend(run.drain(..).rev()); + out +} + +/// 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 + } +} diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 4c843c95bb..8da411172b 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 a4188fdf3e..18464859e9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3727,7 +3727,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..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(|| notice.text.clone()) + .unwrap_or_else(|| crate::i18n::shaped(¬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..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(&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/filedialog.rs b/crates/ui-egui/src/filedialog.rs index 3f9cbe24ef..53daf72d7a 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 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()))) + } + + pub fn pick_file(self) -> Option { + self.0.pick_file() + } + + #[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() + } + + pub fn pick_folder(self) -> Option { + self.0.pick_folder() + } + + #[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() + } + } +} + #[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..3d8ae6b18d --- /dev/null +++ b/crates/ui-egui/src/i18n/boundary_tests.rs @@ -0,0 +1,233 @@ +//! Right-to-left display text paints rewritten, and leaves the screen in logical order. + +use egui::OutputCommand; +use rustgis_engine::data::display_marks::{MARKS, RUN_END, 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(MARKS) +} + +#[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_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_eq!(letters(&back), letters(piece), "{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_without_marks() { + let mut app = persian(); + let args = &[("distance", "500 m")]; + 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(); + // 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"); +} + +#[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.run_offering("project.exportLog", &format!("{shown}.jsonl"), json!({}), None).unwrap(); + set_current(Lang::EN); + assert_eq!(*offered.borrow(), [format!("{text}.csv"), format!("{text}.jsonl")]); +} + +#[test] +fn the_clipboard_and_the_window_title_get_logical_order() { + let 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(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| { + 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(); +} + +/// 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() { + set_current(fa()); + let (shown, _) = message(); + set_current(Lang::EN); + for mark in MARKS { + assert_eq!(logical(&format!("abc (d){mark} def")), None, "{mark:?}"); + } + // 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]), 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 kept_text_is_shaped_only_in_a_right_to_left_interface() { + let data = "رود GeoPackage 42"; + set_current(Lang::EN); + 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"); +} + +/// An error a dialog shows is redacted, which keeps it in logical order, and painted as before. +#[test] +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 144bbf79fa..35704e1230 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, unmarked}; + mod rtl; /// The preference value that follows the system. @@ -528,11 +531,74 @@ 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 fn display(logical: &str) -> String { - rtl::visual(logical) +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) +} + +/// 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) = unmarked(s) { + *s = text; + } + } + Value::Array(items) => items.iter_mut().for_each(unmark_params), + Value::Object(fields) => fields.values_mut().for_each(unmark_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 @@ -677,5 +743,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..ee92b0e748 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_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 @@ -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_START)); + out.extend(run.drain(..).rev().map(mirror)); + out.extend(marked.then_some(RUN_END)); + }; 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_START}{out}{LINE_END}") } /// `s` broken into lines whose display form is no wider than `max_width`, so the @@ -248,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 { @@ -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::MARKS; + + /// What is painted: the display form without its marks. + fn painted(s: &str) -> String { + s.replace(MARKS, "") + } + + 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 838e052267..6862eed518 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3044,8 +3044,10 @@ impl RustGisApp { /// so its file is the same and, in the browser, held to what a download may be. `offered` is /// what is said once the host has taken it, else that it was offered. pub(crate) fn run_offering(&mut self, command: &str, name: &str, mut params: Value, offered: Option) -> Result { + // The file's name is offered in logical order; the parameters are a command's, as in `run`. + i18n::unmark_params(&mut params); // A name is one file's: a `/` in a layer's isn't a folder. - let name = name.replace(['/', '\\'], "_"); + let name = i18n::outgoing(name).replace(['/', '\\'], "_"); // Of something without a name: an extension alone isn't read as one. let name = if name.rfind('.') == Some(0) { format!("untitled{name}") } else { name }; params.as_object_mut().ok_or(tl!("parameters are an object"))?.insert("path".into(), json!(name)); @@ -3086,6 +3088,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)) { @@ -3603,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)) } @@ -3681,7 +3686,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::unmark_params(&mut params); #[cfg(not(target_arch = "wasm32"))] self.session.statistics_need_read_ahead(self.reads_off_frame); #[cfg(not(target_arch = "wasm32"))] @@ -7065,7 +7072,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()))); } } } @@ -7315,6 +7322,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); 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/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() {