Skip to content
Merged
115 changes: 115 additions & 0 deletions crates/data/src/display_marks.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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<String> {
unmark(shown, false)
}

/// [`logical`] when `reorder`, else [`unmarked`].
fn unmark(shown: &str, reorder: bool) -> Option<String> {
if !shown.contains(MARKS) {
return None;
}
let text = shown.split('\n').map(|line| unmark_line(line, reorder)).collect::<Vec<_>>().join("\n");
(text != shown).then_some(text)
}

/// One line of [`unmark`].
fn unmark_line(line: &str, reorder: bool) -> String {
let chars: Vec<char> = line.chars().collect();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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<char> = 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 {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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<bool>,
/// Whether it is one of those two marks.
mark: Vec<bool>,
}

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
}
}
1 change: 1 addition & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 4 additions & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&notice.text, crate::i18n::fmt))
.unwrap_or_else(|| notice.text.clone())
.unwrap_or_else(|| crate::i18n::shaped(&notice.text))
}

/// A deferred message stays in logical order until the complete tooltip is shaped, including
Expand Down Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion crates/ui-egui/src/diagnosticlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
50 changes: 49 additions & 1 deletion crates/ui-egui/src/filedialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>, extensions: &[impl ToString]) -> Self {
Self(self.0.add_filter(&*outgoing(&name.into()), extensions))
}

pub fn set_title(self, title: impl Into<String>) -> 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<String>) -> Self {
Self(self.0.set_file_name(&*outgoing(&name.into())))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

pub fn pick_file(self) -> Option<PathBuf> {
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<Vec<PathBuf>> {
self.0.pick_files()
}

pub fn pick_folder(self) -> Option<PathBuf> {
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<PathBuf> {
self.0.save_file()
}
}
}

#[cfg(any(target_os = "android", target_os = "ios"))]
mod phone {
use std::path::PathBuf;
Expand Down
Loading
Loading