"), "running text became a table: {h}");
+ // The link is a run of its sentence, in its own colour (#4158).
+ assert!(h.contains("6.3. 2. All content shown at http"), "{h}");
for b in &p.blocks {
assert!(h.contains(&b.text), "{} was lost: {h}", b.text);
}
@@ -1487,6 +1638,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
};
let p = Page {
width: 612.0,
@@ -1541,4 +1693,158 @@ mod tests {
let rels = part(&zip, "word/_rels/document.xml.rels");
assert_eq!(rels.matches("relationships/image\"").count(), MAX_MEDIA);
}
+
+ /// The flowing paragraphs of a Word document (table cells left out), each as its runs' text
+ /// and whether the run is italic.
+ fn word_paragraphs(xml: &str) -> Vec> {
+ let body = xml.split("").map(|s| s.split_once("").map_or(s, |(_, after)| after)).collect::();
+ body.split("")
+ .skip(1)
+ .map(|p| {
+ let p = p.split_once("").map_or(p, |(inside, _)| inside);
+ p.split("")
+ .skip(1)
+ .filter_map(|r| {
+ let text = r.split_once("")?.1.split_once("")?.0;
+ Some((text.to_string(), r.contains("")))
+ })
+ .collect::>()
+ })
+ .filter(|runs| !runs.is_empty())
+ .collect()
+ }
+
+ fn runs(r: &[(&str, bool)]) -> Vec<(String, bool)> {
+ r.iter().map(|(t, i)| (t.to_string(), *i)).collect()
+ }
+
+ /// "Before *Chevron* after." on one line: the roman text, the italic case name and the roman
+ /// text after it, the way reading blocks split a sentence at its style changes (#4158). The
+ /// italic face stands a little taller than the roman one around it.
+ fn italic_sentence() -> Vec {
+ vec![
+ block("Before", 72.0, 700.0, 110.0, 712.0),
+ Block { italic: true, ..block("Chevron", 113.0, 700.0, 158.0, 712.6) },
+ block("after.", 161.0, 700.0, 190.0, 712.0),
+ ]
+ }
+
+ /// #4158: a run in another style inside a sentence stays in that sentence's paragraph, as a
+ /// run in its own style, in every Office format.
+ #[test]
+ fn an_italic_word_stays_in_its_sentence() {
+ let mut blocks = italic_sentence();
+ blocks.push(block("The next line is a paragraph of its own.", 72.0, 684.0, 300.0, 696.0));
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
+ assert_eq!(
+ word_paragraphs(&xml),
+ vec![runs(&[("Before ", false), ("Chevron ", true), ("after.", false)]), runs(&[("The next line is a paragraph of its own.", false)])],
+ "{xml}"
+ );
+ let h = html(std::slice::from_ref(&p), "Opinion");
+ assert!(h.contains("Before Chevron after.
"), "{h}");
+ let r = rtf(std::slice::from_ref(&p));
+ assert!(r.contains("{\\pard\\fs24 Before {\\fs24\\b0\\i\\cf0 Chevron }{\\fs24\\b0\\i0\\cf0 after.}\\par}"), "{r}");
+ // The longest line is the slide's title; the sentence is one paragraph of the body.
+ let pxml = part(&pptx(std::slice::from_ref(&p), "Opinion"), "ppt/slides/slide1.xml");
+ assert!(
+ pxml.contains("Before Chevron after."),
+ "{pxml}"
+ );
+ }
+
+ /// #4158: the runs keep their order along the line whatever order the blocks come in, and the
+ /// paragraph keeps its place on the page, though the italic run stands taller than the first.
+ #[test]
+ fn a_sentence_keeps_its_reading_order() {
+ let mut blocks = vec![block("Then the next line.", 72.0, 684.0, 200.0, 696.0)];
+ blocks.extend(italic_sentence().into_iter().rev());
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
+ assert_eq!(
+ word_paragraphs(&xml),
+ vec![runs(&[("Before ", false), ("Chevron ", true), ("after.", false)]), runs(&[("Then the next line.", false)])],
+ "{xml}"
+ );
+ }
+
+ /// The text of a block leaves out the spaces at its ends, and the box of a run often takes in
+ /// its trailing space, so runs can touch. The source's own space still separates them; runs
+ /// that touch with no space between them (a superscript) stay joined.
+ #[test]
+ fn runs_keep_the_spaces_the_source_had_between_them() {
+ let blocks = vec![
+ Block { space_around: [false, true], ..block("Before", 72.0, 700.0, 113.0, 712.0) },
+ Block { italic: true, ..block("Chevron", 113.0, 700.0, 158.0, 712.0) },
+ Block { space_around: [true, false], ..block("after.", 158.0, 700.0, 190.0, 712.0) },
+ block("E = mc", 72.0, 660.0, 110.0, 672.0),
+ Block { size: 8.0, ..block("2", 110.0, 665.0, 115.0, 673.0) },
+ ];
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Spaces"), "word/document.xml");
+ assert_eq!(
+ word_paragraphs(&xml),
+ vec![runs(&[("Before ", false), ("Chevron ", true), ("after.", false)]), runs(&[("E = mc", false), ("2", false)])],
+ "{xml}"
+ );
+ }
+ /// Text turned another way (a label up the margin) is not a run of the line it touches.
+ #[test]
+ fn turned_text_is_not_a_run_of_the_line_beside_it() {
+ let blocks = vec![block("Before", 72.0, 700.0, 110.0, 712.0), Block { rotation: 90.0, ..block("SIDE", 111.0, 690.0, 123.0, 720.0) }];
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let h = html(std::slice::from_ref(&p), "Turned");
+ assert!(h.contains("Before
") && h.contains("SIDE
"), "{h}");
+ }
+ /// A block that starts where the line above ends is the next line, not a run of it.
+ #[test]
+ fn a_block_on_the_next_line_starts_a_paragraph() {
+ let blocks = vec![
+ block("The first line ends here", 72.0, 700.0, 190.0, 712.0),
+ Block { italic: true, ..block("and the next starts there.", 190.5, 690.0, 320.0, 702.0) },
+ ];
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Lines"), "word/document.xml");
+ assert_eq!(word_paragraphs(&xml), vec![runs(&[("The first line ends here", false)]), runs(&[("and the next starts there.", true)])], "{xml}");
+ }
+
+ /// A superscript beside a table cell stays in the table: table detection consumes it before
+ /// paragraphs are formed, and a sentence after the table still keeps its italic run.
+ #[test]
+ fn table_cells_are_not_runs_of_a_paragraph() {
+ let mut blocks = vec![block("PLACE", 100.0, 700.0, 140.0, 712.0), block("PRIZE (euros)", 300.0, 700.0, 380.0, 712.0)];
+ for (n, (row, sup)) in [("1", "st"), ("2", "nd"), ("3", "rd")].iter().enumerate() {
+ let y = 680.0 - 20.0 * n as f64;
+ blocks.push(block(row, 100.0, y, 106.0, y + 12.0));
+ blocks.push(Block { size: 8.0, ..block(sup, 106.0, y + 5.0, 113.0, y + 13.0) });
+ blocks.push(block(&format!("{},000", 30 - 5 * n), 300.0, y, 340.0, y + 12.0));
+ }
+ blocks.extend(italic_sentence().into_iter().map(|b| Block { rect: [b.rect[0], b.rect[1] - 200.0, b.rect[2], b.rect[3] - 200.0], ..b }));
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Prizes"), "word/document.xml");
+ assert_eq!(xml.matches("").count(), 1, "{xml}");
+ for cell in ["st", "nd", "rd", "30,000"] {
+ assert_eq!(xml.matches(&format!("preserve\">{cell}")).count(), 1, "{cell}: {xml}");
+ }
+ // The cells are all in the table: the only flowing paragraph is the sentence.
+ assert_eq!(word_paragraphs(&xml), vec![runs(&[("Before ", false), ("Chevron ", true), ("after.", false)])], "{xml}");
+ }
+
+ /// A bold lead-in followed by body text on its line is body text, not a heading; a heading
+ /// with a smaller footnote marker after it stays a heading.
+ #[test]
+ fn a_paragraph_is_a_heading_only_when_its_text_is() {
+ let blocks = vec![
+ Block { size: 24.0, ..block("Annual Report", 72.0, 740.0, 250.0, 764.0) },
+ Block { size: 14.0, ..block("1", 251.0, 752.0, 258.0, 766.0) },
+ Block { bold: true, ..block("Summary", 72.0, 700.0, 125.0, 712.0) },
+ block("the year closed with more members than it opened with, and fewer debts.", 128.0, 700.0, 540.0, 712.0),
+ ];
+ let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
+ let xml = part(&docx(std::slice::from_ref(&p), "Report"), "word/document.xml");
+ assert_eq!(xml.matches("").count(), 1, "{xml}");
+ assert!(!xml.contains("Heading2"), "the lead-in made its paragraph a heading: {xml}");
+ assert_eq!(word_paragraphs(&xml).len(), 2, "{xml}");
+ }
}
diff --git a/crates/export/src/pptx.rs b/crates/export/src/pptx.rs
index 886a4bdbde..2edc0e25c9 100644
--- a/crates/export/src/pptx.rs
+++ b/crates/export/src/pptx.rs
@@ -1,11 +1,12 @@
//! PowerPoint presentation (.pptx, Office Open XML PresentationML): slides per page,
//! largest text as slide title, remaining paragraphs as body text, images and tables between them.
-use crate::{Block, Image, Page, Table, Zip, esc, hex};
+use crate::{Image, Page, Run, Table, Zip, esc, hex};
/// Items on a slide in reading order.
enum SlideBodyItem<'a> {
- Para(&'a Block),
+ /// A paragraph's runs (at least one).
+ Para(Vec>),
Table(Table),
Img(&'a Image),
}
@@ -136,11 +137,11 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec {
.map(|(i, _)| i);
let mut items: Vec<(f64, f64, SlideBodyItem)> = Vec::new();
- for (bi, b) in p.blocks.iter().enumerate() {
- if Some(bi) == title_idx || consumed.get(bi).copied().unwrap_or(false) {
- continue;
- }
- items.push((b.rect[3], b.rect[0], SlideBodyItem::Para(b)));
+ // The title is a shape of its own, so it joins no paragraph.
+ let skip: Vec = (0..p.blocks.len()).map(|bi| Some(bi) == title_idx || consumed.get(bi).copied().unwrap_or(false)).collect();
+ for runs in crate::paragraphs(&p.blocks, &skip) {
+ let Some(first) = runs.first().map(|r| r.block) else { continue };
+ items.push((first.rect[3], first.rect[0], SlideBodyItem::Para(runs)));
}
for t in tables {
items.push((t.rect[3], t.rect[0], SlideBodyItem::Table(t)));
@@ -173,11 +174,16 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec {
SlideBodyItem::Para(_) => {
let mut paras_xml = String::new();
let mut est_h_pt = 0.0;
- while let Some((_, _, SlideBodyItem::Para(b))) = items.get(i) {
- let run = run_drawingml(&b.text, b.size, b.bold, b.italic, b.color);
- paras_xml.push_str(&format!("{run}"));
- let lines = (b.text.len() as f64 / 60.0).ceil().max(1.0);
- est_h_pt += (b.size.max(10.0) * 1.3) * lines + 6.0;
+ while let Some((_, _, SlideBodyItem::Para(runs))) = items.get(i) {
+ paras_xml.push_str("");
+ for r in runs {
+ paras_xml.push_str(&run_drawingml(&r.text, r.block.size, r.block.bold, r.block.italic, r.block.color));
+ }
+ paras_xml.push_str("");
+ let len = runs.iter().map(|r| r.text.len()).fold(0usize, usize::saturating_add);
+ let size = runs.iter().map(|r| r.block.size).fold(10.0, f64::max);
+ let lines = (len as f64 / 60.0).ceil().max(1.0);
+ est_h_pt += (size * 1.3) * lines + 6.0;
i += 1;
}
let box_h = height_emu(est_h_pt);
@@ -354,6 +360,7 @@ xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" type=\"blank\"
#[cfg(test)]
mod tests {
use super::*;
+ use crate::Block;
use crate::tests::part;
fn sample_page() -> Page {
@@ -369,6 +376,7 @@ mod tests {
italic: false,
color: [0.1, 0.2, 0.3],
rotation: 0.0,
+ space_around: [false; 2],
},
Block {
text: "Revenue grew 25% year over year across all regions.".into(),
@@ -378,6 +386,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
},
Block {
text: "Operational expenses remained flat.".into(),
@@ -387,6 +396,7 @@ mod tests {
italic: true,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
},
],
images: vec![Image {
@@ -510,6 +520,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
};
let table_page = Page {
width: 612.0,
@@ -611,6 +622,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
};
let mut blocks = vec![huge("Title", f64::MAX, 500.0)];
for k in 0..40 {
@@ -682,6 +694,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
};
let p = Page {
width: 720.0,
@@ -696,6 +709,7 @@ mod tests {
italic: false,
color: [0.0; 3],
rotation: 0.0,
+ space_around: [false; 2],
},
// Table where one cell has a very large number (e.g. 36 pt callout in the table)
cell("Metric", 72.0, 400.0, 100.0, 12.0),
diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs
index bc87a16634..980c195709 100644
--- a/crates/fonts/build.rs
+++ b/crates/fonts/build.rs
@@ -2,7 +2,9 @@
//! The recipe is craft-fonts' `docs/integration.md`; unset, `CRAFT_FONTS` is empty. It only reads
//! the local checkout (no network). On wasm32 it embeds only the UI faces (BIZ UDPGothic Regular
//! and any `Arab`, `Telu`, `Hebr`, `Thai` or `Deva` face), to keep the web build within hosting
-//! limits (Cloudflare Pages: 25 MiB per file).
+//! limits (Cloudflare Pages: 25 MiB per file). Native builds also read the optional
+//! `fonts/simplified-chinese-manifest.txt` (LXGW WenKai Lite); it is never embedded on wasm.
+//! `CRAFT_FONTS_REQUIRED` makes both the checkout and that native manifest required.
use std::fmt::Write as _;
use std::path::PathBuf;
@@ -10,18 +12,21 @@ use std::path::PathBuf;
#[path = "src/cjk_scripts.rs"]
mod cjk_scripts;
+/// Build-script entry point: embed craft-fonts from `CRAFT_FONTS_DIR`, make a missing or invalid input fatal
+/// when `CRAFT_FONTS_REQUIRED` is set, and write `craft_fonts.rs` to `OUT_DIR`.
fn main() {
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
+ let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) {
- match craft_fonts(&dir) {
+ match craft_fonts(&dir, required) {
Ok(entries) => src.push_str(&entries),
- Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => {
- println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display());
- }
+ Err(e) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()),
Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()),
}
+ } else if required {
+ println!("cargo::error=CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing");
}
src.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");
@@ -30,26 +35,66 @@ fn main() {
}
}
-/// One `CraftFont { .. }` initialiser per manifest line.
-fn craft_fonts(dir: &std::path::Path) -> Result {
- let manifest = dir.join("fonts/manifest.txt");
- println!("cargo::rerun-if-changed={}", manifest.display());
- let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
+/// The main manifest, plus the native-only Simplified Chinese manifest. The latter is optional
+/// for ordinary builds and required when `CRAFT_FONTS_REQUIRED` is set, so a required build can
+/// never pass the Chinese UI tests only by skipping them.
+fn craft_fonts(dir: &std::path::Path, required: bool) -> Result {
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
+ let mut out = manifest(dir, &dir.join("fonts/manifest.txt"), wasm, false)?;
+ if !wasm {
+ let chinese = dir.join("fonts/simplified-chinese-manifest.txt");
+ println!("cargo::rerun-if-changed={}", chinese.display());
+ match chinese.try_exists() {
+ Ok(false) if required => {
+ return Err(format!("{}: CRAFT_FONTS_REQUIRED is set but the simplified-Chinese font manifest is missing", chinese.display()));
+ }
+ Ok(false) => {}
+ Ok(true) => match manifest(dir, &chinese, false, required) {
+ Ok(entries) => out.push_str(&entries),
+ // A broken optional addition must never discard the main Japanese/symbol/RTL faces.
+ Err(e) if required => return Err(e),
+ Err(e) => println!("cargo::warning=skipping optional Chinese fonts: {e}"),
+ },
+ Err(e) if required => return Err(format!("{}: {e}", chinese.display())),
+ Err(e) => println!("cargo::warning=skipping optional Chinese fonts: {}: {e}", chinese.display()),
+ }
+ }
+ Ok(out)
+}
+
+/// One `CraftFont { .. }` initialiser per manifest line.
+///
+/// `strict_cap` is set for the required native Simplified Chinese manifest: a face that does not
+/// fit its cap must fail the build rather than be silently left out, so a required build cannot
+/// pass without the Chinese face it promises.
+fn manifest(dir: &std::path::Path, manifest: &std::path::Path, wasm: bool, strict_cap: bool) -> Result {
+ println!("cargo::rerun-if-changed={}", manifest.display());
+ let text = std::fs::read_to_string(manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
let mut out = String::new();
+ // A required native Chinese manifest must add the Hans face itself, not merely some other
+ // CJK face that happens to fit: otherwise CRAFT_FONTS_REQUIRED would pass while the promised
+ // Simplified Chinese fallback is still absent.
+ let mut has_hans = false;
for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
let f: Vec<&str> = line.split(" | ").map(str::trim).collect();
let [family, style, file, scripts, ..] = f.as_slice() else {
return Err(format!("malformed manifest line: {line}"));
};
- // Whole CJK faces aren't embedded for size; interface CJK comes from cut faces once the app
- // moves to craft-fonts-build (storytold/craft-libs#213).
+ // Keep the upstream general CJK size cap. The separately pinned native Chinese UI
+ // face has its own bound; web builds retain the smaller general limit. A required
+ // Chinese face over its cap fails the build instead of being silently omitted.
let cjk = scripts.split(',').any(cjk_scripts::is_cjk_script);
- if cjk
- && !cjk_scripts::WHOLE_CJK_FAMILIES.contains(family)
- && std::fs::metadata(dir.join(file)).is_ok_and(|m| m.len() > cjk_scripts::MAX_OTHER_CJK_BYTES)
- {
- continue;
+ if cjk && let Ok(metadata) = std::fs::metadata(dir.join(file)) {
+ match cjk_scripts::cjk_size_decision(family, metadata.len(), wasm, strict_cap) {
+ cjk_scripts::CjkSizeDecision::Embed => {}
+ cjk_scripts::CjkSizeDecision::Skip => continue,
+ cjk_scripts::CjkSizeDecision::Reject => {
+ let cap = cjk_scripts::cjk_cap_bytes(family, wasm);
+ return Err(format!(
+ "{file}: the {family} face is larger than the {cap}-byte native Chinese UI cap; CRAFT_FONTS_REQUIRED cannot embed it"
+ ));
+ }
+ }
}
// Arabic interface faces are small, so the web build keeps them too.
let arabic = scripts.split(',').any(|s| s.trim() == "Arab");
@@ -68,6 +113,7 @@ fn craft_fonts(dir: &std::path::Path) -> Result {
if wasm && !web_face {
continue;
}
+ has_hans |= cjk_scripts::has_script_tag(scripts, "Hans");
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
println!("cargo::rerun-if-changed={}", path.display());
let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();
@@ -78,5 +124,36 @@ fn craft_fonts(dir: &std::path::Path) -> Result {
path.display().to_string(),
);
}
+ if strict_cap && !has_hans {
+ return Err(format!(
+ "{}: CRAFT_FONTS_REQUIRED is set but the manifest emits no Hans face (a Simplified Chinese face is required)",
+ manifest.display()
+ ));
+ }
Ok(out)
}
+
+#[cfg(test)]
+mod manifest_tests {
+ use super::*;
+
+ /// Regression test: a required native-font manifest must declare at least one Hans face, while optional
+ /// input accepts another script and a missing asset still fails.
+ #[test]
+ fn required_native_manifest_rejects_non_hans_faces_after_parsing() {
+ let root = std::env::temp_dir().join(format!("pdfcraft-required-hans-{}", std::process::id()));
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::write(root.join("face.ttf"), b"synthetic manifest fixture").unwrap();
+ let path = root.join("manifest.txt");
+ for scripts in ["Hant,Latn", "Hans-HK,Latn", "Latn"] {
+ std::fs::write(&path, format!("Fixture | Regular | face.ttf | {scripts}\n")).unwrap();
+ assert!(manifest(&root, &path, false, true).unwrap_err().contains("no Hans face"), "{scripts}");
+ assert!(manifest(&root, &path, false, false).unwrap().contains("CraftFont {"), "optional input stays usable");
+ }
+ std::fs::write(&path, "Fixture | Regular | face.ttf | Latn, Hans\n").unwrap();
+ assert!(manifest(&root, &path, false, true).unwrap().contains("CraftFont {"));
+ std::fs::remove_file(root.join("face.ttf")).unwrap();
+ assert!(manifest(&root, &path, false, true).is_err(), "a missing Hans asset cannot satisfy required input");
+ std::fs::remove_dir_all(root).unwrap();
+ }
+}
diff --git a/crates/fonts/src/cjk_scripts.rs b/crates/fonts/src/cjk_scripts.rs
index 16a863c683..1058c6e61b 100644
--- a/crates/fonts/src/cjk_scripts.rs
+++ b/crates/fonts/src/cjk_scripts.rs
@@ -8,6 +8,11 @@ pub const WHOLE_CJK_FAMILIES: [&str; 3] = ["Shippori Mincho", "BIZ UDPGothic", "
/// Any other CJK face over this size is left out.
pub const MAX_OTHER_CJK_BYTES: u64 = 4 << 20;
+/// Reviewed native-only UI fallback from the separate Chinese manifest.
+/// It is never included in the browser payload. Other CJK families keep the 4 MiB cap.
+pub const NATIVE_UI_CJK_FAMILIES: [&str; 1] = ["LXGW WenKai Lite"];
+pub const MAX_NATIVE_UI_CJK_BYTES: u64 = 16 << 20;
+
/// ISO 15924 codes of the Han, Japanese and Korean scripts, Hangul on its own included.
const CJK_SCRIPTS: [&str; 6] = ["Hani", "Hans", "Hant", "Jpan", "Kore", "Hang"];
@@ -17,3 +22,76 @@ pub fn is_cjk_script(tag: &str) -> bool {
let code = tag.trim().split('-').next().unwrap_or_default();
CJK_SCRIPTS.contains(&code)
}
+
+/// Whether a manifest's comma-separated script list contains `script` exactly, ignoring spaces.
+/// The interface and document lookups use exact tags (`CraftFont::covers`), so a regional tag
+/// such as `Hans-HK` is not a `Hans` entry.
+pub fn has_script_tag(scripts: &str, script: &str) -> bool {
+ scripts.split(',').any(|tag| tag.trim() == script)
+}
+
+/// What `build.rs` does with one CJK face from a manifest.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CjkSizeDecision {
+ /// The face fits its cap (or is a Japanese family embedded whole).
+ Embed,
+ /// An optional face over its cap: leave it out and keep the rest.
+ Skip,
+ /// A required face over its cap: fail the build rather than silently omit it.
+ Reject,
+}
+
+/// The size cap that applies to `family` in this build.
+pub fn cjk_cap_bytes(family: &str, wasm: bool) -> u64 {
+ if !wasm && NATIVE_UI_CJK_FAMILIES.contains(&family) { MAX_NATIVE_UI_CJK_BYTES } else { MAX_OTHER_CJK_BYTES }
+}
+
+/// Decide whether a CJK face is embedded, skipped, or rejected.
+///
+/// The Japanese document/UI families are embedded whole. Every other CJK family uses its cap;
+/// `required` marks the native Simplified Chinese manifest of a `CRAFT_FONTS_REQUIRED` build,
+/// where an over-cap face must fail instead of quietly disappearing.
+pub fn cjk_size_decision(family: &str, bytes: u64, wasm: bool, required: bool) -> CjkSizeDecision {
+ if WHOLE_CJK_FAMILIES.contains(&family) {
+ return CjkSizeDecision::Embed;
+ }
+ if bytes <= cjk_cap_bytes(family, wasm) {
+ CjkSizeDecision::Embed
+ } else if required {
+ CjkSizeDecision::Reject
+ } else {
+ CjkSizeDecision::Skip
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Check that a required Chinese manifest needs an exact `Hans` script tag and does not accept
+ /// Traditional or region-suffixed tags.
+ #[test]
+ fn a_required_chinese_manifest_needs_an_exact_hans_entry() {
+ assert!(has_script_tag("Hans,Latn", "Hans"));
+ assert!(has_script_tag(" Latn , Hans ", "Hans"));
+ assert!(!has_script_tag("Hant,Latn", "Hans"), "Traditional Chinese is not the required Simplified face");
+ assert!(!has_script_tag("Hans-HK,Latn", "Hans"), "the UI looks for the exact Hans tag");
+ assert!(!has_script_tag("Hani,Jpan,Kore", "Hans"));
+ }
+
+ /// Check that a native Chinese face over its cap is rejected when required, skipped when optional, and
+ /// uses the web cap on the web.
+ #[test]
+ fn a_required_native_chinese_face_over_its_cap_is_rejected_not_skipped() {
+ let at_cap = MAX_NATIVE_UI_CJK_BYTES;
+ assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap, false, true), CjkSizeDecision::Embed);
+ assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap + 1, false, true), CjkSizeDecision::Reject);
+ assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap + 1, false, false), CjkSizeDecision::Skip);
+ // The web build keeps the smaller general cap even for the native Chinese family.
+ assert_eq!(cjk_size_decision("LXGW WenKai Lite", MAX_OTHER_CJK_BYTES + 1, true, true), CjkSizeDecision::Reject);
+ // Japanese document/UI families are embedded whole.
+ assert_eq!(cjk_size_decision("BIZ UDPGothic", u64::MAX, false, true), CjkSizeDecision::Embed);
+ assert_eq!(cjk_cap_bytes("LXGW WenKai Lite", false), MAX_NATIVE_UI_CJK_BYTES);
+ assert_eq!(cjk_cap_bytes("LXGW WenKai Lite", true), MAX_OTHER_CJK_BYTES);
+ }
+}
diff --git a/crates/fonts/src/craft.rs b/crates/fonts/src/craft.rs
index e778a42ad7..dff96762aa 100644
--- a/crates/fonts/src/craft.rs
+++ b/crates/fonts/src/craft.rs
@@ -315,12 +315,13 @@ mod tests {
}
/// `build.rs` embeds the Japanese CJK faces whole and any other CJK face only up to
- /// `MAX_OTHER_CJK_BYTES`, so a checkout with a large Chinese or Korean face (craft-fonts has the
+ /// `MAX_OTHER_CJK_BYTES` (the explicitly pinned native-only LXGW UI fallback has a separate
+ /// 16 MiB cap), so a checkout with a large Chinese or Korean face (craft-fonts has the
/// 16.4 MB Noto Sans CJK SC) leaves it out. The four Japanese faces of the pinned craft-fonts
/// are 24.1 MB.
#[test]
fn cjk_faces_follow_the_size_rule() {
- use crate::cjk_scripts::{MAX_OTHER_CJK_BYTES, WHOLE_CJK_FAMILIES, is_cjk_script};
+ use crate::cjk_scripts::{MAX_NATIVE_UI_CJK_BYTES, MAX_OTHER_CJK_BYTES, NATIVE_UI_CJK_FAMILIES, WHOLE_CJK_FAMILIES, is_cjk_script};
// A tag can carry a region after the code: craft-fonts tags Noto Sans HK UI `Hant-HK`.
assert!(["Hant-HK", "Hans", "Jpan", "Hang"].iter().all(|s| is_cjk_script(s)));
assert!(!["Latn", "Arab", "Hebr"].iter().any(|s| is_cjk_script(s)));
@@ -328,7 +329,10 @@ mod tests {
let (whole, other): (Vec<_>, Vec<_>) = cjk.partition(|f| WHOLE_CJK_FAMILIES.contains(&f.family));
for face in &other {
let len = face.bytes.len();
- assert!(u64::try_from(len).is_ok_and(|n| n <= MAX_OTHER_CJK_BYTES), "{} is embedded at {len} bytes", face.name());
+ let native_ui = NATIVE_UI_CJK_FAMILIES.contains(&face.family);
+ assert!(!cfg!(target_arch = "wasm32") || !native_ui, "native UI face in web payload");
+ let cap = if native_ui { MAX_NATIVE_UI_CJK_BYTES } else { MAX_OTHER_CJK_BYTES };
+ assert!(u64::try_from(len).is_ok_and(|n| n <= cap), "{} is embedded at {len} bytes", face.name());
}
let bytes: usize = whole.iter().map(|f| f.bytes.len()).sum();
assert!(bytes < 25_000_000, "{bytes} bytes of Japanese faces");
diff --git a/crates/fonts/tests/build_input.rs b/crates/fonts/tests/build_input.rs
new file mode 100644
index 0000000000..832cc2c16c
--- /dev/null
+++ b/crates/fonts/tests/build_input.rs
@@ -0,0 +1,4 @@
+//! Required manifest checks execute the same parser as the production build script.
+#[allow(dead_code)]
+#[path = "../build.rs"]
+mod build_script;
diff --git a/crates/forms/README.md b/crates/forms/README.md
index 2c24ddc6cf..93b65bd14e 100644
--- a/crates/forms/README.md
+++ b/crates/forms/README.md
@@ -60,7 +60,9 @@ let cells: Vec = grid.cells_for(names)?; // "Table1_1", "Table
drawing while the objects it was drawn from are the same (`FieldAppearanceCache`), so typing in
one field redraws that field, not the form. Check boxes and radio buttons with no appearance for
their state are drawn from `/MK` (border, background, and when on the `/MK /CA` ZapfDingbats
- symbol in the `/DA` colour), and push buttons with none from `/MK`, `/BS` and their caption.
+ symbol in the `/DA` colour), and with `/NeedAppearances` so is every one that has an `/MK`,
+ over the appearance the file carries; push buttons with none are drawn from `/MK`, `/BS` and
+ their caption.
- Check boxes and radio buttons switch `/V` and each widget's `/AS`. Widgets with no appearances
get PdfCraft's own (a drawn check mark or dot; no symbol font needed).
- Imported `/MaxLen 0` is treated as unlimited (also clearing an inherited limit), while the
diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs
index 49fa21e76c..c1bb5630a6 100644
--- a/crates/forms/src/appearance.rs
+++ b/crates/forms/src/appearance.rs
@@ -1029,9 +1029,10 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64, color:
}
/// How a check box or radio button widget `w` of field `f` looks in state on (`on`) or Off when
-/// the file has no appearance for that state: its `/MK` background and border ([`frame`]), and
-/// when on, its caption `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes
-/// and radio buttons may use too) as a ZapfDingbats character, as in the check box example of
+/// the file has no appearance for that state, or leaves its appearances to the viewer
+/// (`/NeedAppearances`): its `/MK` background and border ([`frame`]), and when on, its caption
+/// `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes and radio buttons may
+/// use too) as a ZapfDingbats character, as in the check box example of
/// 12.7.5.2.3: `4` (a check mark) by default, `l` (a dot) for a radio button. The character is
/// drawn in the `/DA` colour, at the `/DA` size or, for an automatic size (`0 Tf`), filling most
/// of the box. ZapfDingbats is one of the standard 14 fonts, so no font program is needed.
diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs
index ffd67899cc..39cebd8fdd 100644
--- a/crates/forms/src/lib.rs
+++ b/crates/forms/src/lib.rs
@@ -1553,8 +1553,9 @@ pub fn need_appearances(doc: &Document) -> bool {
/// writer left the appearances to the viewer), and otherwise each widget without a normal
/// appearance (`/AP /N`), as typing the value would draw it (#3470). Check boxes and radio buttons
/// with no normal appearance for their state (`/AS`) are drawn from their `/MK` background, border
-/// and caption, and push buttons with none from their `/MK` and `/BS` (Table 192). `doc` is not
-/// changed: saving writes the file as it was.
+/// and caption, and with `/NeedAppearances` every one that has an `/MK` is, over its own
+/// appearance; push buttons with none are drawn from their `/MK` and `/BS` (Table 192). `doc` is
+/// not changed: saving writes the file as it was.
pub fn with_field_appearances(doc: &Document) -> Option {
with_field_appearances_cached(doc, &mut FieldAppearanceCache::default())
}
@@ -1572,19 +1573,25 @@ pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearance
.and_then(|d| d.get(b"AP"))
.and_then(|ap| doc.resolve(ap).as_dict().and_then(|ap| ap.get(b"N").map(|n| doc.resolve(n))));
// A check box or radio button shows the appearance of its state (12.7.5.2.3): `/AS`,
- // else a check box's value, else Off. An Off state may go without one (it shows
- // nothing); an on state needs one.
+ // else the value when it names this widget's on state (any check box value when the
+ // widget names none), else Off. An Off state may go without one (it shows nothing);
+ // an on state needs one.
let state = match f.kind {
FieldKind::CheckBox | FieldKind::Radio => {
- let value = f.value.first().filter(|v| f.kind == FieldKind::CheckBox && !v.is_empty() && v.as_str() != "Off");
+ let mine = |v: &&String| w.on_state.as_ref().map_or(f.kind == FieldKind::CheckBox, |on| on == *v);
+ let value = f.value.first().filter(|v| !v.is_empty() && v.as_str() != "Off").filter(mine);
Some(w.state.clone().or_else(|| value.cloned()).unwrap_or_else(|| "Off".into()))
}
_ => None,
};
+ // With /NeedAppearances a check box or radio button that describes its look in /MK is
+ // drawn from it (Table 192), its own appearance or not; one without /MK keeps its own.
+ let described = || widget.as_dict().and_then(|d| d.get(b"MK")).is_some_and(|mk| doc.resolve(mk).as_dict().is_some());
let missing = match f.kind {
FieldKind::Text | FieldKind::Combo | FieldKind::List => normal.is_none() || all,
FieldKind::PushButton => normal.is_none(),
FieldKind::CheckBox | FieldKind::Radio => match (normal.as_deref(), state.as_deref()) {
+ _ if all && described() => true,
(None, _) => true,
(Some(Object::Dict(states)), Some(s)) => s != "Off" && !states.contains(&name_bytes(s)),
_ => false,
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index 903e8b6fcd..61dab131e0 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -4360,6 +4360,82 @@ fn comb_fields_show_their_cells() {
assert!(!plain.contains(" m ") && plain.contains("(A) Tj"), "{plain}");
}
+/// Check boxes and radio buttons with an `/MK` look and appearances of their own, in a form that
+/// sets `/NeedAppearances` (`need`) or not.
+fn mk_buttons(need: bool) -> Document {
+ let flag = if need { "/NeedAppearances true " } else { "" };
+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /FT /Btn /T ({n}) /F 4 /P 3 0 R {rest} >>");
+ let states = |on: &str| format!("/AP << /N << /{on} 15 0 R /Off 16 0 R >> >>");
+ document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] >>".into(),
+ format!(
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>"
+ ),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ widget("check", &format!("/V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [50 700 74 724] {}", states("Yes"))), // 6
+ widget("cross", &format!("/V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) >> /Rect [100 700 124 724] {}", states("Yes"))),
+ widget("diamond", &format!("/V /Yes /AS /Yes /MK << /CA (u) /BG [1 1 0] >> /Rect [150 700 174 724] {}", states("Yes"))),
+ widget("square", &format!("/V /Yes /AS /Yes /MK << /CA (n) >> /Rect [200 700 224 724] {}", states("Yes"))),
+ widget("star", &format!("/V /Yes /AS /Yes /MK << /CA (H) >> /Rect [250 700 274 724] {}", states("Yes"))), // 10
+ widget("off", &format!("/V /Off /AS /Off /MK << /BC [0 0 0] /CA (4) >> /Rect [300 700 324 724] {}", states("Yes"))),
+ widget("radio", &format!("/Ff 32768 /V /B /MK << /BC [0 0 1] /CA (l) >> /Rect [350 700 374 724] {}", states("B"))),
+ widget("plain", &format!("/V /Yes /AS /Yes /Rect [400 700 424 724] {}", states("Yes"))),
+ widget(
+ "odd",
+ &format!(
+ "/V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724] {}",
+ states("Yes")
+ ),
+ ),
+ "<< /Length 24 >>\nstream\n0 g 4 4 16 16 re f\nendstream".into(), // 15: a filled square
+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(),
+ ])
+}
+
+/// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its
+/// appearances to the viewer shows each check box and radio button with an `/MK` drawn from it,
+/// over the appearance the file carries: the caption's ZapfDingbats symbol in the `/DA` colour
+/// when on, only the border when off. A widget with no `/MK` keeps its own; the file is untouched.
+#[test]
+fn need_appearances_draws_check_boxes_and_radio_buttons_from_their_captions() {
+ let doc = mk_buttons(true);
+ let copy = with_field_appearances(&doc).expect("buttons to draw");
+ let all = fields(©);
+ for (name, state, symbol, colour) in [
+ ("check", "Yes", "(4) Tj", "0 g"),
+ ("cross", "Yes", "(8) Tj", "1 0 0 rg"),
+ ("diamond", "Yes", "(u) Tj", "0 g"),
+ ("square", "Yes", "(n) Tj", "0 g"),
+ ("star", "Yes", "(H) Tj", "0 g"),
+ ("radio", "B", "(l) Tj", "0 g"),
+ ] {
+ let shown = state_ap(©, &field(&all, name).widgets[0], state);
+ assert!(shown.contains(symbol) && shown.contains(&format!("{colour}\n")), "{name}: {shown}");
+ assert!(!shown.contains("4 4 16 16 re f"), "{name} is not the file's filled square: {shown}");
+ }
+ let check = state_ap(©, &field(&all, "check").widgets[0], "Yes");
+ assert!(check.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "the /BC border: {check}");
+ assert!(state_ap(©, &field(&all, "diamond").widgets[0], "Yes").contains("1 1 0 rg\n0 0 24 24 re f"), "the /BG background");
+ assert!(state_ap(©, &field(&all, "radio").widgets[0], "B").contains("0 0 1 RG"), "the radio's own border");
+ let off = state_ap(©, &field(&all, "off").widgets[0], "Off");
+ assert!(off.contains("re S") && !off.contains("Tj"), "off: only the border: {off}");
+ // Nonsense in /MK, /DA and /BS: the default check, no border, and no panic.
+ let odd = state_ap(©, &field(&all, "odd").widgets[0], "Yes");
+ assert!(odd.contains("(4) Tj") && !odd.contains("re S"), "{odd}");
+ let own = |d: &Document, name: &str| d.get(field(&fields(d), name).widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());
+ assert_eq!(own(©, "plain"), own(&doc, "plain"), "a box without /MK keeps its own look");
+ assert_eq!(state_ap(&doc, &field(&fields(&doc), "check").widgets[0], "Yes").trim_end(), "0 g 4 4 16 16 re f", "the file is untouched");
+}
+
+/// Without `/NeedAppearances` the file's own check box and radio button appearances are shown
+/// as they are, `/MK` or not: no copy is needed.
+#[test]
+fn without_need_appearances_buttons_keep_their_own_appearances() {
+ assert!(with_field_appearances(&mk_buttons(false)).is_none());
+}
+
/// A form for filling many values at once: two summed fields and their calculated total, a
/// name two field dictionaries share, a check box, a radio group, a list and a read-only field.
fn batch_form() -> Document {
diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs
index bc0454c999..e6432d8aec 100644
--- a/crates/print/src/tests.rs
+++ b/crates/print/src/tests.rs
@@ -283,8 +283,8 @@ fn spooler_arguments_and_printer_list() {
assert_eq!(
parse_lpstat(out),
[
- spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None },
- spool::Printer { name: "Label_Writer".into(), default: false, two_sided: None }
+ spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None, description: String::new() },
+ spool::Printer { name: "Label_Writer".into(), default: false, two_sided: None, description: String::new() }
]
);
assert!(parse_lpstat("lpstat: No destinations added.\nno system default destination\n").is_empty());
@@ -327,18 +327,21 @@ fn driverless_printers_join_the_list_without_a_queue() {
assert_eq!(
spool::printers_parsed(queues, Some("Basement_Color\nOffice_Laser\n")),
[
- spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None },
- spool::Printer { name: "Basement_Color".into(), default: false, two_sided: None },
+ spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None, description: String::new() },
+ spool::Printer { name: "Basement_Color".into(), default: false, two_sided: None, description: String::new() },
],
"queues first, then the driverless destination; the queue listed twice is not doubled"
);
// An old spooler without `-e` (CUPS < 1.7) keeps its queues; only the driverless names are lost.
- assert_eq!(spool::printers_parsed(queues, None), [spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None }]);
+ assert_eq!(
+ spool::printers_parsed(queues, None),
+ [spool::Printer { name: "Office_Laser".into(), default: true, two_sided: None, description: String::new() }]
+ );
// The default can itself be driverless (`lpoptions -d` names a destination no queue exists
// for): it keeps its marker, so the dialog preselects the user's default, not the first queue.
assert_eq!(
spool::printers_parsed("system default destination: Basement_Color\n", Some("Basement_Color\n")),
- [spool::Printer { name: "Basement_Color".into(), default: true, two_sided: None }],
+ [spool::Printer { name: "Basement_Color".into(), default: true, two_sided: None, description: String::new() }],
"a default destination without a queue is still the default"
);
assert!(spool::parse_lpstat_e("\n \n").is_empty(), "no destinations is empty, not [\"\"]");
@@ -414,17 +417,17 @@ fn windows_printers_carry_one_default_and_keep_their_names() {
// Windows marks the system default with a `*` no queue name may contain; names hold spaces,
// parentheses and non-ASCII letters, and the lines end with CRLF.
let printers = parse_windows_printers("*Microsoft Print to PDF\r\nHP LaserJet 400 (Copy 2)\r\nКопир Canon iR\r\n\r\n*XPS via USB\r\n");
- assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), default: true, two_sided: None });
- assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false, two_sided: None });
- assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), default: false, two_sided: None });
+ assert_eq!(printers[0], Printer { name: "Microsoft Print to PDF".into(), default: true, two_sided: None, description: String::new() });
+ assert_eq!(printers[1], Printer { name: "HP LaserJet 400 (Copy 2)".into(), default: false, two_sided: None, description: String::new() });
+ assert_eq!(printers[2], Printer { name: "Копир Canon iR".into(), default: false, two_sided: None, description: String::new() });
// A spooler marking two defaults: the first still wins, so the dialog has one to preselect.
- assert_eq!(printers[3], Printer { name: "XPS via USB".into(), default: false, two_sided: None });
+ assert_eq!(printers[3], Printer { name: "XPS via USB".into(), default: false, two_sided: None, description: String::new() });
assert_eq!(parse_windows_printers("\r\n"), Vec::new());
// After a tab, whether the driver reports two-sided printing; a tab inside a name stays.
let sided = parse_windows_printers("*Office PCL\t2\r\nOffice PS\t1\r\nTab\tName\t2\r\n");
- assert_eq!(sided[0], Printer { name: "Office PCL".into(), default: true, two_sided: Some(true) });
- assert_eq!(sided[1], Printer { name: "Office PS".into(), default: false, two_sided: Some(false) });
- assert_eq!(sided[2], Printer { name: "Tab\tName".into(), default: false, two_sided: Some(true) });
+ assert_eq!(sided[0], Printer { name: "Office PCL".into(), default: true, two_sided: Some(true), description: String::new() });
+ assert_eq!(sided[1], Printer { name: "Office PS".into(), default: false, two_sided: Some(false), description: String::new() });
+ assert_eq!(sided[2], Printer { name: "Tab\tName".into(), default: false, two_sided: Some(true), description: String::new() });
}
/// A PPD shaped like a Fiery's: installable options, multi-line PostScript in the choices, Latin-1
diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs
index fa39853a7f..8b94612145 100644
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@ -2265,6 +2265,74 @@ fn unselected_pages_keep_inherited_forms() {
assert_eq!(under(&mut saved, 1, &[[0.0, 190.0, 300.0, 220.0]]), 6);
}
+#[test]
+fn nested_resource_less_forms_keep_live_resources_after_redacting_another_page() {
+ for own_resources in [false, true] {
+ for still_drawn in [false, true] {
+ let original = b"BT /F1 10 Tf 10 200 Td (SECRET) Tj ET";
+ let mut extra = vec![
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", original),
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", if still_drawn { b"/Fm Do".as_slice() } else { b"q Q".as_slice() }),
+ ];
+ if own_resources {
+ extra.push(stream(
+ "/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> /XObject << /Fm 7 0 R /Relay 8 0 R >> >>",
+ b"/Relay Do",
+ ));
+ }
+ let resources =
+ if own_resources { "/XObject << /Fm 7 0 R /Relay 8 0 R /Wrapper 9 0 R >>" } else { "/XObject << /Fm 7 0 R /Relay 8 0 R >>" };
+ let mut doc = one_page(b"/Fm Do", resources, extra);
+ let mut page = doc.get(ObjRef::new(3, 0)).as_dict().unwrap().clone();
+ let inherited = page.remove(b"Resources").unwrap();
+ doc.set(ObjRef::new(3, 0), Object::Dict(page.clone()));
+ let second_content =
+ doc.add(Object::Stream(Stream::from_raw(Dict::new(), if own_resources { b"/Wrapper Do".to_vec() } else { b"/Relay Do".to_vec() })));
+ page.set(b"Contents".to_vec(), Object::Ref(second_content));
+ let second = doc.add(Object::Dict(page));
+ doc.update_dict(ObjRef::new(2, 0), |d| {
+ d.set(b"Resources".to_vec(), inherited);
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(3, 0)), Object::Ref(second)]));
+ d.set(b"Count".to_vec(), Object::Int(2));
+ })
+ .unwrap();
+
+ let region = [[0.0, 190.0, 300.0, 220.0]];
+ let surviving = if still_drawn { 6 } else { 0 };
+ assert_eq!(under(&mut doc, 0, ®ion), 6, "the marked occurrence is real text");
+ assert_eq!(under(&mut doc, 1, ®ion), surviving, "the relay's original nested content is visible");
+ mark(&mut doc, 0, ®ion, "");
+ let report = apply(&mut doc, Some(&[0])).unwrap();
+ assert_eq!((report.marks, report.glyphs), (1, 6));
+ assert_eq!(under(&mut doc, 0, ®ion), 0);
+ assert_eq!(under(&mut doc, 1, ®ion), surviving, "redacting another page must preserve live nested content");
+
+ // A full saved document must retain both the reachable resource and its content,
+ // without relying on an old incremental revision's otherwise-unreachable objects.
+ let mut saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();
+ assert_eq!(under(&mut saved, 0, ®ion), 0);
+ assert_eq!(under(&mut saved, 1, ®ion), surviving);
+ let page = pdfcraft_model::pages(&saved).swap_remove(1);
+ let res = saved.resolve(page.dict.get(b"Resources").unwrap());
+ let xo = saved.resolve(res.as_dict().unwrap().get(b"XObject").unwrap());
+ let mut holder = xo.as_dict().unwrap().clone();
+ if own_resources {
+ let wrapper = saved.resolve(holder.get(b"Wrapper").unwrap());
+ let Object::Stream(wrapper) = &*wrapper else { panic!("a real wrapper form") };
+ let res = saved.resolve(wrapper.dict.get(b"Resources").unwrap());
+ let xo = saved.resolve(res.as_dict().unwrap().get(b"XObject").unwrap());
+ holder = xo.as_dict().unwrap().clone();
+ }
+ assert_eq!(holder.contains(b"Fm"), still_drawn, "keep only resources a surviving nested form actually uses");
+ if still_drawn {
+ let form = saved.resolve(holder.get(b"Fm").unwrap());
+ let Object::Stream(form) = &*form else { panic!("the preserved original form") };
+ assert_eq!(form.decoded().unwrap(), original);
+ }
+ }
+ }
+}
+
/// A page tree of `n` pages that all draw form /Fm and inherit a direct `/Resources` from the root.
fn inheriting_pages(n: usize) -> (Document, Vec) {
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"BT /F1 10 Tf 10 200 Td (SECRET) Tj ET");
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 39eaff6076..b155d117b2 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -11,30 +11,31 @@ workspace = true
[dependencies]
craft-ui = { workspace = true }
-# macOS: a window close quits through `terminate:` (the Touch Bar crash, #1136); elsewhere a no-op.
-craft-quit = { workspace = true, features = ["egui"] }
pdfcraft-fonts = { workspace = true }
pdfcraft-engine = { workspace = true }
pdfcraft-cos = { workspace = true }
pdfcraft-render = { workspace = true }
pdfcraft-model = { workspace = true }
pdfcraft-platform = { workspace = true }
-egui = { workspace = true, features = ["bytemuck"] }
+egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_emoji_fonts"] }
egui_extras = { workspace = true }
-eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence", "links"] }
+eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence", "links", "clipboard"] }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# UTC/calendar display (combine modified-time stamp, the form date picker) goes through chrono
# (no hand-rolled calendar code); std-only, so it stays wasm-safe.
chrono = { workspace = true }
+# Monotonic deadlines for work that runs in `logic` with no UI pass (native and web).
+web-time = { workspace = true }
# Hands rendered rasters to egui as its pixels, without copying; already in the tree through egui and wgpu.
bytemuck = { version = "1", features = ["extern_crate_alloc"] }
rfd = { workspace = true }
png = "0.18"
base64 = "0.22"
-# Right-to-left file names in the chrome (egui shapes but does not reorder); already in the tree.
+# Unicode bidi paragraph segmentation for right-to-left comment wrapping; egui 0.37's epaint owns
+# display reordering. Already in the tree through egui’s epaint.
unicode-bidi = "0.3"
# Checks that an installed fallback font parses and has the glyphs, and reads the vertical metrics
# that put fallback faces on the interface's baseline (#1676); the same skrifa egui uses.
@@ -53,6 +54,9 @@ pollster = "1.0"
fontconfig-parser = "0.5.8"
[target.'cfg(target_os = "macos")'.dependencies]
+# macOS: a window close quits through `terminate:` (the Touch Bar crash, #1136); elsewhere a no-op.
+# The egui feature binds `on_close_request` to the app's egui Context, so it stays macOS-only.
+craft-quit = { workspace = true, features = ["egui"] }
# Safe AppKit calls for drag coordinates and repairing an existing per-file PDFCraft binding.
# The Objective-C wrappers and block support are already in the tree through arboard and rfd.
objc2 = "0.6"
@@ -81,6 +85,9 @@ web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlE
[dev-dependencies]
pdfcraft-xfa = { workspace = true }
egui_kittest = { workspace = true, features = ["eframe", "wgpu"] }
+# Tests draw PdfCraft text without a system provider: the bundled and monochrome emoji faces must
+# be enabled on the test graph itself (a dependency's dev-features do not propagate).
+egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
image = { version = "0.25", default-features = false, features = ["png"] }
# Glyph-coverage test of the interface fonts; the same skrifa pdfcraft-fonts already uses.
skrifa = "0.44"
diff --git a/crates/ui-egui/src/actions_ui.rs b/crates/ui-egui/src/actions_ui.rs
index 89cf2569e8..ddd8a0736c 100644
--- a/crates/ui-egui/src/actions_ui.rs
+++ b/crates/ui-egui/src/actions_ui.rs
@@ -301,16 +301,18 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool
close
}
+/// Draw the custom-action editor: name, description and ordered steps; Save stays disabled until the name is
+/// unique and non-empty and at least one step exists.
fn edit_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
let Some((original, a)) = app.wizard.editing.as_mut() else { return false };
ui.label(egui::RichText::new(if original.is_some() { tl!("Edit Action") } else { tl!("New Action") }).font(theme::semibold(18.0)));
ui.add_space(8.0);
egui::Grid::new("action-edit").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
- ui.label(tl!("Action name:"));
- ui.add(crate::widgets::line(&mut a.name).desired_width(320.0).id_salt("action-name"));
+ let name_label = ui.label(tl!("Action name:"));
+ ui.add(crate::widgets::line(&mut a.name).desired_width(320.0).id_salt("action-name")).labelled_by(name_label.id);
ui.end_row();
- ui.label(tl!("Description:"));
- ui.add(crate::widgets::line(&mut a.description).desired_width(320.0).id_salt("action-description"));
+ let description_label = ui.label(tl!("Description:"));
+ ui.add(crate::widgets::line(&mut a.description).desired_width(320.0).id_salt("action-description")).labelled_by(description_label.id);
ui.end_row();
});
ui.add_space(6.0);
@@ -324,9 +326,9 @@ fn edit_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
for (i, s) in a.steps.iter_mut().enumerate() {
ui.push_id(i, |ui| {
ui.horizontal(|ui| {
- ui.label(format!("{}. {}", i + 1, tl!(s.label())));
+ let step_label = ui.label(format!("{}. {}", i + 1, tl!(s.label())));
if let Some(arg) = s.arg_mut() {
- ui.add(crate::widgets::line(arg).desired_width(220.0));
+ ui.add(crate::widgets::line(arg).desired_width(220.0)).labelled_by(step_label.id);
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.button(tl!("Remove")).clicked() {
diff --git a/crates/ui-egui/src/all_tools_ui.rs b/crates/ui-egui/src/all_tools_ui.rs
index c8c510a11c..9b09c887d1 100644
--- a/crates/ui-egui/src/all_tools_ui.rs
+++ b/crates/ui-egui/src/all_tools_ui.rs
@@ -13,9 +13,8 @@ const TILE: egui::Vec2 = vec2(148.0, 118.0);
const MATCHES_SHOWN: usize = 2;
/// Whether `query` (already trimmed and lower-cased) is in `label` or its translation.
-/// A right-to-left language's translations are in display order (their words run the other way)
-/// while the query is in typing order, so there several words match one by one, as in the
-/// command palette.
+/// Translations and queries stay in logical order. For right-to-left labels, also accept
+/// multiword queries in a different word order, as in the command palette.
fn label_hit(label: &str, translated: &str, query: &str, rtl: bool) -> bool {
let translated = translated.to_lowercase();
label.to_lowercase().contains(query)
@@ -115,7 +114,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
/// short shows in full on hover.
fn tile(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup, items: &[&'static str]) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(g.label)));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label)));
let press = theme::Press::track(ui, &resp);
crate::home::card_lift(ui, t, rect, press);
ui.painter().rect(rect, CornerRadius::same(10), press.fill(t.card, t.hover, t.pressed), Stroke::new(1.0, t.divider), egui::StrokeKind::Inside);
@@ -186,11 +185,13 @@ mod tests {
#[test]
fn right_to_left_labels_match_a_query_typed_in_logical_order() {
- let shown = crate::bidi::display_rtl("تنظيم الصفحات");
- assert_ne!(shown, "تنظيم الصفحات", "the catalogue reverses the words for display");
- assert!(label_hit("Organize pages", &shown, "تنظيم الصفحات", true));
- assert!(label_hit("Organize pages", &shown, "الصفحات", true), "one word");
- assert!(!label_hit("Organize pages", &shown, "تنظيم الملفات", true), "every word must be there");
- assert!(!label_hit("Organize pages", &shown, "تنظيم الصفحات", false), "left-to-right labels stay exact");
+ let arabic = crate::i18n::Lang::from_code("ar").expect("Arabic is registered");
+ let translated = crate::i18n::tr(arabic, "Organize pages");
+ assert_eq!(translated, "تنظيم الصفحات", "the catalogue keeps logical text");
+ assert!(label_hit("Organize pages", translated, "تنظيم الصفحات", true));
+ assert!(label_hit("Organize pages", translated, "الصفحات", true), "one word");
+ assert!(label_hit("Organize pages", translated, "الصفحات تنظيم", true), "RTL word-order fallback");
+ assert!(!label_hit("Organize pages", translated, "تنظيم الملفات", true), "every word must be there");
+ assert!(!label_hit("Organize pages", translated, "الصفحات تنظيم", false), "left-to-right labels stay exact");
}
}
diff --git a/crates/ui-egui/src/appearance.rs b/crates/ui-egui/src/appearance.rs
index 536d8e4d97..1393c9d937 100644
--- a/crates/ui-egui/src/appearance.rs
+++ b/crates/ui-egui/src/appearance.rs
@@ -118,8 +118,8 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The
pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
ui.label(RichText::new(tl_ctx!("theme", "Appearance")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
- ui.label(tl!("Appearance mode"));
- egui::ComboBox::from_id_salt("appearance-mode").selected_text(tl!(mode_label(app.theme_preference))).show_ui(ui, |ui| {
+ let label = ui.label(tl!("Appearance mode"));
+ let combo = egui::ComboBox::from_id_salt("appearance-mode").selected_text(tl!(mode_label(app.theme_preference))).show_ui(ui, |ui| {
for preference in [ThemePreference::System, ThemePreference::Light, ThemePreference::Dark] {
if ui.selectable_label(app.theme_preference == preference, tl!(mode_label(preference))).clicked() {
app.execute(mode_command(preference));
@@ -127,6 +127,8 @@ pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens)
}
}
});
+ // The visible label names the combo box for assistive technology and tests.
+ combo.response.labelled_by(label.id);
});
ui.add_space(4.0);
let light_active = app.theme == ThemeKind::Light;
diff --git a/crates/ui-egui/src/bidi.rs b/crates/ui-egui/src/bidi.rs
index 50cae547e3..c5809c601f 100644
--- a/crates/ui-egui/src/bidi.rs
+++ b/crates/ui-egui/src/bidi.rs
@@ -1,18 +1,18 @@
-//! Visual order for single-line interface text that may hold right-to-left script (file names,
-//! document titles).
+//! Wrapping right-to-left text into logical lines, and test-only display-order helpers.
//!
-//! egui shapes each font-face run with the script's own direction, so the letters of an Arabic
-//! word join and run right to left, but it places the runs themselves left to right in logical
-//! order: `واحد اثنين.pdf` would show its two words swapped. [`visual`] puts the runs in display
-//! order and leaves the letters of each word alone for the shaper.
-//!
-//! [`display_rtl`] does the same for the labels of a right-to-left interface language (the Arabic
-//! catalog), whose base direction is right to left.
+//! egui 0.37's epaint shapes text with the Unicode bidirectional algorithm (UAX #9), so
+//! production code passes it logical (typing-order) text: [`wrap`] breaks a comment into logical
+//! lines and lets epaint reorder each one. [`visual`], [`visual_auto`] and [`display_rtl`] are
+//! kept for the tests that prove the old preordering is gone; they must not be used for painting
+//! with egui 0.37, where they would reverse mixed-direction text a second time.
+#[cfg(test)]
use std::borrow::Cow;
use std::ops::Range;
-use unicode_bidi::{BidiInfo, Level, ParagraphInfo};
+use unicode_bidi::BidiInfo;
+#[cfg(test)]
+use unicode_bidi::{Level, ParagraphInfo};
/// `text` rearranged for an egui call that lays out one line. Text without right-to-left
/// characters comes back borrowed and unchanged.
@@ -20,6 +20,7 @@ use unicode_bidi::{BidiInfo, Level, ParagraphInfo};
/// The base direction is left to right, as the interface is: a file name keeps its extension
/// at the end, the way the window title shows it. Use it for painting only; accessibility
/// labels and anything stored keep the logical text.
+#[cfg(test)]
pub fn visual(text: &str) -> Cow<'_, str> {
if !text.chars().any(is_rtl_script) {
return Cow::Borrowed(text);
@@ -30,6 +31,7 @@ pub fn visual(text: &str) -> Cow<'_, str> {
}
/// `text` in display order for the paragraph direction `base`, appended to `out`.
+#[cfg(test)]
fn push_visual(out: &mut String, text: &str, base: Level) {
let info = BidiInfo::new(text, Some(base));
for para in &info.paragraphs {
@@ -39,6 +41,7 @@ fn push_visual(out: &mut String, text: &str, base: Level) {
/// The `line` of paragraph `para` (a non-empty byte range of `text`) in display order, as egui
/// needs it, appended to `out`.
+#[cfg(test)]
fn push_line(out: &mut String, text: &str, info: &BidiInfo<'_>, para: &ParagraphInfo, line: Range) {
let (levels, runs) = info.visual_runs(para, line);
// First the true display order, every character left to right as it appears on screen.
@@ -62,6 +65,7 @@ fn push_line(out: &mut String, text: &str, info: &BidiInfo<'_>, para: &Paragraph
/// each such stretch goes back to logical order. What lies between them (spaces, punctuation,
/// Latin) is drawn by the Latin face left to right and stays as it is. The stretches include
/// Persian and Arabic-Indic digits: Arabic script to the shaper, though they read left to right.
+#[cfg(test)]
fn push_for_shaper(out: &mut String, shown: &str) {
let mut stretch: Vec = Vec::new();
for c in shown.chars() {
@@ -78,7 +82,7 @@ fn push_for_shaper(out: &mut String, shown: &str) {
/// One line of wrapped text (see [`wrap`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Line {
- /// The line in display order, for one egui call that lays out one line.
+ /// The line in logical (reading) order. epaint shapes and reorders it for display.
pub text: String,
/// The paragraph reads right to left: the line belongs against the right edge.
pub rtl: bool,
@@ -89,14 +93,44 @@ pub fn has_rtl(text: &str) -> bool {
text.chars().any(is_rtl_script)
}
+/// The paragraph direction for translated interface text: explicitly right to left for Arabic,
+/// Kurdish and Persian, and `TextDirection::Auto` otherwise. A label whose first strong character is
+/// Latin or a `{placeholder}` must not fall back to a left-to-right paragraph in an RTL locale.
+pub fn ui_direction() -> egui::epaint::text::TextDirection {
+ if crate::i18n::current().rtl() { egui::epaint::text::TextDirection::RightToLeft } else { egui::epaint::text::TextDirection::Auto }
+}
+
+/// Lay out one line of translated interface text with the locale's explicit base direction.
+pub fn layout_ui(ui: &egui::Ui, text: impl Into, font: egui::FontId, color: egui::Color32) -> std::sync::Arc {
+ layout_one_line(ui, text, font, color, ui_direction())
+}
+
+/// Lay out one line of file or path text left to right, so an Arabic file name keeps `.pdf` at
+/// its visual end exactly as a Latin one does. The text stays logical for accessibility.
+pub fn layout_ltr(ui: &egui::Ui, text: impl Into, font: egui::FontId, color: egui::Color32) -> std::sync::Arc {
+ layout_one_line(ui, text, font, color, egui::epaint::text::TextDirection::LeftToRight)
+}
+
+fn layout_one_line(
+ ui: &egui::Ui,
+ text: impl Into,
+ font: egui::FontId,
+ color: egui::Color32,
+ direction: egui::epaint::text::TextDirection,
+) -> std::sync::Arc {
+ let mut job = egui::text::LayoutJob::simple_singleline(text.into(), font, color);
+ job.direction = direction;
+ ui.painter().layout_job(job)
+}
+
/// Multi-line text with right-to-left script (a comment in Persian, Arabic, Hebrew), broken
-/// into lines that `fits` accepts (it measures a line in logical order) and each put in display
-/// order by the Unicode bidirectional algorithm (UAX #9).
+/// into logical-order lines that `fits` accepts (it measures a line in logical order).
///
-/// Every paragraph takes its direction from its first strong character, as `dir="auto"` does,
-/// so a Persian comment reads right to left with its Latin words and numbers left to right
-/// inside it. Lines break between words, in reading order, and a word wider than a line
-/// between characters. Use it for painting; copying and accessibility keep the logical text.
+/// The lines keep reading order and each line's paragraph direction ([`Line::rtl`]): egui 0.37's
+/// epaint already shapes every line with the Unicode bidirectional algorithm (UAX #9), so
+/// preordering here would reorder mixed Persian/Latin text a second time. Lines break between
+/// words, in reading order, and a word wider than a line between characters. Copying and
+/// accessibility use the same logical text.
pub fn wrap(text: &str, mut fits: impl FnMut(&str) -> bool) -> Vec {
let info = BidiInfo::new(text, None);
let mut lines = Vec::new();
@@ -109,12 +143,7 @@ pub fn wrap(text: &str, mut fits: impl FnMut(&str) -> bool) -> Vec {
let content = para.range.start..para.range.start.saturating_add(whole.trim_end_matches(is_paragraph_separator).len());
let rtl = para.level.is_rtl();
for line in break_lines(text, content, &mut fits) {
- let mut out = String::new();
- // unicode-bidi indexes the first level of a line, so an empty one would panic.
- if !line.is_empty() {
- push_line(&mut out, text, &info, para, line);
- }
- lines.push(Line { text: out, rtl });
+ lines.push(Line { text: text.get(line).unwrap_or_default().to_owned(), rtl });
}
}
lines
@@ -122,12 +151,18 @@ pub fn wrap(text: &str, mut fits: impl FnMut(&str) -> bool) -> Vec {
/// One line of `text` in display order, its direction from its first strong character (an
/// author's name). Text without right-to-left characters comes back borrowed and unchanged.
+///
+/// Only the bidi unit tests use this now: interface labels keep logical text and let the egui
+/// fork reorder, so no production call site preorders a label.
+#[cfg(test)]
pub fn visual_auto(text: &str) -> Cow<'_, str> {
if !has_rtl(text) {
return Cow::Borrowed(text);
}
- let lines: Vec = wrap(text, |_| true).into_iter().map(|l| l.text).collect();
- Cow::Owned(lines.join("\n"))
+ let base = BidiInfo::new(text, None).paragraphs.first().map_or(Level::ltr(), |para| para.level);
+ let mut out = String::with_capacity(text.len());
+ push_visual(&mut out, text, base);
+ Cow::Owned(out)
}
/// The byte ranges of the lines `range` of `text` breaks into: as many words as `fits` accepts
@@ -209,7 +244,9 @@ fn is_paragraph_separator(c: char) -> bool {
/// - A short caption's closing colon stays on the right too, next to the widget it captions.
///
/// Text without right-to-left characters comes back unchanged. Like [`visual`], this is for
-/// painting one line; a label egui wraps breaks at the wrong end.
+/// painting one line; a label egui wraps breaks at the wrong end. Kept for the tests that prove
+/// the old preordering is gone; production catalogs stay logical.
+#[cfg(test)]
pub fn display_rtl(text: &str) -> String {
if !text.chars().any(is_rtl_script) {
return text.to_owned();
@@ -225,13 +262,17 @@ pub fn display_rtl(text: &str) -> String {
}
/// The most words a caption may have for its closing colon to stay on the right.
+#[cfg(test)]
const CAPTION_WORDS: usize = 3;
/// First of the private-use characters that stand for placeholders while a line is reordered.
/// They are strong left-to-right, like the names they replace.
+#[cfg(test)]
const PLACEHOLDER_BASE: u32 = 0xE000;
/// Placeholders protected per line; a line with more keeps the rest as plain text.
+#[cfg(test)]
const MAX_PLACEHOLDERS: usize = 64;
+#[cfg(test)]
fn push_rtl_line(out: &mut String, line: &str) {
let edge = |c: char| c.is_whitespace() || c == '·';
let core = line.trim_start_matches(edge);
@@ -266,6 +307,7 @@ fn push_rtl_line(out: &mut String, line: &str) {
/// `text` with each `{name}` placeholder and each keyboard shortcut (`⇧⌘+`) replaced by one
/// stand-in character, and what they replaced, in order. A shortcut's symbols have no direction
/// of their own, so left alone they would be drawn in reverse.
+#[cfg(test)]
fn mask_placeholders(text: &str) -> (String, Vec<&str>) {
let mut masked = String::with_capacity(text.len());
let mut names: Vec<&str> = Vec::new();
@@ -286,6 +328,7 @@ fn mask_placeholders(text: &str) -> (String, Vec<&str>) {
}
/// The byte range of the first placeholder or keyboard shortcut in `text`.
+#[cfg(test)]
fn next_atom(text: &str) -> Option<(usize, usize)> {
let placeholder = text.find('{').and_then(|open| {
let len = text.get(open..)?.find('}')?;
@@ -308,6 +351,7 @@ fn next_atom(text: &str) -> Option<(usize, usize)> {
}
/// The modifier-key symbols of keyboard shortcuts: ⌘ ⇧ ⌥ ⌃.
+#[cfg(test)]
fn is_modifier_key(c: char) -> bool {
matches!(c, '\u{2318}' | '\u{21E7}' | '\u{2325}' | '\u{2303}')
}
@@ -320,15 +364,18 @@ fn is_rtl_script(c: char) -> bool {
/// The zero-width (non-)joiners inside a word (Persian `میروم`): egui shapes them with the
/// letter before them.
+#[cfg(test)]
fn is_joiner(c: char) -> bool {
matches!(c, '\u{200C}' | '\u{200D}')
}
/// Direction marks, embeddings, overrides and isolates: they steer the reordering and are not drawn.
+#[cfg(test)]
fn is_bidi_control(c: char) -> bool {
matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
+#[cfg(test)]
fn mirrored(c: char) -> char {
match c {
'(' => ')',
@@ -474,50 +521,57 @@ mod tests {
Line { text: text.to_owned(), rtl: false }
}
+ /// Check that a Persian paragraph, including words joined by a zero-width non-joiner, reaches epaint as
+ /// one logical right-to-left run.
#[test]
- fn persian_paragraph_reads_right_to_left() {
- // "I go to school": the words come out in reverse for egui's left-to-right placement.
- assert_eq!(wrap_at("من به مدرسه میروم", 80), [rtl("میروم مدرسه به من")]);
+ fn persian_paragraph_keeps_logical_order_for_epaint() {
+ // The line stays in reading order; epaint shapes and reorders it (see `on_screen`).
+ assert_eq!(wrap_at("من به مدرسه میروم", 80), [rtl("من به مدرسه میروم")]);
// The zero-width non-joiner keeps a word whole, so the shaper gets it as one run.
assert_eq!(wrap_at("کتابها", 80), [rtl("کتابها")]);
}
+ /// Check that Arabic text wraps into lines in logical reading order rather than visual order.
#[test]
fn arabic_lines_break_in_reading_order() {
- // The first words go on the first line, each line reordered on its own.
- assert_eq!(wrap_at("واحد اثنين ثلاثة أربعة", 11), [rtl("اثنين واحد"), rtl("أربعة ثلاثة")]);
- assert_eq!(wrap_at("واحد اثنين ثلاثة أربعة", 80), [rtl("أربعة ثلاثة اثنين واحد")]);
+ // The first words go on the first line, in logical order for epaint to reorder.
+ assert_eq!(wrap_at("واحد اثنين ثلاثة أربعة", 11), [rtl("واحد اثنين"), rtl("ثلاثة أربعة")]);
+ assert_eq!(wrap_at("واحد اثنين ثلاثة أربعة", 80), [rtl("واحد اثنين ثلاثة أربعة")]);
}
+ /// Check that each paragraph takes its base direction from its first strong character, not from leading
+ /// numbers or neutral text.
#[test]
fn base_direction_comes_from_the_first_strong_character() {
// Latin first: a left-to-right paragraph with an Arabic phrase inside it.
- assert_eq!(wrap_at("See واحد اثنين here", 80), [ltr("See اثنين واحد here")]);
- // Persian first: right to left, the Latin words and the number left to right inside it.
- assert_eq!(wrap_at("فایل PDF نسخه 2 است", 80), [rtl("است 2 نسخه PDF فایل")]);
- assert_eq!(wrap_at("سلام Hello World", 80), [rtl("Hello World سلام")]);
+ assert_eq!(wrap_at("See واحد اثنين here", 80), [ltr("See واحد اثنين here")]);
+ // Persian first: right to left, with the Latin words and number in reading order.
+ assert_eq!(wrap_at("فایل PDF نسخه 2 است", 80), [rtl("فایل PDF نسخه 2 است")]);
+ assert_eq!(wrap_at("سلام Hello World", 80), [rtl("سلام Hello World")]);
// Leading neutrals and numbers don't decide it.
- assert_eq!(wrap_at("12. واحد اثنين", 80), [rtl("اثنين واحد .12")]);
+ assert_eq!(wrap_at("12. واحد اثنين", 80), [rtl("12. واحد اثنين")]);
// Each paragraph finds its own direction.
- assert_eq!(wrap_at("واحد اثنين\nOK then\n\nשלום עולם", 80), [rtl("اثنين واحد"), ltr("OK then"), ltr(""), rtl("עולם שלום")]);
+ assert_eq!(wrap_at("واحد اثنين\nOK then\n\nשלום עולם", 80), [rtl("واحد اثنين"), ltr("OK then"), ltr(""), rtl("שלום עולם")]);
}
+ /// Check that right-to-left punctuation and brackets stay in logical order for epaint to mirror when
+ /// displaying.
#[test]
fn rtl_punctuation_and_brackets() {
- // The sentence's full stop ends up on the left, brackets flip.
- assert_eq!(wrap_at("سلام دنیا.", 80), [rtl(".دنیا سلام")]);
- assert_eq!(wrap_at("واحد (اثنين) ثلاثة", 80), [rtl("ثلاثة (اثنين) واحد")]);
- assert_eq!(wrap_at("آیا آماده است؟", 80), [rtl("است؟ آماده آیا")]);
+ // Logical text: epaint mirrors punctuation and brackets for display.
+ assert_eq!(wrap_at("سلام دنیا.", 80), [rtl("سلام دنیا.")]);
+ assert_eq!(wrap_at("واحد (اثنين) ثلاثة", 80), [rtl("واحد (اثنين) ثلاثة")]);
+ assert_eq!(wrap_at("آیا آماده است؟", 80), [rtl("آیا آماده است؟")]);
}
+ /// Check that Persian and Arabic-Indic digits stay in logical order inside a right-to-left paragraph.
#[test]
fn persian_digits_go_to_the_shaper_reversed() {
- // Persian and Arabic-Indic digits are Arabic script, which egui's shaper lays out right to
- // left; they read left to right, so they are handed over reversed.
- assert_eq!(wrap_at("سال ۱۴۰۲ شمسی", 80), [rtl("شمسی ۲۰۴۱ سال")]);
- assert_eq!(wrap_at("صفحه ١٢", 80), [rtl("٢١ صفحه")]);
- // Glued to a word, number and word swap places within one shaped run.
- assert_eq!(wrap_at("ب۱۲", 80), [rtl("ب۲۱")]);
+ // Persian and Arabic-Indic digits stay in logical order; epaint's shaper preserves their
+ // left-to-right reading inside the right-to-left paragraph.
+ assert_eq!(wrap_at("سال ۱۴۰۲ شمسی", 80), [rtl("سال ۱۴۰۲ شمسی")]);
+ assert_eq!(wrap_at("صفحه ١٢", 80), [rtl("صفحه ١٢")]);
+ assert_eq!(wrap_at("ب۱۲", 80), [rtl("ب۱۲")]);
}
#[test]
@@ -546,8 +600,30 @@ mod tests {
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
for line in wrap(text, |_| true) {
let galley = ui.painter().layout_no_wrap(line.text, egui::FontId::proportional(13.0), egui::Color32::WHITE);
- let glyphs = galley.rows.iter().flat_map(|row| row.glyphs.iter());
- shown.push(glyphs.filter(|g| g.advance_width > 0.0).map(|g| g.chr).collect());
+ let atlas = ui.fonts_mut(|fonts| fonts.image());
+ let mut visual = String::new();
+ for row in &galley.rows {
+ // 0.37 keeps glyphs in logical order for selection. Read their actual
+ // positions to test visual order instead of assuming vector order.
+ let mut glyphs: Vec<_> = row.glyphs.iter().filter(|g| g.advance_width > 0.0).collect();
+ glyphs.sort_by(|a, b| a.pos.x.total_cmp(&b.pos.x));
+ visual.extend(glyphs.into_iter().map(|g| match g.chr {
+ // `chr` remains logical even when the shaper mirrors the painted
+ // bracket. Read the bitmap's middle-row ink to check what is visible.
+ '(' | ')' => {
+ let [x0, y0] = g.uv_rect.min.map(usize::from);
+ let [x1, y1] = g.uv_rect.max.map(usize::from);
+ let y = usize::midpoint(y0, y1);
+ let ink: Vec = (x0..x1).map(|x| f32::from(atlas[(x, y)].a())).collect();
+ let total: f32 = ink.iter().sum();
+ assert!(total > 0.0 && !ink.is_empty(), "a bracket must have visible ink");
+ let center = ink.iter().enumerate().map(|(i, alpha)| i as f32 * alpha).sum::() / total;
+ if center < (ink.len() - 1) as f32 / 2.0 { '(' } else { ')' }
+ }
+ _ => g.chr,
+ }));
+ }
+ shown.push(visual);
}
});
output.drop_without_applying_deltas();
@@ -573,6 +649,64 @@ mod tests {
assert_eq!(on_screen("واحد (اثنين)."), [format!(".({}) {}", rev("اثنين"), rev("واحد"))]);
}
+ /// A file name keeps its extension at the visual end even when the first strong word is
+ /// Arabic: with an explicit `LeftToRight` base, `.pdf` is right of every Arabic glyph.
+ #[test]
+ fn file_names_are_laid_out_left_to_right() {
+ if pdfcraft_fonts::ui_arabic_fonts().is_empty() {
+ return;
+ }
+ let ctx = egui::Context::default();
+ ctx.set_fonts(crate::theme::font_definitions());
+ let mut positions: Vec<(char, f32)> = Vec::new();
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ let galley = layout_ltr(ui, "واحد اثنين.pdf", egui::FontId::proportional(13.0), egui::Color32::WHITE);
+ positions = galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x))).collect();
+ })
+ .drop_without_applying_deltas();
+ let rightmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MIN, f32::max);
+ let leftmost_extension = positions.iter().filter(|(c, _)| matches!(*c, '.' | 'p' | 'd' | 'f')).map(|(_, x)| *x).fold(f32::MAX, f32::min);
+ assert!(rightmost_arabic < leftmost_extension, "the extension must stay to the right: {positions:?}");
+ let last = positions.iter().filter(|(c, _)| !c.is_whitespace()).max_by(|a, b| a.1.total_cmp(&b.1));
+ assert_eq!(last.map(|(c, _)| *c), Some('f'), "the painted line ends in the extension");
+ }
+
+ /// Arabic/Kurdish labels get an explicit right-to-left paragraph, even when their first
+ /// strong character is Latin. With English the same text stays left to right.
+ #[test]
+ fn arabic_ui_labels_use_an_explicit_paragraph_direction() {
+ if pdfcraft_fonts::ui_arabic_fonts().is_empty() {
+ return;
+ }
+ let previous = crate::i18n::current();
+ let ctx = egui::Context::default();
+ ctx.set_fonts(crate::theme::font_definitions());
+ let read = |lang: &str| {
+ crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("registered language"));
+ let mut got = None;
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ let galley = layout_ui(ui, "PDF واحد", egui::FontId::proportional(13.0), egui::Color32::WHITE);
+ let positions: Vec<_> = galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x))).collect();
+ got = Some((galley.job.direction, positions));
+ })
+ .drop_without_applying_deltas();
+ got.expect("one layout")
+ };
+ let (direction, positions) = read("ar");
+ crate::i18n::set_current(previous);
+ assert_eq!(direction, egui::epaint::text::TextDirection::RightToLeft);
+ let p = positions.iter().find(|(c, _)| *c == 'P').map(|(_, x)| *x).expect("a Latin P");
+ let rightmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MIN, f32::max);
+ assert!(p > rightmost_arabic, "in an RTL paragraph the first Latin run is at the right: {positions:?}");
+
+ let (direction, positions) = read("en");
+ crate::i18n::set_current(previous);
+ assert_eq!(direction, egui::epaint::text::TextDirection::Auto);
+ let p = positions.iter().find(|(c, _)| *c == 'P').map(|(_, x)| *x).expect("a Latin P");
+ let leftmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MAX, f32::min);
+ assert!(p < leftmost_arabic, "with English the Latin run stays at the left: {positions:?}");
+ }
+
#[test]
fn single_line_with_its_own_direction() {
assert!(matches!(visual_auto("Ada Lovelace"), Cow::Borrowed("Ada Lovelace")));
diff --git a/crates/ui-egui/src/bulk_fields.rs b/crates/ui-egui/src/bulk_fields.rs
index 3101724cff..fe401f0574 100644
--- a/crates/ui-egui/src/bulk_fields.rs
+++ b/crates/ui-egui/src/bulk_fields.rs
@@ -283,7 +283,7 @@ pub(crate) fn body(ui: &mut egui::Ui, d: &mut Draft, t: &theme::Tokens) -> (bool
egui::Grid::new("bulk-field-properties").num_columns(3).spacing([16.0, 10.0]).show(ui, |ui| match d.tab {
Tab::General => {
row(ui, "Tooltip:", &mut d.tooltip, |ui, v| {
- ui.add(egui::TextEdit::singleline(v).desired_width(280.0));
+ ui.add(egui::TextEdit::singleline(v).desired_width(280.0)).accessible_name(tl!("Tooltip"));
});
bool_row(ui, "Read Only", &mut d.read_only);
bool_row(ui, "Required", &mut d.required);
diff --git a/crates/ui-egui/src/calc_order_ui.rs b/crates/ui-egui/src/calc_order_ui.rs
index 70a6dec2c0..4cbfa28177 100644
--- a/crates/ui-egui/src/calc_order_ui.rs
+++ b/crates/ui-egui/src/calc_order_ui.rs
@@ -566,7 +566,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
let is_selected = selected.as_deref() == Some(f.name.as_str());
resp.widget_info(|| {
let label = if row.value.is_empty() { format!("{}. {}", k + 1, f.name) } else { format!("{}. {}: {}", k + 1, f.name, row.value) };
- egui::WidgetInfo::selected(egui::WidgetType::Button, true, is_selected, label)
+ egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, label)
});
if reveal.as_deref() == Some(f.name.as_str()) {
resp.scroll_to_me(Some(egui::Align::Center));
@@ -631,8 +631,9 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
[(up, "chevron-up", true, tl!("Earlier in calculation order")), (down, "chevron-down", false, tl!("Later in calculation order"))]
{
let to = if earlier { k.checked_sub(1) } else { Some(k + 1).filter(|&to| to < count) };
- let b = ui.interact(r, ui.id().with(("calc-order", k, earlier)), if to.is_some() { Sense::click() } else { Sense::hover() });
- b.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, to.is_some(), format!("{tip}: {}", f.name)));
+ let b =
+ ui.interact(r, ui.scope_id().with(("calc-order", k, earlier)), if to.is_some() { Sense::click() } else { Sense::hover() });
+ b.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, to.is_some(), format!("{tip}: {}", f.name)));
if visible {
let bpress = theme::Press::track(ui, &b);
bpress.wash(ui, r, 4, false);
diff --git a/crates/ui-egui/src/camera_ui.rs b/crates/ui-egui/src/camera_ui.rs
index 1cacc4e163..d470378070 100644
--- a/crates/ui-egui/src/camera_ui.rs
+++ b/crates/ui-egui/src/camera_ui.rs
@@ -141,7 +141,7 @@ pub(crate) fn paint(painter: &egui::Painter, xf: &PageXform, page: usize, view:
/// way, choose its look (original, colour, greyscale, black and white) and clean-up level,
/// Crop pages, Organize pages, or Done. The instructions are a notice (`ocr.enhance_camera`).
pub(crate) fn bar(ctx: &egui::Context, view: &mut DocView, area: Rect, t: &Tokens, allowed: bool) {
- egui::Area::new(egui::Id::new("camera-bar"))
+ egui::Area::new(egui::Id::unique("camera-bar"))
.order(egui::Order::Middle)
.pivot(Align2::RIGHT_TOP)
.fixed_pos(area.right_top() + vec2(-18.0, 12.0))
@@ -183,7 +183,7 @@ pub(crate) fn bar(ctx: &egui::Context, view: &mut DocView, area: Rect, t: &Token
let icon = |ui: &mut egui::Ui, name: &str, tip: &str| {
let r = ui.add_enabled(allowed, egui::Button::image(crate::icons::image(name, 18.0, t.text)).frame(false));
// Named for screen readers (and tests), not only on hover.
- r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, allowed, tip));
+ r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, allowed, tip));
r.on_hover_text(tip).clicked()
};
if icon(ui, "rotate-ccw", tl!("Rotate counterclockwise")) {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 02bc000ed6..4f00aa6bec 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -234,6 +234,18 @@ pub struct Find {
/// (page, glyph range) in document order.
pub matches: Vec<(usize, Range)>,
pub current: Option,
+ /// The page a search started from while its match is picked automatically: a text layer
+ /// that arrives out of order can still supply an earlier match, and the automatic choice
+ /// follows this page. Cleared when the user picks a match or moves the view themselves.
+ pub auto_from: Option,
+ /// The page the automatic choice last put the view on (the search's starting page until it
+ /// chose anything). Compared with the viewed page, it tells an automatic scroll from one
+ /// the reader made themselves; `None` with `auto_from` once the choice is the user's.
+ pub auto_page: Option,
+ /// The reader ended automatic following (by navigating, scrolling, or picking a match).
+ /// This is distinct from a search that never followed: a late match must be listed without
+ /// being revealed by scrolling, even when the reader moved before the first match arrived.
+ pub follow_ended: bool,
pub focus: bool,
pub case_query: String,
/// Find options (Acrobat's: case-sensitive, whole words only).
@@ -243,6 +255,51 @@ pub struct Find {
pub in_panel: bool,
}
+/// What a text layer arriving after a search began may do with the automatic choice.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Follow {
+ /// The reader has not moved the view since the automatic choice: it may follow `from`.
+ Active(usize),
+ /// The reader navigated, scrolled or picked a match, so no automatic choice may reveal.
+ Ended,
+ /// No automatic choice is being followed (the search has not started, or the reader chose).
+ Never,
+}
+
+impl Find {
+ /// The first match at or after `page`, or the first match when none follows (the search
+ /// wraps round the document).
+ fn first_at_or_after(&self, page: usize) -> Option {
+ self.matches.iter().position(|(p, _)| *p >= page).or_else(|| (!self.matches.is_empty()).then_some(0))
+ }
+
+ /// How a text layer arriving now relates to the automatic choice. Once the reader has moved
+ /// the view (page box, Pages panel, outline, view history or any scrolling), automatic
+ /// following ends: a later layer must not pull them back to an anchor-derived match.
+ /// `Ended` is deliberately distinct from `Never`, so a first match arriving after that move
+ /// is not revealed by a flash meant only for a search that is still following.
+ fn follow_page(&mut self, viewed: usize) -> Follow {
+ if self.follow_ended {
+ return Follow::Ended;
+ }
+ match (self.auto_from, self.auto_page) {
+ (Some(from), Some(page)) if page == viewed => Follow::Active(from),
+ (Some(_), _) | (_, Some(_)) => {
+ self.stop_following();
+ Follow::Ended
+ }
+ (None, None) => Follow::Never,
+ }
+ }
+
+ /// Ends automatic following: the selected match is now the user's choice to keep.
+ fn stop_following(&mut self) {
+ self.auto_from = None;
+ self.auto_page = None;
+ self.follow_ended = true;
+ }
+}
+
/// A text selection on one page.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Selection {
@@ -730,6 +787,30 @@ impl DocView {
self.auto_scroll.panning()
}
+ /// Abandon only pointer previews: clearing egui's held button must not commit an app-owned
+ /// grab through a tool's `!primary_down` fallback. Keep selections, text drafts and edits
+ /// that were already completed before cancellation.
+ pub(crate) fn cancel_pointer_gestures(&mut self) {
+ self.marquee = None;
+ self.marquee_done = None;
+ self.comments.gesture = None;
+ self.links.drag = None;
+ self.sign.drag = None;
+ self.redact_drag = None;
+ self.crop_drag = None;
+ self.block_drag = None;
+ self.org_drag = None;
+ self.panel_drag = None;
+ self.selection_drag = false;
+ self.auto_scroll.cancel();
+ self.prepare.cancel_pointer_gesture();
+ self.content.cancel_pointer_gesture();
+ self.objects.cancel_pointer_gesture();
+ if let Some(image) = &mut self.image_selection {
+ image.cancel_pointer_gesture();
+ }
+ }
+
/// Pages that could not be rendered, with the reason (for automation; 0-based pages).
pub fn page_errors(&self) -> Vec<(usize, &str)> {
let mut v: Vec<(usize, &str)> = self.errors.iter().map(|(p, e)| (*p, e.as_str())).collect();
@@ -1035,6 +1116,10 @@ impl DocView {
self.last_queue.clear();
self.selection = None;
self.all_text = false;
+ // A content change is not reader navigation: keep the automatic anchor so the
+ // re-extracted layers still follow it, and keep `follow_ended` so a reader who already
+ // took over stays in control. `document_changed` clamps `current`; if the view no longer
+ // sits where the automatic choice left it, `follow_page` ends it.
if let Some(f) = self.find.as_mut() {
f.matches.clear();
f.current = None;
@@ -1225,6 +1310,16 @@ impl DocView {
f.case_query = f.query.clone();
f.matches.clear();
f.current = None;
+ // Refining the query keeps the page the reader started searching from, even when an
+ // automatic choice has already scrolled them to a match. Only a view the reader moved
+ // themselves re-anchors the search on the page now shown.
+ let from = match (f.auto_from, f.auto_page) {
+ (Some(from), Some(page)) if !f.follow_ended && page == self.current => from,
+ _ => self.current,
+ };
+ f.auto_from = Some(from);
+ f.auto_page = Some(self.current);
+ f.follow_ended = false;
if f.case_query.trim().is_empty() {
return;
}
@@ -1236,12 +1331,12 @@ impl DocView {
}
}
f.matches.sort_by_key(|(p, r)| (*p, r.start));
- if !f.matches.is_empty() {
- // First match at or after the page being viewed.
- let cur = self.current;
- let i = f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0);
+ // First match at or after the page the search started from.
+ if let Some(i) = f.first_at_or_after(from)
+ && let Some(&(p, _)) = f.matches.get(i)
+ {
f.current = Some(i);
- let (p, _) = f.matches[i];
+ f.auto_page = Some(p);
self.flash_match(p);
}
}
@@ -1251,21 +1346,33 @@ impl DocView {
if f.case_query.trim().is_empty() {
return;
}
- let current_key = f.current.and_then(|c| f.matches.get(c).cloned());
+ let previous = f.current.and_then(|c| f.matches.get(c).cloned());
+ // An automatic choice follows the page it was anchored on, so a page whose text
+ // arrives late can still supply an earlier match. Once the reader has moved the view,
+ // this arrival must not pull them back; the choice then becomes theirs to keep.
+ let follow = f.follow_page(self.current);
f.matches.retain(|(p, _)| *p != page);
f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));
f.matches.sort_by_key(|(p, r)| (*p, r.start));
- f.current = current_key.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));
- if f.current.is_none() && !f.matches.is_empty() {
- // First match at or after the page being viewed.
- let cur = self.current;
- let i = f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0);
- f.current = Some(i);
- let (p, _) = f.matches[i];
- if current_key.is_none() {
+ if let Follow::Active(from) = follow {
+ f.current = f.first_at_or_after(from);
+ let selected = f.current.and_then(|i| f.matches.get(i).cloned());
+ // Follow a changed automatic choice; the view is still where the last one left it.
+ if selected != previous
+ && let Some((p, _)) = selected
+ {
+ f.auto_page = Some(p);
self.flash_match(p);
}
+ return;
}
+ // A match the user picked keeps its identity, exactly as before automatic following.
+ // When it is gone (or none was picked), the first match at or after the viewed page is
+ // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic
+ // choice to reveal, and a reader who moved before the first layer arrived must not be
+ // pulled back by that late match.
+ let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));
+ f.current = preserved.or_else(|| f.first_at_or_after(self.current));
}
/// Go to match `i` (the Search panel's results).
@@ -1273,6 +1380,7 @@ impl DocView {
let Some(f) = self.find.as_mut() else { return };
let Some(&(p, _)) = f.matches.get(i) else { return };
f.current = Some(i);
+ f.stop_following();
self.go_to_page(p);
self.goto_point = None;
self.flash_match(p);
@@ -1288,6 +1396,7 @@ impl DocView {
let c = f.current.unwrap_or(0);
let next = if forward { (c + 1) % n } else { (c + n - 1) % n };
f.current = Some(next);
+ f.stop_following();
let p = f.matches[next].0;
// Only explicit search navigation joins history; background refresh uses flash_match alone.
self.go_to_page(p);
@@ -1341,8 +1450,18 @@ impl DocView {
self.wheel_boost_y.reset();
}
+ /// Ends automatic search following after the reader navigated or scrolled the view. A
+ /// programmatic search flash never comes through here; it sets `goto` and `current` directly
+ /// so that its own scroll cannot be mistaken for the reader's.
+ fn end_find_following(&mut self) {
+ if let Some(f) = self.find.as_mut() {
+ f.stop_following();
+ }
+ }
+
pub fn go_to_page(&mut self, page: usize) {
let page = page.min(self.page_count.saturating_sub(1));
+ self.end_find_following();
if page != self.current {
// The view history (Previous view / Next view).
if self.back.last() != Some(&self.current) {
@@ -1471,7 +1590,7 @@ impl DocView {
/// Page-editor focus and drafts belong to a document, even while another tab is active.
pub(crate) fn page_input_id(&self) -> egui::Id {
- egui::Id::new(("page-input", self.id.0))
+ egui::Id::unique(("page-input", self.id.0))
}
/// The idle page box and unchanged-input lookup share the same label fallback.
@@ -1504,6 +1623,11 @@ impl DocView {
/// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).
pub fn view_history(&mut self, forward: bool) -> bool {
+ let has_target = if forward { !self.forward.is_empty() } else { !self.back.is_empty() };
+ if !has_target {
+ return false;
+ }
+ self.end_find_following();
let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };
let Some(page) = from.pop() else { return false };
to.push(self.current);
@@ -2127,12 +2251,17 @@ impl DocView {
log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());
self.text_failed.insert(r.request.page);
if let Some(f) = self.find.as_mut() {
- let current_key = f.current.and_then(|c| f.matches.get(c).cloned());
+ let previous = f.current.and_then(|c| f.matches.get(c).cloned());
+ let follow = f.follow_page(self.current);
f.matches.retain(|(p, _)| *p != r.request.page);
- f.current = current_key.and_then(|k| f.matches.iter().position(|m| *m == k));
- if f.current.is_none() && !f.matches.is_empty() {
- let cur = self.current;
- f.current = Some(f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0));
+ match follow {
+ // An automatic choice keeps following its anchor; a failure never
+ // flashes, so the view stays exactly where it was.
+ Follow::Active(from) => f.current = f.first_at_or_after(from),
+ Follow::Ended | Follow::Never => {
+ let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));
+ f.current = preserved.or_else(|| f.first_at_or_after(self.current));
+ }
}
}
}
@@ -2701,15 +2830,14 @@ const SUPPRESS_SECS: f64 = 0.25;
/// Short rolling extension while egui still has an unprocessed wheel tail.
const SUPPRESS_TAIL_SECS: f64 = 0.05;
-// The viewer moves between docking and the central panel as modes change; keep its scroll
-// identity tied to the document instead of either parent UI.
+// Keep the viewer's scroll identity tied to the document instead of its parent UI.
fn page_scroll(
ui: &mut egui::Ui,
scroll: egui::ScrollArea,
id: egui::Id,
draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,
) -> egui::scroll_area::ScrollAreaOutput {
- ui.scope_builder(egui::UiBuilder::new().id(id), |ui| scroll.show_viewport(ui, draw)).inner
+ ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner
}
/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a
@@ -2718,6 +2846,9 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
// Keyboard scrolling applies to this frame's page view only, never later.
let key_scroll = std::mem::take(&mut app.views[index].key_scroll);
+ if key_scroll != 0.0 {
+ app.views[index].end_find_following();
+ }
// The Search panel closed: its search moves to the find bar.
let search_open = app.right == Some(crate::RightPanel::Search);
if let Some(f) = app.views[index].find.as_mut()
@@ -2914,7 +3045,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
// even while the page can't turn.
ui.input(|i| {
for e in &i.events {
- if let egui::Event::MouseWheel { unit, delta, phase, modifiers } = e {
+ if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {
// Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.
let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };
if fits {
@@ -2965,8 +3096,14 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
line_base.y = 0.0;
boost_extra.y = 0.0;
}
- if now < view.precise_scroll_until {
- if ui.input(|i| i.is_scrolling()) {
+ // egui smooths a Point event that moved at least 8 points, keeping part of it for later
+ // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,
+ // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held
+ // point input measured 33 points for a 30-point event). Keep hiding the eased copy until
+ // egui says the action is over, then forget the suppression.
+ let scrolling = ui.input(|i| i.is_scrolling());
+ if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {
+ if scrolling {
// Keep hiding egui's unprocessed copy until it has drained. The short rolling grace
// avoids a delayed duplicate without prolonging suppression after the tail is gone.
view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);
@@ -2988,10 +3125,9 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
}
} else {
precise_scroll = Vec2::ZERO;
- if line_base != Vec2::ZERO || has_page {
- // Selection handling below uses zero to distinguish an inactive window.
- view.precise_scroll_until = 0.0;
- }
+ // Selection handling below uses zero to distinguish an inactive window. Clearing a past
+ // deadline also keeps a later line/page action from being mistaken for the old tail.
+ view.precise_scroll_until = 0.0;
}
if has_page && paging_owns_vertical {
// Page input belongs to egui on the free axis; the pager still owns vertical motion.
@@ -3013,6 +3149,14 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
if view.fling.gliding() {
ui.ctx().request_repaint();
}
+ // Any reader-owned motion ends automatic search following, even when it stays on the same
+ // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the
+ // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so
+ // its programmatic scroll is never mistaken for a reader action.
+ let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;
+ if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {
+ view.end_find_following();
+ }
// The wheel may have turned the page above: draw the row it turned to. Measured from the old
// row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.
let row = shown_row(view);
@@ -3062,6 +3206,9 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
} else {
ui.input(|i| i.pointer.delta())
};
+ if moved != Vec2::ZERO {
+ view.end_find_following();
+ }
// Within the content, as egui keeps it: past an end the page would show there for a
// frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.
let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));
@@ -3204,7 +3351,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
}
}
let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);
- let out = page_scroll(ui, scroll, egui::Id::new(("page-view-scope", view.id)), |ui, viewport| {
+ let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {
// egui's drag responses accept every pointer button. Keep a wheel gesture from also
// selecting text, drawing a mark, or panning with the Hand tool.
if middle_gesture {
@@ -4011,6 +4158,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
{
let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));
if dy != 0.0 {
+ view.end_find_following();
ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());
// Keep scrolling while the pointer rests there and sends no events.
ui.ctx().request_repaint();
@@ -4114,7 +4262,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
&& let Some((page, at)) = view.comments.context_at
{
// The page's content is parsed once per right-click, not on every frame the menu is open.
- let key = egui::Id::new("copy-image-under-menu");
+ let key = egui::Id::unique("copy-image-under-menu");
let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option)>(key)).filter(|c| c.0 == page && c.1 == at);
let hit = match cached {
Some(c) => c.2,
@@ -4145,7 +4293,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
// below the window's top). Within a point, as for wheel paging, so layout rounding
// can't hide an edge.
let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);
- (page, out.state.offset.y <= MARGIN - view.page_gap() + 1.0, out.state.offset.y >= max_y - 1.0)
+ (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)
});
view.viewport_screen = out.inner_rect;
@@ -4160,7 +4308,20 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
// backdrop/older tiles instead of queueing a storm of interprets (one per frame) that
// the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;
// pages with nothing on screen yet still queue.
- let scroll_offset = out.state.offset;
+ let scroll_offset = out.state.clamped_offset();
+ // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas
+ // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag
+ // background. The output gives us the area id, and egui's pinned ScrollArea registers those
+ // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.
+ // Ask for their exact responses instead of treating any held drag as scrolling: a text
+ // selection, a panel splitter or another widget's drag must not excuse the programmatic jump
+ // a search flash makes, while a track click (which moves the offset with no pointer motion)
+ // must still count as the reader scrolling.
+ let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());
+ let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));
+ if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {
+ view.end_find_following();
+ }
let now_settle = ui.input(|i| i.time);
if (scroll_offset - view.last_scroll).length() > 2.0 {
view.pan_hold_until = now_settle + 0.25;
@@ -4293,7 +4454,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
if let Some((pos, text)) = hover_text {
// Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.
- let tip = egui::Area::new(egui::Id::new("canvas-hover")).order(egui::Order::Tooltip).interactable(false);
+ let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);
tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_max_width(320.0);
@@ -4567,26 +4728,29 @@ fn selection_actions(
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));
let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };
let mut chosen = None;
- egui::Area::new(egui::Id::new(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(ui.ctx(), |ui| {
- egui::Frame::popup(ui.style()).show(ui, |ui| {
- ui.horizontal(|ui| {
- for (label, action) in [
- (tl!("Add comment"), SelectionAction::Note),
- (tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
- (tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
- (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
- (tl!("Replace text"), SelectionAction::Replace),
- ] {
- if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
- chosen = Some(action);
+ egui::Area::new(egui::Id::unique(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(
+ ui.ctx(),
+ |ui| {
+ egui::Frame::popup(ui.style()).show(ui, |ui| {
+ ui.horizontal(|ui| {
+ for (label, action) in [
+ (tl!("Add comment"), SelectionAction::Note),
+ (tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
+ (tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
+ (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
+ (tl!("Replace text"), SelectionAction::Replace),
+ ] {
+ if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
+ chosen = Some(action);
+ }
}
- }
- if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
- chosen = Some(SelectionAction::Copy);
- }
+ if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
+ chosen = Some(SelectionAction::Copy);
+ }
+ });
});
- });
- });
+ },
+ );
let Some(action) = chosen else { return false };
if let SelectionAction::Copy = action {
// Copying closes the bar but keeps the words selected, for ⌘C or a second action.
@@ -4755,7 +4919,7 @@ fn page_size_hint(view: &DocView, info: &DocInfo, units: crate::units::Unit, are
return;
}
let text = units.size(f64::from(page.width), f64::from(page.height));
- egui::Area::new(egui::Id::new("page-size-hint"))
+ egui::Area::new(egui::Id::unique("page-size-hint"))
.order(egui::Order::Foreground)
.interactable(false)
.pivot(egui::Align2::LEFT_BOTTOM)
@@ -4782,7 +4946,7 @@ fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t:
let mut close = false;
let mut step: Option = None;
let searched = view.texts.len() + view.text_failed.len();
- egui::Area::new(egui::Id::new("find-bar"))
+ egui::Area::new(egui::Id::unique("find-bar"))
.order(egui::Order::Middle)
.pivot(Align2::RIGHT_TOP)
.fixed_pos(area.right_top() + vec2(-18.0, 12.0))
@@ -4797,11 +4961,11 @@ fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t:
ui.horizontal(|ui| {
ui.add(icons::image("search", 16.0, t.text_muted));
let edit = egui::TextEdit::singleline(&mut find.query)
- .id(egui::Id::new("find-input"))
+ .id(egui::Id::unique("find-input"))
.hint_text(tl!("Find text"))
.desired_width(220.0)
.frame(egui::Frame::NONE);
- let r = ui.add(edit);
+ let r = ui.add(edit).accessible_name(tl!("Find text"));
if find.focus {
r.request_focus();
find.focus = false;
@@ -5112,7 +5276,7 @@ fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, te
fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let pos = area.left_top() + vec2(14.0, 14.0);
- egui::Area::new(egui::Id::new("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {
+ egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::NONE
.fill(t.card)
.stroke(Stroke::new(1.0, t.border))
@@ -5174,7 +5338,7 @@ fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {
}
let click = theme::hand(click);
let info = tl!(tool.label()).to_string();
- click.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, on, info.clone()));
+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));
if click.clicked() {
app.execute(tool.command());
ui.close();
@@ -5253,7 +5417,7 @@ fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {
}
let click = theme::hand(click);
let info = tl!(tool.label()).to_string();
- click.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, on, info.clone()));
+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));
if click.clicked() {
app.execute(tool.command());
ui.close();
@@ -5387,7 +5551,7 @@ fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, dirty: b
let percent = egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted))
.frame(false);
let percent = ui.add_sized([44.0, 30.0], percent);
- percent.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Reset page size")));
+ percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));
if percent.on_hover_text(tl!("Reset page size")).clicked() {
view.grid_zoom_request = Some(1.0);
}
@@ -5450,8 +5614,8 @@ fn copy_modifier(ctx: &egui::Context, m: &egui::Modifiers) -> bool {
/// A "+" on a gap of the page grid: insert files there. Returns whether it was clicked.
fn gap_button(ui: &mut egui::Ui, gap: usize, at: Pos2, height: f32, label: String, t: &Tokens) -> bool {
- let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.id().with(("org-gap", gap)), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.clone()));
+ let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.scope_id().with(("org-gap", gap)), Sense::click());
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));
let hot = resp.hovered();
if hot {
ui.painter().line_segment([pos2(at.x, at.y - height / 2.0), pos2(at.x, at.y + height / 2.0)], Stroke::new(3.0, t.accent));
@@ -5515,7 +5679,7 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool
let Some(p) = info.pages.get(i) else { break };
let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);
view.need_thumbnail(i, c.intersects(ui.clip_rect()));
- let resp = ui.interact(c, ui.id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });
+ let resp = ui.interact(c, ui.scope_id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });
cells.push((i, c));
if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {
ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());
@@ -5534,7 +5698,7 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool
drop = true;
}
let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, view.selected.contains(&i), page_label.clone()));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, view.selected.contains(&i), page_label.clone()));
let pr = grid_page_rect(c, vec2(p.width, p.height));
let size = pr.size();
let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);
@@ -5587,7 +5751,7 @@ fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool
let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));
let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;
let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);
- check.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, checked, label.clone()));
+ check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, checked, label.clone()));
if check.on_hover_text(label).changed() {
view.click_page(i, egui::Modifiers::COMMAND, false);
// The document shows the page picked here when the grid closes, as after a
@@ -6149,14 +6313,445 @@ trailer << /Root 1 0 R >>
assert_eq!(v.goto, Some((3, 0.5)));
assert!(v.back.is_empty());
assert_eq!(v.forward, vec![4]);
- v.current = 0;
v.find.as_mut().unwrap().current = None;
- v.refresh_find_page(3);
- assert_eq!(v.current, 3);
- assert!(v.back.is_empty());
+ v.texts.insert(1, Arc::new(find_test_text("match")));
+ v.refresh_find_page(1);
+ assert_eq!(v.current, 1, "an automatic late match still follows its anchor");
+ assert!(v.back.is_empty(), "automatic search updates do not record history");
assert_eq!(v.forward, vec![4]);
}
+ /// One glyph per character on one line, for the search-order tests below.
+ fn find_test_text(s: &str) -> PageText {
+ PageText {
+ glyphs: s
+ .chars()
+ .map(|c| pdfcraft_render::TextGlyph { text: c.into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] })
+ .collect(),
+ line_of: s.chars().map(|_| 0).collect(),
+ space_before: s.chars().map(|_| false).collect(),
+ }
+ }
+
+ /// A text-layer result for `page`, for the search tests below.
+ fn find_text_result(page: usize, text: &str) -> pdfcraft_render::RenderedPage {
+ pdfcraft_render::RenderedPage {
+ request: RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() },
+ width: 0,
+ height: 0,
+ rgba: Default::default(),
+ error: None,
+ text: Some(Arc::new(find_test_text(text))),
+ warnings: Vec::new(),
+ millis: 0,
+ }
+ }
+
+ /// Text layers arrive in whatever order the workers finish, not in page order. A search
+ /// started on page 1 must settle on page 1's match even when page 2's text arrives first,
+ /// instead of keeping the later match picked only because page 1 had not been read yet.
+ #[test]
+ fn automatic_search_match_follows_the_viewed_page_when_text_arrives_out_of_order() {
+ let mut v = view(2, PageLayout::Single, true);
+ v.current = 0;
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!(v.find.as_ref().unwrap().current, None, "no text yet, so no match");
+
+ let ctx = egui::Context::default();
+ let request = |page| RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ let result = |page, text: &str| pdfcraft_render::RenderedPage {
+ request: request(page),
+ width: 0,
+ height: 0,
+ rgba: Default::default(),
+ error: None,
+ text: Some(Arc::new(find_test_text(text))),
+ warnings: Vec::new(),
+ millis: 0,
+ };
+ v.last_queue = vec![request(1), request(0)];
+ // Page 2's text finishes first, as it can when the workers race.
+ v.receive_result(&ctx, result(1, "Second page sample text"));
+ assert_eq!(v.find.as_ref().unwrap().current, Some(0), "the only known match is picked while page 1 is pending");
+
+ v.receive_result(&ctx, result(0, "Panel sample draft notes"));
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::>(), vec![0, 1]);
+ assert_eq!(f.current, Some(0), "page 1's match takes over once its text arrives");
+ assert_eq!(v.current, 0, "the view follows the first match at or after the page being viewed");
+ }
+
+ /// A match the user picked (a click in the Search panel, or ⌘G) is not moved by a text
+ /// layer that arrives later: only automatic choices follow the viewed page.
+ #[test]
+ fn a_user_picked_search_match_stays_put_when_earlier_text_arrives() {
+ let mut v = view(2, PageLayout::Single, true);
+ v.current = 0;
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ v.texts.insert(1, Arc::new(find_test_text("Second page sample text")));
+ v.refresh_find_page(1);
+ v.go_to_match(0);
+ assert_eq!(v.find.as_ref().unwrap().auto_from, None, "an explicit choice is not automatic");
+
+ v.texts.insert(0, Arc::new(find_test_text("Panel sample draft notes")));
+ v.refresh_find_page(0);
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::>(), vec![0, 1]);
+ assert_eq!(f.current, Some(1), "the picked match keeps its identity after page 1 is inserted");
+ assert_eq!(v.current, 1, "the user's page does not change under them");
+ }
+
+ /// The automatic choice may move the view only while the reader has left it where that
+ /// choice put it. Navigating by the page box/Pages panel/outline or by view history is the
+ /// reader's decision: a text layer arriving afterwards must not pull them back to an
+ /// anchor-derived match. (The harness covers same-page wheel and pointer scrolling.)
+ #[test]
+ fn a_late_automatic_match_does_not_override_the_readers_navigation() {
+ enum Nav {
+ Page,
+ History,
+ }
+ for nav in [Nav::Page, Nav::History] {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(2, Arc::new(find_test_text("Second page sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (2, Some(2)), "the automatic match was shown");
+ match nav {
+ // The page box, the Pages panel and outline destinations all end here.
+ Nav::Page => v.go_to_page(1),
+ // View ▸ Page navigation ▸ Previous view writes `current` directly.
+ Nav::History => {
+ v.back = vec![1];
+ assert!(v.view_history(false));
+ }
+ }
+ assert_eq!(v.current, 1);
+ v.texts.insert(0, Arc::new(find_test_text("First page sample")));
+ v.refresh_find_page(0);
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.auto_from, None, "the reader's navigation ends automatic following");
+ assert_eq!(f.auto_page, None);
+ assert_eq!(v.current, 1, "a late match cannot pull the reader back");
+ }
+ }
+
+ /// Typing on while the results arrive must not re-anchor the search on a page the automatic
+ /// flash picked. The anchor stays the page the reader was on when they started searching.
+ #[test]
+ fn refining_the_query_keeps_the_page_the_search_started_from() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(2, Arc::new(find_test_text("Second page sample text")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (2, Some(0)), "the first query's match scrolled the view");
+
+ // Page 1 has a match for the refined query, and so has page 3. Anchored on the page the
+ // automatic flash reached, the search would pick page 3; the starting page picks page 1.
+ v.texts.insert(0, Arc::new(find_test_text("Panel draft text")));
+ v.find.as_mut().unwrap().query = "text".into();
+ v.rerun_find();
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader searched from");
+ assert_eq!(f.matches.first().map(|(p, _)| *p), Some(0));
+ assert_eq!(f.current, Some(0));
+ assert_eq!(v.current, 0);
+ }
+
+ /// ⌘G / Ctrl+G goes through `find_step`, an explicit choice like a Search-panel click: a
+ /// text layer arriving later must not undo it.
+ #[test]
+ fn keyboard_find_step_is_explicit_and_a_late_text_layer_cannot_undo_it() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(1, Arc::new(find_test_text("first sample")));
+ v.texts.insert(2, Arc::new(find_test_text("second sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (1, Some(0)));
+
+ let ctx = egui::Context::default();
+ ctx.input_mut(|i| {
+ i.events.push(egui::Event::Key {
+ key: egui::Key::G,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::COMMAND,
+ });
+ });
+ shortcuts(&mut v, &ctx, Default::default());
+
+ assert_eq!(v.current, 2, "the keyboard step chose the next match");
+ assert_eq!(v.find.as_ref().unwrap().auto_from, None, "the keyboard step is the user's choice");
+ assert_eq!(v.back, vec![1], "an explicit search jump records its origin");
+
+ v.texts.insert(0, Arc::new(find_test_text("intro sample")));
+ v.refresh_find_page(0);
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(v.current, 2, "the chosen match keeps the view");
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(2));
+ }
+
+ /// A page whose text extraction failed keeps the automatic anchor: the failure selects the
+ /// next match without moving the view, and a later text layer can still follow the anchor.
+ #[test]
+ fn a_failed_text_layer_keeps_the_automatic_anchor_without_jitter() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(1, Arc::new(find_test_text("first sample")));
+ v.texts.insert(2, Arc::new(find_test_text("second sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)));
+
+ let goto = v.goto;
+ let ctx = egui::Context::default();
+ let request = RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() };
+ v.last_queue = vec![request];
+ v.receive_result(
+ &ctx,
+ pdfcraft_render::RenderedPage {
+ request,
+ width: 0,
+ height: 0,
+ rgba: Default::default(),
+ error: Some("extraction failed".into()),
+ text: None,
+ warnings: Vec::new(),
+ millis: 0,
+ },
+ );
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::>(), vec![2]);
+ assert_eq!(f.current, Some(0), "the remaining match is selected");
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)), "a failure does not end automatic following");
+ assert_eq!(v.current, 1, "a failure never moves the view");
+ assert_eq!(v.goto, goto, "a failure never flashes the match");
+
+ // The search still follows its original page when that page's text arrives.
+ v.last_queue = vec![RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }];
+ v.receive_result(&ctx, find_text_result(0, "intro sample"));
+ assert_eq!(v.current, 0, "the anchor's earlier match takes over");
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0));
+ }
+
+ /// A reader who navigated before a page's text failed is not pulled back by a later
+ /// matching layer: the failure path must preserve the same `Ended` state as a successful
+ /// one, and the result list may select the late match without revealing it.
+ #[test]
+ fn a_failed_text_layer_after_navigation_does_not_reveal_a_late_match() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ v.go_to_page(2);
+ let moved = v.goto;
+ assert!(v.find.as_ref().unwrap().follow_ended, "the reader navigated before any match arrived");
+
+ let ctx = egui::Context::default();
+ let failed = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ v.last_queue = vec![failed];
+ v.receive_result(
+ &ctx,
+ pdfcraft_render::RenderedPage {
+ request: failed,
+ width: 0,
+ height: 0,
+ rgba: Default::default(),
+ error: Some("extraction failed".into()),
+ text: None,
+ warnings: Vec::new(),
+ millis: 0,
+ },
+ );
+ let f = v.find.as_ref().unwrap();
+ assert!(f.follow_ended, "a failure after navigation does not restart following");
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ assert_eq!(v.current, 2, "a failure never moves the view");
+ assert_eq!(v.goto, moved);
+
+ let arrived = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ v.last_queue = vec![arrived];
+ v.receive_result(&ctx, find_text_result(0, "intro sample"));
+ let f = v.find.as_ref().unwrap();
+ assert!(f.follow_ended);
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ assert_eq!(v.current, 2, "the late matching layer does not pull the reader back");
+ assert_eq!(v.goto, moved, "no flash was issued");
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");
+ }
+
+ /// The reader can navigate before any text layer has supplied a match. That navigation
+ /// still ends automatic following, so the first late match is listed but not revealed by
+ /// a flash that would pull the reader back.
+ #[test]
+ fn navigation_before_the_first_match_is_not_overridden_by_a_late_text_layer() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.current, None, "no text layer has arrived yet");
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));
+
+ v.go_to_page(2);
+ assert_eq!(v.goto, Some((2, 0.0)), "the reader moved to page 3");
+ assert!(v.find.as_ref().unwrap().follow_ended, "moving the view ends automatic following");
+
+ let ctx = egui::Context::default();
+ let request = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ v.last_queue = vec![request];
+ v.receive_result(&ctx, find_text_result(1, "late sample"));
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(v.current, 2, "the late first match does not pull the reader back");
+ assert_eq!(v.goto, Some((2, 0.0)), "no flash was issued");
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the result list still selects the match");
+ }
+
+ /// A page-box jump to the page already shown is still the reader's navigation: automatic
+ /// following must end, so a late earlier match is listed without moving the view. (The
+ /// harness covers wheel, scrollbar and pointer scrolling through the production paint path.)
+ #[test]
+ fn a_same_page_page_box_jump_ends_automatic_following() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(1, Arc::new(find_test_text("first sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");
+
+ // Choosing the page already shown still ends following; it stays on page 2 at its top.
+ v.go_to_page(1);
+ let shown = v.goto;
+ assert_eq!(shown, Some((1, 0.0)));
+
+ v.texts.insert(0, Arc::new(find_test_text("intro sample")));
+ v.refresh_find_page(0);
+ let f = v.find.as_ref().unwrap();
+ assert!(f.follow_ended);
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ assert_eq!(v.current, 1, "the late earlier match does not move the reader within the page");
+ assert_eq!(v.goto, shown, "no flash was issued");
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the page-2 match stays selected");
+ }
+
+ /// A document-wide invalidation (a layer toggle, an edit, undo/redo) clears results for
+ /// re-extraction but is not the reader navigating. Automatic following keeps its anchor so
+ /// the re-extracted layers still reveal the automatic choice; a reader who already took
+ /// over stays in control. If `document_changed` clamps the view away from that anchor, the
+ /// next layer ends following instead of revealing a match from the stale page.
+ #[test]
+ fn content_invalidation_keeps_the_following_state() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(1, Arc::new(find_test_text("first sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");
+
+ v.invalidate_content();
+ let f = v.find.as_ref().unwrap();
+ assert!(f.matches.is_empty() && f.current.is_none(), "results wait for the re-extracted text");
+ assert!(!f.follow_ended, "a content change is not reader navigation");
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)));
+
+ // Re-extracted text still follows the page the search started from.
+ let ctx = egui::Context::default();
+ let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ v.last_queue = vec![request];
+ v.receive_result(&ctx, find_text_result(0, "intro sample"));
+ assert_eq!(v.current, 0, "the re-extracted match is revealed by the still-active search");
+ let f = v.find.as_ref().unwrap();
+ assert!(!f.follow_ended);
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));
+
+ // A reader who navigated first keeps the view they chose across the invalidation.
+ v.go_to_page(2);
+ let moved = v.goto;
+ assert!(v.find.as_ref().unwrap().follow_ended);
+ v.invalidate_content();
+ let f = v.find.as_ref().unwrap();
+ assert!(f.follow_ended);
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ v.last_queue = vec![request];
+ v.receive_result(&ctx, find_text_result(0, "late sample"));
+ assert_eq!(v.current, 2, "no delayed reveal after the reader navigated");
+ assert_eq!(v.goto, moved, "no flash was issued");
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");
+ }
+
+ /// A document edit can shrink the page count. `document_changed` clamps `current` but leaves
+ /// the automatic anchor's page index alone; a re-extracted layer must then end following
+ /// rather than reveal a match by scrolling from a page that no longer exists.
+ #[test]
+ fn a_page_count_shrink_ends_following_before_a_late_reveal() {
+ let mut v = view(5, PageLayout::Single, true);
+ v.current = 0;
+ v.texts.insert(4, Arc::new(find_test_text("last sample")));
+ v.find = Some(Find { query: "sample".into(), ..Default::default() });
+ v.rerun_find();
+ assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (4, Some(4)), "the automatic choice is on the last page");
+
+ let info = pdfcraft_render::DocInfo {
+ pages: (0..2)
+ .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })
+ .collect(),
+ ..Default::default()
+ };
+ v.document_changed(&info);
+ assert_eq!(v.current, 1, "the view clamps to the last remaining page");
+ let f = v.find.as_ref().unwrap();
+ assert!(!f.follow_ended, "the content change itself keeps the automatic state");
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(4)), "the anchor still names the removed page");
+ let goto = v.goto;
+
+ let ctx = egui::Context::default();
+ let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };
+ v.last_queue = vec![request];
+ v.receive_result(&ctx, find_text_result(0, "intro sample"));
+ let f = v.find.as_ref().unwrap();
+ assert!(f.follow_ended, "a layer for the remaining pages ends the stale follow");
+ assert_eq!((f.auto_from, f.auto_page), (None, None));
+ assert_eq!(v.current, 1, "the late layer cannot pull the view back");
+ assert_eq!(v.goto, goto, "no flash was issued");
+ assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the match");
+ }
+
+ /// Typing refinements while text layers keep arriving must keep the page the search began
+ /// on, not re-anchor on whichever page an earlier automatic flash happened to show.
+ #[test]
+ fn rapid_query_edits_interleaved_with_text_results_keep_the_start_anchor() {
+ let mut v = view(3, PageLayout::Single, true);
+ v.current = 0;
+ v.find = Some(Find { query: "sam".into(), ..Default::default() });
+ v.rerun_find();
+ assert!(v.find.as_ref().unwrap().current.is_none());
+
+ let edits = [("samp", 2, "Page three sample", 2), ("sampl", 1, "Page two sample", 1), ("sample", 0, "Page one sample", 0)];
+ for (query, page, text, shown) in edits {
+ v.find.as_mut().unwrap().query = query.into();
+ v.rerun_find();
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader started from");
+ assert!(!f.follow_ended);
+ v.texts.insert(page, Arc::new(find_test_text(text)));
+ v.refresh_find_page(page);
+ let f = v.find.as_ref().unwrap();
+ assert_eq!(v.current, shown, "the late page follows the automatic anchor {shown}");
+ assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(shown)));
+ assert!(!f.follow_ended, "the automatic flash itself does not end following");
+ }
+ assert!(v.back.is_empty(), "automatic search updates do not record history");
+ }
+
#[test]
fn text_layers_evict_far_pages_but_keep_visible_and_matches() {
let info = thumbnail_info(100);
@@ -6978,6 +7573,7 @@ trailer << /Root 1 0 R >>
delta: vec2(0.0, -100_000.0),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
});
// Well past egui's longest scroll animation (about 0.3 s).
h.run_steps(40);
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index 2723d16c23..b977112460 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -1,6 +1,7 @@
//! Window chrome: tab strip (with the integrated macOS title bar), mode bar, right rail.
-use egui::{Align, Align2, Color32, CornerRadius, Layout, Rect, Sense, Stroke, vec2};
+use craft_ui::panes::{Edge, Rail, RailItem, RailRequest};
+use egui::{Align, Color32, CornerRadius, Layout, Rect, Sense, Stroke, vec2};
use crate::canvas::{DocView, Fit, PageLayout};
use crate::theme::{self, ThemePreference, Tokens};
@@ -26,6 +27,8 @@ const TAB_STRIP: f32 = 38.0;
const TAB_HEIGHT: f32 = 30.0;
const STRIP_BUTTON: f32 = 28.0;
+/// Draw the window's tab strip: home and open controls, shrinkable and scrollable document tabs with drag
+/// reordering, and platform window controls.
pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
// macOS: the strip is the 28 pt title bar, so the traffic lights are centred in it; tabs and
@@ -38,7 +41,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
.frame(egui::Frame::NONE.fill(t.titlebar).inner_margin(egui::Margin { left, right: 10, top: 0, bottom: 0 }))
.show(ui, |ui| {
let full = ui.max_rect();
- let drag = ui.interact(full, ui.id().with("titledrag"), Sense::click_and_drag());
+ let drag = ui.interact(full, ui.scope_id().with("titledrag"), Sense::click_and_drag());
if drag.drag_started() {
window_controls::desktop_grab(ui.ctx(), egui::ViewportCommand::StartDrag);
}
@@ -92,7 +95,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
let cap = tab_cap(&natural, tabs_width, gap, TAB_MIN_WIDTH);
// Where the tabs were scrolled to last frame, and how far they can go.
- let scroll_id = ui.id().with("tab_scroll");
+ let scroll_id = ui.scope_id().with("tab_scroll");
let (offset, max_offset) = ui.data(|d| d.get_temp::<(f32, f32)>(scroll_id)).unwrap_or((0.0, 0.0));
let mut scroll_to = None;
if overflow && arrow(ui, "chevron-left", offset > 0.5, tl!("Scroll tabs left")) {
@@ -102,7 +105,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
// the strip jumping to it.
let state = (app.active_ids().map(|(_, id)| id), app.views.len(), app.combine_showing());
let changed = ui.data_mut(|data| {
- let id = ui.id().with("active_tab");
+ let id = ui.scope_id().with("active_tab");
let changed = data.get_temp::<(Option, usize, bool)>(id) != Some(state);
data.insert_temp(id, state);
changed
@@ -131,7 +134,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let file = (name != doc.name).then_some(doc.name.as_str());
let response = tab(
ui,
- ui.id().with(("document-tab", app.views[i].id)),
+ ui.scope_id().with(("document-tab", app.views[i].id)),
&t,
"file-text",
&name,
@@ -213,7 +216,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let mut close = None;
let response = tab(
ui,
- ui.id().with("combine-tab"),
+ ui.scope_id().with("combine-tab"),
&t,
"files",
tl!("Combine files"),
@@ -239,7 +242,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
});
});
let max = (out.content_size.x - out.inner_rect.width()).max(0.0);
- ui.data_mut(|d| d.insert_temp(scroll_id, (out.state.offset.x, max)));
+ ui.data_mut(|d| d.insert_temp(scroll_id, (out.state.clamped_offset().x, max)));
// A tab dragged to either edge of a strip that scrolls brings the hidden tabs in.
if let Some(x) = drag_x
&& max > 0.0
@@ -252,7 +255,7 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
0.0
};
if step != 0.0 {
- ui.data_mut(|d| d.insert_temp(scroll_id.with("to"), (out.state.offset.x + step).clamp(0.0, max)));
+ ui.data_mut(|d| d.insert_temp(scroll_id.with("to"), (out.state.clamped_offset().x + step).clamp(0.0, max)));
ui.ctx().request_repaint();
}
}
@@ -383,7 +386,7 @@ fn tab_name(name: &str) -> String {
/// The width a tab takes when nothing has to shrink.
fn tab_natural_width(ui: &egui::Ui, t: &Tokens, name: &str) -> f32 {
- let label = crate::bidi::visual(&tab_name(name)).into_owned();
+ let label = tab_name(name);
ui.fonts_mut(|f| f.layout_no_wrap(label, theme::regular(13.0), t.text).size().x) + TAB_CHROME
}
@@ -411,6 +414,8 @@ fn tab_cap(natural: &[f32], budget: f32, gap: f32, min: f32) -> Option {
None
}
+/// Draw one tab with its icon, elided label, close button and unsaved dot; records a close request and
+/// returns the tab response for drag handling.
#[allow(clippy::too_many_arguments)]
fn tab(
ui: &mut egui::Ui,
@@ -432,13 +437,13 @@ fn tab(
// A shrunk tab shows as much of its name as fits (the tooltip has all of it).
if let Some(cap) = cap {
let room = (cap - TAB_CHROME).max(0.0);
- label = ui.fonts_mut(|f| {
- crate::panels::ellipsized_prefix(&label, |s| f.layout_no_wrap(crate::bidi::visual(s).into_owned(), font.clone(), t.text).size().x <= room)
- });
+ label = crate::panels::ellipsized_prefix(&label, |s| crate::bidi::layout_ltr(ui, s.to_owned(), font.clone(), t.text).size().x <= room);
}
- // Painted text only: the accessibility name below keeps the logical order.
- let label = crate::bidi::visual(&label).into_owned();
- let text_w = ui.fonts_mut(|f| f.layout_no_wrap(label.clone(), font.clone(), t.text).size().x);
+ // Logical text, laid out explicitly left to right: the fork shapes and reorders it once,
+ // and an Arabic file name keeps its extension at the visual end. AccessKit names stay logical.
+ let label_color = if active { t.text } else { t.text_muted };
+ let label_galley = crate::bidi::layout_ltr(ui, label.clone(), font.clone(), label_color);
+ let text_w = label_galley.size().x;
let width = cap.map_or(text_w + TAB_CHROME, |cap| (text_w + TAB_CHROME).min(cap));
// Full strip height so the active tab sits on the mode bar instead of floating in the title bar.
let height = ui.available_height().max(height);
@@ -462,7 +467,7 @@ fn tab(
15.0,
if active { t.accent } else { t.text_muted },
);
- ui.painter().text(rect.min + vec2(28.0, rect.height() / 2.0), Align2::LEFT_CENTER, label, font, if active { t.text } else { t.text_muted });
+ ui.painter().galley(rect.min + vec2(28.0, (rect.height() - label_galley.size().y) / 2.0), label_galley.clone(), label_color);
});
let x_rect = Rect::from_center_size(rect.right_center() - vec2(16.0, 0.0), vec2(20.0, 20.0));
let x = ui.interact(x_rect, id.with("close"), Sense::click());
@@ -478,14 +483,10 @@ fn tab(
*close = Some(index);
}
let shown = match file {
- Some(file) => std::borrow::Cow::Owned(format!("{}\n{}", crate::bidi::visual(name), crate::bidi::visual(file))),
- None => crate::bidi::visual(name),
+ Some(file) => format!("{name}\n{file}"),
+ None => name.to_string(),
};
- theme::hand(resp).on_hover_text(if dirty {
- crate::i18n::fmt(tl!("{name} — unsaved changes"), &[("name", shown.as_ref())])
- } else {
- shown.into_owned()
- })
+ theme::hand(resp).on_hover_text(if dirty { crate::i18n::fmt(tl!("{name} — unsaved changes"), &[("name", &shown)]) } else { shown })
}
pub fn mode_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
@@ -636,6 +637,8 @@ fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
});
}
+/// Draw the right tool rail with page navigation, history, zoom, rotation and page-display controls for the
+/// active view.
pub fn right_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Some((index, id)) = app.active_ids() else { return };
@@ -651,166 +654,165 @@ pub fn right_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
);
let page_count = doc.info.pages.len();
let labels: Vec = doc.info.pages.iter().map(|p| p.label.clone()).collect();
- egui::Panel::right("rail")
- .resizable(false)
- .exact_size(48.0)
+ let item = |panel: RightPanel, icon: &str, label: &str, marker: Option<&str>| {
+ let item = RailItem::new(panel, icons::source(icon), tl!(label)).marker(marker.is_some());
+ match marker {
+ Some(marker) => item.marker_label(tl!(marker)),
+ None => item,
+ }
+ };
+ let has = |has: bool, label: &'static str| has.then_some(label);
+ let mut items = vec![
+ item(RightPanel::Comments, "message-square-text", "Comments", has(has_comments, "Has comments")),
+ item(RightPanel::Bookmarks, "bookmark", "Bookmarks", has(has_outline, "Has bookmarks")),
+ item(RightPanel::Pages, "files", "Page thumbnails", None),
+ item(RightPanel::Fields, "text-cursor-input", "Form fields", has(has_fields, "Has form fields")),
+ item(RightPanel::Layers, "layers", "Layers", has(has_layers, "Has layers")),
+ item(RightPanel::Attachments, "paperclip", "Attachments", has(has_files, "Has attachments")),
+ item(RightPanel::Signatures, "signature", "Signatures", has(has_signatures, "Signed")),
+ ];
+ if has_check {
+ items.push(item(RightPanel::Accessibility, "accessibility", "Accessibility Checker", None));
+ }
+ items.push(item(RightPanel::Tags, "tag", "Tags", None));
+ let view = &mut app.views[index];
+ let mut page_display = None;
+ let rail = Rail::new(egui::Id::unique("rail"))
+ .edge(Edge::End)
.frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(6, 8)).stroke(Stroke::new(1.0, t.divider)))
- .show(ui, |ui| {
- // Page navigation cluster at the bottom (as in Acrobat's rail). It is a panel of its own so
- // that in a short window the buttons above scroll instead of running into it (#3282).
- let view = &mut app.views[index];
- let mut page_display = None;
- egui::Panel::bottom("rail-nav").frame(egui::Frame::NONE).show_separator_line(false).resizable(false).show(ui, |ui| {
- ui.with_layout(Layout::bottom_up(Align::Center), |ui| {
- ui.spacing_mut().item_spacing.y = 2.0;
- let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom out ({key})"), crate::commands::ZOOM_OUT);
- if icons::button(ui, "zoom-out", 32.0, false, &tip).clicked() {
- view.zoom_step(false);
+ .show(ui, &items, app.right.as_ref(), |ui| {
+ // Page navigation cluster at the bottom, a panel of its own so that in a short
+ // window the buttons above scroll instead of running into it (#3282).
+ ui.with_layout(Layout::bottom_up(Align::Center), |ui| {
+ ui.spacing_mut().item_spacing.y = 2.0;
+ let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom out ({key})"), crate::commands::ZOOM_OUT);
+ if icons::button(ui, "zoom-out", 32.0, false, &tip).clicked() {
+ view.zoom_step(false);
+ }
+ let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom in ({key})"), crate::commands::ZOOM_IN);
+ if icons::button(ui, "zoom-in", 32.0, false, &tip).clicked() {
+ view.zoom_step(true);
+ }
+ // Between rotate and zoom, as in Acrobat. Its command runs once `view` is free.
+ let tip = crate::i18n::fmt(tl!("Page display: {layout}"), &[("layout", tl!(view.layout.label()))]);
+ let resp = icons::button(ui, view.layout.icon(), 32.0, false, &tip);
+ page_display = egui::Popup::menu(&resp)
+ .show(|ui| {
+ ui.set_min_width(220.0);
+ rail_view_menu(ui, view)
+ })
+ .and_then(|r| r.inner);
+ let tip = crate::commands::key_tip(ui.ctx(), tl!("Rotate view clockwise ({key})"), crate::commands::ROTATE_CW);
+ if icons::button(ui, "rotate-cw", 32.0, false, &tip).clicked() {
+ view.rotate_view(true);
+ }
+ // Not `columns-2` while fitting the page: that is the two-page view's icon.
+ let fit_icon = if view.fit == Fit::Width { "maximize" } else { "maximize-2" };
+ if icons::button(ui, fit_icon, 32.0, false, tl!("Toggle fit page / fit width")).clicked() {
+ view.fit = if view.fit == Fit::Width { Fit::Page } else { Fit::Width };
+ view.goto = Some((view.current, 0.0));
+ }
+ let id = egui::Id::unique("zoom-input");
+ let draft = id.with("draft");
+ let mut typed = ui.data(|d| d.get_temp::(draft)).unwrap_or_else(|| format!("{:.0}%", view.zoom * 100.0));
+ let edit = egui::TextEdit::singleline(&mut typed)
+ .id(id)
+ .desired_width(40.0)
+ .align(egui::Align2::CENTER_TOP)
+ .font(theme::medium(11.0))
+ .text_color(t.text_muted)
+ .frame(egui::Frame::NONE)
+ .margin(vec2(2.0, 2.0));
+ let r = ui.add(edit).on_hover_text(tl!("Zoom — type a percentage and press Enter"));
+ ui.ctx().accesskit_node_builder(id, |node| node.set_label(tl!("Zoom")));
+ if r.gained_focus() {
+ let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default();
+ let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(typed.chars().count()));
+ state.cursor.set_char_range(Some(all));
+ state.store(ui.ctx(), id);
+ }
+ if r.has_focus() {
+ ui.data_mut(|d| d.insert_temp(draft, typed.clone()));
+ } else {
+ ui.data_mut(|d| d.remove::(draft));
+ if r.lost_focus()
+ && ui.input(|i| i.key_pressed(egui::Key::Enter))
+ && let Some(zoom) = DocView::parse_zoom_percent(&typed)
+ {
+ view.set_zoom(zoom);
}
- let tip = crate::commands::key_tip(ui.ctx(), tl!("Zoom in ({key})"), crate::commands::ZOOM_IN);
- if icons::button(ui, "zoom-in", 32.0, false, &tip).clicked() {
- view.zoom_step(true);
+ }
+ ui.add_space(6.0);
+ if icons::button(ui, "chevron-down", 30.0, false, tl!("Next page")).clicked() {
+ view.step_page(true);
+ }
+ if icons::button(ui, "chevron-up", 30.0, false, tl!("Previous page")).clicked() {
+ view.step_page(false);
+ }
+ // History is distinct from stepping to the adjacent page, and belongs to this tab.
+ for (forward, icon, label, shortcut, enabled) in [
+ (true, "chevron-right", tl!("Next view"), crate::commands::NEXT_VIEW, !view.forward.is_empty()),
+ (false, "chevron-left", tl!("Previous view"), crate::commands::PREV_VIEW, !view.back.is_empty()),
+ ] {
+ let tip = format!("{label} ({})", crate::commands::shortcut_label(ui.ctx(), shortcut));
+ if ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, 30.0, false, &tip)).inner.clicked() {
+ view.view_history(forward);
}
- // Between rotate and zoom, as in Acrobat. Its command runs once `view` is free.
- let tip = crate::i18n::fmt(tl!("Page display: {layout}"), &[("layout", tl!(view.layout.label()))]);
- let resp = icons::button(ui, view.layout.icon(), 32.0, false, &tip);
- page_display = egui::Popup::menu(&resp)
- .show(|ui| {
- ui.set_min_width(220.0);
- rail_view_menu(ui, view)
- })
- .and_then(|r| r.inner);
- let tip = crate::commands::key_tip(ui.ctx(), tl!("Rotate view clockwise ({key})"), crate::commands::ROTATE_CW);
- if icons::button(ui, "rotate-cw", 32.0, false, &tip).clicked() {
- view.rotate_view(true);
+ }
+ let font = theme::regular(11.0);
+ let mut position = page_position(view.current, page_count, labels.get(view.current).map_or("", String::as_str));
+ if widgets::text_width(ui, &position, &font) > ui.available_width() {
+ position = page_count.to_string();
+ }
+ // Out of range (an empty document), like `page_position`: "Page 0 of 0", never past the end.
+ let shown = if view.current < page_count { view.current + 1 } else { page_count };
+ let of = crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &shown.to_string()), ("n", &page_count.to_string())]);
+ ui.label(egui::RichText::new(position).font(font).color(t.text_muted)).on_hover_text(of);
+ let page_input_id = view.page_input_id();
+ // Consume replacement selection once, including when the editor has lost focus.
+ let reselect = std::mem::take(&mut view.page_input_reselect);
+ // Navigation updates the idle display, never the text being edited.
+ if !ui.memory(|m| m.has_focus(page_input_id)) {
+ view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str));
+ } else if reselect {
+ // The replacement changed the label while egui retained this editor's cursor.
+ let mut state = egui::TextEdit::load_state(ui.ctx(), page_input_id).unwrap_or_default();
+ let end = egui::text::CCursor::new(view.page_input.chars().count());
+ state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), end)));
+ state.store(ui.ctx(), page_input_id);
+ }
+ let edit = egui::TextEdit::singleline(&mut view.page_input)
+ .id(page_input_id)
+ .desired_width(34.0)
+ .align(egui::Align2::CENTER_TOP)
+ .font(theme::medium(12.0))
+ .margin(vec2(2.0, 4.0));
+ let r = egui::Frame::NONE
+ .fill(t.field)
+ .stroke(Stroke::new(1.0, t.border))
+ .corner_radius(CornerRadius::same(5))
+ .show(ui, |ui| ui.add(edit))
+ .inner
+ .on_hover_text(tl!("Current page — type a page number or label (such as iv) and press Enter"))
+ .accessible_name(tl!("Current page"));
+ if r.lost_focus() {
+ if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ // A page label first (logical page numbers, as Acrobat), then a number.
+ let typed = view.page_input.clone();
+ view.go_to_typed(&typed, &labels);
}
- // Not `columns-2` while fitting the page: that is the two-page view's icon.
- let fit_icon = if view.fit == Fit::Width { "maximize" } else { "maximize-2" };
- if icons::button(ui, fit_icon, 32.0, false, tl!("Toggle fit page / fit width")).clicked() {
- view.fit = if view.fit == Fit::Width { Fit::Page } else { Fit::Width };
- view.goto = Some((view.current, 0.0));
- }
- let id = egui::Id::new("zoom-input");
- let draft = id.with("draft");
- let mut typed = ui.data(|d| d.get_temp::(draft)).unwrap_or_else(|| format!("{:.0}%", view.zoom * 100.0));
- let edit = egui::TextEdit::singleline(&mut typed)
- .id(id)
- .desired_width(40.0)
- .horizontal_align(Align::Center)
- .font(theme::medium(11.0))
- .text_color(t.text_muted)
- .frame(egui::Frame::NONE)
- .margin(vec2(2.0, 2.0));
- let r = ui.add(edit).on_hover_text(tl!("Zoom — type a percentage and press Enter"));
- ui.ctx().accesskit_node_builder(id, |node| node.set_label(tl!("Zoom")));
- if r.gained_focus() {
- let mut state = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default();
- let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(typed.chars().count()));
- state.cursor.set_char_range(Some(all));
- state.store(ui.ctx(), id);
- }
- if r.has_focus() {
- ui.data_mut(|d| d.insert_temp(draft, typed.clone()));
- } else {
- ui.data_mut(|d| d.remove::(draft));
- if r.lost_focus()
- && ui.input(|i| i.key_pressed(egui::Key::Enter))
- && let Some(zoom) = DocView::parse_zoom_percent(&typed)
- {
- view.set_zoom(zoom);
- }
- }
- ui.add_space(6.0);
- if icons::button(ui, "chevron-down", 30.0, false, tl!("Next page")).clicked() {
- view.step_page(true);
- }
- if icons::button(ui, "chevron-up", 30.0, false, tl!("Previous page")).clicked() {
- view.step_page(false);
- }
- // History is distinct from stepping to the adjacent page, and belongs to this tab.
- for (forward, icon, label, shortcut, enabled) in [
- (true, "chevron-right", tl!("Next view"), crate::commands::NEXT_VIEW, !view.forward.is_empty()),
- (false, "chevron-left", tl!("Previous view"), crate::commands::PREV_VIEW, !view.back.is_empty()),
- ] {
- let tip = format!("{label} ({})", crate::commands::shortcut_label(ui.ctx(), shortcut));
- if ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, 30.0, false, &tip)).inner.clicked() {
- view.view_history(forward);
- }
- }
- let font = theme::regular(11.0);
- let mut position = page_position(view.current, page_count, labels.get(view.current).map_or("", String::as_str));
- if widgets::text_width(ui, &position, &font) > ui.available_width() {
- position = page_count.to_string();
- }
- // Out of range (an empty document), like `page_position`: "Page 0 of 0", never past the end.
- let shown = if view.current < page_count { view.current + 1 } else { page_count };
- let of = crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &shown.to_string()), ("n", &page_count.to_string())]);
- ui.label(egui::RichText::new(position).font(font).color(t.text_muted)).on_hover_text(of);
- let page_input_id = view.page_input_id();
- // Consume replacement selection once, including when the editor has lost focus.
- let reselect = std::mem::take(&mut view.page_input_reselect);
- // Navigation updates the idle display, never the text being edited.
- if !ui.memory(|m| m.has_focus(page_input_id)) {
- view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str));
- } else if reselect {
- // The replacement changed the label while egui retained this editor's cursor.
- let mut state = egui::TextEdit::load_state(ui.ctx(), page_input_id).unwrap_or_default();
- let end = egui::text::CCursor::new(view.page_input.chars().count());
- state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), end)));
- state.store(ui.ctx(), page_input_id);
- }
- let edit = egui::TextEdit::singleline(&mut view.page_input)
- .id(page_input_id)
- .desired_width(34.0)
- .horizontal_align(Align::Center)
- .font(theme::medium(12.0))
- .margin(vec2(2.0, 4.0));
- let r = egui::Frame::NONE
- .fill(t.field)
- .stroke(Stroke::new(1.0, t.border))
- .corner_radius(CornerRadius::same(5))
- .show(ui, |ui| ui.add(edit))
- .inner
- .on_hover_text(tl!("Current page — type a page number or label (such as iv) and press Enter"));
- if r.lost_focus() {
- if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
- // A page label first (logical page numbers, as Acrobat), then a number.
- let typed = view.page_input.clone();
- view.go_to_typed(&typed, &labels);
- }
- view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str));
- }
- });
- });
- egui::ScrollArea::vertical().id_salt("rail-panels").show(ui, |ui| {
- ui.spacing_mut().item_spacing.y = 4.0;
- let mut rail_button = |ui: &mut egui::Ui, panel: RightPanel, icon: &str, tip: &str, has: bool| {
- let selected = app.right == Some(panel) && (app.mode == Mode::Read || app.docking.exposed(crate::docking::Panel::Inspector));
- let r = icons::button(ui, icon, 34.0, selected, tl!(tip));
- if has && !selected {
- let c = r.rect.right_top() + vec2(-8.0, 8.0);
- ui.painter().circle_filled(c, 3.0, t.accent);
- }
- if r.clicked() {
- app.choose_right_panel(if selected { None } else { Some(panel) });
- }
- };
- rail_button(ui, RightPanel::Comments, "message-square-text", "Comments", has_comments);
- rail_button(ui, RightPanel::Bookmarks, "bookmark", "Bookmarks", has_outline);
- rail_button(ui, RightPanel::Pages, "files", "Page thumbnails", false);
- rail_button(ui, RightPanel::Fields, "text-cursor-input", "Form fields", has_fields);
- rail_button(ui, RightPanel::Layers, "layers", "Layers", has_layers);
- rail_button(ui, RightPanel::Attachments, "paperclip", "Attachments", has_files);
- rail_button(ui, RightPanel::Signatures, "signature", "Signatures", has_signatures);
- if has_check {
- rail_button(ui, RightPanel::Accessibility, "accessibility", "Accessibility Checker", false);
+ view.page_input = view.current_page_label(labels.get(view.current).map(String::as_str));
}
- rail_button(ui, RightPanel::Tags, "tag", "Tags", false);
});
- if let Some(id) = page_display {
- app.execute(id);
- }
});
+ match rail.request {
+ Some(RailRequest::Open(panel)) => app.choose_right_panel(Some(panel)),
+ Some(RailRequest::Close(_)) => app.choose_right_panel(None),
+ _ => {}
+ }
+ if let Some(id) = page_display {
+ app.execute(id);
+ }
}
/// What the rail shows under the page box: the page count, or, when the current page's label is
diff --git a/crates/ui-egui/src/combine_grid.rs b/crates/ui-egui/src/combine_grid.rs
index ee3b03f698..f66ec0b843 100644
--- a/crates/ui-egui/src/combine_grid.rs
+++ b/crates/ui-egui/src/combine_grid.rs
@@ -614,7 +614,14 @@ pub(crate) fn grid(
let over_grid = ui.rect_contains_pointer(viewport);
let mut width = viewport.width();
let mut focused_card = None;
- let output = egui::ScrollArea::vertical().id_salt("combine-grid").auto_shrink([false, false]).show_viewport(ui, |ui, clip| {
+ // A zoom in the previous frame asks for a new scroll position. 0.37 keeps `State`'s offset
+ // private, so the request is applied through the builder and consumed here.
+ let pending_offset = ctx.data_mut(|d| d.remove_temp::(pending_offset_id()));
+ let mut grid = egui::ScrollArea::vertical().id_salt("combine-grid").auto_shrink([false, false]);
+ if let Some(offset) = pending_offset {
+ grid = grid.vertical_scroll_offset(offset.y);
+ }
+ grid.show_viewport(ui, |ui, clip| {
// Dragging near the top or bottom edge scrolls.
if drag.is_some()
&& let Some(p) = pointer
@@ -792,12 +799,10 @@ pub(crate) fn grid(
let cols = columns_in(width, cell);
let content = TOP + places.len().div_ceil(cols) as f32 * cell.y;
let y = (TOP + (i / cols) as f32 * cell.y - above).min(content - viewport.height()).max(0.0);
- // Set as the scroll position itself, before the next frame draws anything: no
+ // Applied by the next frame's scroll area, before anything is drawn there: no
// jump, and no scroll still animating (to a card revealed by the keys, say) can
- // carry it elsewhere.
- let mut state = egui::scroll_area::State::default();
- state.offset = vec2(0.0, y);
- state.store(&ctx, output.id);
+ // carry it elsewhere. The request is consumed once.
+ ctx.data_mut(|d| d.insert_temp(pending_offset_id(), vec2(0.0, y)));
}
ctx.request_repaint();
}
@@ -806,6 +811,11 @@ pub(crate) fn grid(
action
}
+/// The scroll position a zoom asked the next frame's grid to start at.
+fn pending_offset_id() -> egui::Id {
+ egui::Id::unique("pdfcraft-combine-grid-offset")
+}
+
/// One card's place and what it shows.
struct Card {
/// The file, by its place in the list.
@@ -826,8 +836,8 @@ struct Card {
impl Card {
fn id(&self, ui: &egui::Ui, f: &CombineFile) -> egui::Id {
match self.page {
- None => ui.id().with(("combine-card", f.id)),
- Some((nth, ..)) => ui.id().with(("combine-page", f.id, nth)),
+ None => ui.scope_id().with(("combine-card", f.id)),
+ Some((nth, ..)) => ui.scope_id().with(("combine-page", f.id, nth)),
}
}
@@ -845,7 +855,7 @@ impl Card {
};
// As the organize grid's pages: a check box that is on when selected; and, for screen
// readers, selected as items in a list are.
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, self.selected, &label));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.selected, &label));
let pages = match self.page {
// For screen readers: which page of how many.
Some((_, p, _)) => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &p.saturating_add(1).to_string()), ("n", &f.pages.to_string())]),
@@ -969,9 +979,11 @@ impl Card {
}
None => (theme::medium(12.5), t.text, name_y),
};
- let fits = |s: &str| painter.layout_no_wrap(crate::bidi::visual(s).into_owned(), font.clone(), colour).size().x <= max_w;
- let shown = crate::bidi::visual(&fit_name(&f.name, fits)).into_owned();
- painter.text(pos2(c.center().x, y), Align2::CENTER_CENTER, shown, font, colour);
+ let fits = |s: &str| crate::bidi::layout_ltr(ui, s.to_owned(), font.clone(), colour).size().x <= max_w;
+ let shown = fit_name(&f.name, fits);
+ // A file name is file/path chrome: always left to right, so an Arabic name ends in `.pdf`.
+ let name_galley = crate::bidi::layout_ltr(ui, shown, font, colour);
+ painter.galley(pos2(c.center().x - name_galley.size().x / 2.0, y - name_galley.size().y / 2.0), name_galley, colour);
let note = if self.page.is_none() && !f.range.trim().is_empty() {
match &self.check {
Ok(k) => Some((crate::i18n::fmt(tl!("Pages: {k} of {n}"), &[("k", &k.to_string()), ("n", &f.pages.to_string())]), t.text_muted)),
@@ -1143,10 +1155,10 @@ pub(crate) fn preview(app: &mut PdfCraftApp, ctx: &egui::Context, t: &Tokens) {
// No larger than the GPU takes, or the render would be refused.
let longest = ctx.input(|i| i.max_texture_side as f32).min(PREVIEW_SIDE);
let thumbs = &mut app.combine_thumbs;
- let modal = egui::Modal::new(egui::Id::new("combine-preview")).show(ctx, |ui| {
+ let modal = egui::Modal::new(egui::Id::unique("combine-preview")).show(ctx, |ui| {
ui.set_width(width);
ui.horizontal(|ui| {
- ui.label(egui::RichText::new(crate::bidi::visual(&f.name)).font(theme::semibold(15.0)));
+ ui.label(egui::RichText::new(f.name.clone()).font(theme::semibold(15.0)));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icons::button(ui, "x", 30.0, false, tl!("Close")).clicked() {
close = true;
diff --git a/crates/ui-egui/src/combine_ui.rs b/crates/ui-egui/src/combine_ui.rs
index 62d9163154..e7f7f26a19 100644
--- a/crates/ui-egui/src/combine_ui.rs
+++ b/crates/ui-egui/src/combine_ui.rs
@@ -742,7 +742,7 @@ pub(crate) fn page(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
ui.close();
}
for (i, name) in &open_docs {
- if ui.button(crate::bidi::visual(name).as_ref()).clicked() {
+ if ui.button(name.as_str()).clicked() {
app.add_open_documents(&[*i]);
ui.close();
}
@@ -921,7 +921,7 @@ fn skip_prompt(app: &mut PdfCraftApp, ctx: &egui::Context) {
left_out.push((f.name.as_str(), f.problem.as_deref().unwrap_or_default()));
}
let mut choice: Option = None;
- let modal = egui::Modal::new(egui::Id::new("combine-skip")).show(ctx, |ui| {
+ let modal = egui::Modal::new(egui::Id::unique("combine-skip")).show(ctx, |ui| {
ui.set_width(460.0);
ui.horizontal(|ui| {
ui.add(icons::image("triangle-alert", 22.0, ERROR));
@@ -932,7 +932,7 @@ fn skip_prompt(app: &mut PdfCraftApp, ctx: &egui::Context) {
ui.add_space(6.0);
for (name, why) in left_out.iter().take(SKIP_PROMPT_NAMES) {
ui.horizontal_wrapped(|ui| {
- ui.label(egui::RichText::new(format!("• {}", crate::bidi::visual(name))).strong());
+ ui.label(egui::RichText::new(format!("• {name}")).strong());
ui.label(egui::RichText::new(*why).color(t.text_muted));
});
}
@@ -978,7 +978,7 @@ fn unlock_prompt(app: &mut PdfCraftApp, ctx: &egui::Context) {
};
let batch = files.len() > 1;
let (mut submit, mut cancel) = (false, false);
- let area = egui::Area::new(egui::Id::new("combine-unlock")).order(egui::Order::Foreground).fixed_pos(prompt.at).show(ctx, |ui| {
+ let area = egui::Area::new(egui::Id::unique("combine-unlock")).order(egui::Order::Foreground).fixed_pos(prompt.at).show(ctx, |ui| {
egui::Frame::popup(ui.style()).inner_margin(egui::Margin::same(14)).show(ui, |ui| {
ui.set_width(340.0);
ui.horizontal(|ui| {
@@ -1189,7 +1189,7 @@ fn zoom_controls(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, edge: f32
let percent =
egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted)).frame(false);
let percent = ui.add_sized([44.0, 30.0], percent);
- percent.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Reset page size")));
+ percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));
if percent.on_hover_text(tl!("Reset page size")).clicked() {
app.combine_tab.zoom_request = Some(1.0);
}
@@ -1347,7 +1347,7 @@ fn heading(ui: &mut egui::Ui, t: &Tokens, key: SortKey, sort: Option<(SortKey, b
None => "",
};
let a11y = if state.is_empty() { text.to_owned() } else { format!("{text}, {state}") };
- response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &a11y));
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &a11y));
let being_dragged = egui::DragAndDrop::payload::(ui.ctx()).is_some_and(|p| p.0 == key);
if being_dragged || response.is_pointer_button_down_on() {
ui.painter().rect_filled(rect, CornerRadius::same(4), t.pressed);
@@ -1395,6 +1395,8 @@ fn heading(ui: &mut egui::Ui, t: &Tokens, key: SortKey, sort: Option<(SortKey, b
event
}
+/// Draw the Combine files table body: reorder handles, editable page ranges with validation, file metadata
+/// and per-row warnings.
#[allow(clippy::too_many_arguments)]
fn table_body(
app: &mut PdfCraftApp,
@@ -1410,7 +1412,7 @@ fn table_body(
let order = app.combine_columns.order;
// The heading being dragged follows the pointer.
if let (Some(dragged), Some(pos)) = (egui::DragAndDrop::payload::(ui.ctx()), ui.ctx().pointer_latest_pos()) {
- let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("combine-heading-drag")));
+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("combine-heading-drag")));
let galley = painter.layout_no_wrap(dragged.0.label().to_owned(), theme::medium(12.5), t.text);
let r = Rect::from_min_size(pos + vec2(10.0, 8.0), galley.size() + vec2(16.0, 8.0));
painter.rect(r, CornerRadius::same(4), t.card, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
@@ -1454,7 +1456,7 @@ fn table_body(
row.set_selected(rows.selected.get(i).copied().unwrap_or(false));
// Drag handle.
row.col(|ui| {
- let id = ui.id().with(("combine-drag", f.id));
+ let id = ui.scope_id().with(("combine-drag", f.id));
ui.dnd_drag_source(id, i, |ui| {
let (rect, resp) = ui.allocate_exact_size(vec2(12.0, 18.0), Sense::hover());
grip(ui, rect, if resp.hovered() || rows.dragging { t.text_muted } else { t.text_faint });
@@ -1467,7 +1469,8 @@ fn table_body(
row.col(|ui| match kind {
SortKey::Name => {
ui.add(icons::image("file-text", 16.0, t.icon));
- ui.add(egui::Label::new(crate::bidi::visual(&f.name).as_ref()).truncate().selectable(false));
+ // A file name is file/path chrome: explicitly LTR, extension last.
+ crate::widgets::label_ltr_truncated(ui, f.name.clone(), theme::regular(13.0), t.text);
}
// The range field and how many pages it takes.
SortKey::Pages => {
@@ -1581,7 +1584,7 @@ fn table_body(
let r = response.rect;
let y = if from > i { r.top() } else { r.bottom() };
if from != i {
- response.ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("combine-drop-line"))).hline(
+ response.ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("combine-drop-line"))).hline(
r.x_range(),
y,
Stroke::new(2.0, t.accent),
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index c0e12d5d09..a27a25ff82 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -157,10 +157,12 @@ impl PdfCraftApp {
let targets = active.map(|i| self.views[i].target_pages()).unwrap_or_default();
match id {
"ui.dock.reset" => {
- if let Err(error) = crate::docking::command(self, true, &serde_json::Value::Null) {
+ if let Err(error) = crate::side_panels::command(self, true, &serde_json::Value::Null) {
self.notify(error);
}
}
+ "view.side_panel" => self.toggle_side_panel(),
+ "view.tools_pane" => self.left_open = !self.left_open,
"file.open" => self.open_dialog(),
"file.open_recent" => match self.recent.first().map(|r| r.path.clone()) {
// The palette runs commands without a submenu: open the most recent file.
diff --git a/crates/ui-egui/src/comments.rs b/crates/ui-egui/src/comments.rs
index 928d5cbf6b..bf9b5fe72c 100644
--- a/crates/ui-egui/src/comments.rs
+++ b/crates/ui-egui/src/comments.rs
@@ -1621,12 +1621,12 @@ pub(crate) fn composer(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
anchor = anchor.clamp(viewport.min, viewport.max);
}
let pos = pos2(anchor.x + 12.0, anchor.y);
- let area = egui::Area::new(egui::Id::new(("comment-composer", view.id.0))).order(egui::Order::Foreground).constrain_to(viewport);
+ let area = egui::Area::new(egui::Id::unique(("comment-composer", view.id.0))).order(egui::Order::Foreground).constrain_to(viewport);
area.fixed_pos(pos).show(ctx, |ui| {
egui::Frame::popup(ui.style()).inner_margin(egui::Margin::same(12)).corner_radius(CornerRadius::same(8)).show(ui, |ui| {
ui.set_width(260.0);
ui.horizontal(|ui| {
- ui.label(egui::RichText::new(crate::bidi::visual_auto(&prefs.author)).font(theme::semibold(13.0)));
+ ui.label(egui::RichText::new(prefs.author.clone()).font(theme::semibold(13.0)));
ui.label(egui::RichText::new(tl!(title)).font(theme::regular(11.5)).color(t.text_faint));
});
ui.add_space(6.0);
@@ -1636,8 +1636,10 @@ pub(crate) fn composer(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
ComposerKind::Replace => tl!("Replacement text"),
_ => tl!("Add a comment"),
};
- let edit =
- ui.add(egui::TextEdit::multiline(&mut c.text).hint_text(hint).desired_rows(3).desired_width(f32::INFINITY).id_salt("composer-text"));
+ let edit = ui
+ .add(egui::TextEdit::multiline(&mut c.text).hint_text(hint).desired_rows(3).desired_width(f32::INFINITY).id_salt("composer-text"))
+ // 0.37 kittest rejects an unnamed text input; the hint is its logical name.
+ .accessible_name(hint);
if c.focus {
edit.request_focus();
c.focus = false;
@@ -2056,8 +2058,9 @@ pub enum CanvasAction {
/// How many custom colours the "Recent colours" row keeps.
const RECENT_CUSTOM: usize = 5;
+/// Return the stable egui id for the recent custom-colour palette.
fn recent_custom_id() -> egui::Id {
- egui::Id::new("pdfcraft-recent-custom-colours")
+ egui::Id::unique("pdfcraft-recent-custom-colours")
}
/// Custom colours picked with "Other colour…" this session, newest first (#1193).
@@ -2091,7 +2094,7 @@ fn rgb_of(c: Color32) -> Rgb {
/// One round swatch; `on` rings it as the current colour.
fn swatch(ui: &mut egui::Ui, c: Rgb, on: bool, tooltip: &str) -> egui::Response {
let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tooltip));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip));
ui.painter().circle_filled(r.center(), 9.0, color32(c));
ui.painter().circle_stroke(r.center(), 9.0, Stroke::new(1.0, Color32::from_black_alpha(40)));
if on || resp.hovered() {
@@ -2113,7 +2116,7 @@ fn other_colour_swatch(ui: &mut egui::Ui, open: bool) -> egui::Response {
ui.painter().circle_stroke(c, 11.0, Stroke::new(1.5, SELECT_BLUE));
}
let label = tl!("Other colour…");
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, open, label));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, open, label));
resp.on_hover_text(label)
}
@@ -2202,7 +2205,7 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m
let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click());
ui.painter().circle_filled(r.center(), 9.0, color32(style.color));
ui.painter().circle_stroke(r.center(), 9.0, Stroke::new(1.0, Color32::from_black_alpha(50)));
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Colour")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Colour")));
let resp = resp.on_hover_text(tl!("Colour"));
egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
if let Some(c) = swatch_grid(ui, Some(style.color)) {
@@ -2266,7 +2269,7 @@ fn fill_button(ui: &mut egui::Ui, fill: Option) -> egui::Response {
Some(_) => tl!("Fill colour"),
None => tl!("Fill colour: none"),
};
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
resp.on_hover_text(label)
}
@@ -2587,7 +2590,7 @@ mod tests {
h.run();
h.get_by_label("Page").click_secondary();
h.run();
- h.get_by_label("Colour ⏵").click();
+ h.get_by_label("Colour").click();
h.run();
h.get_by_label("Other colour…").click();
h.run();
diff --git a/crates/ui-egui/src/comments_panel.rs b/crates/ui-egui/src/comments_panel.rs
index 627385b228..54ca9e5152 100644
--- a/crates/ui-egui/src/comments_panel.rs
+++ b/crates/ui-egui/src/comments_panel.rs
@@ -124,7 +124,9 @@ pub(crate) fn show(
let mut edit = None;
// Search (the header's magnifier toggles it).
if let Some(q) = view.comments.search.as_mut() {
- let r = ui.add(crate::widgets::line(q).hint_text(tl!("Search comments")).desired_width(f32::INFINITY).id_salt("comment-search"));
+ let r = ui
+ .add(crate::widgets::line(q).hint_text(tl!("Search comments")).desired_width(f32::INFINITY).id_salt("comment-search"))
+ .accessible_name(tl!("Search comments"));
if view.comments.search_focus {
r.request_focus();
view.comments.search_focus = false;
@@ -133,9 +135,14 @@ pub(crate) fn show(
}
// "Add a comment": a sticky note on the current page, near its top-right corner.
if allowed {
- let r = ui.add(
- crate::widgets::line(&mut view.comments.add_box).hint_text(tl!("Add a comment")).desired_width(f32::INFINITY).id_salt("comment-add-box"),
- );
+ let r = ui
+ .add(
+ crate::widgets::line(&mut view.comments.add_box)
+ .hint_text(tl!("Add a comment"))
+ .desired_width(f32::INFINITY)
+ .id_salt("comment-add-box"),
+ )
+ .accessible_name(tl!("Add a comment"));
if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !view.comments.add_box.trim().is_empty() {
let page = view.current.min(info.pages.len().saturating_sub(1));
if let Some(p) = info.pages.get(page) {
@@ -238,9 +245,7 @@ pub(crate) fn show(
if g.is_some() && g != group {
ui.add_space(6.0);
let title = g.clone().unwrap_or_default();
- // Catalog labels are already in display order; an author's name is put in it here.
- let shown = if sort == SortBy::Author && a.author.is_some() { crate::bidi::visual_auto(&title) } else { tl!(&title).into() };
- ui.label(egui::RichText::new(shown).font(theme::semibold(12.5)).color(t.text_muted));
+ ui.label(egui::RichText::new(tl!(&title)).font(theme::semibold(12.5)).color(t.text_muted));
group = g;
}
} else if a.page != page {
@@ -287,6 +292,8 @@ pub(crate) fn show(
edit
}
+/// Draw one comment thread card, including author, body or inline editor, replies, status and per-comment
+/// actions; returns an edit to apply.
#[allow(clippy::too_many_arguments)]
fn card(
ui: &mut egui::Ui,
@@ -322,7 +329,8 @@ fn card(
let mut above = egui::Rect::NOTHING;
let head = ui.horizontal(|ui| {
above = avatar(ui, t, Some(subtype_icon(&a.subtype)), None, color);
- let author = a.author.as_deref().map_or_else(|| tl!("Unknown author").into(), crate::bidi::visual_auto);
+ // The catalogue and author names stay logical: egui lays out RTL text itself.
+ let author = a.author.as_deref().map_or_else(|| tl!("Unknown author"), |name| name);
ui.label(egui::RichText::new(author).font(theme::semibold(12.5)).color(t.text));
if let Some(m) = &a.modified {
ui.add(egui::Label::new(egui::RichText::new(m).font(theme::regular(11.0)).color(t.text_faint)).truncate());
@@ -402,7 +410,7 @@ fn card(
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.horizontal(|ui| {
- let author = r.author.as_deref().map_or_else(|| tl!("Reply").into(), crate::bidi::visual_auto);
+ let author = r.author.as_deref().map_or_else(|| tl!("Reply"), |name| name);
ui.label(egui::RichText::new(author).font(theme::semibold(12.0)));
if let Some(m) = &r.modified {
ui.add(egui::Label::new(egui::RichText::new(m).font(theme::regular(11.0)).color(t.text_faint)).truncate());
@@ -461,7 +469,7 @@ fn card(
// clickable everywhere.
let hit = if selected { frame.inner } else { rect };
let click = ui
- .interact(hit, ui.id().with(("card", key)), Sense::click())
+ .interact(hit, ui.scope_id().with(("card", key)), Sense::click())
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(crate::i18n::fmt(tl!("{kind} — click to show it on the page"), &[("kind", tl!(kind_label(a)))]));
if click.clicked() {
@@ -472,7 +480,7 @@ fn card(
if click.double_clicked() && allowed {
view.comments.open_editor(a.page, a.index, a.contents.clone().unwrap_or_default());
}
- let menu_id = ui.id().with(("card-menu", key));
+ let menu_id = ui.scope_id().with(("card-menu", key));
if open_menu {
egui::Popup::open_id(ui.ctx(), menu_id);
}
@@ -636,8 +644,7 @@ pub(crate) fn header_controls(ui: &mut egui::Ui, info: &DocInfo, view: &mut DocV
ui.separator();
ui.label(egui::RichText::new(tl!("Author")).small());
for a in &authors {
- let name = crate::bidi::visual_auto(a);
- toggle(ui, &mut cv.hidden_authors, a, if a.is_empty() { tl!("Unknown author") } else { &name });
+ toggle(ui, &mut cv.hidden_authors, a, if a.is_empty() { tl!("Unknown author") } else { a.as_str() });
}
ui.separator();
ui.label(egui::RichText::new(tl!("Status")).small());
diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rs
index 0d86f7dd8f..0da3b235c8 100644
--- a/crates/ui-egui/src/content_ui.rs
+++ b/crates/ui-egui/src/content_ui.rs
@@ -91,6 +91,11 @@ pub struct ContentView {
}
impl ContentView {
+ /// Forget an in-progress pointer grab for content editing.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ self.grab = None;
+ }
+
pub(crate) fn finish_draft(&mut self, added: &[Added]) -> Option {
self.draft.take().and_then(|d| finish(self, d, added))
}
@@ -585,7 +590,7 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad
// Shown at once, like the paragraph editor: a fade-in shows the page's copy through it. Over
// the page, so only where the document shows: text scrolled under the mode bar or a side
// panel must leave them their pointer (#2755).
- egui::Area::new(egui::Id::new(("added-text", view.id.0)))
+ egui::Area::new(egui::Id::unique(("added-text", view.id.0)))
.fade_in(false)
.order(egui::Order::Foreground)
.fixed_pos(at)
@@ -619,7 +624,10 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad
.font(font.clone())
.desired_width(width)
.desired_rows(1)
- .horizontal_align(halign)
+ .align(egui::Align2::new(halign, egui::Align::TOP))
+ // Keep the page editor's original inset; the theme's larger button padding
+ // otherwise shifts narrow right-aligned boxes away from their text edge.
+ .margin(egui::Margin::symmetric(4, 2))
.background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })
.text_color(Color32::from_rgb(cr, cg, cb))
.hint_text(tl!("Type text"))
@@ -627,7 +635,7 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad
if letter_spacing != 0.0 {
edit = edit.layouter(&mut spaced);
}
- let resp = ui.add(edit);
+ let resp = ui.add(edit).accessible_name(tl!("Added text"));
if t.focus {
resp.request_focus();
t.focus = false;
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 47c5b200a3..db6e2445db 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -53,21 +53,14 @@ use serde_json::{Value, json};
pub type Reply = Result;
/// Seconds to wait for frames (input to be handled, a screenshot to be taken) before reporting
-/// that the window is not being drawn. While a window is hidden, minimized or fully covered,
-/// eframe keeps calling `logic` but runs no egui pass, so input and screenshots wait.
+/// that the window is not being drawn. `App::logic` also runs while a window is hidden,
+/// minimized or fully covered, where egui's own input clock does not advance; every deadline
+/// here uses a monotonic `web_time::Instant` so hidden logic cannot stall or restart it.
const NOT_DRAWN_TIMEOUT: f64 = 5.0;
-/// Wall-clock seconds (egui's own clock stops while the window is not drawn).
-fn now_secs() -> f64 {
- #[cfg(not(target_arch = "wasm32"))]
- {
- static START: std::sync::OnceLock = std::sync::OnceLock::new();
- START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64()
- }
- #[cfg(target_arch = "wasm32")]
- {
- js_sys::Date::now() / 1000.0
- }
+/// Return the deadline used to reject control requests that wait for a drawn window.
+fn timeout() -> std::time::Duration {
+ std::time::Duration::from_secs_f64(NOT_DRAWN_TIMEOUT)
}
fn not_drawn(what: &str) -> String {
@@ -76,8 +69,23 @@ fn not_drawn(what: &str) -> String {
)
}
+/// Return the actionable error text for a control request whose window was not drawn in time.
+fn still_starting() -> String {
+ format!("the app was still starting after {NOT_DRAWN_TIMEOUT:.0} s; the control request was not applied, retry when the window is drawn")
+}
+
+/// The app finished starting, but only after this request's one admission deadline had already
+/// passed. Report that instead of claiming the app is still starting.
+fn startup_deadline_expired() -> String {
+ format!(
+ "the app finished starting after this control request's {NOT_DRAWN_TIMEOUT:.0} s deadline; the request was not applied, retry now that the window is drawn"
+ )
+}
+
/// One request from a client, answered on `reply`.
pub struct ControlRequest {
+ /// Admission time on the sending thread, including time waiting for the next app tick.
+ pub since: web_time::Instant,
pub method: String,
pub params: Value,
pub reply: Sender,
@@ -94,7 +102,7 @@ impl ControlClient {
/// Queue a request; the reply arrives on the returned receiver once the app has handled it.
pub fn send(&self, method: &str, params: Value) -> Receiver {
let (reply, rx) = channel();
- let req = ControlRequest { method: method.into(), params, reply };
+ let req = ControlRequest { since: web_time::Instant::now(), method: method.into(), params, reply };
if let Err(e) = self.tx.send(req) {
let _ = e.0.reply.send(Err("the app has closed".into()));
}
@@ -109,12 +117,99 @@ struct Shared {
nodes: HashMap,
root: Option,
focus: Option,
- /// Event batches to inject, one batch per frame.
- inject: VecDeque>,
- /// Real egui passes so far (counted in `output_hook`, which `logic`-only calls never reach).
+ /// Queued synthetic-input requests, each with one event batch per UI pass.
+ inject: VecDeque,
+ /// Accepted (not discarded) egui passes, counted in `output_hook`.
passes: u64,
+ /// The document/focus generation the app last admitted input for.
+ epoch: u64,
+ /// Input requests whose queued events became stale before a UI pass consumed them.
+ dropped: Vec,
+ next_batch: u64,
+ /// A batch admitted before its deadline may finish this pass. Expiry runs before the next
+ /// input hook (or in hidden logic), never after egui has already calculated its interaction.
+ in_pass: bool,
+ expired: Vec,
+ cleanup: Vec,
+ cancel_pointer: bool,
+ cancel_gestures: bool,
}
+/// One queued synthetic-input request: its batches are injected one per UI pass.
+struct RequestBatches {
+ request: u64,
+ /// The document/dialog/focus generation the request was admitted for.
+ epoch: u64,
+ /// The first batch was injected, so a focus/dialog change does not reject its own remaining
+ /// batches. The admission deadline still cancels a partially delivered gesture.
+ started: bool,
+ since: web_time::Instant,
+ /// Inverse presses still held by this request. Pointer entries are ownership markers for
+ /// cancellation only: replaying one on timeout would click or drop the abandoned gesture.
+ release: Vec,
+ batches: VecDeque>,
+}
+
+/// Track only presses that reached egui and have not yet been released. A pointer release is
+/// retained as an ownership marker, never as a timeout event.
+fn note_pressed(release: &mut Vec, events: &[egui::Event]) {
+ for event in events {
+ match event {
+ egui::Event::Key { key, pressed: true, .. }
+ if !release.iter().any(|event| matches!(event, egui::Event::Key { key: seen, pressed: false, .. } if seen == key)) =>
+ {
+ release.push(egui::Event::Key { key: *key, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE });
+ }
+ egui::Event::PointerButton { pos, button, pressed: true, .. }
+ if !release
+ .iter()
+ .any(|event| matches!(event, egui::Event::PointerButton { button: seen, pressed: false, .. } if seen == button)) =>
+ {
+ release.push(egui::Event::PointerButton { pos: *pos, button: *button, pressed: false, modifiers: egui::Modifiers::NONE });
+ }
+ egui::Event::ModifiersChanged(modifiers)
+ if *modifiers != egui::Modifiers::NONE && !release.contains(&egui::Event::ModifiersChanged(egui::Modifiers::NONE)) =>
+ {
+ release.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ }
+ egui::Event::Key { key, pressed: false, .. } => {
+ release.retain(|event| !matches!(event, egui::Event::Key { key: seen, .. } if seen == key));
+ }
+ egui::Event::PointerButton { button, pressed: false, .. } => {
+ release.retain(|event| !matches!(event, egui::Event::PointerButton { button: seen, .. } if seen == button));
+ }
+ egui::Event::ModifiersChanged(modifiers) if *modifiers == egui::Modifiers::NONE => {
+ release.retain(|event| !matches!(event, egui::Event::ModifiersChanged(_)));
+ }
+ _ => {}
+ }
+ }
+}
+
+/// Cancel expired requests before egui computes interaction. Hidden logic calls this too, so
+/// replies do not wait for a visible frame. Never complete an abandoned pointer gesture.
+fn expire_input(shared: &mut Shared, now: web_time::Instant) {
+ shared.inject.retain_mut(|request| {
+ if now.duration_since(request.since) <= timeout() {
+ return true;
+ }
+ shared.expired.push(request.request);
+ for event in request.release.drain(..) {
+ if matches!(event, egui::Event::PointerButton { .. }) {
+ shared.cancel_pointer = true;
+ shared.cancel_gestures = true;
+ } else {
+ shared.cleanup.push(event);
+ }
+ }
+ false
+ });
+}
+
+/// Synthetic input is bounded like screenshots: a local authenticated client must not be able to
+/// queue unbounded batches (one frame each) and hold the control channel's memory for ever.
+const MAX_QUEUED_BATCHES: usize = 512;
+
/// The egui plugin half of the control channel.
pub struct ControlPlugin {
shared: Arc>,
@@ -125,19 +220,71 @@ impl egui::Plugin for ControlPlugin {
"pdfcraft-control"
}
+ /// Inject admitted control batches into the current pass, dropping stale requests, applying cancellations
+ /// and scheduling repaints.
fn input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) {
let Ok(mut s) = self.shared.lock() else { return };
- if let Some(batch) = s.inject.pop_front() {
- input.events.extend(batch);
+ expire_input(&mut s, web_time::Instant::now());
+ if std::mem::take(&mut s.cancel_pointer) {
+ // input_hook precedes Context::begin_pass. stop_dragging sets the OLD snapshot's
+ // drag_stopped; begin_pass replaces that snapshot without a release/click/drop.
+ ctx.input_mut(|i| i.pointer = Default::default());
+ ctx.stop_dragging();
+ egui::DragAndDrop::clear_payload(ctx);
+ }
+ input.events.append(&mut s.cleanup);
+ s.in_pass = true;
+ let epoch = s.epoch;
+ let Some(front) = s.inject.front_mut() else { return };
+ if !front.started {
+ if front.epoch != epoch {
+ // The document, dialog or focus changed after this request was admitted, before
+ // any of its input landed. Drop only this request; later requests are unrelated.
+ let request = front.request;
+ s.inject.pop_front();
+ s.dropped.push(request);
+ if !s.inject.is_empty() {
+ ctx.request_repaint();
+ }
+ return;
+ }
+ front.started = true;
+ }
+ // A non-expired request's own earlier batch may have changed focus or opened a dialog.
+ // Let it finish normally; expiry above cancels held pointer state instead of completing
+ // an abandoned click/drop.
+ let events = front.batches.pop_front();
+ if let Some(events) = &events {
+ // Remember the inverse of what this request presses as it is applied, so a timeout
+ // after this batch can still release exactly those inputs.
+ note_pressed(&mut front.release, events);
+ }
+ let done = front.batches.is_empty();
+ if done {
+ s.inject.pop_front();
+ }
+ if let Some(events) = events {
+ input.events.extend(events);
}
if !s.inject.is_empty() {
ctx.request_repaint();
}
}
- fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) {
+ /// Record presented passes and the accesskit tree and focus after a pass, so control replies observe only
+ /// drawn frames.
+ fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
let Ok(mut s) = self.shared.lock() else { return };
- s.passes += 1;
+ s.in_pass = false;
+ // A discarded pass is layout work, not a frame the agent can observe. Only count passes
+ // whose output is actually presented, so a request cannot be answered early. The last
+ // pass of a frame is presented even when its own discard request was refused because
+ // `max_passes` is reached; egui still reports that request in the output.
+ let max_passes = ctx.options(|o| o.max_passes.get());
+ let final_pass = output.platform_output.num_completed_passes >= max_passes;
+ if output.platform_output.request_discard_reasons.is_empty() || final_pass {
+ s.passes += 1;
+ }
let Some(update) = &output.platform_output.accesskit_update else { return };
s.nodes = update.nodes.iter().cloned().collect();
s.root = update.tree.as_ref().map(|t| t.root);
@@ -145,30 +292,271 @@ impl egui::Plugin for ControlPlugin {
}
}
+/// Screenshot admission limits: bounded requests, per-image bytes and aggregate retained bytes.
+const MAX_PENDING_SCREENSHOTS: usize = 4;
+const MAX_IMAGE_BYTES: usize = 128 * 1024 * 1024;
+const MAX_TOTAL_BYTES: usize = 256 * 1024 * 1024;
+/// One image's encode working copies are bounded too: the RGBA buffer fed to the PNG encoder,
+/// the encoded PNG, and the base64 string in the reply. They are made one capture at a time,
+/// after the retained image budget above has been checked. Peak encoding memory is therefore at
+/// most the retained aggregate plus one crop, one PNG and one base64 string; it is not hidden
+/// behind the retained-image limit.
+const MAX_ENCODED_BYTES: usize = MAX_IMAGE_BYTES;
+const MAX_BASE64_BYTES: usize = 192 * 1024 * 1024;
+
+/// Replace one pending capture's reservation with `bytes`, keeping the other reservations.
+///
+/// The drain retries captures one at a time: using a single total taken before the loop would
+/// let several retries each see room that no longer exists together, and the aggregate would
+/// grow past [`MAX_TOTAL_BYTES`].
+fn retried_reservation(total: usize, old: usize, bytes: usize) -> Option {
+ let without_this = total.saturating_sub(old);
+ let new_total = without_this.saturating_add(bytes);
+ (bytes <= MAX_IMAGE_BYTES && new_total <= MAX_TOTAL_BYTES).then_some(new_total)
+}
+
+/// The window content a screenshot request was admitted and issued for.
+///
+/// Only the viewport's local size and scale matter: the window's position on the monitor does not
+/// change a single captured pixel, and keyboard focus is not part of the captured content.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Geometry {
+ size: egui::Vec2,
+ pixels_per_point: f32,
+ /// Active document and open dialog/prompt identity, never the focused widget.
+ epoch: u64,
+}
+
+impl Geometry {
+ /// Capture the current viewport size and effective pixels-per-point for the request epoch.
+ fn current(ctx: &egui::Context, epoch: u64) -> Self {
+ // Viewport info is refreshed by `run_logic`; the last UI pass's `viewport_rect` can be
+ // stale while the window is hidden. Fall back to it only when the host cannot say. Only
+ // its size is kept: `inner_rect` is in monitor space and its origin may move.
+ let (rect, native) = ctx.input(|i| {
+ let viewport = i.viewport();
+ (viewport.inner_rect.unwrap_or_else(|| i.viewport_rect()), viewport.native_pixels_per_point)
+ });
+ let native = native.or_else(|| ctx.native_pixels_per_point()).unwrap_or(1.0);
+ Self { size: rect.size(), pixels_per_point: native * ctx.zoom_factor(), epoch }
+ }
+
+ /// Checked bytes an image of this geometry needs, before the capture is issued.
+ fn image_bytes(self) -> Option {
+ let width = (self.size.x * self.pixels_per_point).ceil();
+ let height = (self.size.y * self.pixels_per_point).ceil();
+ if !(width.is_finite() && height.is_finite()) || width <= 0.0 || height <= 0.0 {
+ return None;
+ }
+ checked_image_bytes(width as usize, height as usize)
+ }
+
+ /// Whether `region` is a non-empty rectangle inside this viewport, in logical points.
+ fn contains_region(self, region: egui::Rect) -> bool {
+ region.min.x.is_finite()
+ && region.min.y.is_finite()
+ && region.max.x.is_finite()
+ && region.max.y.is_finite()
+ && region.min.x >= 0.0
+ && region.min.y >= 0.0
+ && region.max.x > region.min.x
+ && region.max.y > region.min.y
+ && region.max.x <= self.size.x
+ && region.max.y <= self.size.y
+ }
+}
+
+/// Return the byte size of an RGBA image of the given dimensions, or `None` when the multiplication
+/// overflows.
+fn checked_image_bytes(width: usize, height: usize) -> Option {
+ width.checked_mul(height)?.checked_mul(core::mem::size_of::())
+}
+
enum Pending {
- /// Answer after `frames` more frames (the injected input has been handled by then).
+ /// Answer after `frames` more accepted frames (the injected input has been handled by then).
Frames {
- /// Answer once this many egui passes have run (the injected input has been handled).
+ /// Answer once this many accepted UI passes have run.
until_pass: u64,
- since: f64,
+ /// The queued batches this request depends on; a stale one fails the request.
+ batches: Vec,
+ since: web_time::Instant,
reply: Sender,
value: Value,
},
Screenshot {
- tag: u64,
+ slot: craft_ui::capture::CaptureSlot,
+ /// The one-shot callback, kept until the settled pass that issues it.
+ callback: Option,
region: Option,
reply: Sender,
- /// When it was requested (egui time, seconds).
- since: f64,
+ since: web_time::Instant,
+ geometry: Geometry,
+ /// Bytes reserved in the aggregate budget for this request.
+ reserved: usize,
+ attempts: u8,
},
}
+/// A request that arrived while the app could not yet run a real UI pass (fonts not ready).
+struct DeferredRequest {
+ request: ControlRequest,
+ /// When this request reached the control queue. One admission deadline runs from here through
+ /// startup, input injection, pending frames and screenshot issuance: dispatching it later must
+ /// not start a fresh 5 s in each phase, and a request that used up the deadline while the app
+ /// was starting is never applied against a later UI state.
+ since: web_time::Instant,
+}
+
+/// A screenshot pending in the `finish_pending` pass, with ownership of its reply.
+struct PendingCapture {
+ slot: craft_ui::capture::CaptureSlot,
+ callback: Option,
+ region: Option,
+ reply: Sender,
+ since: web_time::Instant,
+ geometry: Geometry,
+ reserved: usize,
+ attempts: u8,
+}
+
+impl PendingCapture {
+ /// Convert a screenshot request into the pending form that later frames finish.
+ fn into_pending(self) -> Pending {
+ Pending::Screenshot {
+ slot: self.slot,
+ callback: self.callback,
+ region: self.region,
+ reply: self.reply,
+ since: self.since,
+ geometry: self.geometry,
+ reserved: self.reserved,
+ attempts: self.attempts,
+ }
+ }
+}
+
+/// The state one `finish_pending` pass needs while resolving pending replies.
+struct PendingFinisher {
+ now: web_time::Instant,
+ passes: u64,
+ current: Geometry,
+ in_pass: bool,
+ dropped: Vec,
+ expired: Vec,
+ reserved_total: usize,
+}
+
+impl PendingFinisher {
+ /// Answer or keep one queued-input request, preserving its one arrival deadline.
+ fn resolve_frames(&self, until_pass: u64, batches: Vec, since: web_time::Instant, reply: Sender, value: Value) -> Option {
+ if batches.iter().any(|id| self.expired.contains(id)) {
+ let _ = reply.send(Err(not_drawn("handling the input")));
+ return None;
+ }
+ if batches.iter().any(|id| self.dropped.contains(id)) {
+ let _ = reply.send(Err("the document, dialog or focus changed before the input could be applied; nothing was done".into()));
+ return None;
+ }
+ if self.passes >= until_pass {
+ let _ = reply.send(Ok(value));
+ return None;
+ }
+ if !self.in_pass && self.now.duration_since(since) > timeout() {
+ let _ = reply.send(Err(not_drawn("handling the input")));
+ return None;
+ }
+ Some(Pending::Frames { until_pass, batches, since, reply, value })
+ }
+
+ /// Give one reservation back to the running aggregate budget.
+ fn release_reservation(&mut self, reserved: usize) {
+ self.reserved_total = self.reserved_total.saturating_sub(reserved);
+ }
+
+ /// Resolve one screenshot request, keeping it only while its capture is still pending.
+ fn finish_capture(&mut self, ctx: &egui::Context, capture: PendingCapture) -> Option {
+ // Completion cannot restart or bypass the admission deadline, even when the callback
+ // arrived before this delayed tick or a resize would retry it.
+ if self.now.duration_since(capture.since) > timeout() {
+ capture.slot.cancel();
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err(not_drawn("the screenshot")));
+ return None;
+ }
+ match capture.slot.take() {
+ Some(Ok(image)) => self.finish_captured_image(ctx, capture, image),
+ Some(Err(error)) => {
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err(format!("the screenshot could not be captured: {error}")));
+ None
+ }
+ None => Some(capture.into_pending()),
+ }
+ }
+
+ /// Finish a screenshot whose callback produced an image.
+ fn finish_captured_image(&mut self, ctx: &egui::Context, capture: PendingCapture, image: Arc) -> Option {
+ if self.current.epoch != capture.geometry.epoch {
+ // The document/dialog changed: never save a capture of the previous context, and do
+ // not retry it into the new one.
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err("the document or dialog changed while the screenshot was being captured; it was not saved".into()));
+ return None;
+ }
+ if self.current.size != capture.geometry.size || self.current.pixels_per_point != capture.geometry.pixels_per_point {
+ // A late completion after a resize/DPI change is never encoded: retry once with a
+ // fresh slot, else report a defined error.
+ return self.retry_captured_image(ctx, capture);
+ }
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(screenshot_png(&image, capture.region, capture.geometry));
+ None
+ }
+
+ /// Retry one resize/DPI-stale capture with the current geometry.
+ fn retry_captured_image(&mut self, ctx: &egui::Context, capture: PendingCapture) -> Option {
+ if capture.attempts >= 1 {
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err("the window geometry changed while the screenshot was being captured; it was not saved".into()));
+ return None;
+ }
+ if capture.region.as_ref().is_some_and(|region| !self.current.contains_region(*region)) {
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err("the region must lie inside the window".into()));
+ return None;
+ }
+ let Some(bytes) = self.current.image_bytes() else {
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err("the window has no capturable size".into()));
+ return None;
+ };
+ let Some(new_total) = retried_reservation(self.reserved_total, capture.reserved, bytes) else {
+ self.release_reservation(capture.reserved);
+ let _ = capture.reply.send(Err("the screenshot no longer fits the screenshot budget".into()));
+ return None;
+ };
+ self.reserved_total = new_total;
+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ Some(Pending::Screenshot {
+ slot,
+ callback: Some(callback),
+ region: capture.region,
+ reply: capture.reply,
+ since: capture.since,
+ geometry: self.current,
+ reserved: bytes,
+ attempts: capture.attempts + 1,
+ })
+ }
+}
+
/// The app half: the request queue and requests waiting for later frames.
pub struct Control {
rx: Receiver,
shared: Arc>,
pending: Vec,
- next_tag: u64,
+ /// Requests admitted while the app cannot yet run a real UI pass (fonts not ready).
+ deferred: VecDeque,
}
/// Install the control channel on `ctx`: returns the app half and a client.
@@ -177,117 +565,363 @@ pub fn attach(ctx: &egui::Context) -> (Control, ControlClient) {
ctx.add_plugin(ControlPlugin { shared: shared.clone() });
ctx.enable_accesskit();
let (tx, rx) = channel();
- (Control { rx, shared, pending: Vec::new(), next_tag: 1 }, ControlClient { tx, ctx: ctx.clone() })
+ (Control { rx, shared, pending: Vec::new(), deferred: VecDeque::new() }, ControlClient { tx, ctx: ctx.clone() })
}
/// What a request needs from the app (implemented by `PdfCraftApp`).
pub(crate) trait Host {
+ /// Return the UI-state snapshot reported by `ui.state`.
fn state(&self) -> Value;
+ /// Run one registered command by id and return its reply.
fn command(&mut self, id: &str) -> Reply;
- fn dock(&mut self, reset: bool, params: &Value) -> Reply;
+ /// Apply or reset the side panel layout from a control request.
+ fn panel(&mut self, reset: bool, params: &Value) -> Reply;
+ /// List the commands available to the control channel.
fn commands(&self) -> Value;
+ /// Set one application option from a control request.
fn set(&mut self, key: &str, value: &str) -> Reply;
+ /// Open a document path requested through the control channel.
fn open(&mut self, path: &str) -> Reply;
+ /// Request application exit; returns whether it closed without asking for confirmation.
fn quit(&mut self, ctx: &egui::Context) -> bool;
+
+ /// A generation that changes when the input target (document, dialog, focus) does.
+ ///
+ /// Synthetic input admitted for one generation must not be replayed into another.
+ fn input_epoch(&self) -> u64 {
+ 0
+ }
+
+ /// A generation for the captured content (document and dialog identity only).
+ ///
+ /// Screenshots do not depend on keyboard focus, so a field gaining focus must not discard a
+ /// pending capture. Hosts that do not distinguish the two reuse the input generation.
+ fn capture_epoch(&self) -> u64 {
+ self.input_epoch()
+ }
+
+ /// Whether the app can apply a real UI pass yet (fonts installed, no early return).
+ fn accepts_input(&self) -> bool {
+ true
+ }
+
+ /// Drop transient app-owned grabs before widgets observe the canceled pointer as up.
+ fn cancel_pointer_gestures(&mut self) {}
}
impl Control {
- /// Handle new requests and finish waiting ones. Call at the start of every frame.
+ /// Handle new requests and finish waiting ones. Call at the start of every frame (`logic`).
pub(crate) fn tick(&mut self, ctx: &egui::Context, host: &mut impl Host) {
- self.finish_pending(ctx);
- while let Ok(req) = self.rx.try_recv() {
- match self.handle(ctx, host, &req.method, &req.params) {
- Handled::Now(r) => {
- let _ = req.reply.send(r);
+ self.set_epoch(host.input_epoch());
+ self.finish_pending(ctx, host);
+ let ready = host.accepts_input();
+ if !ready {
+ // Expiry applies while the app is still starting too: a request that waited through
+ // the startup gate must fail at the same deadline instead of running whenever fonts
+ // arrive.
+ let now = web_time::Instant::now();
+ while self.deferred.front().is_some_and(|deferred| now.duration_since(deferred.since) > timeout()) {
+ if let Some(deferred) = self.deferred.pop_front() {
+ let _ = deferred.request.reply.send(Err(still_starting()));
}
- Handled::AfterFrames(frames, value) => {
- let until_pass = self.passes() + u64::from(frames);
- self.pending.push(Pending::Frames { until_pass, since: now_secs(), reply: req.reply, value });
- }
- Handled::Screenshot(region) => {
- let tag = self.next_tag;
- self.next_tag += 1;
- ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(tag)));
- self.pending.push(Pending::Screenshot { tag, region, reply: req.reply, since: now_secs() });
+ }
+ } else {
+ // Deferred requests reached the queue before anything still in the channel, so they
+ // are dispatched first: one client's requests keep their arrival order. Each carries
+ // its own admission timestamp, so startup time counts against its deadline.
+ while let Some(deferred) = self.deferred.pop_front() {
+ if web_time::Instant::now().duration_since(deferred.since) > timeout() {
+ let _ = deferred.request.reply.send(Err(startup_deadline_expired()));
+ } else {
+ self.dispatch(ctx, host, deferred.request, deferred.since);
}
}
}
- if !self.pending.is_empty() {
+ while let Ok(req) = self.rx.try_recv() {
+ // One admission timestamp per request: queued input, pending frames and an admitted
+ // screenshot all measure their deadline from the sending thread, including time
+ // waiting in this channel, never from a later phase.
+ let since = req.since;
+ if web_time::Instant::now().duration_since(since) > timeout() {
+ let _ = req.reply.send(Err(if ready { startup_deadline_expired() } else { still_starting() }));
+ continue;
+ }
+ if !ready {
+ if self.deferred.len() < 32 {
+ self.deferred.push_back(DeferredRequest { request: req, since });
+ } else {
+ let _ = req.reply.send(Err("the app is still starting; too many control requests queued".into()));
+ }
+ continue;
+ }
+ self.dispatch(ctx, host, req, since);
+ }
+ if !self.pending.is_empty() || !self.deferred.is_empty() {
ctx.request_repaint();
+ // A hidden or occluded window runs `logic` without a UI pass. Ask for one so queued
+ // input and screenshots can be applied; the screenshot command itself also paints.
+ //
+ // The shared fork's web host does not implement `RequestPaintWhileHidden` yet: a
+ // hidden browser tab still times out rather than falsely succeeding. Recorded as a
+ // pending fork prerequisite, not qualified here.
+ #[cfg(not(target_arch = "wasm32"))]
+ if ctx.input(|i| i.viewport().visible()) != Some(true) {
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
+ }
}
}
- fn finish_pending(&mut self, ctx: &egui::Context) {
- let shots: Vec<(u64, Arc)> = ctx.input(|i| {
- i.raw
- .events
- .iter()
- .filter_map(|e| match e {
- egui::Event::Screenshot { user_data, image, .. } => {
- user_data.data.as_ref().and_then(|d| d.downcast_ref::()).map(|tag| (*tag, image.clone()))
+ /// Refresh the input-target generation before a pass consumes queued synthetic input.
+ ///
+ /// `raw_input_hook` runs before the plugin's `input_hook`, so a dialog opened by the
+ /// previous pass already invalidates a request that has not started yet, instead of a pass
+ /// later. Only that request is rejected; requests already started finish their batches.
+ pub(crate) fn set_epoch(&self, epoch: u64) {
+ if let Ok(mut s) = self.shared.lock() {
+ s.epoch = epoch;
+ }
+ }
+
+ /// Issue admitted captures after a settled UI pass. Call at the end of `App::ui`.
+ pub(crate) fn finish_frame(&mut self, ctx: &egui::Context, host: &mut impl Host) {
+ if !host.accepts_input() || ctx.will_discard() {
+ return;
+ }
+ let current = Geometry::current(ctx, host.capture_epoch());
+ let mut reserved_total = self.reserved_bytes();
+ let mut kept = Vec::new();
+ for pending in self.pending.drain(..) {
+ let mut entry = pending;
+ if let Pending::Screenshot { slot, callback, reply, region, geometry, reserved, attempts, since } = &mut entry
+ && callback.is_some()
+ {
+ if web_time::Instant::now().duration_since(*since) > timeout() {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err(not_drawn("the screenshot")));
+ continue;
+ }
+ if geometry.epoch != current.epoch {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err("the document or dialog changed before the screenshot could be issued; it was not saved".into()));
+ continue;
+ }
+ if *geometry != current {
+ // Resize, DPI or zoom between admission and issuance: retry once with the
+ // real geometry rather than cropping with stale numbers.
+ if *attempts >= 1 {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err("the window geometry changed while the screenshot was being prepared; it was not saved".into()));
+ continue;
}
- _ => None,
- })
- .collect()
- });
- let ppp = ctx.pixels_per_point();
- let now = now_secs();
- let passes = self.passes();
+ if region.as_ref().is_some_and(|region| !current.contains_region(*region)) {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err("the region must lie inside the window".into()));
+ continue;
+ }
+ let Some(bytes) = current.image_bytes() else {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err("the window has no capturable size".into()));
+ continue;
+ };
+ let Some(new_total) = retried_reservation(reserved_total, *reserved, bytes) else {
+ slot.cancel();
+ reserved_total = reserved_total.saturating_sub(*reserved);
+ let _ = reply.send(Err("the screenshot no longer fits the screenshot budget".into()));
+ continue;
+ };
+ reserved_total = new_total;
+ slot.cancel();
+ let (new_slot, new_callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ *slot = new_slot;
+ *callback = Some(new_callback);
+ *geometry = current;
+ *reserved = bytes;
+ *attempts += 1;
+ }
+ if let Some(callback) = callback.take() {
+ // The screenshot command itself requests a paint, including while hidden.
+ ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
+ }
+ }
+ kept.push(entry);
+ }
+ self.pending = kept;
+ if !self.pending.is_empty() {
+ #[cfg(not(target_arch = "wasm32"))]
+ if ctx.input(|i| i.viewport().visible()) != Some(true) {
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
+ }
+ }
+ }
+
+ /// `since` is the request's arrival time: the one admission deadline it was admitted under.
+ fn dispatch(&mut self, ctx: &egui::Context, host: &mut impl Host, req: ControlRequest, since: web_time::Instant) {
+ match self.handle(ctx, host, &req.method, &req.params, since) {
+ Handled::Now(r) => {
+ let _ = req.reply.send(r);
+ }
+ Handled::AfterFrames(frames, value) => {
+ let until_pass = self.passes() + u64::from(frames);
+ self.pending.push(Pending::Frames { until_pass, batches: Vec::new(), since, reply: req.reply, value });
+ }
+ Handled::AfterInput { batches, frames, value } => {
+ let until_pass = self.passes() + u64::from(frames) + 1;
+ self.pending.push(Pending::Frames { until_pass, batches, since, reply: req.reply, value });
+ }
+ Handled::Screenshot(region) => self.admit_screenshot(ctx, host, region, req.reply, since),
+ }
+ }
+
+ /// Return the total screenshot bytes reserved by pending captures without overflowing.
+ fn reserved_bytes(&self) -> usize {
+ self.pending
+ .iter()
+ .filter_map(|p| if let Pending::Screenshot { reserved, .. } = p { Some(*reserved) } else { None })
+ .fold(0usize, usize::saturating_add)
+ }
+
+ /// Count the screenshot requests still waiting for a capture.
+ fn pending_screenshots(&self) -> usize {
+ self.pending.iter().filter(|p| matches!(p, Pending::Screenshot { .. })).count()
+ }
+
+ /// Admit one screenshot request within the count, per-image and aggregate limits.
+ fn admit_screenshot(
+ &mut self,
+ ctx: &egui::Context,
+ host: &mut impl Host,
+ region: Option,
+ reply: Sender,
+ since: web_time::Instant,
+ ) {
+ if self.pending_screenshots() >= MAX_PENDING_SCREENSHOTS {
+ let _ = reply.send(Err(format!("too many screenshots are already pending (limit {MAX_PENDING_SCREENSHOTS})")));
+ return;
+ }
+ let geometry = Geometry::current(ctx, host.capture_epoch());
+ let Some(bytes) = geometry.image_bytes() else {
+ let _ = reply.send(Err("the window has no capturable size".into()));
+ return;
+ };
+ if let Some(region) = region
+ && !geometry.contains_region(region)
+ {
+ let _ = reply.send(Err("the region must lie inside the window".into()));
+ return;
+ }
+ if bytes > MAX_IMAGE_BYTES {
+ let _ = reply.send(Err(format!("the screenshot would use {bytes} bytes, over the {MAX_IMAGE_BYTES}-byte image limit")));
+ return;
+ }
+ if self.reserved_bytes().saturating_add(bytes) > MAX_TOTAL_BYTES {
+ let _ = reply.send(Err(format!("the screenshot would exceed the {MAX_TOTAL_BYTES}-byte aggregate screenshot budget")));
+ return;
+ }
+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ self.pending.push(Pending::Screenshot { slot, callback: Some(callback), region, reply, since, geometry, reserved: bytes, attempts: 0 });
+ }
+
+ /// Resolve completed frame and screenshot requests while retaining those that still need a pass or a
+ /// retry.
+ fn finish_pending(&mut self, ctx: &egui::Context, host: &mut impl Host) {
+ let now = web_time::Instant::now();
+ let (dropped, expired, in_pass) = self.take_finished_shared(ctx, host, now);
+ let mut finisher = PendingFinisher {
+ now,
+ passes: self.passes(),
+ current: Geometry::current(ctx, host.capture_epoch()),
+ in_pass,
+ dropped,
+ expired,
+ reserved_total: self.reserved_bytes(),
+ };
let mut keep = Vec::new();
- for p in self.pending.drain(..) {
- match p {
- Pending::Frames { until_pass, reply, value, .. } if passes >= until_pass => {
- let _ = reply.send(Ok(value));
+ for pending in std::mem::take(&mut self.pending) {
+ let kept = match pending {
+ Pending::Frames { until_pass, batches, since, reply, value } => finisher.resolve_frames(until_pass, batches, since, reply, value),
+ Pending::Screenshot { slot, callback, region, reply, since, geometry, reserved, attempts } => {
+ finisher.finish_capture(ctx, PendingCapture { slot, callback, region, reply, since, geometry, reserved, attempts })
}
- Pending::Frames { since, reply, .. } if now - since > NOT_DRAWN_TIMEOUT => {
- // The agent is told it failed, so it must not happen later either.
- if let Ok(mut sh) = self.shared.lock() {
- sh.inject.clear();
- }
- let _ = reply.send(Err(not_drawn("handling the input")));
- }
- p @ Pending::Frames { .. } => keep.push(p),
- Pending::Screenshot { tag, region, reply, since } => match shots.iter().find(|(t, _)| *t == tag) {
- Some((_, image)) => {
- let _ = reply.send(screenshot_png(image, region, ppp));
- }
- // The platform skips painting windows that are hidden, minimized or fully
- // covered, so no screenshot ever arrives: say so instead of hanging.
- None if now - since > NOT_DRAWN_TIMEOUT => {
- let _ = reply.send(Err(not_drawn("the screenshot")));
- }
- None => keep.push(Pending::Screenshot { tag, region, reply, since }),
- },
+ };
+ if let Some(pending) = kept {
+ keep.push(pending);
}
}
self.pending = keep;
}
+ /// Expire queued input and collect the batches a pending reply must react to.
+ fn take_finished_shared(&self, ctx: &egui::Context, host: &mut impl Host, now: web_time::Instant) -> (Vec, Vec, bool) {
+ let (dropped, expired, in_pass) = self
+ .shared
+ .lock()
+ .map(|mut s| {
+ if !s.in_pass {
+ expire_input(&mut s, now);
+ }
+ if std::mem::take(&mut s.cancel_gestures) {
+ host.cancel_pointer_gestures();
+ }
+ (std::mem::take(&mut s.dropped), std::mem::take(&mut s.expired), s.in_pass)
+ })
+ .unwrap_or_default();
+ if !expired.is_empty() {
+ ctx.request_repaint(); // Run the queued key/modifier cleanup and pointer cancellation.
+ }
+ (dropped, expired, in_pass)
+ }
+
fn passes(&self) -> u64 {
self.shared.lock().map(|s| s.passes).unwrap_or(0)
}
- fn inject(&self, batches: Vec>) -> u32 {
- let n = batches.len() as u32;
- if let Ok(mut s) = self.shared.lock() {
- s.inject.extend(batches);
+ /// Queue one request's event batches (one per UI pass) and return its request id.
+ ///
+ /// The request is stamped once, at admission: all of its batches share the input-target
+ /// generation and the caller's single arrival deadline (`since`), so a deferred startup wait
+ /// is not restarted here. A poisoned mutex or a full queue is an error, never a silently empty
+ /// queue that would let the caller answer `Ok` for input that never happened.
+ fn inject(&self, batches: Vec>, since: web_time::Instant) -> Result, String> {
+ let mut s = self.shared.lock().map_err(|_| "control state poisoned".to_string())?;
+ let queued: usize = s.inject.iter().map(|request| request.batches.len()).sum();
+ if queued.saturating_add(batches.len()) > MAX_QUEUED_BATCHES {
+ return Err(format!("too many synthetic input batches are already queued (limit {MAX_QUEUED_BATCHES})"));
}
- // The last batch is handled during the frame it is injected into; answer one frame later.
- n + 1
+ s.next_batch += 1;
+ let id = s.next_batch;
+ let epoch = s.epoch;
+ s.inject.push_back(RequestBatches { request: id, epoch, started: false, since, release: Vec::new(), batches: batches.into() });
+ Ok(vec![id])
}
- fn handle(&mut self, ctx: &egui::Context, host: &mut impl Host, method: &str, p: &Value) -> Handled {
+ /// Queue synthetic input batches and reply only after the requested number of frames has been presented.
+ fn after_input(&self, batches: Vec>, value: Value, since: web_time::Instant) -> Result {
+ let frames = batches.len() as u32;
+ let batches = self.inject(batches, since)?;
+ Ok(Handled::AfterInput { batches, frames, value })
+ }
+
+ /// Validate and dispatch one control method, rejecting unknown methods and malformed parameters with
+ /// actionable errors.
+ fn handle(&mut self, ctx: &egui::Context, host: &mut impl Host, method: &str, p: &Value, since: web_time::Instant) -> Handled {
let str_param = |k: &str| p.get(k).and_then(Value::as_str).ok_or_else(|| format!("{method}: missing string parameter {k}"));
let r: Result = (|| match method {
"ui.state" => {
let mut state = host.state();
- let size = ctx.input(|i| i.viewport_rect().size());
- state["window"] = json!({ "width": size.x, "height": size.y, "pixels_per_point": ctx.pixels_per_point() });
+ // Viewport info is fresh in `logic`; the last UI pass's rectangle can be stale.
+ let geometry = Geometry::current(ctx, host.capture_epoch());
+ let size = geometry.size;
+ state["window"] = json!({ "width": size.x, "height": size.y, "pixels_per_point": geometry.pixels_per_point });
Ok(Handled::Now(Ok(state)))
}
"ui.commands" => Ok(Handled::Now(Ok(host.commands()))),
- "ui.dock" | "ui.dock.reset" => Ok(Handled::Now(host.dock(method == "ui.dock.reset", p))),
- "ui.command" if str_param("id")? == "ui.dock" => Ok(Handled::Now(host.dock(false, p.get("params").unwrap_or(p)))),
+ "ui.panel" | "ui.dock.reset" => Ok(Handled::Now(host.panel(method == "ui.dock.reset", p))),
+ "ui.command" if str_param("id")? == "ui.panel" => Ok(Handled::Now(host.panel(false, p.get("params").unwrap_or(p)))),
"ui.command" => Ok(Handled::Now(host.command(str_param("id")?))),
"ui.set" => {
let value = match p.get("value") {
@@ -299,8 +933,8 @@ impl Control {
}
"ui.open" => Ok(Handled::Now(host.open(str_param("path")?))),
"ui.inspect" => Ok(Handled::Now(Ok(self.inspect(p)))),
- "ui.click" => self.click(p),
- "ui.focus" => self.focus(p),
+ "ui.click" => self.click(p, since),
+ "ui.focus" => self.focus(p, since),
"ui.resize" => {
only_params(p, method, &["width", "height"])?;
let dimension = |key: &str| -> Result {
@@ -326,7 +960,7 @@ impl Control {
let quitting = host.quit(ctx);
Ok(Handled::Now(Ok(json!({ "quitting": quitting, "needs_confirmation": !quitting }))))
}
- "ui.drag" => self.drag(p),
+ "ui.drag" => self.drag(p, since),
"ui.move" => {
let point = |key: &str| -> Result {
p.get(key)
@@ -336,19 +970,18 @@ impl Control {
.ok_or_else(|| format!("ui.move: {key} must be a finite coordinate in points"))
};
let pos = egui::pos2(point("x")?, point("y")?);
- Ok(Handled::AfterFrames(self.inject(vec![vec![egui::Event::PointerMoved(pos)]]), json!({ "moved": [pos.x, pos.y] })))
+ self.after_input(vec![vec![egui::Event::PointerMoved(pos)]], json!({ "moved": [pos.x, pos.y] }), since)
}
"ui.type" => {
let text = str_param("text")?.to_string();
- Ok(Handled::AfterFrames(self.inject(vec![vec![egui::Event::Text(text)]]), json!({ "typed": true })))
+ self.after_input(vec![vec![egui::Event::Text(text)]], json!({ "typed": true }), since)
}
"ui.key" => {
let name = str_param("key")?;
let key = egui::Key::from_name(name)
.ok_or_else(|| format!("ui.key: unknown key {name:?} (egui key names: A, Enter, Escape, ArrowDown, F5, …)"))?;
let modifiers = modifiers(p.get("modifiers"))?;
- let ev = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers };
- Ok(Handled::AfterFrames(self.inject(vec![vec![ev(true)], vec![ev(false)]]), json!({ "key": name })))
+ self.after_input(key_batches(key, modifiers), json!({ "key": name }), since)
}
"ui.screenshot" => {
let region = match p.get("region") {
@@ -397,7 +1030,7 @@ impl Control {
}
/// Press at `from`, move to `to` in `steps` frames, release (drawing, selecting text, moving).
- fn drag(&mut self, p: &Value) -> Result {
+ fn drag(&mut self, p: &Value, since: web_time::Instant) -> Result {
let point = |k: &str| -> Result {
match p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect::>()).as_deref() {
Some([x, y]) => Some(egui::pos2(*x as f32, *y as f32))
@@ -430,11 +1063,11 @@ impl Control {
if modifiers != egui::Modifiers::NONE {
frames.push(vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
}
- let n = self.inject(frames);
- Ok(Handled::AfterFrames(n, json!({ "dragged": [[from.x, from.y], [to.x, to.y]] })))
+ self.after_input(frames, json!({ "dragged": [[from.x, from.y], [to.x, to.y]] }), since)
}
- fn click(&mut self, p: &Value) -> Result {
+ /// Click at a point, or on an accesskit widget by id or unique enabled label.
+ fn click(&mut self, p: &Value, since: web_time::Instant) -> Result {
if let (Some(x), Some(y)) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
let point = |key: &str, n: f64| {
Some(n as f32).filter(|n| n.is_finite()).ok_or_else(|| format!("ui.click: {key} must be a finite coordinate in points"))
@@ -443,8 +1076,8 @@ impl Control {
let which = pointer_button(p, "ui.click")?;
let button = |pressed| egui::Event::PointerButton { pos, button: which, pressed, modifiers: egui::Modifiers::NONE };
// Keep hover/layout warmup, then make an instantaneous click even on slow frames.
- let frames = self.inject(vec![vec![egui::Event::PointerMoved(pos)], vec![button(true), button(false)]]);
- return Ok(Handled::AfterFrames(frames, json!({ "clicked": [x, y] })));
+ let frames = vec![vec![egui::Event::PointerMoved(pos)], vec![button(true), button(false)]];
+ return self.after_input(frames, json!({ "clicked": [x, y] }), since);
}
let s = self.shared.lock().map_err(|_| "control state poisoned")?;
let id = match (p.get("id"), p.get("label").and_then(Value::as_str)) {
@@ -480,11 +1113,12 @@ impl Control {
let label = node.label().map(str::to_owned);
let action = accesskit::ActionRequest { action: Action::Click, target_tree: accesskit::TreeId::ROOT, target_node: id, data: None };
drop(s);
- let frames = self.inject(vec![vec![egui::Event::AccessKitActionRequest(action)]]);
- Ok(Handled::AfterFrames(frames, json!({ "clicked": id.0.to_string(), "label": label })))
+ let frames = vec![vec![egui::Event::AccessKitActionRequest(action)]];
+ self.after_input(frames, json!({ "clicked": id.0.to_string(), "label": label }), since)
}
- fn focus(&mut self, p: &Value) -> Result {
+ /// Focus an accesskit widget by id or unique enabled label.
+ fn focus(&mut self, p: &Value, since: web_time::Instant) -> Result {
only_params(p, "ui.focus", &["id", "label"])?;
let s = self.shared.lock().map_err(|_| "control state poisoned")?;
let id = match (p.get("id"), p.get("label")) {
@@ -512,14 +1146,20 @@ impl Control {
}
let action = accesskit::ActionRequest { action: Action::Focus, target_tree: accesskit::TreeId::ROOT, target_node: id, data: None };
drop(s);
- let frames = self.inject(vec![vec![egui::Event::AccessKitActionRequest(action)]]);
- Ok(Handled::AfterFrames(frames, json!({ "focus_requested": id.0.to_string() })))
+ let frames = vec![vec![egui::Event::AccessKitActionRequest(action)]];
+ self.after_input(frames, json!({ "focus_requested": id.0.to_string() }), since)
}
}
enum Handled {
Now(Reply),
+ /// Answer after this many accepted UI passes, without injecting input.
AfterFrames(u32, Value),
+ AfterInput {
+ batches: Vec,
+ frames: u32,
+ value: Value,
+ },
Screenshot(Option),
}
@@ -584,6 +1224,23 @@ fn pointer_button(p: &Value, method: &str) -> Result Vec> {
+ let key_event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers };
+ let mut press = vec![key_event(true)];
+ if modifiers != egui::Modifiers::NONE {
+ press.insert(0, egui::Event::ModifiersChanged(modifiers));
+ }
+ let mut release = vec![key_event(false)];
+ if modifiers != egui::Modifiers::NONE {
+ release.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ }
+ vec![press, release]
+}
+
fn modifiers(v: Option<&Value>) -> Result {
let mut m = egui::Modifiers::NONE;
for name in v.and_then(Value::as_array).into_iter().flatten() {
@@ -616,19 +1273,47 @@ fn rect_param(v: &Value) -> Result {
}
/// Encode (a region of) a screenshot as PNG; the reply carries base64 data and the size.
-fn screenshot_png(image: &egui::ColorImage, region: Option, ppp: f32) -> Reply {
+///
+/// The image scale is derived from the returned pixels and the logical viewport the capture was
+/// admitted for, never from the current `Context`: egui-wgpu's surface fit may have shrunk the
+/// surface (and a resize/DPI change has already been rejected before this call).
+fn screenshot_png(image: &egui::ColorImage, region: Option, geometry: Geometry) -> Reply {
let [w, h] = image.size;
+ let view = geometry.size;
+ if w == 0 || h == 0 {
+ return Err("the screenshot has no pixels".into());
+ }
+ if !(view.x.is_finite() && view.y.is_finite()) || view.x <= 0.0 || view.y <= 0.0 {
+ return Err("the window has no capturable size".into());
+ }
+ if region.is_some_and(|region| !geometry.contains_region(region)) {
+ return Err("the region must lie inside the window".into());
+ }
+ let scale_x = w as f32 / view.x;
+ let scale_y = h as f32 / view.y;
+ // A fitted surface shrinks both sides by one factor; a different x/y scale means the window
+ // changed shape and this image cannot be cropped honestly.
+ if (scale_x - scale_y).abs() > 0.01 * scale_x.max(1.0) {
+ return Err("the screenshot's aspect ratio does not match the window".into());
+ }
let (x0, y0, x1, y1) = match region {
Some(r) => {
- let px = |v: f32, max: usize| ((v * ppp).round().max(0.0) as usize).min(max);
- (px(r.min.x, w), px(r.min.y, h), px(r.max.x, w), px(r.max.y, h))
+ let px = |v: f32, scale: f32, max: usize| ((v * scale).round().max(0.0) as usize).min(max);
+ (px(r.min.x, scale_x, w), px(r.min.y, scale_y, h), px(r.max.x, scale_x, w), px(r.max.y, scale_y, h))
}
None => (0, 0, w, h),
};
if x1 <= x0 || y1 <= y0 {
return Err("the region is outside the window".into());
}
- let mut rgba = Vec::with_capacity((x1 - x0) * (y1 - y0) * 4);
+ let crop_bytes = (x1 - x0)
+ .checked_mul(y1 - y0)
+ .and_then(|pixels| pixels.checked_mul(core::mem::size_of::()))
+ .ok_or_else(|| "the screenshot region is too large".to_string())?;
+ if crop_bytes > MAX_ENCODED_BYTES {
+ return Err(format!("the screenshot region would need {crop_bytes} bytes to encode, over the {MAX_ENCODED_BYTES}-byte encode limit"));
+ }
+ let mut rgba = Vec::with_capacity(crop_bytes);
for y in y0..y1 {
for px in &image.pixels[y * w + x0..y * w + x1] {
rgba.extend_from_slice(&px.to_srgba_unmultiplied());
@@ -642,13 +1327,71 @@ fn screenshot_png(image: &egui::ColorImage, region: Option, ppp: f32
let mut writer = enc.write_header().map_err(|e| e.to_string())?;
writer.write_image_data(&rgba).map_err(|e| e.to_string())?;
writer.finish().map_err(|e| e.to_string())?;
+ if out.len() > MAX_ENCODED_BYTES {
+ return Err(format!("the encoded screenshot is {} bytes, over the {MAX_ENCODED_BYTES}-byte encode limit", out.len()));
+ }
+ let encoded = out.len().div_ceil(3).checked_mul(4).ok_or_else(|| "the encoded screenshot is too large".to_string())?;
+ if encoded > MAX_BASE64_BYTES {
+ return Err(format!("the screenshot's base64 reply would be {encoded} bytes, over the {MAX_BASE64_BYTES}-byte limit"));
+ }
use base64::Engine as _;
- Ok(json!({ "png_base64": base64::engine::general_purpose::STANDARD.encode(out), "width": cw, "height": ch, "pixels_per_point": ppp }))
+ Ok(json!({
+ "png_base64": base64::engine::general_purpose::STANDARD.encode(out),
+ "width": cw,
+ "height": ch,
+ "pixels_per_point": scale_x,
+ }))
}
impl Host for crate::PdfCraftApp {
- fn dock(&mut self, reset: bool, params: &Value) -> Reply {
- crate::docking::command(self, reset, params)
+ /// Cancel any in-progress pointer gesture in every open view.
+ fn cancel_pointer_gestures(&mut self) {
+ for view in &mut self.views {
+ view.cancel_pointer_gestures();
+ }
+ }
+
+ /// The input target: active document, open dialog/prompt, palette and find state.
+ ///
+ /// Synthetic input admitted for one generation is never replayed into another document or
+ /// dialog. Only these identities are hashed, never text or document content.
+ fn input_epoch(&self) -> u64 {
+ use std::hash::{Hash as _, Hasher as _};
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ self.capture_epoch().hash(&mut hasher);
+ // The focused widget is part of the input target: keys typed for one field must not land
+ // in another after focus moves. Only the id value is hashed, never text.
+ let focused = self.ctx.as_ref().and_then(|ctx| ctx.memory(|m| m.focused())).map(|id| id.value());
+ focused.hash(&mut hasher);
+ hasher.finish()
+ }
+
+ /// The captured content: active document and open dialog/prompt, never keyboard focus.
+ fn capture_epoch(&self) -> u64 {
+ use std::hash::{Hash as _, Hasher as _};
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ let doc = self.active.and_then(|i| self.views.get(i)).map(|v| v.id.0);
+ doc.hash(&mut hasher);
+ format!(
+ "{:?}/{:?}/{:?}/{:?}/{:?}",
+ self.dialog,
+ self.password_prompt.is_some(),
+ self.palette_open,
+ self.close_request.is_some(),
+ self.active.and_then(|i| self.views.get(i)).and_then(|v| v.find.as_ref().map(|_| true)),
+ )
+ .hash(&mut hasher);
+ hasher.finish()
+ }
+
+ /// Control requests wait for the first UI pass that installs fonts; a font-gated early
+ /// return cannot consume injected input or issue a screenshot.
+ fn accepts_input(&self) -> bool {
+ self.fonts_ready
+ }
+
+ fn panel(&mut self, reset: bool, params: &Value) -> Reply {
+ crate::side_panels::command(self, reset, params)
}
fn quit(&mut self, ctx: &egui::Context) -> bool {
@@ -672,7 +1415,7 @@ impl Host for crate::PdfCraftApp {
#[cfg(target_arch = "wasm32")]
let pending_opens: Vec = Vec::new();
json!({
- "docking": self.docking,
+ "side_panels": crate::side_panels::state(self),
"documents": docs,
"pending_opens": pending_opens,
"active": active.map(|v| json!({
@@ -735,7 +1478,7 @@ impl Host for crate::PdfCraftApp {
"default_mode": self.default_mode,
"comment_tool_pinned": self.comment_prefs.pinned,
"left_panel": if self.left_open { json!(format!("{:?}", self.left)) } else { Value::Null },
- "tools_side": if self.docking.tools_on_right() { "right" } else { "left" },
+ "tools_side": if self.side_panels.tools_on_right() { "right" } else { "left" },
"right_panel": self.right.map(|r| format!("{r:?}")),
"dialog": self.dialog.map(|d| format!("{d:?}")),
"palette_open": self.palette_open,
@@ -763,7 +1506,7 @@ impl Host for crate::PdfCraftApp {
.iter()
.map(|c| json!({ "id": c.id, "label": c.label, "menu": c.menu, "enabled": self.command_enabled(c), "shortcut": c.shortcut.map(|s| s.label(cfg!(target_os = "macos"))) }))
.collect();
- list.push(json!({"id": "ui.dock", "label": "Arrange Panel", "enabled": true, "params": "action, or operation/panel; move: target/zone/before; float/moveFloating: rect; resizeSplit: path/size; setStackOpen: open; resizeStack: height"}));
+ list.push(json!({"id": "ui.panel", "label": "Side panel", "enabled": true, "params": "panel: tools or side; open: boolean; width: number (clamped to the panel's limits)"}));
json!({ "commands": list })
}
@@ -1401,6 +2144,1009 @@ mod transport_tests {
}
}
+#[cfg(test)]
+mod lifecycle_tests {
+ use super::*;
+ use egui::Plugin as _;
+ use egui_kittest::Harness;
+
+ /// A request is answered after accepted frames only: a discarded layout pass is not a frame
+ /// the agent can see, so it must not advance the count.
+ #[test]
+ fn discarded_passes_are_not_counted_as_accepted_frames() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let mut plugin = ControlPlugin { shared: shared.clone() };
+ let ctx = egui::Context::default();
+ let mut accepted = egui::FullOutput::default();
+ plugin.output_hook(&ctx, &mut accepted);
+ let mut discarded = egui::FullOutput::default();
+ discarded.platform_output.request_discard_reasons.push(egui::RepaintCause::new_reason("control test discard"));
+ plugin.output_hook(&ctx, &mut discarded);
+ assert_eq!(shared.lock().unwrap().passes, 1, "only the presented pass counts");
+ }
+
+ /// A frame that requests discard on every pass and hits `max_passes` still presents its
+ /// last pass: that presented pass must count, or `Pending::Frames` waits for a frame that
+ /// never arrives. This runs the real multi-pass loop rather than a hand-built FullOutput.
+ #[test]
+ fn a_final_capped_pass_is_counted_as_presented() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let ctx = egui::Context::default();
+ ctx.add_plugin(ControlPlugin { shared: shared.clone() });
+ ctx.options_mut(|o| o.max_passes = 2.try_into().expect("two is non-zero"));
+ let mut output = ctx.run_ui(egui::RawInput::default(), |ui| ui.ctx().request_discard("control test must discard"));
+ output.textures_delta.clear();
+ assert_eq!(output.platform_output.num_completed_passes, 2, "the cap was reached");
+ assert!(!output.platform_output.request_discard_reasons.is_empty(), "the last pass still requested a discard");
+ assert_eq!(shared.lock().unwrap().passes, 1, "the presented final pass counts once");
+ }
+
+ /// `max_passes` above two still counts a frame that settles after earlier discarded passes:
+ /// egui clears the previous pass's discard reasons at the start of each pass, so the merged
+ /// output of a presented final pass is not mistaken for a discarded one.
+ #[test]
+ fn a_frame_that_settles_before_a_higher_pass_cap_is_counted_once() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let ctx = egui::Context::default();
+ ctx.add_plugin(ControlPlugin { shared: shared.clone() });
+ ctx.options_mut(|o| o.max_passes = 3.try_into().expect("three is non-zero"));
+ let mut pass = 0;
+ let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
+ pass += 1;
+ if pass < 3 {
+ ui.ctx().request_discard("control test must discard the first two passes");
+ }
+ });
+ output.textures_delta.clear();
+ assert_eq!(output.platform_output.num_completed_passes, 3, "the third pass settled at the higher cap");
+ assert!(output.platform_output.request_discard_reasons.is_empty(), "earlier discard reasons do not survive the settling pass");
+ assert_eq!(shared.lock().unwrap().passes, 1, "the one presented frame counts once");
+ }
+
+ /// `ui.key` delivers held modifiers through `ModifiersChanged`, because egui does not derive
+ /// `InputState.modifiers` from a key event's own field. Shift+Tab and ⌘Enter handlers read it.
+ #[test]
+ fn key_commands_deliver_modifier_state() {
+ let held = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE };
+ let batches = key_batches(egui::Key::Enter, held);
+ let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: held };
+ assert_eq!(
+ batches,
+ vec![vec![egui::Event::ModifiersChanged(held), key(true)], vec![key(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]]
+ );
+ let ctx = egui::Context::default();
+ let mut press_seen = None;
+ ctx.run_ui(egui::RawInput { events: batches[0].clone(), ..Default::default() }, |ui| press_seen = Some(ui.input(|i| i.modifiers)))
+ .textures_delta
+ .clear();
+ let mut release_seen = None;
+ ctx.run_ui(egui::RawInput { events: batches[1].clone(), ..Default::default() }, |ui| release_seen = Some(ui.input(|i| i.modifiers)))
+ .textures_delta
+ .clear();
+ assert_eq!(press_seen, Some(held), "the press sees the modifiers it was sent with");
+ assert_eq!(release_seen, Some(egui::Modifiers::NONE), "the modifier release follows the key-up");
+ }
+
+ /// A batch admitted for one document/focus generation must not apply after that generation
+ /// changes; the request is reported as stale instead of replaying the input.
+ #[test]
+ fn a_stale_synthetic_batch_is_dropped_and_reported() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let mut plugin = ControlPlugin { shared: shared.clone() };
+ {
+ let mut s = shared.lock().unwrap();
+ s.epoch = 2;
+ s.inject.push_back(RequestBatches {
+ request: 41,
+ epoch: 1,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([vec![egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]]),
+ });
+ }
+ let mut raw = egui::RawInput::default();
+ plugin.input_hook(&egui::Context::default(), &mut raw);
+ assert!(raw.events.is_empty(), "stale input must not reach the new document");
+ let s = shared.lock().unwrap();
+ assert_eq!(s.dropped, vec![41]);
+ assert!(s.inject.is_empty());
+ }
+
+ /// A stale request is dropped alone. A request admitted later for the current generation
+ /// behind it still runs: one agent's outdated input must not fail another's.
+ #[test]
+ fn a_stale_request_does_not_drop_a_later_current_one() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let mut plugin = ControlPlugin { shared: shared.clone() };
+ {
+ let mut s = shared.lock().unwrap();
+ s.epoch = 2;
+ s.inject.push_back(RequestBatches {
+ request: 41,
+ epoch: 1,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([vec![egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]]),
+ });
+ s.inject.push_back(RequestBatches {
+ request: 42,
+ epoch: 2,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([vec![egui::Event::PointerMoved(egui::pos2(2.0, 2.0))]]),
+ });
+ }
+ let ctx = egui::Context::default();
+ let mut first = egui::RawInput::default();
+ plugin.input_hook(&ctx, &mut first);
+ assert!(first.events.is_empty(), "the stale request is not replayed");
+ let mut second = egui::RawInput::default();
+ plugin.input_hook(&ctx, &mut second);
+ assert_eq!(second.events, [egui::Event::PointerMoved(egui::pos2(2.0, 2.0))], "the current request still applies");
+ let s = shared.lock().unwrap();
+ assert_eq!(s.dropped, vec![41]);
+ assert!(s.inject.is_empty());
+ }
+
+ /// Once a request has started, the focus/dialog change caused by its own first batch must not
+ /// drop its release: a key press without its release leaves `keys_down` stuck.
+ #[test]
+ fn a_started_request_finishes_its_batches_after_focus_moves() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let mut plugin = ControlPlugin { shared: shared.clone() };
+ {
+ let mut s = shared.lock().unwrap();
+ s.epoch = 7;
+ s.inject.push_back(RequestBatches {
+ request: 9,
+ epoch: 7,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([
+ vec![egui::Event::Key {
+ key: egui::Key::Tab,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ vec![egui::Event::Key {
+ key: egui::Key::Tab,
+ physical_key: None,
+ pressed: false,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ ]),
+ });
+ }
+ let ctx = egui::Context::default();
+ let mut press = egui::RawInput::default();
+ plugin.input_hook(&ctx, &mut press);
+ assert!(matches!(press.events.as_slice(), [egui::Event::Key { pressed: true, .. }]));
+ // The press moved focus: the next pass sees another input-target generation.
+ shared.lock().unwrap().epoch = 8;
+ let mut release = egui::RawInput::default();
+ plugin.input_hook(&ctx, &mut release);
+ assert!(matches!(release.events.as_slice(), [egui::Event::Key { pressed: false, .. }]), "the release still arrives");
+ let s = shared.lock().unwrap();
+ assert!(s.dropped.is_empty(), "a started request is not reported as stale");
+ assert!(s.inject.is_empty());
+ }
+
+ /// A host for timeout tests: the control layer must not need a real app.
+ struct NoopHost;
+
+ impl Host for NoopHost {
+ fn state(&self) -> Value {
+ json!({})
+ }
+ fn command(&mut self, _id: &str) -> Reply {
+ Err("no commands in this test".into())
+ }
+ fn panel(&mut self, _reset: bool, _params: &Value) -> Reply {
+ Err("no side panels in this test".into())
+ }
+ fn commands(&self) -> Value {
+ json!([])
+ }
+ fn set(&mut self, _key: &str, _value: &str) -> Reply {
+ Err("no settings in this test".into())
+ }
+ fn open(&mut self, _path: &str) -> Reply {
+ Err("no files in this test".into())
+ }
+ fn quit(&mut self, _ctx: &egui::Context) -> bool {
+ false
+ }
+ }
+
+ /// A host that starts unready (fonts not installed) and counts dispatched state reads.
+ /// `state` takes `&self`, so the count sits in a `Cell`.
+ struct ReadinessHost {
+ ready: bool,
+ states: std::cell::Cell,
+ /// Methods the host was asked to run, in dispatch order.
+ calls: std::cell::RefCell>,
+ }
+
+ impl ReadinessHost {
+ fn new(ready: bool) -> Self {
+ Self { ready, states: std::cell::Cell::new(0), calls: std::cell::RefCell::new(Vec::new()) }
+ }
+ }
+
+ impl Host for ReadinessHost {
+ fn state(&self) -> Value {
+ self.states.set(self.states.get() + 1);
+ self.calls.borrow_mut().push("ui.state");
+ json!({ "ready": self.ready })
+ }
+ fn command(&mut self, _id: &str) -> Reply {
+ Err("no commands in this test".into())
+ }
+ fn panel(&mut self, _reset: bool, _params: &Value) -> Reply {
+ Err("no side panels in this test".into())
+ }
+ fn commands(&self) -> Value {
+ self.calls.borrow_mut().push("ui.commands");
+ json!([])
+ }
+ fn set(&mut self, _key: &str, _value: &str) -> Reply {
+ Err("no settings in this test".into())
+ }
+ fn open(&mut self, _path: &str) -> Reply {
+ Err("no files in this test".into())
+ }
+ fn quit(&mut self, _ctx: &egui::Context) -> bool {
+ false
+ }
+ fn accepts_input(&self) -> bool {
+ self.ready
+ }
+ }
+
+ /// The admission timestamp of the one pending request, whichever kind it is.
+ fn pending_since(control: &Control) -> Option {
+ let first = control.pending.first()?;
+ match first {
+ Pending::Frames { since, .. } | Pending::Screenshot { since, .. } => Some(*since),
+ }
+ }
+
+ #[test]
+ fn a_request_expired_in_the_channel_is_never_dispatched_or_deferred() {
+ for ready in [false, true] {
+ let ctx = egui::Context::default();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(ready);
+ let (reply, waiting) = channel();
+ let since = web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap();
+ client.tx.send(ControlRequest { since, method: "ui.state".into(), params: json!({}), reply }).unwrap();
+ control.tick(&ctx, &mut host);
+ let error = waiting.try_recv().expect("expired channel request replies on the first tick").expect_err("expired request cannot dispatch");
+ assert!(error.contains(if ready { "finished starting" } else { "still starting" }), "{error}");
+ assert_eq!(host.states.get(), 0);
+ assert!(control.deferred.is_empty() && control.pending.is_empty());
+ }
+ }
+
+ /// A request held during startup keeps its arrival time. Once the app accepts input, one
+ /// older than the control deadline fails instead of being dispatched into a later UI.
+ #[test]
+ fn a_deferred_request_expires_instead_of_dispatching_after_the_deadline() {
+ let ctx = egui::Context::default();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(false);
+ let waiting = client.send("ui.state", json!({}));
+ control.tick(&ctx, &mut host);
+ assert_eq!(control.deferred.len(), 1, "unready host defers the request");
+ assert!(waiting.try_recv().is_err(), "it is not answered while starting");
+ let past = web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap();
+ for deferred in &mut control.deferred {
+ deferred.since = past;
+ }
+ // It expires even while the app is still not ready, so the client is not left waiting.
+ control.tick(&ctx, &mut host);
+ let error = waiting.try_recv().expect("expired deferred request receives a reply").expect_err("it must not dispatch");
+ assert!(error.contains("still starting"), "{error}");
+ assert!(control.deferred.is_empty());
+ // And readiness arriving later cannot revive it.
+ host.ready = true;
+ control.tick(&ctx, &mut host);
+ assert_eq!(host.states.get(), 0, "an expired request is never dispatched");
+ }
+
+ /// A request deferred only briefly still runs once fonts are ready.
+ #[test]
+ fn a_fresh_deferred_request_still_dispatches_when_the_app_becomes_ready() {
+ let ctx = egui::Context::default();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(false);
+ let waiting = client.send("ui.state", json!({}));
+ control.tick(&ctx, &mut host);
+ assert!(waiting.try_recv().is_err());
+ host.ready = true;
+ control.tick(&ctx, &mut host);
+ let reply = waiting.try_recv().expect("fresh deferred request replies").expect("it dispatches");
+ assert_eq!(reply["ready"], true);
+ assert_eq!(host.states.get(), 1, "the fresh deferred request is dispatched once");
+ }
+
+ /// A request deferred during startup keeps its one arrival timestamp. Dispatching it into
+ /// synthetic input, a deferred frame reply or a screenshot reservation must not start a fresh
+ /// 5 s in that phase: every later phase measures the same deadline from arrival.
+ #[test]
+ fn a_startup_wait_counts_against_one_admission_deadline_in_every_phase() {
+ let params = [("ui.type", json!({ "text": "x" })), ("ui.resize", json!({ "width": 800, "height": 600 })), ("ui.screenshot", json!({}))];
+ for (method, params) in params {
+ // `ui.resize` needs a native window; the other phases are checked on every target.
+ if method == "ui.resize" && cfg!(target_arch = "wasm32") {
+ continue;
+ }
+ let ctx = egui::Context::default();
+ // A real window size, so an admitted screenshot has capturable geometry.
+ ctx.run_ui(
+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))), ..Default::default() },
+ |_| {},
+ )
+ .drop_without_applying_deltas();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(false);
+ let waiting = client.send(method, params);
+ control.tick(&ctx, &mut host);
+ assert_eq!(control.deferred.len(), 1, "{method}: deferred while starting");
+ // Three of the five seconds were spent starting: the request is still inside its
+ // deadline, but only just.
+ let arrived = web_time::Instant::now().checked_sub(std::time::Duration::from_secs(3)).unwrap();
+ for deferred in &mut control.deferred {
+ deferred.since = arrived;
+ }
+ host.ready = true;
+ control.tick(&ctx, &mut host);
+ assert!(control.deferred.is_empty(), "{method}: dispatched once the app accepts input");
+ assert!(waiting.try_recv().is_err(), "{method}: a preserved deadline does not answer early");
+ assert_eq!(pending_since(&control), Some(arrived), "{method}: the pending reply keeps the arrival deadline");
+ if method == "ui.type" {
+ let shared = control.shared.lock().unwrap();
+ assert_eq!(shared.inject.front().map(|request| request.since), Some(arrived), "{method}: queued input keeps the arrival deadline");
+ }
+ // Move that same shared timestamp past its own deadline (five seconds after arrival).
+ // Expiry measures the one admission instant, so nothing waits for a fresh five.
+ let past = arrived.checked_sub(timeout()).expect("a representable instant");
+ for pending in &mut control.pending {
+ match pending {
+ Pending::Frames { since, .. } | Pending::Screenshot { since, .. } => *since = past,
+ }
+ }
+ if let Ok(mut shared) = control.shared.lock() {
+ for request in &mut shared.inject {
+ request.since = past;
+ }
+ }
+ control.finish_pending(&ctx, &mut host);
+ let error = waiting.try_recv().expect("the expired request replies").expect_err("it must not succeed");
+ assert!(error.contains("not being drawn"), "{method}: {error}");
+ assert!(control.pending.is_empty(), "{method}: the expired request is not retried");
+ assert_eq!(control.reserved_bytes(), 0, "{method}: any reservation is released");
+ }
+ }
+
+ /// One client's requests keep their arrival order: a request deferred during startup runs
+ /// before a newer request that was still waiting in the channel when the app became ready.
+ #[test]
+ fn a_deferred_request_runs_before_a_newer_queued_one() {
+ let ctx = egui::Context::default();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(false);
+ let older = client.send("ui.state", json!({}));
+ control.tick(&ctx, &mut host);
+ assert_eq!(control.deferred.len(), 1, "the older request is deferred while starting");
+ let newer = client.send("ui.commands", json!({}));
+ host.ready = true;
+ control.tick(&ctx, &mut host);
+ assert_eq!(*host.calls.borrow(), ["ui.state", "ui.commands"], "the older deferred request is dispatched first");
+ assert_eq!(older.try_recv().expect("the older request replies").expect("it dispatches")["ready"], true);
+ assert_eq!(newer.try_recv().expect("the newer request replies").expect("it dispatches"), json!([]));
+ }
+
+ /// A request whose startup wait used up the deadline is refused once the app is ready, and the
+ /// message says the app finished starting instead of claiming it is still starting.
+ #[test]
+ fn a_request_that_outlasted_startup_reports_that_the_app_finished_starting() {
+ let ctx = egui::Context::default();
+ let (mut control, client) = attach(&ctx);
+ let mut host = ReadinessHost::new(false);
+ let waiting = client.send("ui.state", json!({}));
+ control.tick(&ctx, &mut host);
+ assert_eq!(control.deferred.len(), 1);
+ let past = web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap();
+ for deferred in &mut control.deferred {
+ deferred.since = past;
+ }
+ host.ready = true;
+ control.tick(&ctx, &mut host);
+ let error = waiting.try_recv().expect("the expired request replies").expect_err("it is never dispatched");
+ assert!(error.contains("finished starting"), "{error}");
+ assert!(!error.contains("was still starting"), "the app is ready now: {error}");
+ assert_eq!(host.states.get(), 0, "an expired request is never dispatched");
+ assert!(control.deferred.is_empty() && control.pending.is_empty());
+ }
+
+ /// Keep key/modifier cleanup, but a canceled pointer must never produce a release event.
+ #[test]
+ fn a_timed_out_started_request_cancels_pointer_and_releases_keys() {
+ let ctx = egui::Context::default();
+ let (mut control, _client) = attach(&ctx);
+ let held = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE };
+ let pos = egui::pos2(24.0, 32.0);
+ let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: held };
+ let ids = control
+ .inject(
+ vec![
+ vec![
+ egui::Event::ModifiersChanged(held),
+ key(true),
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: held },
+ ],
+ vec![egui::Event::PointerMoved(egui::pos2(40.0, 48.0))],
+ vec![key(false), egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: held }],
+ ],
+ web_time::Instant::now(),
+ )
+ .unwrap();
+ let (reply, rx) = channel();
+ control.pending.push(Pending::Frames { until_pass: u64::MAX, batches: ids, since: web_time::Instant::now(), reply, value: json!({}) });
+ ctx.run_ui(egui::RawInput::default(), |_| {}).drop_without_applying_deltas();
+ assert!(ctx.input(|i| i.keys_down.contains(&egui::Key::Enter) && i.pointer.primary_down()));
+ assert_eq!(ctx.input(|i| i.modifiers), held);
+ age_input(&mut control);
+ let next = egui::pos2(80.0, 90.0);
+ control.inject(vec![vec![egui::Event::PointerMoved(next)]], web_time::Instant::now()).unwrap();
+ control.finish_pending(&ctx, &mut NoopHost);
+ assert!(rx.try_recv().unwrap().unwrap_err().contains("not being drawn"));
+ assert!(control.pending.is_empty());
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ assert!(!ui.input(|i| i.keys_down.contains(&egui::Key::Enter)));
+ assert_eq!(ui.input(|i| i.modifiers), egui::Modifiers::NONE);
+ assert_eq!(ui.input(|i| i.pointer.hover_pos()), Some(next), "another live request survives");
+ assert!(!ui.input(|i| i.pointer.any_down() || i.pointer.any_released()));
+ assert!(ui.ctx().dragged_id().is_none() && ui.ctx().drag_stopped_id().is_none());
+ })
+ .drop_without_applying_deltas();
+ assert!(control.shared.lock().unwrap().inject.is_empty());
+ assert!(rx.try_recv().is_err(), "only one timeout reply");
+ }
+
+ #[test]
+ fn a_deadline_crossing_inside_an_admitted_pass_cancels_before_the_next_interaction() {
+ let ctx = egui::Context::default();
+ let (mut control, _client) = attach(&ctx);
+ let pos = egui::pos2(24.0, 32.0);
+ let ids = control
+ .inject(
+ vec![
+ vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE },
+ ],
+ vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }],
+ ],
+ web_time::Instant::now(),
+ )
+ .unwrap();
+ let (reply, rx) = channel();
+ control.pending.push(Pending::Frames { until_pass: u64::MAX, batches: ids, since: web_time::Instant::now(), reply, value: json!({}) });
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ assert!(ui.input(|i| i.pointer.primary_down()), "the press was admitted before expiry");
+ age_input(&mut control);
+ control.finish_pending(ui.ctx(), &mut NoopHost);
+ assert!(rx.try_recv().is_err(), "do not cancel an already-calculated interaction mid-pass");
+ })
+ .drop_without_applying_deltas();
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ control.finish_pending(ui.ctx(), &mut NoopHost);
+ assert!(!ui.input(|i| i.pointer.any_down() || i.pointer.any_released()));
+ assert!(ui.ctx().drag_stopped_id().is_none());
+ })
+ .drop_without_applying_deltas();
+ assert!(rx.try_recv().unwrap().unwrap_err().contains("not being drawn"));
+ assert!(control.shared.lock().unwrap().inject.is_empty());
+ }
+
+ /// Deterministic elapsed-time input: age the same admission in both halves, without sleeping
+ /// or fabricating any egui pointer/widget state.
+ fn age_input(control: &mut Control) {
+ let past = web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap();
+ for request in &mut control.shared.lock().unwrap().inject {
+ request.since = past;
+ }
+ for pending in &mut control.pending {
+ if let Pending::Frames { since, .. } = pending {
+ *since = past;
+ }
+ }
+ }
+
+ /// The public gestures this test drives through real UI passes.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ enum Gesture {
+ AtomicClick,
+ HeldClick,
+ Marquee,
+ }
+
+ fn gesture_request(gesture: Gesture, from: egui::Pos2, to: egui::Pos2) -> (&'static str, Value) {
+ match gesture {
+ Gesture::AtomicClick => ("ui.click", json!({"x": from.x, "y": from.y})),
+ Gesture::HeldClick => ("ui.drag", json!({"from": [from.x, from.y], "to": [from.x, from.y], "steps": 6})),
+ Gesture::Marquee => ("ui.drag", json!({"from": [from.x, from.y], "to": [to.x, to.y], "steps": 6})),
+ }
+ }
+
+ fn marquee_harness() -> (Harness<'static, crate::PdfCraftApp>, ControlClient) {
+ let client_slot: Arc>> = Arc::new(Mutex::new(None));
+ let slot = client_slot.clone();
+ let h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(0.01).build_eframe(move |cc| {
+ let mut app = crate::PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("synthetic-form.pdf", None, include_bytes!("../tests/data/form.pdf").to_vec()).unwrap();
+ app.set_option("quick", "marquee-zoom").unwrap();
+ *slot.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx));
+ app
+ });
+ let client = client_slot.lock().unwrap().take().unwrap();
+ (h, client)
+ }
+
+ fn marquee_step(h: &mut Harness<'static, crate::PdfCraftApp>) {
+ let ctx = h.ctx.clone();
+ let mut raw = std::mem::take(h.input_mut());
+ h.state_mut().prepare_raw_input(&ctx, &mut raw);
+ *h.input_mut() = raw;
+ h.step();
+ }
+
+ /// The actual laid-out page rect and a short point gesture inside it.
+ fn gesture_target(h: &Harness<'static, crate::PdfCraftApp>) -> (egui::Pos2, egui::Pos2) {
+ let page = h.state().views[0].page_screen_rect(0).expect("the actual PDF page was laid out").intersect(h.state().views[0].viewport_rect());
+ assert!(page.width() > 100.0 && page.height() > 100.0, "a visible hit target: {page:?}");
+ let from = page.center();
+ let to = from + egui::vec2(40.0, 50.0);
+ assert!(page.contains(to));
+ (from, to)
+ }
+
+ /// Step until the public request has really reached egui and can still be interrupted.
+ fn await_gesture_admission(h: &mut Harness<'static, crate::PdfCraftApp>, gesture: Gesture) -> bool {
+ let mut admitted = false;
+ for _ in 0..8 {
+ marquee_step(h);
+ admitted = if gesture == Gesture::AtomicClick {
+ let shared = h.state().control.as_ref().unwrap().shared.lock().unwrap();
+ shared.inject.front().is_some_and(|request| request.started && request.batches.len() == 1)
+ } else {
+ h.ctx.input(|i| i.pointer.primary_down()) && (gesture != Gesture::Marquee || h.state().views[0].marquee.is_some())
+ };
+ if admitted {
+ break;
+ }
+ }
+ admitted
+ }
+
+ /// The request is queued exactly once, with the expected terminal batch not yet applied.
+ fn assert_interruptible_admission(h: &Harness<'static, crate::PdfCraftApp>, gesture: Gesture, from: egui::Pos2) {
+ {
+ let shared = h.state().control.as_ref().unwrap().shared.lock().unwrap();
+ assert_eq!(shared.inject.len(), 1, "only the actual public request is queued");
+ let pending = shared.inject.front().unwrap();
+ assert!(pending.started);
+ let terminal = pending.batches.back().expect("the terminal batch is still pending");
+ if gesture == Gesture::AtomicClick {
+ assert_eq!(pending.batches.len(), 1);
+ assert_eq!(terminal.len(), 2);
+ assert!(
+ matches!(terminal[0], egui::Event::PointerButton { pressed: true, button: egui::PointerButton::Primary, pos, .. } if pos == from)
+ );
+ assert!(
+ matches!(terminal[1], egui::Event::PointerButton { pressed: false, button: egui::PointerButton::Primary, pos, .. } if pos == from)
+ );
+ assert!(!h.ctx.input(|i| i.pointer.primary_down()), "atomic click has only hovered so far");
+ } else {
+ assert!(h.ctx.input(|i| i.pointer.primary_down()), "a real pass consumed the press");
+ assert_eq!(terminal.len(), 1);
+ assert!(matches!(terminal[0], egui::Event::PointerButton { pressed: false, button: egui::PointerButton::Primary, .. }));
+ }
+ }
+ assert!(!h.ctx.input(|i| i.pointer.any_released()), "the terminal release has not run");
+ assert!(h.ctx.drag_stopped_id().is_none());
+ if gesture == Gesture::Marquee {
+ assert!(h.ctx.dragged_id().is_some() && h.state().views[0].marquee.is_some(), "the app has a real drag preview");
+ } else {
+ assert!(h.state().views[0].marquee.is_none() && h.state().views[0].marquee_done.is_none());
+ }
+ }
+
+ /// Expire the admission both through hidden logic and through the next input hook, then
+ /// assert that cancellation left no gesture, zoom or edit behind.
+ fn assert_timed_out_gesture(h: &mut Harness<'static, crate::PdfCraftApp>, reply: &Receiver, hidden_logic: bool, zoom: f32, bytes: &[u8]) {
+ age_input(h.state_mut().control.as_mut().unwrap());
+ if hidden_logic {
+ let ctx = h.ctx.clone();
+ let app = h.state_mut();
+ let mut control = app.control.take().unwrap();
+ control.tick(&ctx, app);
+ app.control = Some(control);
+ assert!(reply.try_recv().unwrap().unwrap_err().contains("not being drawn"));
+ }
+ marquee_step(h);
+ if !hidden_logic {
+ assert!(reply.try_recv().unwrap().unwrap_err().contains("not being drawn"));
+ }
+ for _ in 0..2 {
+ marquee_step(h);
+ }
+ assert!(!h.ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()));
+ assert!(h.ctx.dragged_id().is_none() && h.ctx.drag_stopped_id().is_none());
+ assert!(h.state().views[0].marquee.is_none() && h.state().views[0].marquee_done.is_none());
+ assert_eq!(h.state().views[0].zoom, zoom, "canceling must not turn a drag into a zoom click");
+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes.as_slice(), bytes, "no abandoned edit");
+ assert!(h.state().control.as_ref().unwrap().shared.lock().unwrap().inject.is_empty());
+ assert!(h.state().control.as_ref().unwrap().pending.is_empty());
+ assert!(reply.try_recv().is_err(), "the cancellation replies once");
+ }
+
+ /// Complete one public gesture and check its real event trace and one-step zoom.
+ fn complete_positive_gesture(
+ h: &mut Harness<'static, crate::PdfCraftApp>,
+ client: &ControlClient,
+ gesture: Gesture,
+ positive: Gesture,
+ bytes: &[u8],
+ ) {
+ let (from, to) = gesture_target(h);
+ let zoom = h.state().views[0].zoom;
+ let (method, params) = gesture_request(positive, from, to);
+ let reply = client.send(method, params);
+ let mut value = None;
+ let mut buttons = Vec::new();
+ let mut positions = Vec::new();
+ for _ in 0..20 {
+ marquee_step(h);
+ h.ctx.input(|i| {
+ for event in &i.events {
+ match event {
+ egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, pos, .. } => {
+ buttons.push((*pressed, i.time));
+ positions.push(*pos);
+ }
+ egui::Event::PointerMoved(pos) => positions.push(*pos),
+ _ => {}
+ }
+ }
+ });
+ if let Ok(result) = reply.try_recv() {
+ value = Some(result.unwrap());
+ break;
+ }
+ }
+ assert!(value.is_some(), "a fresh completed request succeeds: {positive:?}, after {gesture:?}");
+ assert_eq!(buttons.iter().map(|(pressed, _)| *pressed).collect::>(), [true, false]);
+ assert!(!h.ctx.input(|i| i.pointer.any_down()));
+ assert!(h.ctx.dragged_id().is_none());
+ if positive == Gesture::Marquee {
+ assert!(h.state().views[0].zoom > zoom, "the normal marquee rectangle zooms");
+ } else {
+ let options = h.ctx.options(|o| o.input_options);
+ assert!(buttons[1].1 - buttons[0].1 < options.max_click_duration, "real press/release remain a short click");
+ assert!(positions.iter().all(|pos| pos.distance(from) < options.max_click_dist), "real input remains stationary");
+ assert!((h.state().views[0].zoom - zoom * 1.5).abs() < 0.001, "a normal click zooms one step");
+ }
+ assert!(h.state().views[0].marquee.is_none() && h.state().views[0].marquee_done.is_none());
+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes.as_slice(), bytes, "completed zooms do not edit the document");
+ assert!(reply.try_recv().is_err(), "successful request replies once");
+ }
+
+ /// Real page hit-testing, real control batches and the production marquee completion path.
+ /// Exercise both hidden-logic expiry and expiry first observed by the next input hook.
+ #[test]
+ fn a_timed_out_marquee_never_zooms_and_completed_clicks_and_drags_still_work() {
+ for hidden_logic in [false, true] {
+ for gesture in [Gesture::AtomicClick, Gesture::HeldClick, Gesture::Marquee] {
+ let (mut h, client) = marquee_harness();
+ for _ in 0..5 {
+ marquee_step(&mut h);
+ }
+ let (from, to) = gesture_target(&h);
+ let zoom = h.state().views[0].zoom;
+ let bytes = h.state().session.get(h.state().views[0].id).unwrap().bytes.clone();
+ let (method, params) = gesture_request(gesture, from, to);
+ let reply = client.send(method, params);
+ assert!(await_gesture_admission(&mut h, gesture), "a real interruptible admission: {gesture:?}, hidden={hidden_logic}");
+ assert_interruptible_admission(&h, gesture, from);
+ assert!(reply.try_recv().is_err(), "the terminal batch has not run");
+ assert_eq!(h.state().views[0].zoom, zoom);
+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes, bytes);
+ assert_timed_out_gesture(&mut h, &reply, hidden_logic, zoom, &bytes);
+
+ // Complete the same public gesture, then an atomic click after held input.
+ // Real event traces prove the stationary drag is a valid short point click.
+ let positives = [gesture, Gesture::AtomicClick];
+ let count = if gesture == Gesture::AtomicClick { 1 } else { 2 };
+ for positive in positives.into_iter().take(count) {
+ complete_positive_gesture(&mut h, &client, gesture, positive, &bytes);
+ }
+ }
+ }
+ }
+
+ /// A screenshot that times out cancels its slot and gives its reservation back, with a
+ /// defined error instead of a silent success.
+ #[test]
+ fn a_timed_out_screenshot_releases_its_slot_and_budget() {
+ struct FakeHost;
+ impl Host for FakeHost {
+ fn state(&self) -> Value {
+ json!({})
+ }
+ fn command(&mut self, _id: &str) -> Reply {
+ Err("no commands in this test".into())
+ }
+ fn panel(&mut self, _reset: bool, _params: &Value) -> Reply {
+ Err("no side panels in this test".into())
+ }
+ fn commands(&self) -> Value {
+ json!([])
+ }
+ fn set(&mut self, _key: &str, _value: &str) -> Reply {
+ Err("no settings in this test".into())
+ }
+ fn open(&mut self, _path: &str) -> Reply {
+ Err("no files in this test".into())
+ }
+ fn quit(&mut self, _ctx: &egui::Context) -> bool {
+ false
+ }
+ }
+ let ctx = egui::Context::default();
+ let (mut control, _client) = attach(&ctx);
+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(&ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ let (reply, rx) = channel();
+ control.pending.push(Pending::Screenshot {
+ slot,
+ callback: Some(callback),
+ region: None,
+ reply,
+ since: web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap_or_else(web_time::Instant::now),
+ geometry: Geometry { size: egui::vec2(800.0, 600.0), pixels_per_point: 1.0, epoch: 0 },
+ reserved: 800 * 600 * 4,
+ attempts: 0,
+ });
+ control.finish_pending(&ctx, &mut FakeHost);
+ let error = rx.try_recv().expect("the request is answered").expect_err("a timeout is an error");
+ assert!(error.contains("not being drawn"), "{error}");
+ assert_eq!(control.reserved_bytes(), 0, "the reservation is released");
+ assert!(control.pending.is_empty(), "the cancelled capture is not retried");
+ }
+
+ /// A real successful callback must not bypass expiry, including when resize would otherwise
+ /// retry it. A non-expired completion still produces a real encoded PNG reply.
+ #[test]
+ fn completed_screenshots_obey_the_admission_deadline_before_success_or_retry() {
+ for (expired, resized) in [(false, false), (true, false), (true, true)] {
+ let ctx = egui::Context::default();
+ ctx.run_ui(
+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(64.0, 32.0))), ..Default::default() },
+ |_| {},
+ )
+ .drop_without_applying_deltas();
+ let (mut control, _client) = attach(&ctx);
+ let geometry = Geometry::current(&ctx, 0);
+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(&ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ let image = Arc::new(egui::ColorImage::filled([64, 32], egui::Color32::RED));
+ let weak_image = Arc::downgrade(&image);
+ callback.complete(image);
+ assert!(weak_image.upgrade().is_some(), "the completed slot really retains pixels");
+ let (reply, rx) = channel();
+ control.pending.push(Pending::Screenshot {
+ slot,
+ callback: None,
+ region: None,
+ reply,
+ since: if expired {
+ web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap()
+ } else {
+ web_time::Instant::now()
+ },
+ geometry,
+ reserved: geometry.image_bytes().unwrap(),
+ attempts: 0,
+ });
+ if resized {
+ ctx.run_ui(
+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(80.0, 40.0))), ..Default::default() },
+ |_| {},
+ )
+ .drop_without_applying_deltas();
+ assert_ne!(Geometry::current(&ctx, 0).size, geometry.size);
+ }
+ control.finish_pending(&ctx, &mut NoopHost);
+ let result = rx.try_recv().expect("one settled reply");
+ if expired {
+ assert!(result.unwrap_err().contains("not being drawn"), "expiry takes priority over success or resize");
+ } else {
+ let image = result.expect("the live completed capture still succeeds");
+ assert_eq!(image["width"], 64);
+ assert_eq!(image["height"], 32);
+ use base64::Engine as _;
+ let png = base64::engine::general_purpose::STANDARD.decode(image["png_base64"].as_str().expect("actual PNG reply")).unwrap();
+ assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
+ }
+ assert!(control.pending.is_empty(), "an expired capture is never retried");
+ assert_eq!(control.reserved_bytes(), 0);
+ assert!(weak_image.upgrade().is_none(), "the slot releases its pixels");
+ assert!(rx.try_recv().is_err(), "exactly one reply");
+ }
+ }
+
+ #[test]
+ fn expired_unissued_screenshots_are_not_issued_and_late_callbacks_are_harmless() {
+ let ctx = egui::Context::default();
+ let (mut control, _client) = attach(&ctx);
+ let (slot, callback) = craft_ui::capture::CaptureSlot::new(&ctx, egui::ViewportId::ROOT, MAX_IMAGE_BYTES);
+ let late_callback = callback.clone();
+ let geometry = Geometry { size: egui::vec2(64.0, 32.0), pixels_per_point: 1.0, epoch: 0 };
+ let (reply, rx) = channel();
+ control.pending.push(Pending::Screenshot {
+ slot,
+ callback: Some(callback),
+ region: None,
+ reply,
+ since: web_time::Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap(),
+ geometry,
+ reserved: 64 * 32 * 4,
+ attempts: 0,
+ });
+ let output = ctx.run_ui(egui::RawInput::default(), |ui| control.finish_frame(ui.ctx(), &mut NoopHost));
+ assert!(
+ output
+ .viewport_output
+ .values()
+ .all(|viewport| !viewport.commands.iter().any(|command| matches!(command, egui::ViewportCommand::Screenshot(_))))
+ );
+ output.drop_without_applying_deltas();
+ assert!(rx.try_recv().unwrap().unwrap_err().contains("not being drawn"));
+ assert!(control.pending.is_empty());
+ assert_eq!(control.reserved_bytes(), 0);
+ let image = Arc::new(egui::ColorImage::filled([64, 32], egui::Color32::RED));
+ let weak_image = Arc::downgrade(&image);
+ late_callback.complete(image);
+ assert!(weak_image.upgrade().is_none(), "a late completion cannot resurrect a canceled request");
+ control.finish_pending(&ctx, &mut NoopHost);
+ assert!(rx.try_recv().is_err(), "no second reply");
+ }
+
+ /// One queued batch is consumed by exactly one UI pass.
+ #[test]
+ fn one_batch_is_consumed_by_one_pass() {
+ let shared = Arc::new(Mutex::new(Shared::default()));
+ let mut plugin = ControlPlugin { shared: shared.clone() };
+ {
+ let mut s = shared.lock().unwrap();
+ s.epoch = 3;
+ s.inject.push_back(RequestBatches {
+ request: 1,
+ epoch: 3,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([vec![egui::Event::PointerMoved(egui::pos2(2.0, 3.0))]]),
+ });
+ s.inject.push_back(RequestBatches {
+ request: 2,
+ epoch: 3,
+ started: false,
+ since: web_time::Instant::now(),
+ release: Vec::new(),
+ batches: VecDeque::from([vec![egui::Event::PointerMoved(egui::pos2(4.0, 5.0))]]),
+ });
+ }
+ let mut first = egui::RawInput::default();
+ plugin.input_hook(&egui::Context::default(), &mut first);
+ assert_eq!(first.events.len(), 1);
+ let mut second = egui::RawInput::default();
+ plugin.input_hook(&egui::Context::default(), &mut second);
+ assert_eq!(second.events.len(), 1);
+ assert_eq!(second.events[0], egui::Event::PointerMoved(egui::pos2(4.0, 5.0)));
+ let mut third = egui::RawInput::default();
+ plugin.input_hook(&egui::Context::default(), &mut third);
+ assert!(third.events.is_empty(), "a consumed batch is never repeated");
+ }
+}
+
+#[cfg(test)]
+mod screenshot_geometry_tests {
+ use super::*;
+
+ #[test]
+ fn image_bytes_are_checked_against_overflow_and_limits() {
+ assert_eq!(checked_image_bytes(2, 3), Some(24));
+ assert_eq!(checked_image_bytes(usize::MAX, 2), None);
+ let big = Geometry { size: egui::vec2(10_000.0, 10_000.0), pixels_per_point: 8.0, epoch: 0 };
+ assert!(big.image_bytes().is_some_and(|bytes| bytes > MAX_IMAGE_BYTES));
+ }
+
+ /// The crop is derived from the returned pixels and the admitted logical rect, not from a
+ /// current `pixels_per_point`: a fitted surface may return a smaller image.
+ #[test]
+ fn region_crop_uses_the_capture_geometry() {
+ let image = egui::ColorImage::filled([200, 100], egui::Color32::RED);
+ let geometry = Geometry { size: egui::vec2(100.0, 50.0), pixels_per_point: 2.0, epoch: 7 };
+ let reply =
+ screenshot_png(&image, Some(egui::Rect::from_min_max(egui::pos2(10.0, 5.0), egui::pos2(60.0, 30.0))), geometry).expect("a valid crop");
+ assert_eq!(reply["width"], 100);
+ assert_eq!(reply["height"], 50);
+ assert_eq!(reply["pixels_per_point"], 2.0);
+ }
+
+ /// A retry replaces one reservation in a running aggregate. Three 50 MiB captures that each
+ /// retry to 100 MiB must not all be admitted against a stale 150 MiB snapshot.
+ #[test]
+ fn retries_keep_one_running_aggregate_budget() {
+ const MIB: usize = 1024 * 1024;
+ let first = retried_reservation(3 * 50 * MIB, 50 * MIB, 100 * MIB).expect("the first retry fits");
+ let second = retried_reservation(first, 50 * MIB, 100 * MIB).expect("the second retry fits");
+ assert_eq!(second, 250 * MIB);
+ assert_eq!(retried_reservation(second, 50 * MIB, 100 * MIB), None, "the third would pass 256 MiB");
+ assert_eq!(retried_reservation(0, 0, MAX_IMAGE_BYTES + 1), None, "a single image over the per-image limit never fits");
+ }
+
+ #[test]
+ fn an_image_with_another_aspect_ratio_is_rejected() {
+ let image = egui::ColorImage::filled([200, 100], egui::Color32::RED);
+ let geometry = Geometry { size: egui::vec2(100.0, 60.0), pixels_per_point: 2.0, epoch: 0 };
+ assert!(screenshot_png(&image, None, geometry).is_err());
+ }
+
+ #[test]
+ fn an_outside_region_is_rejected_not_panicking() {
+ let image = egui::ColorImage::filled([20, 10], egui::Color32::RED);
+ let geometry = Geometry { size: egui::vec2(10.0, 5.0), pixels_per_point: 2.0, epoch: 0 };
+ assert!(screenshot_png(&image, Some(egui::Rect::from_min_max(egui::pos2(11.0, 6.0), egui::pos2(15.0, 9.0))), geometry).is_err());
+ }
+
+ /// A region that a shrink now cuts off is refused, not silently clamped to a smaller crop.
+ #[test]
+ fn a_region_cut_by_a_shrink_is_rejected_instead_of_cropped() {
+ let image = egui::ColorImage::filled([20, 10], egui::Color32::RED);
+ let shrunk = Geometry { size: egui::vec2(10.0, 5.0), pixels_per_point: 2.0, epoch: 0 };
+ let region = egui::Rect::from_min_max(egui::pos2(8.0, 4.0), egui::pos2(15.0, 9.0));
+ assert!(!shrunk.contains_region(region));
+ let error = screenshot_png(&image, Some(region), shrunk).expect_err("a cut region must not become a smaller image");
+ assert!(error.contains("inside the window"), "{error}");
+ }
+
+ /// Screenshot identity is the captured content, not the window's monitor-space origin or the
+ /// focused widget: only the capture epoch and the viewport-local size/scale matter.
+ #[test]
+ fn capture_geometry_compares_size_scale_and_capture_epoch_only() {
+ let admitted = Geometry { size: egui::vec2(800.0, 600.0), pixels_per_point: 2.0, epoch: 5 };
+ assert_eq!(admitted, Geometry { size: egui::vec2(800.0, 600.0), pixels_per_point: 2.0, epoch: 5 });
+ assert_ne!(admitted, Geometry { size: egui::vec2(801.0, 600.0), pixels_per_point: 2.0, epoch: 5 });
+ assert_ne!(admitted, Geometry { size: egui::vec2(800.0, 600.0), pixels_per_point: 1.5, epoch: 5 });
+ assert_ne!(admitted, Geometry { size: egui::vec2(800.0, 600.0), pixels_per_point: 2.0, epoch: 6 });
+ assert!(admitted.contains_region(egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(800.0, 600.0))));
+ assert!(!admitted.contains_region(egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(801.0, 600.0))));
+ assert!(!admitted.contains_region(egui::Rect::from_min_max(egui::pos2(-1.0, 0.0), egui::pos2(10.0, 10.0))));
+ }
+}
+
#[cfg(test)]
mod pointer_tests {
use super::*;
@@ -1436,6 +3182,8 @@ mod pointer_tests {
let slow_dt = (max_duration + 0.25) as f32;
assert!(f64::from(slow_dt) > max_duration);
for discard in [false, true] {
+ // This probe draws its own UI with the harness's fonts, not PdfCraftApp::ui.
+ // Exercise the readiness gate explicitly before allowing this host's input.
let state = Probe {
control: None,
client: None,
@@ -1484,6 +3232,26 @@ mod pointer_tests {
);
h.run_steps(3);
let c = h.state().client.as_ref().unwrap().clone();
+ let probe_pos = h.get_by_label("Click probe").rect().center();
+ let waiting = c.send("ui.click", json!({"x":probe_pos.x,"y":probe_pos.y}));
+ h.run_steps(3);
+ assert!(waiting.try_recv().is_err(), "unready host must defer control input");
+ assert_eq!(h.state().primary, 0);
+ assert!(h.state().events.is_empty());
+ h.state_mut().host.fonts_ready = true;
+ let mut ready_reply = None;
+ for _ in 0..8 {
+ h.step();
+ if let Ok(reply) = waiting.try_recv() {
+ ready_reply = Some(reply);
+ break;
+ }
+ }
+ assert!(ready_reply.expect("ready host completes deferred click").is_ok());
+ assert_eq!(h.state().primary, 1);
+ h.state_mut().primary = 0;
+ h.state_mut().events.clear();
+ h.state_mut().discarded = false;
assert_eq!(h.ctx.options(|o| o.input_options.max_click_duration), max_duration);
let pos = h.get_by_label("Click probe").rect().center();
assert_eq!((h.state().primary, h.state().secondary, h.state().disabled), (0, 0, 0));
diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs
index 59535f35e6..4fe58a6714 100644
--- a/crates/ui-egui/src/credits.rs
+++ b/crates/ui-egui/src/credits.rs
@@ -232,7 +232,7 @@ impl Default for View {
/// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table.
pub fn contributors_ui(ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
- let id = egui::Id::new("credits_view");
+ let id = egui::Id::unique("credits_view");
let mut v = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_default();
ui.horizontal_wrapped(|ui| {
ui.label(crate::i18n::t("Show"));
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index a6f2477572..b3437246a0 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -21,6 +21,7 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
unlock(app, ctx);
}
+/// Draw the active modal dialog and apply the action the user chose.
fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
password(app, ctx);
save_prompt(app, ctx);
@@ -154,6 +155,22 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
});
ui.end_row();
};
+ // A file name or path is read left to right even in an RTL UI: the extension
+ // stays at its visual end, as in the tab strip.
+ let path_row = |ui: &mut egui::Ui, k: &str, v: String| {
+ ui.label(egui::RichText::new(tl!(k)).color(t.text_muted));
+ ui.scope(|ui| {
+ ui.set_max_width(420.0);
+ // Align path text with editable fields while keeping its LTR text order.
+ ui.add_space(inset);
+ if v.is_empty() {
+ ui.label(egui::RichText::new("—").color(t.text_faint));
+ } else {
+ crate::widgets::label_ltr(ui, v, crate::theme::regular(13.0), t.text);
+ }
+ });
+ ui.end_row();
+ };
egui::ScrollArea::vertical().max_height(460.0).auto_shrink([false, true]).show(ui, |ui| {
if tab == PropsTab::SpaceAudit {
ui.add_space(4.0);
@@ -162,7 +179,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
}
egui::Grid::new("props").num_columns(2).spacing([18.0, 8.0]).min_col_width(140.0).show(ui, |ui| match tab {
PropsTab::Description => {
- row(ui, "File", crate::bidi::visual(&doc.name).into_owned());
+ path_row(ui, "File", doc.name.clone());
match app.props_draft.as_mut() {
Some((_, draft)) if editable_info => {
for (k, v) in INFO_KEYS.iter().zip(draft.iter_mut()) {
@@ -192,7 +209,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
let Some((_, v)) = app.view_draft.as_mut() else { return };
ui.label(egui::RichText::new(tl!("Layout and Magnification")).font(theme::semibold(12.5)));
ui.end_row();
- ui.label(tl!("Navigation tab"));
+ let label = ui.label(tl!("Navigation tab"));
ui.add_enabled_ui(editable, |ui| {
egui::ComboBox::from_id_salt("iv-nav")
.selected_text(tl!(format!("{:?}", v.navigation)
@@ -209,10 +226,12 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
] {
ui.selectable_value(&mut v.navigation, n, l);
}
- });
+ })
+ .response
+ .labelled_by(label.id);
});
ui.end_row();
- ui.label(tl!("Page layout"));
+ let label = ui.label(tl!("Page layout"));
ui.add_enabled_ui(editable, |ui| {
let names = [
(L::Default, tl!("Default")),
@@ -224,14 +243,18 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
(L::TwoUpContinuousCoverPage, tl!("Two-Up Continuous (Cover Page)")),
];
let shown = names.iter().find(|(l, _)| *l == v.layout).map_or(tl!("Default"), |(_, n)| n);
- egui::ComboBox::from_id_salt("iv-layout").selected_text(shown).show_ui(ui, |ui| {
- for (l, n) in names {
- ui.selectable_value(&mut v.layout, l, n);
- }
- });
+ egui::ComboBox::from_id_salt("iv-layout")
+ .selected_text(shown)
+ .show_ui(ui, |ui| {
+ for (l, n) in names {
+ ui.selectable_value(&mut v.layout, l, n);
+ }
+ })
+ .response
+ .labelled_by(label.id);
});
ui.end_row();
- ui.label(tl!("Magnification"));
+ let label = ui.label(tl!("Magnification"));
ui.add_enabled_ui(editable, |ui| {
ui.horizontal(|ui| {
let names = [
@@ -246,21 +269,25 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
M::Percent(p) => format!("{p:.0}%"),
m => names.iter().find(|(x, _)| *x == m).map_or(tl!("Default").to_string(), |(_, n)| n.to_string()),
};
- egui::ComboBox::from_id_salt("iv-mag").selected_text(shown).show_ui(ui, |ui| {
- for (m, n) in names {
- ui.selectable_value(&mut v.magnification, m, n);
- }
- for p in [50.0, 75.0, 125.0, 150.0, 200.0] {
- ui.selectable_value(&mut v.magnification, M::Percent(p), format!("{p:.0}%"));
- }
- });
+ egui::ComboBox::from_id_salt("iv-mag")
+ .selected_text(shown)
+ .show_ui(ui, |ui| {
+ for (m, n) in names {
+ ui.selectable_value(&mut v.magnification, m, n);
+ }
+ for p in [50.0, 75.0, 125.0, 150.0, 200.0] {
+ ui.selectable_value(&mut v.magnification, M::Percent(p), format!("{p:.0}%"));
+ }
+ })
+ .response
+ .labelled_by(label.id);
});
});
ui.end_row();
- ui.label(tl!("Open to page"));
+ let label = ui.label(tl!("Open to page"));
ui.add_enabled_ui(editable, |ui| {
let mut p = v.page + 1;
- if ui.add(egui::DragValue::new(&mut p).range(1..=pages.max(1))).changed() {
+ if ui.add(egui::DragValue::new(&mut p).range(1..=pages.max(1))).labelled_by(label.id).changed() {
v.page = p - 1;
}
ui.label(crate::i18n::fmt(tl!("of {pages}"), &[("pages", &pages.to_string())]));
@@ -455,7 +482,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
}
PropsTab::Advanced => {
row(ui, "PDF version", i.pdf_version.clone());
- row(ui, "Location", crate::bidi::visual(doc.path.as_deref().unwrap_or_default()).into_owned());
+ path_row(ui, "Location", doc.path.clone().unwrap_or_default());
row(ui, "File size", format!("{} ({})", human_size(i.file_size), crate::panels::byte_count(i.file_size)));
let p = &i.pages[0];
row(ui, "Page size", units.size(f64::from(p.width), f64::from(p.height)));
@@ -606,10 +633,10 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
d.to = d.to.clamp(1, count);
d.from = d.from.clamp(1, d.to);
ui.horizontal(|ui| {
- ui.label(tl!("Original: replace pages"));
- let from = ui.add(egui::DragValue::new(&mut d.from).range(1..=count));
- ui.label(tl!("to"));
- let to = ui.add(egui::DragValue::new(&mut d.to).range(1..=count));
+ let from_label = ui.label(tl!("Original: replace pages"));
+ let from = ui.add(egui::DragValue::new(&mut d.from).range(1..=count)).labelled_by(from_label.id);
+ let to_label = ui.label(tl!("to"));
+ let to = ui.add(egui::DragValue::new(&mut d.to).range(1..=count)).labelled_by(to_label.id);
if from.changed() || to.changed() {
d.range_edited = true;
}
@@ -619,8 +646,8 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
let max_start = d.src_pages.saturating_sub(n) + 1;
d.src_from = d.src_from.clamp(1, max_start.max(1));
ui.horizontal(|ui| {
- ui.label(crate::i18n::fmt(tl!("Replacement: pages of {name}"), &[("name", &d.name)]));
- ui.add(egui::DragValue::new(&mut d.src_from).range(1..=max_start.max(1)));
+ let replacement_label = ui.label(crate::i18n::fmt(tl!("Replacement: pages of {name}"), &[("name", &d.name)]));
+ ui.add(egui::DragValue::new(&mut d.src_from).range(1..=max_start.max(1))).labelled_by(replacement_label.id);
ui.label(crate::i18n::fmt(tl!("to {n}"), &[("n", &(d.src_from + n - 1).to_string())]));
ui.label(egui::RichText::new(crate::i18n::fmt(tl!("of {name}"), &[("name", &d.src_pages.to_string())])).color(t.text_muted));
});
@@ -1286,7 +1313,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
}
Dialog::About => {
// Tabs About · Contributors · Models (craftrules standards/contributors.md).
- let tab_id = egui::Id::new("about_tab");
+ let tab_id = egui::Id::unique("about_tab");
let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0);
ui.horizontal_wrapped(|ui| {
for (i, label) in ["About", "Contributors", "Models"].into_iter().enumerate() {
@@ -1882,7 +1909,16 @@ fn remote_link_prompt(app: &mut PdfCraftApp, ctx: &egui::Context) {
ui.add_space(6.0);
ui.label(tl!("This document is trying to open a local file:"));
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
- ui.add(egui::Label::new(egui::RichText::new(pending.path.to_string_lossy()).monospace()).wrap().selectable(true));
+ // A local path is file/path chrome: left to right, so its final component stays last.
+ let mut job = egui::text::LayoutJob::simple(
+ pending.path.to_string_lossy().into_owned(),
+ egui::FontId::monospace(13.0),
+ crate::theme::Tokens::get(ui.ctx()).text,
+ ui.available_width().max(0.0),
+ );
+ job.direction = egui::epaint::text::TextDirection::LeftToRight;
+ let galley = ui.painter().layout_job(job);
+ ui.add(egui::Label::new(egui::WidgetText::Galley(galley)).selectable(true));
});
ui.add_space(8.0);
ui.label(tl!("Only allow this if you trust the source document."));
diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs
deleted file mode 100644
index 11eb732be3..0000000000
--- a/crates/ui-egui/src/docking.rs
+++ /dev/null
@@ -1,547 +0,0 @@
-//! Application panel identities and persistence around the shared docking renderer.
-//! Document contents remain owned by their existing view implementations.
-
-use craft_ui::docking::{Action, DockArea, DockStyle, Layout, Location, Node, PanelLimits, Permissions, Placement, Zone};
-use craft_ui::layout::{SplitAxis, SplitSize};
-use serde::{Deserialize, Serialize};
-use serde_json::{Value, json};
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum Panel {
- Canvas,
- Tools,
- Inspector,
-}
-
-impl Panel {
- pub const ALL: &[Self] = &[Self::Canvas, Self::Tools, Self::Inspector];
- pub fn id(self) -> &'static str {
- match self {
- Self::Canvas => "canvas",
- Self::Tools => "tools",
- Self::Inspector => "inspector",
- }
- }
- fn label(self) -> &'static str {
- match self {
- Self::Canvas => "Document",
- Self::Tools => "Tools",
- Self::Inspector => "Inspector",
- }
- }
- fn default_side(self) -> Zone {
- match self {
- Self::Canvas => Zone::Right,
- Self::Tools => Zone::Left,
- Self::Inspector => Zone::Right,
- }
- }
- fn parse(id: &str) -> Result {
- Self::ALL.iter().copied().find(|panel| panel.id() == id).ok_or_else(|| format!("Unknown panel: {id}"))
- }
-}
-
-fn permissions(panel: &Panel) -> Permissions {
- if *panel == Panel::Canvas { Permissions::PROTECTED } else { Permissions::default() }
-}
-
-fn tabs(panel: Panel) -> Node {
- Node::Tabs { panels: vec![panel], active: 0 }
-}
-
-fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node {
- Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[serde(default)]
-pub struct Workspace {
- pub layout: Layout,
- /// Closed panels retain their most recent group, side, size or floating rectangle.
- pub hidden: Vec<(Panel, Location)>,
-}
-
-impl Default for Workspace {
- fn default() -> Self {
- Self {
- layout: Layout {
- root: Some(split(
- SplitAxis::Horizontal,
- SplitSize::FixedFirst(272.0),
- tabs(Panel::Tools),
- split(SplitAxis::Horizontal, SplitSize::FixedSecond(330.0), tabs(Panel::Canvas), tabs(Panel::Inspector)),
- )),
- floating: Vec::new(),
- },
- hidden: Vec::new(),
- }
- }
-}
-
-impl Workspace {
- /// Side of the Tools panel, including its saved position while closed.
- pub fn tools_on_right(&self) -> bool {
- let location = self
- .layout
- .location(&Panel::Tools)
- .ok()
- .or_else(|| self.hidden.iter().find(|(panel, _)| *panel == Panel::Tools).map(|(_, location)| location.clone()));
- location.is_some_and(|location| matches!(location.placement, Placement::Split(Zone::Right)))
- }
-
- /// Place Tools at the outer left or right edge while preserving its open state.
- pub fn set_tools_on_right(&mut self, right: bool) -> Result<(), String> {
- let was_open = self.layout.contains(&Panel::Tools);
- self.set_visible(Panel::Tools, true)?;
- let anchor = if right && self.layout.contains(&Panel::Inspector) { Panel::Inspector } else { Panel::Canvas };
- self.apply(Action::Move { panel: Panel::Tools, anchor, placement: Placement::Split(if right { Zone::Right } else { Zone::Left }) })?;
- if !was_open {
- self.set_visible(Panel::Tools, false)?;
- }
- Ok(())
- }
-
- pub fn validate(&self) -> Result<(), String> {
- self.layout.validate().map_err(|error| error.to_string())?;
- if !self.layout.contains(&Panel::Canvas) || self.hidden.len() > Panel::ALL.len() {
- return Err("The panel layout must contain its document view and bounded hidden panels".into());
- }
- // Saved settings cannot turn the protected document view into a floating or closable tab.
- if self.layout.floating.iter().any(|group| group.panels.contains(&Panel::Canvas)) {
- return Err("The document view cannot float".into());
- }
- let mut nodes: Vec<_> = self.layout.root.iter().collect();
- while let Some(node) = nodes.pop() {
- match node {
- Node::Split { first, second, .. } => {
- nodes.push(first);
- nodes.push(second);
- }
- Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) && panels.len() != 1 => {
- return Err("The document view cannot share a tab group".into());
- }
- Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => {
- return Err("The document view cannot be collapsed".into());
- }
- _ => {}
- }
- }
- let mut seen = std::collections::HashSet::new();
- for (panel, location) in &self.hidden {
- if *panel == Panel::Canvas || self.layout.contains(panel) || !seen.insert(*panel) {
- return Err("A hidden panel has an invalid or duplicate identity".into());
- }
- if location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center)) {
- return Err("A hidden panel cannot restore over the document view".into());
- }
- let mut probe = self.layout.clone();
- if let Err(error) = probe.restore(*panel, location)
- && error != craft_ui::docking::DockError::MissingTarget
- {
- return Err(error.to_string());
- }
- }
- Ok(())
- }
-
- pub fn apply(&mut self, action: Action) -> Result<(), String> {
- self.validate()?;
- let mut next = self.clone();
- if let Action::Close { panel } = &action {
- let location = next.layout.location(panel).map_err(|error| error.to_string())?;
- next.hidden.retain(|(id, _)| id != panel);
- next.hidden.push((*panel, location));
- } else if let Action::Open { panel, .. } | Action::OpenAt { panel, .. } = &action {
- next.hidden.retain(|(id, _)| id != panel);
- }
- next.layout.apply_with_permissions(action, permissions).map_err(|error| error.to_string())?;
- next.validate()?;
- *self = next;
- Ok(())
- }
-
- /// Whether a panel's body is exposed by its selected tab or open stack entry.
- pub(crate) fn exposed(&self, panel: Panel) -> bool {
- if self.layout.floating.iter().any(|group| group.panels.get(group.active) == Some(&panel)) {
- return true;
- }
- let mut pending: Vec<_> = self.layout.root.iter().collect();
- while let Some(node) = pending.pop() {
- match node {
- Node::Split { first, second, .. } => {
- pending.push(first);
- pending.push(second);
- }
- Node::Tabs { panels, active } if panels.get(*active) == Some(&panel) => return true,
- Node::Stack { entries } if entries.iter().any(|entry| entry.panel == panel && entry.open) => return true,
- _ => {}
- }
- }
- false
- }
-
- pub fn set_visible(&mut self, panel: Panel, visible: bool) -> Result<(), String> {
- if self.layout.contains(&panel) == visible {
- return Ok(());
- }
- if !visible {
- return self.apply(Action::Close { panel });
- }
- self.validate()?;
- let mut next = self.clone();
- let mut location = next.hidden.iter().find(|(id, _)| *id == panel).map(|(_, location)| location.clone());
- next.hidden.retain(|(id, _)| *id != panel);
- if let Some(saved) = &mut location
- && saved.floating.is_some()
- && saved.anchor.as_ref().is_some_and(|anchor| !next.layout.floating.iter().any(|group| group.panels.contains(anchor)))
- {
- // The other members of a floating group may have been closed too.
- saved.anchor = None;
- saved.placement = Placement::Tab { before: None };
- }
- let restored = location.as_ref().is_some_and(|location| next.layout.restore(panel, location).is_ok());
- if !restored {
- next.layout
- .apply_with_permissions(
- Action::OpenAt { panel, anchor: Panel::Canvas, placement: Placement::Split(panel.default_side()) },
- permissions,
- )
- .map_err(|error| error.to_string())?;
- }
- next.validate()?;
- *self = next;
- Ok(())
- }
-
- fn command(&mut self, params: &Value) -> Result<(), String> {
- self.validate()?;
- if let Some(action) = params.get("action") {
- let action: Action = serde_json::from_value(action.clone()).map_err(|error| error.to_string())?;
- return self.apply(action);
- }
- let operation = params.get("operation").and_then(Value::as_str).ok_or("operation is required")?;
- if operation == "resizeSplit" {
- let path: Vec =
- serde_json::from_value(params.get("path").cloned().ok_or("path is required")?).map_err(|error| error.to_string())?;
- let size: SplitSize =
- serde_json::from_value(params.get("size").cloned().ok_or("size is required")?).map_err(|error| error.to_string())?;
- return self.apply(Action::ResizeSplit { path, size });
- }
- let panel = Panel::parse(params.get("panel").and_then(Value::as_str).ok_or("panel is required")?)?;
- let action = match operation {
- "open" => {
- self.set_visible(panel, true)?;
- return self.apply(Action::Activate { panel });
- }
- "close" => Action::Close { panel },
- "activate" => Action::Activate { panel },
- "setStackOpen" => Action::SetStackOpen { panel, open: params.get("open").and_then(Value::as_bool).ok_or("open must be a boolean")? },
- "resizeStack" => {
- let value = params.get("height").ok_or("height is required")?;
- let height = if value.is_null() {
- None
- } else {
- Some(
- value
- .as_f64()
- .filter(|height| height.is_finite() && (0.0..=1_000_000.0).contains(height))
- .ok_or("height must be finite and bounded")? as f32,
- )
- };
- Action::ResizeStack { panel, height }
- }
- "float" | "moveFloating" => {
- let rect = params.get("rect").and_then(Value::as_array).filter(|rect| rect.len() == 4).ok_or("rect must be [x,y,width,height]")?;
- let mut values = [0.0f32; 4];
- for (output, value) in values.iter_mut().zip(rect) {
- *output = value
- .as_f64()
- .filter(|number| number.is_finite() && number.abs() <= 1_000_000.0)
- .ok_or("rect values must be finite and bounded")? as f32;
- }
- if operation == "float" { Action::Float { panel, rect: values } } else { Action::MoveFloating { panel, rect: values } }
- }
- "move" => {
- let anchor = Panel::parse(params.get("target").and_then(Value::as_str).ok_or("target is required")?)?;
- let placement = match params.get("zone").and_then(Value::as_str).unwrap_or("center") {
- "center" => Placement::Split(Zone::Center),
- "left" => Placement::Split(Zone::Left),
- "right" => Placement::Split(Zone::Right),
- "top" => Placement::Split(Zone::Top),
- "bottom" => Placement::Split(Zone::Bottom),
- _ => return Err("zone must be center, left, right, top or bottom".into()),
- };
- let placement = if let Some(before) = params.get("before") {
- if !matches!(placement, Placement::Split(Zone::Center)) {
- return Err("before only applies to a center move".into());
- }
- Placement::Tab {
- before: if before.is_null() {
- None
- } else {
- Some(Panel::parse(before.as_str().ok_or("before must be a panel ID or null")?)?)
- },
- }
- } else {
- placement
- };
- Action::Move { panel, anchor, placement }
- }
- _ => return Err("operation must be open, close, activate, float, move, moveFloating, resizeSplit, setStackOpen or resizeStack".into()),
- };
- self.apply(action)
- }
-}
-
-fn sync(workspace: &mut Workspace, app: &crate::PdfCraftApp) -> Result<(), String> {
- workspace.set_visible(Panel::Tools, app.left_open)?;
- workspace.set_visible(Panel::Inspector, app.right.is_some())
-}
-
-fn drain_reveals(workspace: &mut Workspace, app: &mut crate::PdfCraftApp) {
- for panel in std::mem::take(&mut app.pending_panel_reveals) {
- if workspace.layout.contains(&panel) {
- let _ = workspace.apply(Action::Activate { panel });
- }
- }
-}
-
-fn publish_visibility(app: &mut crate::PdfCraftApp, workspace: &Workspace) {
- app.left_open = workspace.layout.contains(&Panel::Tools);
- if !workspace.layout.contains(&Panel::Inspector) {
- if app.right.is_some() {
- app.choose_right_panel(None);
- }
- } else if app.right.is_none() {
- app.choose_right_panel(Some(crate::RightPanel::Comments));
- }
-}
-
-pub fn command(app: &mut crate::PdfCraftApp, reset: bool, params: &Value) -> Result {
- let mut workspace = app.docking.clone();
- if reset {
- workspace = Workspace::default();
- workspace.set_visible(Panel::Inspector, app.right.is_some())?;
- } else {
- sync(&mut workspace, app)?;
- workspace.command(params)?;
- }
- publish_visibility(app, &workspace);
- app.docking = workspace;
- Ok(json!({"docking": app.docking}))
-}
-
-// Split paths change when a temporarily unavailable pane is pruned. Translate renderer
-// paths back to the saved tree before applying geometry changes.
-fn saved_split_path(saved: &Layout, rendered: &Layout, path: &[bool]) -> Option> {
- let mut target = rendered.root.as_ref()?;
- for second in path {
- let Node::Split { first, second: other, .. } = target else { return None };
- target = if *second { other } else { first };
- }
- let mut pending = vec![(saved.root.as_ref()?, Vec::new())];
- while let Some((node, original_path)) = pending.pop() {
- if let Node::Split { first, second, .. } = node {
- let mut projection = Layout { root: Some(node.clone()), floating: Vec::new() };
- if projection.contains(&Panel::Inspector) {
- let _ = projection.apply(Action::Close { panel: Panel::Inspector });
- }
- let has_available_panel = |child: &Node| {
- Layout { root: Some(child.clone()), floating: Vec::new() }.panels().into_iter().any(|panel| *panel != Panel::Inspector)
- };
- // An ancestor whose Inspector-only side disappeared projects to its surviving
- // child. Its divider is absent, so only the child's split may own this resize.
- if has_available_panel(first) && has_available_panel(second) && projection.root.as_ref() == Some(target) {
- return Some(original_path);
- }
- let mut second_path = original_path.clone();
- second_path.push(true);
- pending.push((second, second_path));
- let mut first_path = original_path;
- first_path.push(false);
- pending.push((first, first_path));
- }
- }
- None
-}
-
-pub fn show(app: &mut crate::PdfCraftApp, ui: &mut egui::Ui) {
- let t = crate::theme::Tokens::get(ui.ctx());
- let mut workspace = std::mem::take(&mut app.docking);
- if let Err(error) = workspace.validate().and_then(|()| sync(&mut workspace, app)) {
- app.notify_fmt("Panel layout could not be restored: {error}", &[("error", &error)]);
- workspace = Workspace::default();
- let _ = sync(&mut workspace, app);
- }
- let mut style = DockStyle::from_ui(ui);
- style.min_pane = 96.0;
- style.float_label = crate::i18n::t("Float panel").into();
- style.close_label = crate::i18n::t("Close panel").into();
- style.move_label = crate::i18n::t("Move to group").into();
- style.panels_label = crate::i18n::t("Panels").into();
- style.resize_label = crate::i18n::t("Resize panels").into();
- style.resize_window_label = crate::i18n::t("Resize panel window").into();
- style.background = t.panel;
- style.tab_background = t.chrome;
- style.active_background = t.selected;
- style.text = t.text;
- style.inactive_text = t.text_muted;
- style.border = egui::Stroke::new(1.0, t.divider);
- style.accent = t.accent;
- style.font = crate::theme::medium(12.0);
- drain_reveals(&mut workspace, app);
- let mut rendered = workspace.layout.clone();
- if app.active.is_none() && rendered.contains(&Panel::Inspector) {
- // Availability is a render projection: the saved group, selection and width survive Home.
- let _ = rendered.apply(Action::Close { panel: Panel::Inspector });
- }
- // Tools docked on its own is drawn bare, without a tab strip, like Acrobat's tool pane. Grouped
- // with another panel, or floating, it keeps its tab so it can be dragged away again; moving it
- // to the other side stays a preference and a command.
- let bare_tools = rendered.location(&Panel::Tools).is_ok_and(|l| l.floating.is_none() && matches!(l.placement, Placement::Split(_)));
- let render_permissions = move |panel: &Panel| if bare_tools && *panel == Panel::Tools { Permissions::PROTECTED } else { permissions(panel) };
- let output = DockArea::new(egui::Id::new("pdfcraft-docking")).show_with_limits(
- ui,
- &rendered,
- &style,
- |panel| crate::i18n::t(panel.label()).into(),
- render_permissions,
- panel_limits,
- |ui, panel| match panel {
- Panel::Canvas => {
- ui.painter().rect_filled(ui.max_rect(), 0.0, t.pasteboard);
- match app.active {
- None if app.combine_showing() => crate::combine_ui::page(app, ui),
- None => crate::home::show(app, ui),
- Some(index) => match crate::compare_ui::side_by_side(app, index) {
- Some((old, new)) => crate::compare_ui::compare_area(app, old, new, ui),
- None => crate::canvas::document_area(app, index, ui),
- },
- }
- }
- Panel::Tools => crate::panels::left_panel(app, ui),
- Panel::Inspector => {
- ui.data_mut(|data| data.insert_temp(egui::Id::new("pdfcraft-inspector-body"), ui.max_rect()));
- crate::panels::right_panel(app, ui);
- }
- },
- );
- let _ = sync(&mut workspace, app);
- drain_reveals(&mut workspace, app);
- publish_visibility(app, &workspace);
- app.docking = workspace;
- for mut action in output.actions {
- if app.active.is_none()
- && let Action::ResizeSplit { path, .. } = &mut action
- {
- let Some(saved_path) = saved_split_path(&app.docking.layout, &rendered, path) else { continue };
- *path = saved_path;
- }
- if let Err(error) =
- serde_json::to_value(action).map_err(|error| error.to_string()).and_then(|action| command(app, false, &json!({"action": action})))
- {
- app.notify_fmt("Panel move was not applied: {error}", &[("error", &error)]);
- }
- }
-}
-
-fn panel_limits(panel: &Panel) -> PanelLimits {
- let (min, max_width) = match panel {
- Panel::Canvas => (egui::vec2(160.0, 160.0), 1_000_000.0),
- Panel::Tools => (egui::vec2(240.0, 120.0), 520.0),
- Panel::Inspector => (egui::vec2(260.0, 120.0), 520.0),
- };
- PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn tools_side_moves_to_both_edges_and_survives_closed_restore() {
- let mut workspace = Workspace::default();
- assert!(!workspace.tools_on_right());
- workspace.set_tools_on_right(true).unwrap();
- assert!(workspace.tools_on_right());
- workspace.set_visible(Panel::Tools, false).unwrap();
- assert!(workspace.tools_on_right());
- workspace.set_tools_on_right(false).unwrap();
- assert!(!workspace.tools_on_right());
- assert!(!workspace.layout.contains(&Panel::Tools));
- workspace.set_visible(Panel::Tools, true).unwrap();
- assert!(!workspace.tools_on_right());
- workspace.validate().unwrap();
- }
-
- #[test]
- fn exposed_respects_collapsed_stack_and_inactive_floating_tabs() {
- let mut workspace = Workspace {
- layout: Layout {
- root: Some(split(
- SplitAxis::Horizontal,
- SplitSize::FixedFirst(272.0),
- Node::Stack {
- entries: vec![
- craft_ui::docking::StackEntry { panel: Panel::Tools, open: true, height: None },
- craft_ui::docking::StackEntry { panel: Panel::Inspector, open: false, height: None },
- ],
- },
- tabs(Panel::Canvas),
- )),
- floating: Vec::new(),
- },
- hidden: Vec::new(),
- };
- workspace.validate().unwrap();
- assert!(workspace.exposed(Panel::Tools));
- assert!(!workspace.exposed(Panel::Inspector));
- workspace.apply(Action::Activate { panel: Panel::Inspector }).unwrap();
- assert!(workspace.exposed(Panel::Inspector));
- workspace.apply(Action::Float { panel: Panel::Tools, rect: [10.0, 20.0, 300.0, 400.0] }).unwrap();
- workspace.apply(Action::Move { panel: Panel::Inspector, anchor: Panel::Tools, placement: Placement::Split(Zone::Center) }).unwrap();
- assert!(!workspace.exposed(Panel::Tools));
- assert!(workspace.exposed(Panel::Inspector));
- }
-
- #[test]
- fn unavailable_inspector_split_resize_targets_saved_tools_split() {
- let mut workspace = Workspace::default();
- // Inspector at the outer edge makes the visible Tools split move to the root.
- workspace.apply(Action::Move { panel: Panel::Inspector, anchor: Panel::Tools, placement: Placement::Split(Zone::Left) }).unwrap();
- let mut rendered = workspace.layout.clone();
- rendered.apply(Action::Close { panel: Panel::Inspector }).unwrap();
- let path = saved_split_path(&workspace.layout, &rendered, &[]).unwrap();
- workspace.apply(Action::ResizeSplit { path, size: SplitSize::FixedFirst(290.0) }).unwrap();
- let mut resized = workspace.layout.clone();
- resized.apply(Action::Close { panel: Panel::Inspector }).unwrap();
- assert!(matches!(resized.root, Some(Node::Split { size: SplitSize::FixedFirst(290.0), .. })));
- }
-
- #[test]
- fn unavailable_outer_inspector_does_not_capture_its_childs_resize() {
- let mut workspace = Workspace {
- layout: Layout {
- root: Some(split(
- SplitAxis::Horizontal,
- SplitSize::FixedSecond(330.0),
- split(SplitAxis::Horizontal, SplitSize::FixedFirst(272.0), tabs(Panel::Tools), tabs(Panel::Canvas)),
- tabs(Panel::Inspector),
- )),
- floating: Vec::new(),
- },
- hidden: Vec::new(),
- };
- workspace.validate().unwrap();
- let mut rendered = workspace.layout.clone();
- rendered.apply(Action::Close { panel: Panel::Inspector }).unwrap();
- let path = saved_split_path(&workspace.layout, &rendered, &[]).unwrap();
- assert_eq!(path, vec![false]);
- workspace.apply(Action::ResizeSplit { path, size: SplitSize::FixedFirst(290.0) }).unwrap();
- assert!(matches!(workspace.layout.root, Some(Node::Split { size: SplitSize::FixedSecond(330.0), .. })));
- let mut resized = workspace.layout.clone();
- resized.apply(Action::Close { panel: Panel::Inspector }).unwrap();
- assert!(matches!(resized.root, Some(Node::Split { size: SplitSize::FixedFirst(290.0), .. })));
- }
-}
diff --git a/crates/ui-egui/src/edit_text_ui.rs b/crates/ui-egui/src/edit_text_ui.rs
index f67398d84f..4f5630c0b9 100644
--- a/crates/ui-egui/src/edit_text_ui.rs
+++ b/crates/ui-egui/src/edit_text_ui.rs
@@ -471,6 +471,19 @@ pub struct ImageSelection {
settled: Option<(Rect, Rect)>,
}
+impl ImageSelection {
+ /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ self.drag = None;
+ self.turning = false;
+ if let Some(crop) = &mut self.crop
+ && let Some((_, _, before)) = crop.drag.take()
+ {
+ crop.keep = before;
+ }
+ }
+}
+
/// Cropping a page image: the handles trim instead of resizing, the part that will go is
/// dimmed, Enter or Done applies and Esc or Cancel leaves it.
#[derive(Clone, Debug, PartialEq)]
@@ -1615,7 +1628,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -
// Over the page, so only where the document shows: a paragraph scrolled under the mode bar or
// a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as
// the page is, rather than pushed back into the window.
- egui::Area::new(egui::Id::new("edit-text-line"))
+ egui::Area::new(egui::Id::unique("edit-text-line"))
.order(egui::Order::Foreground)
.fade_in(false)
.fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))
@@ -1677,7 +1690,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -
if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }
};
let output = egui::TextEdit::multiline(&mut ed.text)
- .id(egui::Id::new("edit-text-line-input"))
+ .id(egui::Id::unique("edit-text-line-input"))
.font(font.clone())
.margin(egui::Margin::ZERO)
.layouter(&mut layouter)
@@ -1686,6 +1699,8 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -
.desired_width(width)
.desired_rows(rows)
.show(ui);
+ // The editor paints over the page with no visible label; name it for assistive tech.
+ output.response.response.clone().accessible_name(tl!("Text editing line"));
if ed.has_changes() {
if background_ready {
reveal = true;
diff --git a/crates/ui-egui/src/field_table_ui.rs b/crates/ui-egui/src/field_table_ui.rs
index d9b5255bfd..6dacf67a65 100644
--- a/crates/ui-egui/src/field_table_ui.rs
+++ b/crates/ui-egui/src/field_table_ui.rs
@@ -159,7 +159,7 @@ pub(crate) fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
let mut choice = None;
let mut laid = None;
egui::Window::new(tl!("Text Field Table"))
- .id(egui::Id::new("field_table_window"))
+ .id(egui::Id::unique("field_table_window"))
.open(&mut open)
.collapsible(false)
.resizable(false)
@@ -255,15 +255,20 @@ fn body(ui: &mut egui::Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[For
for (c, column) in d.table.columns.iter_mut().enumerate() {
let width = layout.cells.as_ref().ok().and_then(|cells| cells.get(c)).map(|cell| cell.rect[2] - cell.rect[0]);
let share = shares.get(c).copied().unwrap_or_default();
+ let mut column_label_response = None;
ui.horizontal(|ui| {
- ui.label(RichText::new(column_label(c)).strong());
+ let label = ui.label(RichText::new(column_label(c)).strong());
+ column_label_response = Some(label.id);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let size = width.map_or_else(|| "—".to_owned(), |w| format!("{w:.1} pt · {:.0}%", share * 100.0));
ui.label(RichText::new(size).color(t.text_muted).size(11.0));
});
});
let full = ui.available_width();
- ui.add(widgets::line(&mut column.pattern).desired_width(full).id_salt(("field table column", c)));
+ let pattern = ui.add(widgets::line(&mut column.pattern).desired_width(full).id_salt(("field table column", c)));
+ if let Some(label) = column_label_response {
+ pattern.labelled_by(label);
+ }
ui.add_space(4.0);
}
};
@@ -375,7 +380,7 @@ fn column_dividers(ui: &mut egui::Ui, d: &mut FieldTableDraft, bar: Rect, ends:
let mut active = None;
for (i, &x) in ends.iter().enumerate().take(n.saturating_sub(1)) {
let hit = Rect::from_min_max(pos2(x - reach, bar.top()), pos2(x + reach, bar.bottom()));
- let resp = ui.interact(hit, ui.id().with(("field table divider", i)), Sense::click_and_drag());
+ let resp = ui.interact(hit, ui.scope_id().with(("field table divider", i)), Sense::click_and_drag());
let share = d.shares().get(i).copied().unwrap_or_default();
resp.widget_info(|| egui::WidgetInfo::slider(true, (share * 100.0).round(), column_label(i)));
let mut delta = f64::from(resp.drag_delta().x) / f64::from(bar.width());
@@ -469,7 +474,7 @@ mod tests {
|ui| {
let other = ui.button("Other control");
if let Some(i) = focus {
- ui.memory_mut(|memory| memory.request_focus(ui.id().with(("field table divider", i))));
+ ui.memory_mut(|memory| memory.request_focus(ui.scope_id().with(("field table divider", i))));
} else {
other.request_focus();
}
diff --git a/crates/ui-egui/src/fill_sign.rs b/crates/ui-egui/src/fill_sign.rs
index 862b63e72d..aab071b508 100644
--- a/crates/ui-egui/src/fill_sign.rs
+++ b/crates/ui-egui/src/fill_sign.rs
@@ -555,7 +555,7 @@ pub(crate) fn signature_entries(ui: &mut egui::Ui, app: &mut crate::PdfCraftApp,
ui.horizontal(|ui| {
let (rect, response) = ui.allocate_exact_size(vec2((ui.available_width() - 68.0).max(140.0), 52.0), Sense::click());
let use_label = label("Use {what}");
- response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, use_label.clone()));
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, use_label.clone()));
let painter = ui.painter_at(rect);
painter.rect_filled(rect, CornerRadius::same(4), Color32::WHITE);
painter.rect_stroke(
@@ -718,7 +718,7 @@ pub(crate) fn type_box(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
// Over the page, so only where the document shows: a box scrolled under the mode bar or a
// side panel must leave them their pointer (#2755). It stays where it was placed, cut off as
// the page is, rather than pushed back into the window.
- egui::Area::new(egui::Id::new(("fill-text", view.id.0)))
+ egui::Area::new(egui::Id::unique(("fill-text", view.id.0)))
.fade_in(false)
.order(egui::Order::Foreground)
.fixed_pos(pos)
@@ -732,15 +732,17 @@ pub(crate) fn type_box(ctx: &egui::Context, view: &mut DocView, info: &DocInfo,
// The area's max rect is last frame's size, which caps the edit's width; widen it so the
// box grows as text is typed.
ui.set_min_width(width);
- let r = ui.add(
- egui::TextEdit::singleline(&mut t.text)
- .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))
- .desired_width(width)
- .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))
- .text_color(Color32::BLACK)
- .hint_text(tl!("Type text"))
- .id_salt("fill-text-edit"),
- );
+ let r = ui
+ .add(
+ egui::TextEdit::singleline(&mut t.text)
+ .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))
+ .desired_width(width)
+ .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))
+ .text_color(Color32::BLACK)
+ .hint_text(tl!("Type text"))
+ .id_salt("fill-text-edit"),
+ )
+ .accessible_name(tl!("Text to place"));
if t.focus {
r.request_focus();
t.focus = false;
@@ -911,10 +913,10 @@ fn scan_tab(
}
let Some(scan) = d.scan.as_mut() else {
painter.text(area.center(), egui::Align2::CENTER_CENTER, tl!("No photo chosen"), egui::FontId::proportional(13.0), t.text_muted);
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, tl!("Photo")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Photo")));
return browse;
};
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, tl!("Photo")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Photo")));
// The photo, fitted into the area; `to_screen`/`to_photo` map between its pixels and points.
let [pw, ph] = scan.photo.size();
let (pw, ph) = (pw.max(1) as f32, ph.max(1) as f32);
diff --git a/crates/ui-egui/src/fling.rs b/crates/ui-egui/src/fling.rs
index cce004ce53..b5eafe69d1 100644
--- a/crates/ui-egui/src/fling.rs
+++ b/crates/ui-egui/src/fling.rs
@@ -64,7 +64,7 @@ impl Fling {
/// (animations off, single-page paging, a zoom, a dialog).
pub(crate) fn read(&mut self, events: &[Event], now: f64, glide: bool) {
for event in events {
- let Event::MouseWheel { unit, delta, phase, modifiers } = event else { continue };
+ let Event::MouseWheel { unit, delta, phase, modifiers, .. } = event else { continue };
self.stop();
// Zooming, a mouse wheel and sideways Shift scrolling never glide.
if *unit != MouseWheelUnit::Point || modifiers.command || modifiers.ctrl || modifiers.shift {
@@ -160,7 +160,13 @@ mod tests {
use egui::{Modifiers, vec2};
fn wheel(dy: f32, phase: TouchPhase) -> Event {
- Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, dy), phase, modifiers: Modifiers::NONE }
+ Event::MouseWheel {
+ unit: MouseWheelUnit::Point,
+ delta: vec2(0.0, dy),
+ phase,
+ modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
+ }
}
/// A swipe of `moves` passes of `dy` each, 60 per second, lifted the pass after the last.
@@ -213,6 +219,7 @@ mod tests {
assert!(!fling.gliding(), "the finger rested before it lifted");
}
+ /// Check that new finger or wheel input stops an in-progress glide.
#[test]
fn new_input_stops_a_glide() {
let mut fling = Fling::new(true);
@@ -222,11 +229,18 @@ mod tests {
let mut fling = Fling::new(true);
let now = swipe(&mut fling, -25.0, 6);
- let notch = Event::MouseWheel { unit: MouseWheelUnit::Line, delta: vec2(0.0, -1.0), phase: TouchPhase::Move, modifiers: Modifiers::NONE };
+ let notch = Event::MouseWheel {
+ unit: MouseWheelUnit::Line,
+ delta: vec2(0.0, -1.0),
+ phase: TouchPhase::Move,
+ modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
+ };
fling.read(&[notch], now + 0.1, true);
assert!(!fling.gliding(), "a wheel notch");
}
+ /// Check that disabled flinging, a false glide flag, and a command-modified zoom gesture prevent glide.
#[test]
fn no_glide_where_it_is_off_or_not_wanted() {
let mut off = Fling::new(false);
@@ -242,7 +256,13 @@ mod tests {
assert!(!fling.gliding(), "animations off, paging or a dialog");
let mut zoom = Fling::new(true);
- let ctrl = |phase| Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, -25.0), phase, modifiers: Modifiers::COMMAND };
+ let ctrl = |phase| Event::MouseWheel {
+ unit: MouseWheelUnit::Point,
+ delta: vec2(0.0, -25.0),
+ phase,
+ modifiers: Modifiers::COMMAND,
+ source: egui::MouseWheelSource::Unknown,
+ };
zoom.read(&[ctrl(TouchPhase::Start)], 0.0, true);
zoom.read(&[ctrl(TouchPhase::Move)], dt, true);
zoom.read(&[ctrl(TouchPhase::Move)], 2.0 * dt, true);
diff --git a/crates/ui-egui/src/folders_ui.rs b/crates/ui-egui/src/folders_ui.rs
index 727417e2fc..fe9b2c3706 100644
--- a/crates/ui-egui/src/folders_ui.rs
+++ b/crates/ui-egui/src/folders_ui.rs
@@ -314,20 +314,21 @@ pub(crate) fn section(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
let (icon, _) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::hover());
icons::paint(ui, icon, "folder", 20.0, t.icon);
- ui.label(egui::RichText::new(crate::bidi::visual(&name)).font(theme::semibold(14.0))).on_hover_text(folder);
+ // Folder names and paths are file/path chrome: explicitly left to right, so an
+ // Arabic location keeps its `.pdf`/extension at the visual end.
+ widgets::label_ltr(ui, name.clone(), theme::semibold(14.0), t.text).on_hover_text(folder);
ui.add_space(4.0);
// Leave room for Unpin: a long location is cut short, never the button.
let room = (ui.available_width() - 110.0).max(0.0);
ui.scope(|ui| {
ui.set_max_width(room);
- let place = egui::RichText::new(crate::bidi::visual(&location(folder))).font(theme::regular(12.0)).color(t.text_faint);
- ui.add(egui::Label::new(place).truncate()).on_hover_text(folder);
+ widgets::label_ltr(ui, location(folder), theme::regular(12.0), t.text_faint).on_hover_text(folder);
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let resp = widgets::ghost_button(ui, "x", tl!("Unpin"));
// Every folder has an Unpin button: say which one it is.
let label = crate::i18n::fmt(tl!("Unpin {folder}"), &[("folder", &name)]);
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label));
if resp.clicked() {
unpin = Some(folder.clone());
}
@@ -353,7 +354,7 @@ pub(crate) fn section(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let shown = if expanded { listing.files.len() } else { listing.files.len().min(SHOWN) };
for f in listing.files.iter().take(shown) {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &f.name));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &f.name));
if resp.hovered() {
ui.painter().rect_filled(rect, CornerRadius::same(8), t.hover);
}
@@ -369,7 +370,7 @@ pub(crate) fn section(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let detail = if when.is_empty() { size } else { format!("{when} · {size}") };
let detail = ui.painter().text(rect.right_center() - vec2(12.0, 0.0), Align2::RIGHT_CENTER, detail, theme::regular(12.0), t.text_muted);
let width = detail.left() - 16.0 - (rect.left() + 62.0);
- widgets::row_text(ui, rect.min + vec2(62.0, 19.0), crate::bidi::visual(&f.name), theme::medium(13.0), t.text, width);
+ widgets::row_text(ui, rect.min + vec2(62.0, 19.0), f.name.as_str(), theme::medium(13.0), t.text, width);
if resp.on_hover_text(&f.path).clicked() {
open = Some(f.path.clone());
}
diff --git a/crates/ui-egui/src/format_text_ui.rs b/crates/ui-egui/src/format_text_ui.rs
index 9849920ac6..69a49704a2 100644
--- a/crates/ui-egui/src/format_text_ui.rs
+++ b/crates/ui-egui/src/format_text_ui.rs
@@ -280,7 +280,7 @@ fn flyout(ui: &egui::Ui, t: &Tokens, resp: egui::Response) -> egui::Response {
/// labels.
fn labelled_icon(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(LABEL_ICON, 26.0), Sense::hover());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), label));
let tint = if ui.is_enabled() { t.icon } else { t.text_faint };
icons::paint(ui, Rect::from_center_size(rect.center(), vec2(18.0, 18.0)), icon, 17.0, tint);
resp.on_hover_text(label)
@@ -317,7 +317,7 @@ fn number_with_presets(ui: &mut egui::Ui, n: Number<'_>, presets: &[f64], width:
/// The text colour as a square swatch that opens the palette.
fn colour_button(ui: &mut egui::Ui, t: &Tokens, color: [f64; 3]) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Colour")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Colour")));
let [r, g, b] = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
let fill = rect.shrink(4.0);
ui.painter().rect_filled(fill, CornerRadius::same(2), Color32::from_rgb(r, g, b));
diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs
index 8caa44ced2..28494160c5 100644
--- a/crates/ui-egui/src/forms_ui.rs
+++ b/crates/ui-egui/src/forms_ui.rs
@@ -322,7 +322,7 @@ pub(crate) fn commit(view: &mut DocView, form: &[FormField]) {
#[allow(clippy::too_many_arguments)]
fn combo_editor(ctx: &egui::Context, view: &mut DocView, form: &[FormField], f: &FormField, w: &FormWidget, rect: Rect, zoom: f32, widget: usize) {
let mut enter = false;
- egui::Area::new(egui::Id::new(("form-editor", view.id.0)))
+ egui::Area::new(egui::Id::unique(("form-editor", view.id.0)))
.fade_in(false)
.order(egui::Order::Foreground)
.fixed_pos(rect.min)
@@ -340,8 +340,9 @@ fn combo_editor(ctx: &egui::Context, view: &mut DocView, form: &[FormField], f:
.background_color(FIELD_FILL)
.text_color(Color32::BLACK)
.margin(egui::Margin::symmetric(3, 1))
- .id(egui::Id::new(("form-field", view.id.0, &f.name, widget)));
- let r = ui.add_sized(rect.size(), te);
+ .id(egui::Id::unique(("form-field", view.id.0, &f.name, widget)));
+ // The form field's own logical name; not a visual/preordered label.
+ let r = ui.add_sized(rect.size(), te).accessible_name(f.name.clone());
if std::mem::take(&mut fx.request_focus) {
r.request_focus();
// Entered with Tab: typing replaces the value.
@@ -381,7 +382,7 @@ fn calendar(ctx: &egui::Context, view: &mut DocView, field: egui::Rect, fmt: &st
fx.calendar_text = Some(fx.text.clone());
}
let mut picked = None;
- let area = egui::Area::new(egui::Id::new(("date-picker", view.id.0)))
+ let area = egui::Area::new(egui::Id::unique(("date-picker", view.id.0)))
.order(egui::Order::Foreground)
.fixed_pos(field.left_bottom() + vec2(0.0, 2.0))
.show(ctx, |ui| {
@@ -672,7 +673,7 @@ pub(crate) fn overlay(
// Over the page, so only where the document shows: a field scrolled under the mode bar
// or a side panel must leave them their pointer (#2755). It stays on its field, cut off
// as the page is, rather than pushed back into the window.
- egui::Area::new(egui::Id::new(("form-editor", view.id.0)))
+ egui::Area::new(egui::Id::unique(("form-editor", view.id.0)))
.fade_in(false)
.order(egui::Order::Foreground)
.fixed_pos(rect.min)
@@ -697,7 +698,7 @@ pub(crate) fn overlay(
.text_color(Color32::BLACK)
.margin(egui::Margin::symmetric(3, 1))
.password(f.has(field_flags::PASSWORD))
- .id(egui::Id::new(("form-field", view.id.0, &f.name, focus.widget)));
+ .id(egui::Id::unique(("form-field", view.id.0, &f.name, focus.widget)));
if let Some(max) = f.max_len {
te = te.char_limit(max);
}
@@ -705,11 +706,14 @@ pub(crate) fn overlay(
te = te.desired_rows(((rect.height() / (font * 1.3)).floor() as usize).max(1));
}
let mut laid_out = None;
- let r = ui.add_sized(rect.size(), |ui: &mut egui::Ui| {
- let out = te.show(ui);
- laid_out = Some((out.galley, out.galley_pos));
- out.response.response
- });
+ let r = ui
+ .add_sized(rect.size(), |ui: &mut egui::Ui| {
+ let out = te.show(ui);
+ laid_out = Some((out.galley, out.galley_pos));
+ out.response.response
+ })
+ // The form field's own logical name; not a visual/preordered label.
+ .accessible_name(f.name.clone());
if let (Some(tb), Some(before)) = (text_box, before)
&& fx.text != before
{
@@ -784,7 +788,7 @@ pub(crate) fn overlay(
if editable_combo(f) {
combo_editor(ctx, view, form, f, w, rect, zoom, focus.widget);
}
- let resp = egui::Area::new(egui::Id::new(("form-choices", view.id.0)))
+ let resp = egui::Area::new(egui::Id::unique(("form-choices", view.id.0)))
.order(egui::Order::Foreground)
.fixed_pos(rect.left_bottom() + vec2(0.0, 2.0))
.show(ctx, |ui| {
@@ -843,10 +847,10 @@ pub(crate) fn overlay(
FormFieldKind::CheckBox | FormFieldKind::Radio => {
// Nothing is drawn over the box, but a widget there holds egui's keyboard focus, so
// Space, Tab and the arrows come here instead of turning or scrolling the page.
- let id = egui::Id::new(("form-field", view.id.0, &f.name, focus.widget));
+ let id = egui::Id::unique(("form-field", view.id.0, &f.name, focus.widget));
let mut has_focus = false;
// Not interactable, so clicks still reach the page under it.
- let area = egui::Area::new(egui::Id::new(("form-toggle", view.id.0))).order(egui::Order::Foreground).interactable(false);
+ let area = egui::Area::new(egui::Id::unique(("form-toggle", view.id.0))).order(egui::Order::Foreground).interactable(false);
area.fixed_pos(rect.min).show(ctx, |ui| {
let r = ui.interact(rect, id, egui::Sense::focusable_noninteractive());
if let Some(fx) = view.forms.focus.as_mut()
diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs
index 59b0a52bb3..bfabf701e6 100644
--- a/crates/ui-egui/src/home.rs
+++ b/crates/ui-egui/src/home.rs
@@ -18,6 +18,7 @@ pub(crate) fn card_lift(ui: &egui::Ui, t: &Tokens, rect: Rect, press: theme::Pre
}
}
+/// Draw the Home page with the welcome text, community card and recent documents.
pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
@@ -72,7 +73,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
for id in RECOMMENDED {
let Some(g) = catalog::group(id) else { continue };
let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 104.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(g.label)));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label)));
let press = theme::Press::track(ui, &resp);
card_lift(ui, &t, rect, press);
let fill = press.fill(t.card, t.hover, t.pressed);
@@ -110,7 +111,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
}
let (rect, resp) = ui.allocate_exact_size(vec2(170.0, 104.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Open file")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Open file")));
let press = theme::Press::track(ui, &resp);
card_lift(ui, &t, rect, press);
ui.painter().rect(
@@ -142,7 +143,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
if !app.recent.is_empty() {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let resp = widgets::ghost_button(ui, "trash-2", tl!("Clear"));
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Clear Recent Files")));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Clear Recent Files")));
clear = resp.on_hover_text(tl!("Clear Recent Files")).clicked();
});
}
@@ -155,7 +156,7 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let mut remove = None;
for r in &app.recent {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &r.name));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &r.name));
let press = theme::Press::track(ui, &resp);
// The row, not its response: the pointer stays "in" the row over its remove button.
let hovered = ui.rect_contains_pointer(rect);
@@ -168,9 +169,9 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
if hovered {
// Remove just this file from the list (#430); the file itself is untouched.
let x_rect = Rect::from_center_size(rect.right_center() - vec2(26.0, 0.0), vec2(28.0, 28.0));
- let x = ui.interact(x_rect, ui.id().with(("remove-recent", &r.path)), Sense::click());
+ let x = ui.interact(x_rect, ui.scope_id().with(("remove-recent", &r.path)), Sense::click());
let label = crate::i18n::fmt(tl!("Remove {name} from Recent"), &[("name", &r.name)]);
- x.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));
+ x.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label));
if x.hovered() {
ui.painter().rect_filled(x_rect, CornerRadius::same(6), t.pressed);
}
@@ -197,8 +198,8 @@ pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
);
// The name and path stop short of the page count; hovering shows the whole path.
let width = detail.left() - 16.0 - (body.left() + 46.0);
- widgets::row_text(ui, body.min + vec2(46.0, 15.0), crate::bidi::visual(&r.name), theme::medium(13.5), t.text, width);
- widgets::row_text(ui, body.min + vec2(46.0, 32.0), crate::bidi::visual(&r.path), theme::regular(11.0), t.text_faint, width);
+ widgets::row_text(ui, body.min + vec2(46.0, 15.0), r.name.as_str(), theme::medium(13.5), t.text, width);
+ widgets::row_text(ui, body.min + vec2(46.0, 32.0), r.path.as_str(), theme::regular(11.0), t.text_faint, width);
if theme::hand(resp).on_hover_text(&r.path).clicked() {
open = Some(r.path.clone());
}
diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv
index 25ddac1d5f..3e6d735523 100644
--- a/crates/ui-egui/src/i18n/ar.tsv
+++ b/crates/ui-egui/src/i18n/ar.tsv
@@ -16,9 +16,9 @@
# Product and technology names (PdfCraft, PDF, Acrobat JavaScript ...) stay in Latin letters;
# the trailing "…" of dialog commands is kept. Digits are Western (0-9).
#
-# Write every entry in logical (typing) order. The interface draws text left to right, so
-# i18n/mod.rs puts each entry into display order when it loads the catalog (bidi::display_rtl);
-# spaces and a colon at either end of an entry stay at that end, next to what the code appends.
+# Write every entry in logical (typing) order. Catalogs stay logical: epaint shapes and
+# reorders each line with UAX #9, so preordering here would reverse right-to-left text twice.
+# Spaces and a colon at either end of an entry stay at that end, next to what the code appends.
Menu القائمة
File ملف
@@ -184,6 +184,15 @@
Available متاح
Ready جاهز
Search tools and commands… البحث في الأدوات والأوامر…
+
+# Accessible names for inputs that have no visible label.
+ Added text النص المضاف
+ Link URL عنوان URL للرابط
+ Search tools and commands البحث في الأدوات والأوامر
+ Text editing line سطر تحرير النص
+ Text to place النص المراد وضعه
+ Tooltip تلميح
+ Words or phrases to redact الكلمات أو العبارات المراد حجبها
No matching tools لا توجد أدوات مطابقة
Tool أداة
Command أمر
@@ -2816,3 +2825,11 @@ certificate Version الإصدار
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today اليوم
@plural {n} reply|{n} replies {n} رد|{n} رد|{n} ردّان|{n} ردود|{n} ردًا|{n} رد
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools أدوات الصفحات
+ Insert pages from a file after the selection… إدراج صفحات من ملف بعد التحديد…
+ Rotate the selected pages counterclockwise تدوير الصفحات المحددة عكس اتجاه عقارب الساعة
+ Rotate the selected pages clockwise تدوير الصفحات المحددة باتجاه عقارب الساعة
+ Extract the selected pages… استخراج الصفحات المحددة…
+ Delete the selected pages حذف الصفحات المحددة
diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv
index a8af8ed655..ec0339f18a 100644
--- a/crates/ui-egui/src/i18n/bg.tsv
+++ b/crates/ui-egui/src/i18n/bg.tsv
@@ -1832,6 +1832,15 @@
Tool Инструмент
Command Команда
Search tools and commands… Търсене на инструменти и команди…
+
+# Accessible names for inputs that have no visible label.
+ Added text Добавен текст
+ Link URL URL на връзката
+ Search tools and commands Търсене на инструменти и команди
+ Text editing line Ред за редактиране на текст
+ Text to place Текст за поставяне
+ Tooltip Подсказка
+ Words or phrases to redact Думи или фрази за заличаване
No matching tools Няма съответстващи инструменти
All tools Всички инструменти
Read Четене
@@ -2503,3 +2512,11 @@ animation effects Off Изключени
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Днес
@plural {n} reply|{n} replies {n} отговор|{n} отговора
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Инструменти за страници
+ Insert pages from a file after the selection… Вмъкване на страници от файл след избраното…
+ Rotate the selected pages counterclockwise Завъртане на избраните страници обратно на часовниковата стрелка
+ Rotate the selected pages clockwise Завъртане на избраните страници по часовниковата стрелка
+ Extract the selected pages… Извличане на избраните страници…
+ Delete the selected pages Изтриване на избраните страници
diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv
index 42b036d161..0cacae3c2c 100644
--- a/crates/ui-egui/src/i18n/ca.tsv
+++ b/crates/ui-egui/src/i18n/ca.tsv
@@ -178,6 +178,15 @@
Available Disponible
Ready Llest
Search tools and commands… Cerca eines i ordres…
+
+# Accessible names for inputs that have no visible label.
+ Added text Text afegit
+ Link URL URL de l'enllaç
+ Search tools and commands Cerca eines i ordres
+ Text editing line Línia d'edició de text
+ Text to place Text que cal col·locar
+ Tooltip Suggeriment
+ Words or phrases to redact Paraules o frases per censurar
No matching tools Cap eina coincident
Tool Eina
Command Ordre
@@ -2801,3 +2810,11 @@ theme Appearance Aspecte
Delete attachment Elimina l'adjunt
Delete attachment {key} Elimina l'adjunt {key}
@plural {n} reply|{n} replies {n} resposta|{n} respostes
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Eines de pàgina
+ Insert pages from a file after the selection… Insereix pàgines d'un fitxer després de la selecció…
+ Rotate the selected pages counterclockwise Gira les pàgines seleccionades en sentit antihorari
+ Rotate the selected pages clockwise Gira les pàgines seleccionades en sentit horari
+ Extract the selected pages… Extreu les pàgines seleccionades…
+ Delete the selected pages Suprimeix les pàgines seleccionades
diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs
index 864cdb434f..7bf4296662 100644
--- a/crates/ui-egui/src/i18n/catalog.rs
+++ b/crates/ui-egui/src/i18n/catalog.rs
@@ -155,15 +155,6 @@ impl Catalog {
(c, errors)
}
- /// Rewrite every translation (each plural form on its own), e.g. into display order for a
- /// right-to-left language. Keys are untouched.
- pub fn map_translations(&mut self, f: impl Fn(&str) -> String) {
- let tables = std::iter::once(&mut self.plain).chain(self.contextual.values_mut()).chain(std::iter::once(&mut self.ids));
- for translation in tables.flat_map(HashMap::values_mut).chain(self.plurals.values_mut().flatten()) {
- *translation = f(translation);
- }
- }
-
pub fn plain(&self, s: &str) -> Option<&str> {
self.plain.get(s).map(String::as_str)
}
diff --git a/crates/ui-egui/src/i18n/ckb.tsv b/crates/ui-egui/src/i18n/ckb.tsv
index 845f437845..71c0c62869 100644
--- a/crates/ui-egui/src/i18n/ckb.tsv
+++ b/crates/ui-egui/src/i18n/ckb.tsv
@@ -16,9 +16,9 @@
# Product and technology names (PdfCraft, PDF, Acrobat JavaScript ...) stay in Latin letters;
# the trailing "…" of dialog commands is kept. Digits are Western (0-9).
#
-# Write every entry in logical (typing) order. The interface draws text left to right, so
-# i18n/mod.rs puts each entry into display order when it loads the catalog (bidi::display_rtl);
-# spaces and a colon at either end of an entry stay at that end, next to what the code appends.
+# Write every entry in logical (typing) order. Catalogs stay logical: epaint shapes and
+# reorders each line with UAX #9, so preordering here would reverse right-to-left text twice.
+# Spaces and a colon at either end of an entry stay at that end, next to what the code appends.
Menu پێڕست
File فایل
@@ -184,6 +184,15 @@
Available بەردەست
Ready ئامادە
Search tools and commands… گەڕان لە ئامرازەکان و فەرمانەکان…
+
+# Accessible names for inputs that have no visible label.
+ Added text دەقی زیادکراو
+ Link URL ناونیشانی URLی بەستەر
+ Search tools and commands گەڕان لە ئامرازەکان و فەرمانەکان
+ Text editing line هێڵی دەستکاریکردنی دەق
+ Text to place دەقی دانان
+ Tooltip ڕێنمایی
+ Words or phrases to redact وشە یان دەستەواژەکان بۆ شاردنەوە
No matching tools هیچ ئامرازێکی گونجاو نییە
Tool ئامراز
Command فەرمان
@@ -2732,3 +2741,11 @@ certificate Version وەشان
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today ئەمڕۆ
@plural {n} reply|{n} replies {n} وەڵام|{n} وەڵام
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools ئامرازەکانی پەڕە
+ Insert pages from a file after the selection… پەڕەکان لە فایلێکەوە لە دوای هەڵبژاردەکە دابنێ…
+ Rotate the selected pages counterclockwise پەڕە هەڵبژێردراوەکان پێچەوانەی میلی کاتژمێر بسوڕێنە
+ Rotate the selected pages clockwise پەڕە هەڵبژێردراوەکان بە ئاڕاستەی میلی کاتژمێر بسوڕێنە
+ Extract the selected pages… پەڕە هەڵبژێردراوەکان دەربهێنە…
+ Delete the selected pages پەڕە هەڵبژێردراوەکان بسڕەوە
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 3cadb98e3b..ed6d051b57 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -305,6 +305,15 @@ key Space Mezerník
Available Dostupné
Ready Připraveno
Search tools and commands… Hledat nástroje a příkazy…
+
+# Accessible names for inputs that have no visible label.
+ Added text Přidaný text
+ Link URL Adresa URL odkazu
+ Search tools and commands Hledat nástroje a příkazy
+ Text editing line Řádek pro úpravu textu
+ Text to place Text k umístění
+ Tooltip Popisek
+ Words or phrases to redact Slova nebo fráze k začernění
No matching tools Žádné odpovídající nástroje
Tool Nástroj
Command Příkaz
@@ -2847,3 +2856,11 @@ certificate Version Verze
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Dnes
@plural {n} reply|{n} replies {n} odpověď|{n} odpovědi|{n} odpovědí
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Nástroje stránek
+ Insert pages from a file after the selection… Vložit stránky ze souboru za výběr…
+ Rotate the selected pages counterclockwise Otočit vybrané stránky proti směru hodinových ručiček
+ Rotate the selected pages clockwise Otočit vybrané stránky po směru hodinových ručiček
+ Extract the selected pages… Extrahovat vybrané stránky…
+ Delete the selected pages Odstranit vybrané stránky
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 7b9dcc06f0..8586a21d43 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -157,6 +157,15 @@
Available Verfügbar
Ready Bereit
Search tools and commands… Tools und Befehle suchen…
+
+# Accessible names for inputs that have no visible label.
+ Added text Hinzugefügter Text
+ Link URL URL des Links
+ Search tools and commands Tools und Befehle suchen
+ Text editing line Textbearbeitungszeile
+ Text to place Einzufügender Text
+ Tooltip Tooltip
+ Words or phrases to redact Zu schwärzende Wörter oder Ausdrücke
No matching tools Keine passenden Werkzeuge
Tool Werkzeug
Command Befehl
@@ -2541,3 +2550,11 @@ animation effects Off Aus
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Heute
@plural {n} reply|{n} replies {n} Antwort|{n} Antworten
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Seitenwerkzeuge
+ Insert pages from a file after the selection… Seiten aus einer Datei nach der Auswahl einfügen…
+ Rotate the selected pages counterclockwise Ausgewählte Seiten gegen den Uhrzeigersinn drehen
+ Rotate the selected pages clockwise Ausgewählte Seiten im Uhrzeigersinn drehen
+ Extract the selected pages… Ausgewählte Seiten extrahieren…
+ Delete the selected pages Ausgewählte Seiten löschen
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index dbe7969173..e3eac77caa 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -2167,6 +2167,15 @@
View more Περισσότερα
Available Διαθέσιμο
Search tools and commands… Αναζήτηση εργαλείων και εντολών…
+
+# Accessible names for inputs that have no visible label.
+ Added text Προστιθέμενο κείμενο
+ Link URL Διεύθυνση URL συνδέσμου
+ Search tools and commands Αναζήτηση εργαλείων και εντολών
+ Text editing line Γραμμή επεξεργασίας κειμένου
+ Text to place Κείμενο προς τοποθέτηση
+ Tooltip Συμβουλή εργαλείου
+ Words or phrases to redact Λέξεις ή φράσεις για απόκρυψη
No matching tools Δεν βρέθηκαν εργαλεία
Tool Εργαλείο
Command Εντολή
@@ -2546,3 +2555,11 @@ animation effects Off Ανενεργά
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Σήμερα
@plural {n} reply|{n} replies {n} απάντηση|{n} απαντήσεις
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Εργαλεία σελίδων
+ Insert pages from a file after the selection… Εισαγωγή σελίδων από αρχείο μετά την επιλογή…
+ Rotate the selected pages counterclockwise Περιστροφή των επιλεγμένων σελίδων αριστερόστροφα
+ Rotate the selected pages clockwise Περιστροφή των επιλεγμένων σελίδων δεξιόστροφα
+ Extract the selected pages… Εξαγωγή των επιλεγμένων σελίδων…
+ Delete the selected pages Διαγραφή των επιλεγμένων σελίδων
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 951a3dd8c1..0d4e505a70 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -180,6 +180,15 @@
Available Disponible
Ready Listo
Search tools and commands… Buscar herramientas y comandos…
+
+# Accessible names for inputs that have no visible label.
+ Added text Texto añadido
+ Link URL URL del enlace
+ Search tools and commands Buscar herramientas y comandos
+ Text editing line Línea de edición de texto
+ Text to place Texto que colocar
+ Tooltip Información sobre herramientas
+ Words or phrases to redact Palabras o frases que censurar
No matching tools Ninguna herramienta coincide
Tool Herramienta
Command Comando
@@ -2863,3 +2872,11 @@ theme Appearance Aspecto
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Hoy
@plural {n} reply|{n} replies {n} respuesta|{n} respuestas
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Herramientas de página
+ Insert pages from a file after the selection… Insertar páginas de un archivo después de la selección…
+ Rotate the selected pages counterclockwise Girar las páginas seleccionadas en sentido antihorario
+ Rotate the selected pages clockwise Girar las páginas seleccionadas en sentido horario
+ Extract the selected pages… Extraer las páginas seleccionadas…
+ Delete the selected pages Eliminar las páginas seleccionadas
diff --git a/crates/ui-egui/src/i18n/fa.tsv b/crates/ui-egui/src/i18n/fa.tsv
index 297d3084b9..5cfc217533 100644
--- a/crates/ui-egui/src/i18n/fa.tsv
+++ b/crates/ui-egui/src/i18n/fa.tsv
@@ -14,9 +14,9 @@
# (Acrobat's included) was consulted or copied; add entries the same way.
# Product and technology names (PdfCraft, PDF, Acrobat JavaScript ...) stay in Latin letters.
#
-# Right to left: like Arabic and Kurdish, `rtl: true` in i18n/mod.rs puts every entry into display
-# order when the catalog loads ([`crate::bidi::display_rtl`]); entries are written here in logical
-# (typing) order. The Persian comma \u060c and question mark \u061f are used, and \u200c (ZWNJ) joins
+# Right to left: like Arabic and Kurdish, entries stay in logical (typing) order.
+# `rtl: true` in i18n/mod.rs selects explicit right-to-left text direction; epaint reorders
+# each rendered line. The Persian comma \u060c and question mark \u061f are used, and \u200c (ZWNJ) joins
# compound words.
Menu منو
diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv
index cd5a8040de..a542ee9b91 100644
--- a/crates/ui-egui/src/i18n/fi.tsv
+++ b/crates/ui-egui/src/i18n/fi.tsv
@@ -178,6 +178,15 @@
Available Käytettävissä
Ready Valmis
Search tools and commands… Hae työkaluja ja komentoja…
+
+# Accessible names for inputs that have no visible label.
+ Added text Lisätty teksti
+ Link URL Linkin URL-osoite
+ Search tools and commands Hae työkaluja ja komentoja
+ Text editing line Tekstin muokkausrivi
+ Text to place Sijoitettava teksti
+ Tooltip Työkaluvihje
+ Words or phrases to redact Peitettävät sanat tai lauseet
No matching tools Ei vastaavia työkaluja
Tool Työkalu
Command Komento
@@ -2810,3 +2819,11 @@ theme Appearance Teema
Delete attachment Poista liite
Delete attachment {key} Poista liite {key}
@plural {n} reply|{n} replies {n} vastaus|{n} vastausta
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Sivutyökalut
+ Insert pages from a file after the selection… Lisää sivuja tiedostosta valinnan jälkeen…
+ Rotate the selected pages counterclockwise Kierrä valittuja sivuja vastapäivään
+ Rotate the selected pages clockwise Kierrä valittuja sivuja myötäpäivään
+ Extract the selected pages… Pura valitut sivut…
+ Delete the selected pages Poista valitut sivut
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index ea6008039f..61c8b5171d 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -157,6 +157,15 @@
Available Disponible
Ready Prêt
Search tools and commands… Rechercher des outils et des commandes…
+
+# Accessible names for inputs that have no visible label.
+ Added text Texte ajouté
+ Link URL URL du lien
+ Search tools and commands Rechercher des outils et des commandes
+ Text editing line Ligne de modification du texte
+ Text to place Texte à placer
+ Tooltip Info-bulle
+ Words or phrases to redact Mots ou expressions à biffer
No matching tools Aucun outil correspondant
Tool Outil
Command Commande
@@ -2806,3 +2815,11 @@ certificate Version Version
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Aujourd'hui
@plural {n} reply|{n} replies {n} réponse|{n} réponses
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Outils de page
+ Insert pages from a file after the selection… Insérer des pages d'un fichier après la sélection…
+ Rotate the selected pages counterclockwise Faire pivoter les pages sélectionnées dans le sens antihoraire
+ Rotate the selected pages clockwise Faire pivoter les pages sélectionnées dans le sens horaire
+ Extract the selected pages… Extraire les pages sélectionnées…
+ Delete the selected pages Supprimer les pages sélectionnées
diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv
index 7f403caba1..e9d627aca9 100644
--- a/crates/ui-egui/src/i18n/hi.tsv
+++ b/crates/ui-egui/src/i18n/hi.tsv
@@ -162,6 +162,15 @@
Available उपलब्ध
Ready तैयार
Search tools and commands… टूल और कमांड खोजें…
+
+# Accessible names for inputs that have no visible label.
+ Added text जोड़ा गया टेक्स्ट
+ Link URL लिंक का URL
+ Search tools and commands टूल और कमांड खोजें
+ Text editing line टेक्स्ट संपादन पंक्ति
+ Text to place रखने के लिए टेक्स्ट
+ Tooltip टूलटिप
+ Words or phrases to redact रेडैक्ट करने के लिए शब्द या वाक्यांश
No matching tools कोई मेल खाता टूल नहीं
Tool टूल
Command कमांड
@@ -2777,3 +2786,11 @@ theme Appearance स्वरूप
Delete attachment अनुलग्नक हटाएँ
Delete attachment {key} अनुलग्नक {key} हटाएँ
@plural {n} reply|{n} replies {n} जवाब
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools पृष्ठ उपकरण
+ Insert pages from a file after the selection… चयन के बाद किसी फ़ाइल से पृष्ठ डालें…
+ Rotate the selected pages counterclockwise चयनित पृष्ठों को वामावर्त घुमाएँ
+ Rotate the selected pages clockwise चयनित पृष्ठों को दक्षिणावर्त घुमाएँ
+ Extract the selected pages… चयनित पृष्ठ निकालें…
+ Delete the selected pages चयनित पृष्ठ हटाएँ
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 33ced9925d..6b37b9169b 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -155,6 +155,15 @@
Available Elérhető
Ready Kész
Search tools and commands… Eszközök és parancsok keresése…
+
+# Accessible names for inputs that have no visible label.
+ Added text Hozzáadott szöveg
+ Link URL Hivatkozás URL-je
+ Search tools and commands Eszközök és parancsok keresése
+ Text editing line Szövegszerkesztő sor
+ Text to place Elhelyezendő szöveg
+ Tooltip Elemleírás
+ Words or phrases to redact Kitakarni kívánt szavak vagy kifejezések
No matching tools Nincs illeszkedő eszköz
Tool Eszköz
Command Parancs
@@ -2539,3 +2548,11 @@ animation effects Off Ki
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Ma
@plural {n} reply|{n} replies {n} válasz|{n} válasz
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Oldaleszközök
+ Insert pages from a file after the selection… Oldalak beszúrása fájlból a kijelölés után…
+ Rotate the selected pages counterclockwise A kijelölt oldalak forgatása az óramutató járásával ellentétesen
+ Rotate the selected pages clockwise A kijelölt oldalak forgatása az óramutató járásával megegyezően
+ Extract the selected pages… A kijelölt oldalak kibontása…
+ Delete the selected pages A kijelölt oldalak törlése
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 422fac2793..292b336e10 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -1011,6 +1011,15 @@
Scroll tabs right Gulir tab ke kanan
Search comments Cari komentar
Search tools and commands… Cari alat dan perintah…
+
+# Accessible names for inputs that have no visible label.
+ Added text Teks yang ditambahkan
+ Link URL URL tautan
+ Search tools and commands Cari alat dan perintah
+ Text editing line Baris penyuntingan teks
+ Text to place Teks yang akan ditempatkan
+ Tooltip Tooltip
+ Words or phrases to redact Kata atau frasa untuk disensor
Searchable Image (Exact) Gambar yang Dapat Dicari (Tepat)
Searching… {s} of {p} pages Mencari… {s} dari {p} halaman
Searching… {s}/{p} Mencari… {s}/{p}
@@ -2778,3 +2787,11 @@ theme Appearance Tampilan
Delete attachment Hapus lampiran
Delete attachment {key} Hapus lampiran {key}
@plural {n} reply|{n} replies {n} balasan
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Alat halaman
+ Insert pages from a file after the selection… Sisipkan halaman dari file setelah pilihan…
+ Rotate the selected pages counterclockwise Putar halaman yang dipilih berlawanan arah jarum jam
+ Rotate the selected pages clockwise Putar halaman yang dipilih searah jarum jam
+ Extract the selected pages… Ekstrak halaman yang dipilih…
+ Delete the selected pages Hapus halaman yang dipilih
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 60ecf2de3c..20729bae6a 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -181,6 +181,15 @@
Available Disponibile
Ready Pronto
Search tools and commands… Cerca strumenti e comandi…
+
+# Accessible names for inputs that have no visible label.
+ Added text Testo aggiunto
+ Link URL URL del collegamento
+ Search tools and commands Cerca strumenti e comandi
+ Text editing line Riga di modifica del testo
+ Text to place Testo da posizionare
+ Tooltip Descrizione comando
+ Words or phrases to redact Parole o frasi da oscurare
No matching tools Nessuno strumento corrispondente
Tool Strumento
Command Comando
@@ -2772,3 +2781,11 @@ certificate SHA-256 digest Impronta SHA-256
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Oggi
@plural {n} reply|{n} replies {n} risposta|{n} risposte
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Strumenti pagina
+ Insert pages from a file after the selection… Inserisci pagine da un file dopo la selezione…
+ Rotate the selected pages counterclockwise Ruota le pagine selezionate in senso antiorario
+ Rotate the selected pages clockwise Ruota le pagine selezionate in senso orario
+ Extract the selected pages… Estrai le pagine selezionate…
+ Delete the selected pages Elimina le pagine selezionate
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index db338ebb11..1ed4d43b6c 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -184,6 +184,15 @@
Available 使用可能
Ready 使用可能
Search tools and commands… ツールとコマンドを検索…
+
+# Accessible names for inputs that have no visible label.
+ Added text 追加したテキスト
+ Link URL リンクの URL
+ Search tools and commands ツールとコマンドを検索
+ Text editing line テキスト編集行
+ Text to place 配置するテキスト
+ Tooltip ツールチップ
+ Words or phrases to redact 墨消しする単語または語句
No matching tools 該当するツールがありません
Tool ツール
Command コマンド
@@ -2540,3 +2549,11 @@ animation effects Off オフ
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today 今日
@plural {n} reply|{n} replies {n} 件の返信
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools ページツール
+ Insert pages from a file after the selection… 選択範囲の後にファイルからページを挿入…
+ Rotate the selected pages counterclockwise 選択したページを反時計回りに回転
+ Rotate the selected pages clockwise 選択したページを時計回りに回転
+ Extract the selected pages… 選択したページを抽出…
+ Delete the selected pages 選択したページを削除
diff --git a/crates/ui-egui/src/i18n/kk.tsv b/crates/ui-egui/src/i18n/kk.tsv
index ea0d0d0fb4..9022c3591c 100644
--- a/crates/ui-egui/src/i18n/kk.tsv
+++ b/crates/ui-egui/src/i18n/kk.tsv
@@ -145,6 +145,15 @@
Available Қолжетімді
Ready Дайын
Search tools and commands… Құралдар мен командаларды іздеу…
+
+# Accessible names for inputs that have no visible label.
+ Added text Қосылған мәтін
+ Link URL Сілтеменің URL мекенжайы
+ Search tools and commands Құралдар мен командаларды іздеу
+ Text editing line Мәтінді өңдеу жолы
+ Text to place Орналастырылатын мәтін
+ Tooltip Қалтқы
+ Words or phrases to redact Жасырылатын сөздер немесе сөз тіркестері
No matching tools Сәйкес құралдар жоқ
Tool Құрал
Command Команда
@@ -2538,3 +2547,11 @@ animation effects Off Өшірулі
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Бүгін
@plural {n} reply|{n} replies {n} жауап|{n} жауап
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Бет құралдары
+ Insert pages from a file after the selection… Таңдаудан кейін файлдан беттер кірістіру…
+ Rotate the selected pages counterclockwise Таңдалған беттерді сағат тіліне қарсы бұру
+ Rotate the selected pages clockwise Таңдалған беттерді сағат тілімен бұру
+ Extract the selected pages… Таңдалған беттерді шығарып алу…
+ Delete the selected pages Таңдалған беттерді жою
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index a9ee5b4878..09b9cad9fa 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -162,6 +162,15 @@
Available 사용 가능
Ready 준비됨
Search tools and commands… 도구 및 명령 검색…
+
+# Accessible names for inputs that have no visible label.
+ Added text 추가한 텍스트
+ Link URL 링크 URL
+ Search tools and commands 도구 및 명령 검색
+ Text editing line 텍스트 편집 줄
+ Text to place 배치할 텍스트
+ Tooltip 도구 설명
+ Words or phrases to redact 민감 정보를 제거할 단어 또는 구문
No matching tools 일치하는 도구가 없습니다
Tool 도구
Command 명령
@@ -2777,3 +2786,11 @@ theme Appearance 모양
Delete attachment 첨부 파일 삭제
Delete attachment {key} 첨부 파일 {key} 삭제
@plural {n} reply|{n} replies 답글 {n}개
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools 페이지 도구
+ Insert pages from a file after the selection… 선택 영역 뒤에 파일에서 페이지 삽입…
+ Rotate the selected pages counterclockwise 선택한 페이지를 시계 반대 방향으로 회전
+ Rotate the selected pages clockwise 선택한 페이지를 시계 방향으로 회전
+ Extract the selected pages… 선택한 페이지 추출…
+ Delete the selected pages 선택한 페이지 삭제
diff --git a/crates/ui-egui/src/i18n/lo.tsv b/crates/ui-egui/src/i18n/lo.tsv
index 3b702756bc..964467d823 100644
--- a/crates/ui-egui/src/i18n/lo.tsv
+++ b/crates/ui-egui/src/i18n/lo.tsv
@@ -182,6 +182,15 @@
Available ພ້ອມໃຊ້ງານ
Ready ພ້ອມແລ້ວ
Search tools and commands… ຄົ້ນຫາເຄື່ອງມື ແລະ ຄຳສັ່ງ…
+
+# Accessible names for inputs that have no visible label.
+ Added text ຂໍ້ຄວາມທີ່ເພີ່ມ
+ Link URL URL ຂອງລິ້ງຄ໌
+ Search tools and commands ຄົ້ນຫາເຄື່ອງມື ແລະ ຄຳສັ່ງ
+ Text editing line ແຖວແກ້ໄຂຂໍ້ຄວາມ
+ Text to place ຂໍ້ຄວາມທີ່ຈະວາງ
+ Tooltip ຄຳແນະນຳເຄື່ອງມື
+ Words or phrases to redact ຄຳ ຫຼື ວະລີທີ່ຈະປິດບັງ
No matching tools ບໍ່ພົບເຄື່ອງມືທີ່ກົງກັນ
Tool ເຄື່ອງມື
Command ຄຳສັ່ງ
@@ -2448,3 +2457,11 @@ animation effects Off ປິດ
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today ມື້ນີ້
@plural {n} reply|{n} replies ການຕອບກັບ {n} ລາຍການ
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools ເຄື່ອງມືໜ້າ
+ Insert pages from a file after the selection… ແຊກໜ້າຈາກໄຟລ໌ຫຼັງການເລືອກ…
+ Rotate the selected pages counterclockwise ໝູນໜ້າທີ່ເລືອກທວນເຂັມໂມງ
+ Rotate the selected pages clockwise ໝູນໜ້າທີ່ເລືອກຕາມເຂັມໂມງ
+ Extract the selected pages… ແຍກໜ້າທີ່ເລືອກອອກ…
+ Delete the selected pages ລຶບໜ້າທີ່ເລືອກ
diff --git a/crates/ui-egui/src/i18n/lt.tsv b/crates/ui-egui/src/i18n/lt.tsv
index 058bbe9052..43749f4ec8 100644
--- a/crates/ui-egui/src/i18n/lt.tsv
+++ b/crates/ui-egui/src/i18n/lt.tsv
@@ -1067,6 +1067,15 @@
Scroll tabs right Slinkti korteles dešinėn
Search comments Ieškoti komentaruose
Search tools and commands… Ieškoti įrankių ir komandų…
+
+# Accessible names for inputs that have no visible label.
+ Added text Pridėtas tekstas
+ Link URL Saito URL
+ Search tools and commands Ieškoti įrankių ir komandų
+ Text editing line Teksto redagavimo eilutė
+ Text to place Tekstas, kurį reikia įdėti
+ Tooltip Patarimas
+ Words or phrases to redact Šalinami žodžiai ar frazės
Searchable Image (Exact) Paveikslėlis su tiksliu atpažinimu
Searching… {s} of {p} pages Ieškoma… {s} iš {p} puslapių
Searching… {s}/{p} Ieškoma… {s}/{p}
@@ -2801,3 +2810,11 @@ theme Appearance Išvaizda
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Šiandien
@plural {n} reply|{n} replies {n} atsakymas|{n} atsakymai|{n} atsakymų
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Puslapių įrankiai
+ Insert pages from a file after the selection… Įterpti puslapius iš failo po pasirinkimo…
+ Rotate the selected pages counterclockwise Pasukti pasirinktus puslapius prieš laikrodžio rodyklę
+ Rotate the selected pages clockwise Pasukti pasirinktus puslapius pagal laikrodžio rodyklę
+ Extract the selected pages… Išskleisti pasirinktus puslapius…
+ Delete the selected pages Ištrinti pasirinktus puslapius
diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs
index 15a27becbc..f57894f6c4 100644
--- a/crates/ui-egui/src/i18n/mod.rs
+++ b/crates/ui-egui/src/i18n/mod.rs
@@ -44,8 +44,8 @@ pub struct LangInfo {
/// Plural form index for a count (English: 0 = one, 1 = other; Japanese: always 0). A catalog's
/// `@plural` entries list one form per index.
pub plural: fn(u64) -> usize,
- /// The language is written right to left. egui lays text out left to right, so the catalog's
- /// translations are put into display order when it loads ([`crate::bidi::display_rtl`]).
+ /// The language is written right to left. Catalogs stay in logical order: the egui 0.37 fork
+ /// owns bidi shaping/reordering (E5/E12), so preordering here would reverse Arabic twice.
pub rtl: bool,
catalog: OnceLock,
}
@@ -265,15 +265,16 @@ impl LangInfo {
(0..=1000).map(self.plural).max().unwrap_or(0).saturating_add(1)
}
+ /// Return the parsed catalogue, building it on first use and warning about entries that fall back to
+ /// English.
fn catalog(&self) -> &Catalog {
self.catalog.get_or_init(|| {
- let (mut catalog, errors) = Catalog::parse(self.source, self.plural_forms());
+ let (catalog, errors) = Catalog::parse(self.source, self.plural_forms());
for error in errors {
log::warn!("{} interface catalog: {error}; that entry shows in English", self.code);
}
- if self.rtl {
- catalog.map_translations(crate::bidi::display_rtl);
- }
+ // Catalogs keep logical text: the fork shapes and reorders each run once. Accessibility
+ // names, copied text and search therefore see the same logical string as the source.
catalog
})
}
@@ -325,8 +326,17 @@ impl Lang {
/// Čeština sits under C rather than after Z. Names in other scripts follow the Latin ones in
/// code point order: Greek, Cyrillic, Arabic, then the CJK languages.
pub fn for_picker() -> Vec {
+ Self::for_picker_by(Lang::name)
+ }
+
+ /// [`for_picker`](Self::for_picker), ordered by the names the picker actually shows.
+ ///
+ /// `shown` must return each language's displayed name. Pass [`Lang::picker_name`] to keep a
+ /// Latin-script fallback with the other Latin names when a script's face is missing, rather
+ /// than sorting it into a block of unrenderable labels.
+ pub fn for_picker_by(mut shown: impl FnMut(Lang) -> &'static str) -> Vec {
let mut rest: Vec = Lang::all().filter(|l| l.code() != Lang::EN.code()).collect();
- rest.sort_by_cached_key(|l| name_sort_key(l.name()));
+ rest.sort_by_cached_key(|l| name_sort_key(shown(*l)));
std::iter::once(Lang::EN).chain(rest).collect()
}
@@ -334,8 +344,61 @@ impl Lang {
self.0.name
}
- /// Whether the language is written right to left. Its translations come back from the
- /// lookups in display order (see [`LangInfo::rtl`]).
+ /// The language's name in English, used by [`picker_name`](Self::picker_name) when this
+ /// build's fonts cannot draw [`name`](Self::name).
+ pub fn english_name(self) -> &'static str {
+ match self.code() {
+ "en" => "English",
+ "ja" => "Japanese",
+ "zh-hans" => "Simplified Chinese",
+ "zh-hant" => "Traditional Chinese",
+ "cs" => "Czech",
+ "pt-br" => "Portuguese (Brazil)",
+ "de" => "German",
+ "es" => "Spanish",
+ "fr" => "French",
+ "ru" => "Russian",
+ "kk" => "Kazakh",
+ "bg" => "Bulgarian",
+ "te" => "Telugu",
+ "hu" => "Hungarian",
+ "uk" => "Ukrainian",
+ "it" => "Italian",
+ "ar" => "Arabic",
+ "ckb" => "Central Kurdish",
+ "fa" => "Persian",
+ "pl" => "Polish",
+ "sl" => "Slovenian",
+ "el" => "Greek",
+ "tr" => "Turkish",
+ "lt" => "Lithuanian",
+ "id" => "Indonesian",
+ "vi" => "Vietnamese",
+ "fi" => "Finnish",
+ "nb" => "Norwegian Bokmål",
+ "sq" => "Albanian",
+ "th" => "Thai",
+ "ca" => "Catalan",
+ "ro" => "Romanian",
+ "lo" => "Lao",
+ "hi" => "Hindi",
+ "ko" => "Korean",
+ // Only reached if a language is added to `LANGUAGES` without an English name; the
+ // code still tells the reader which entry it is.
+ _ => self.0.code,
+ }
+ }
+
+ /// The name to show in the language picker: the native name when the current fonts can draw
+ /// it, otherwise the English name. With egui 0.37's default `MissingGlyphPolicy::Panic`, a
+ /// native name whose script has no face (for example Hindi in a build without a Devanagari
+ /// face and with installed fonts turned off) would otherwise abort while the list opens.
+ pub fn picker_name(self, drawable: impl FnOnce(&str) -> bool) -> &'static str {
+ if drawable(self.name()) { self.name() } else { self.english_name() }
+ }
+
+ /// Whether the language is written right to left. Lookups stay logical; the egui fork
+ /// shapes and reorders each run for display (see [`LangInfo::rtl`]).
pub fn rtl(self) -> bool {
self.0.rtl
}
@@ -711,6 +774,20 @@ mod tests {
set_current(previous);
}
+ /// Regression test: a language picker uses its native name only when a face can draw it, otherwise its
+ /// English name.
+ #[test]
+ fn picker_names_fall_back_to_english_when_their_script_has_no_face() {
+ let hi = Lang::from_code("hi").expect("hi registered");
+ assert_eq!(hi.picker_name(|_| true), "हिन्दी", "the native name is kept when it can be drawn");
+ assert_eq!(hi.picker_name(|_| false), "Hindi", "no Devanagari face: an English name, not an unrenderable label");
+ assert_eq!(Lang::EN.picker_name(|_| false), "English");
+ for language in Lang::all() {
+ assert!(!language.english_name().is_empty(), "{}", language.code());
+ assert_ne!(language.english_name(), language.code(), "{} needs an English picker fallback", language.code());
+ }
+ }
+
#[test]
fn tags_map_to_languages() {
assert_eq!(lang_from_tag("ja_JP.UTF-8"), Some(JA()));
@@ -1694,25 +1771,24 @@ mod tests {
assert_eq!(restored.language, "ar");
}
- /// Lookups return Arabic in display order: egui draws the words left to right as given, and
- /// joins the letters of each word itself.
+ /// Catalog lookups stay in logical order; the egui 0.37 fork owns bidi shaping and display
+ /// reordering (E5/E12), so preordering here would reverse Arabic twice. Accessibility names,
+ /// copied labels and search therefore see the source string.
#[test]
- fn arabic_lookups_are_in_display_order() {
+ fn arabic_catalog_stays_logical() {
let ar = arabic();
- // "حفظ باسم…" as typed; the ellipsis ends the phrase on the left.
- assert_eq!(tr(ar, "Save as…"), "…باسم حفظ");
- // Latin names keep their own direction inside the phrase.
- assert_eq!(tr(ar, "About PdfCraft"), "PdfCraft حول");
- // A caption's colon stays beside the widget on its right.
+ assert_eq!(tr(ar, "Save as…"), "حفظ باسم…");
+ assert_eq!(tr(ar, "About PdfCraft"), "حول PdfCraft");
assert_eq!(tr(ar, "Name:"), "الاسم:");
- assert_eq!(tr(ar, "Issued by: "), "عن صادرة: ");
- // Placeholders survive and are filled in place.
- assert_eq!(tr(ar, "Couldn't open {name}: {e}"), "{name}: {e} فتح تعذّر");
- assert_eq!(fmt(tr(ar, "Couldn't open {name}: {e}"), &[("name", "a {e}.pdf"), ("e", "x")]), "a {e}.pdf: x فتح تعذّر");
- assert_eq!(fmt(tr(ar, "Page {p} of {n}"), &[("p", "3"), ("n", "12")]), "12 من 3 الصفحة");
+ assert_eq!(tr(ar, "Issued by: "), "صادرة عن: ");
+ // Placeholders survive in their logical positions.
+ assert_eq!(tr(ar, "Couldn't open {name}: {e}"), "تعذّر فتح {name}: {e}");
+ assert_eq!(fmt(tr(ar, "Couldn't open {name}: {e}"), &[("name", "a {e}.pdf"), ("e", "x")]), "تعذّر فتح a {e}.pdf: x");
+ assert_eq!(fmt(tr(ar, "Page {p} of {n}"), &[("p", "3"), ("n", "12")]), "الصفحة 3 من 12");
set_current(ar);
- assert_eq!(command_label("Undo Insert pages from a.pdf"), "a.pdf من صفحات إدراج عن التراجع");
- assert_eq!(menu_label("file.saveAs", "Save as…"), "…باسم حفظ");
+ let command = command_label("Undo Insert pages from a.pdf");
+ assert!(command.contains("a.pdf") && command.contains("إدراج صفحات"), "logical command label: {command:?}");
+ assert_eq!(menu_label("file.saveAs", "Save as…"), "حفظ باسم…");
set_current(Lang::EN);
}
@@ -1744,7 +1820,7 @@ mod tests {
assert_eq!(lang_from_tag(tag), Some(fa), "{tag}");
}
assert_eq!(first_supported("fa-IR\r\nen-US"), Some(fa));
- // Lookups return Persian (single words in display order).
+ // Lookups return Persian in logical order; epaint handles visual ordering.
assert_eq!(tr(fa, "Save"), "ذخیره");
assert_eq!(tr(fa, "Cancel"), "لغو");
assert_eq!(tr(fa, "File"), "فایل");
diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv
index bc5fc98f58..6f1739974a 100644
--- a/crates/ui-egui/src/i18n/nb.tsv
+++ b/crates/ui-egui/src/i18n/nb.tsv
@@ -1020,6 +1020,15 @@
Scroll tabs right Rull faner til høyre
Search comments Søk i kommentarer
Search tools and commands… Søk etter verktøy og kommandoer…
+
+# Accessible names for inputs that have no visible label.
+ Added text Lagt til tekst
+ Link URL URL for lenken
+ Search tools and commands Søk etter verktøy og kommandoer
+ Text editing line Tekstredigeringslinje
+ Text to place Tekst som skal plasseres
+ Tooltip Verktøytips
+ Words or phrases to redact Ord eller fraser som skal sladdes
Searchable Image (Exact) Søkbart bilde (eksakt)
Searching… {s} of {p} pages Søker… {s} av {p} sider
Searching… {s}/{p} Søker… {s}/{p}
@@ -2716,3 +2725,11 @@ key Space Mellomrom
# AI-assisted additions for restoring the last view (#1767) (2026-10-22); not reviewed by a native speaker.
Restore the last view (page, zoom and page display) when a document is opened again Gjenopprett den siste visningen (side, zoom og sidevisning) når et dokument åpnes igjen
@plural {n} reply|{n} replies {n} svar|{n} svar
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Sideverktøy
+ Insert pages from a file after the selection… Sett inn sider fra en fil etter utvalget…
+ Rotate the selected pages counterclockwise Roter de valgte sidene mot klokken
+ Rotate the selected pages clockwise Roter de valgte sidene med klokken
+ Extract the selected pages… Trekk ut de valgte sidene…
+ Delete the selected pages Slett de valgte sidene
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 056ca7d403..963d717584 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -180,6 +180,15 @@
Available Dostępne
Ready Gotowe
Search tools and commands… Szukaj narzędzi i poleceń…
+
+# Accessible names for inputs that have no visible label.
+ Added text Dodany tekst
+ Link URL Adres URL łącza
+ Search tools and commands Szukaj narzędzi i poleceń
+ Text editing line Wiersz edycji tekstu
+ Text to place Tekst do umieszczenia
+ Tooltip Podpowiedź
+ Words or phrases to redact Słowa lub frazy do utajenia
No matching tools Brak pasujących narzędzi
Tool Narzędzie
Command Polecenie
@@ -2636,3 +2645,11 @@ animation effects Off Wyłączone
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Dzisiaj
@plural {n} reply|{n} replies {n} odpowiedź|{n} odpowiedzi|{n} odpowiedzi
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Narzędzia stron
+ Insert pages from a file after the selection… Wstaw strony z pliku po zaznaczeniu…
+ Rotate the selected pages counterclockwise Obróć zaznaczone strony w lewo
+ Rotate the selected pages clockwise Obróć zaznaczone strony w prawo
+ Extract the selected pages… Wyodrębnij zaznaczone strony…
+ Delete the selected pages Usuń zaznaczone strony
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 1434c7c6e2..c34ae83bc5 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -1705,6 +1705,15 @@
Tool Ferramenta
Command Comando
Search tools and commands… Pesquisar ferramentas e comandos…
+
+# Accessible names for inputs that have no visible label.
+ Added text Texto adicionado
+ Link URL URL do link
+ Search tools and commands Pesquisar ferramentas e comandos
+ Text editing line Linha de edição de texto
+ Text to place Texto a colocar
+ Tooltip Dica de ferramenta
+ Words or phrases to redact Palavras ou frases para ocultar
No matching tools Nenhuma ferramenta correspondente
All tools Todas as ferramentas
Read Ler
@@ -2825,3 +2834,11 @@ theme Appearance Aparência
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Hoje
@plural {n} reply|{n} replies {n} resposta|{n} respostas
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Ferramentas de página
+ Insert pages from a file after the selection… Inserir páginas de um arquivo após a seleção…
+ Rotate the selected pages counterclockwise Girar as páginas selecionadas no sentido anti-horário
+ Rotate the selected pages clockwise Girar as páginas selecionadas no sentido horário
+ Extract the selected pages… Extrair as páginas selecionadas…
+ Delete the selected pages Excluir as páginas selecionadas
diff --git a/crates/ui-egui/src/i18n/ro.tsv b/crates/ui-egui/src/i18n/ro.tsv
index 7c739932e2..78d2298b93 100644
--- a/crates/ui-egui/src/i18n/ro.tsv
+++ b/crates/ui-egui/src/i18n/ro.tsv
@@ -1020,6 +1020,15 @@
Scroll tabs right Derulare file la dreapta
Search comments Căutare în comentarii
Search tools and commands… Căutare instrumente și comenzi…
+
+# Accessible names for inputs that have no visible label.
+ Added text Text adăugat
+ Link URL URL-ul linkului
+ Search tools and commands Căutare instrumente și comenzi
+ Text editing line Linie de editare a textului
+ Text to place Text de plasat
+ Tooltip Sfat ecran
+ Words or phrases to redact Cuvinte sau expresii de anonimizat
Searchable Image (Exact) Imagine în care se poate căuta (exactă)
Searching… {s} of {p} pages Se caută… {s} din {p} pagini
Searching… {s}/{p} Se caută… {s}/{p}
@@ -2801,3 +2810,11 @@ theme Appearance Aspect
Delete attachment Ștergere atașament
Delete attachment {key} Ștergere atașament {key}
@plural {n} reply|{n} replies {n} răspuns|{n} răspunsuri|{n} de răspunsuri
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Instrumente pentru pagini
+ Insert pages from a file after the selection… Inserează pagini dintr-un fișier după selecție…
+ Rotate the selected pages counterclockwise Rotește paginile selectate în sens antiorar
+ Rotate the selected pages clockwise Rotește paginile selectate în sens orar
+ Extract the selected pages… Extrage paginile selectate…
+ Delete the selected pages Șterge paginile selectate
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index bea98cd797..274232d586 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -177,6 +177,15 @@
Available Доступно
Ready Готово
Search tools and commands… Поиск инструментов и команд…
+
+# Accessible names for inputs that have no visible label.
+ Added text Добавленный текст
+ Link URL URL-адрес ссылки
+ Search tools and commands Поиск инструментов и команд
+ Text editing line Строка редактирования текста
+ Text to place Текст для размещения
+ Tooltip Подсказка
+ Words or phrases to redact Слова или фразы для скрытия
No matching tools Нет подходящих инструментов
Tool Инструмент
Command Команда
@@ -2453,3 +2462,11 @@ animation effects Off Выкл
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Сегодня
@plural {n} reply|{n} replies {n} ответ|{n} ответа|{n} ответов
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Инструменты страниц
+ Insert pages from a file after the selection… Вставить страницы из файла после выделения…
+ Rotate the selected pages counterclockwise Повернуть выбранные страницы против часовой стрелки
+ Rotate the selected pages clockwise Повернуть выбранные страницы по часовой стрелке
+ Extract the selected pages… Извлечь выбранные страницы…
+ Delete the selected pages Удалить выбранные страницы
diff --git a/crates/ui-egui/src/i18n/sl.tsv b/crates/ui-egui/src/i18n/sl.tsv
index ccbb42d57b..420e6a5996 100644
--- a/crates/ui-egui/src/i18n/sl.tsv
+++ b/crates/ui-egui/src/i18n/sl.tsv
@@ -1636,6 +1636,15 @@
Search Iskanje
Search comments Išči po komentarjih
Search tools and commands… Poišči orodja in ukaze…
+
+# Accessible names for inputs that have no visible label.
+ Added text Dodano besedilo
+ Link URL URL povezave
+ Search tools and commands Poišči orodja in ukaze
+ Text editing line Vrstica za urejanje besedila
+ Text to place Besedilo za postavitev
+ Tooltip Namig
+ Words or phrases to redact Besede ali fraze za počrnitev
Searchable Image (Exact) Iskalna slika (natančna)
Searching… {s} of {p} pages Iskanje… {s} od {p} strani
Searching… {s}/{p} Iskanje… {s}/{p}
@@ -2545,3 +2554,11 @@ animation effects Off Izklopljeni
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Danes
@plural {n} reply|{n} replies {n} odgovor|{n} odgovora|{n} odgovori|{n} odgovorov
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Orodja za strani
+ Insert pages from a file after the selection… Vstavi strani iz datoteke za izborom…
+ Rotate the selected pages counterclockwise Zavrti izbrane strani v nasprotni smeri urnega kazalca
+ Rotate the selected pages clockwise Zavrti izbrane strani v smeri urnega kazalca
+ Extract the selected pages… Izvleci izbrane strani…
+ Delete the selected pages Izbriši izbrane strani
diff --git a/crates/ui-egui/src/i18n/sq.tsv b/crates/ui-egui/src/i18n/sq.tsv
index a720a5333f..ba7c9dc5b3 100644
--- a/crates/ui-egui/src/i18n/sq.tsv
+++ b/crates/ui-egui/src/i18n/sq.tsv
@@ -1585,6 +1585,15 @@
Search Kërko
Search comments Kërko te komentet
Search tools and commands… Kërko mjete dhe komanda…
+
+# Accessible names for inputs that have no visible label.
+ Added text Tekst i shtuar
+ Link URL URL e lidhjes
+ Search tools and commands Kërko mjete dhe komanda
+ Text editing line Rreshti i redaktimit të tekstit
+ Text to place Teksti për t'u vendosur
+ Tooltip Këshilla e mjetit
+ Words or phrases to redact Fjalë ose fraza për redaktim
Searchable Image (Exact) Imazh i kërkueshëm (i saktë)
Searching… {s} of {p} pages Po kërkohet… {s} nga {p} faqe
Searching… {s}/{p} Po kërkohet… {s}/{p}
@@ -2527,3 +2536,11 @@ animation effects Off Joaktiv
Delete attachment Fshi bashkëngjitjen
Delete attachment {key} Fshi bashkëngjitjen {key}
@plural {n} reply|{n} replies {n} përgjigje|{n} përgjigje
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Mjetet e faqes
+ Insert pages from a file after the selection… Fut faqe nga një skedar pas përzgjedhjes…
+ Rotate the selected pages counterclockwise Rrotullo faqet e përzgjedhura në drejtim të kundërt me orën
+ Rotate the selected pages clockwise Rrotullo faqet e përzgjedhura në drejtim të orës
+ Extract the selected pages… Nxirr faqet e përzgjedhura…
+ Delete the selected pages Fshi faqet e përzgjedhura
diff --git a/crates/ui-egui/src/i18n/te.tsv b/crates/ui-egui/src/i18n/te.tsv
index 317d47f9b9..7f339989ee 100644
--- a/crates/ui-egui/src/i18n/te.tsv
+++ b/crates/ui-egui/src/i18n/te.tsv
@@ -161,6 +161,15 @@ comment menu Edit సవరించు
Available అందుబాటులో ఉంది
Ready సిద్ధం
Search tools and commands… సాధనాలు, కమాండ్లలో వెతుకు…
+
+# Accessible names for inputs that have no visible label.
+ Added text జోడించిన టెక్స్ట్
+ Link URL లింక్ URL
+ Search tools and commands సాధనాలు, కమాండ్లలో వెతుకు
+ Text editing line టెక్స్ట్ సవరణ పంక్తి
+ Text to place ఉంచాల్సిన టెక్స్ట్
+ Tooltip టూల్టిప్
+ Words or phrases to redact రెడాక్ట్ చేయాల్సిన పదాలు లేదా పదబంధాలు
No matching tools సరిపోలే సాధనాలు లేవు
Tool సాధనం
Command కమాండ్
@@ -2449,3 +2458,11 @@ animation effects Off ఆఫ్
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today ఈరోజు
@plural {n} reply|{n} replies {n} ప్రత్యుత్తరం|{n} ప్రత్యుత్తరాలు
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools పేజీ సాధనాలు
+ Insert pages from a file after the selection… ఎంపిక తర్వాత ఫైల్ నుండి పేజీలను చొప్పించు…
+ Rotate the selected pages counterclockwise ఎంచుకున్న పేజీలను అపసవ్య దిశలో తిప్పు
+ Rotate the selected pages clockwise ఎంచుకున్న పేజీలను సవ్య దిశలో తిప్పు
+ Extract the selected pages… ఎంచుకున్న పేజీలను సంగ్రహించు…
+ Delete the selected pages ఎంచుకున్న పేజీలను తొలగించు
diff --git a/crates/ui-egui/src/i18n/th.tsv b/crates/ui-egui/src/i18n/th.tsv
index 92bb15f1ad..2c9b892ed7 100644
--- a/crates/ui-egui/src/i18n/th.tsv
+++ b/crates/ui-egui/src/i18n/th.tsv
@@ -172,6 +172,15 @@
Available พร้อมใช้งาน
Ready พร้อมใช้
Search tools and commands… ค้นหาเครื่องมือและคำสั่ง…
+
+# Accessible names for inputs that have no visible label.
+ Added text ข้อความที่เพิ่ม
+ Link URL URL ของลิงก์
+ Search tools and commands ค้นหาเครื่องมือและคำสั่ง
+ Text editing line บรรทัดแก้ไขข้อความ
+ Text to place ข้อความที่จะวาง
+ Tooltip คำแนะนำเครื่องมือ
+ Words or phrases to redact คำหรือวลีที่จะปิดทับ
No matching tools ไม่มีเครื่องมือที่ตรงกัน
Tool เครื่องมือ
Command คำสั่ง
@@ -2703,3 +2712,11 @@ theme Appearance ลักษณะที่ปรากฏ
# AI-assisted additions for restoring the last view (#1767) (2026-10-22); not reviewed by a native speaker.
Restore the last view (page, zoom and page display) when a document is opened again คืนค่ามุมมองล่าสุด (หน้า การซูม และการแสดงหน้า) เมื่อเปิดเอกสารอีกครั้ง
@plural {n} reply|{n} replies การตอบกลับ {n} รายการ
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools เครื่องมือหน้า
+ Insert pages from a file after the selection… แทรกหน้าจากไฟล์หลังส่วนที่เลือก…
+ Rotate the selected pages counterclockwise หมุนหน้าที่เลือกทวนเข็มนาฬิกา
+ Rotate the selected pages clockwise หมุนหน้าที่เลือกตามเข็มนาฬิกา
+ Extract the selected pages… แยกหน้าที่เลือกออก…
+ Delete the selected pages ลบหน้าที่เลือก
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index bcdfe9a90e..a2ecaea179 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -142,6 +142,15 @@
Available Kullanılabilir
Ready Hazır
Search tools and commands… Araçları ve komutları ara…
+
+# Accessible names for inputs that have no visible label.
+ Added text Eklenen metin
+ Link URL Bağlantı URL'si
+ Search tools and commands Araçları ve komutları ara
+ Text editing line Metin düzenleme satırı
+ Text to place Yerleştirilecek metin
+ Tooltip İpucu
+ Words or phrases to redact Karartılacak sözcükler veya ifadeler
No matching tools Eşleşen araç yok
Tool Araç
Command Komut
@@ -2536,3 +2545,11 @@ animation effects Off Kapalı
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Bugün
@plural {n} reply|{n} replies {n} yanıt
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Sayfa araçları
+ Insert pages from a file after the selection… Seçimin ardından dosyadan sayfa ekle…
+ Rotate the selected pages counterclockwise Seçili sayfaları saat yönünün tersine döndür
+ Rotate the selected pages clockwise Seçili sayfaları saat yönünde döndür
+ Extract the selected pages… Seçili sayfaları ayıkla…
+ Delete the selected pages Seçili sayfaları sil
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 599b4b63af..9c76868839 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -182,6 +182,15 @@
Available Доступно
Ready Готово
Search tools and commands… Пошук інструментів і команд…
+
+# Accessible names for inputs that have no visible label.
+ Added text Доданий текст
+ Link URL URL-адреса посилання
+ Search tools and commands Пошук інструментів і команд
+ Text editing line Рядок редагування тексту
+ Text to place Текст для розміщення
+ Tooltip Підказка
+ Words or phrases to redact Слова або фрази для вилучення
No matching tools Відповідних інструментів немає
Tool Інструмент
Command Команда
@@ -2562,3 +2571,11 @@ animation effects Off Вимкнено
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today Сьогодні
@plural {n} reply|{n} replies {n} відповідь|{n} відповіді|{n} відповідей
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Інструменти сторінок
+ Insert pages from a file after the selection… Вставити сторінки з файлу після виділення…
+ Rotate the selected pages counterclockwise Повернути вибрані сторінки проти годинникової стрілки
+ Rotate the selected pages clockwise Повернути вибрані сторінки за годинниковою стрілкою
+ Extract the selected pages… Витягнути вибрані сторінки…
+ Delete the selected pages Видалити вибрані сторінки
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 048f78f624..973ba870ea 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -1057,6 +1057,15 @@ theme Appearance Giao diện
Scroll tabs right Cuộn các thẻ sang phải
Search comments Tìm bình luận
Search tools and commands… Tìm công cụ và lệnh…
+
+# Accessible names for inputs that have no visible label.
+ Added text Văn bản đã thêm
+ Link URL URL của liên kết
+ Search tools and commands Tìm công cụ và lệnh
+ Text editing line Dòng chỉnh sửa văn bản
+ Text to place Văn bản cần đặt
+ Tooltip Chú giải công cụ
+ Words or phrases to redact Từ hoặc cụm từ cần xóa
Searchable Image (Exact) Ảnh có thể tìm kiếm (Chính xác)
Searching… {s} of {p} pages Đang tìm… {s} trên {p} trang
Searching… {s}/{p} Đang tìm… {s}/{p}
@@ -2807,3 +2816,11 @@ key Space Space
# AI-assisted additions for restoring the last view (#1767) (2026-10-16); not reviewed by a native speaker.
Restore the last view (page, zoom and page display) when a document is opened again Khôi phục chế độ xem gần nhất (trang, thu phóng và hiển thị trang) khi mở lại tài liệu
@plural {n} reply|{n} replies {n} câu trả lời
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools Công cụ trang
+ Insert pages from a file after the selection… Chèn trang từ tệp sau vùng chọn…
+ Rotate the selected pages counterclockwise Xoay các trang đã chọn ngược chiều kim đồng hồ
+ Rotate the selected pages clockwise Xoay các trang đã chọn theo chiều kim đồng hồ
+ Extract the selected pages… Trích xuất các trang đã chọn…
+ Delete the selected pages Xóa các trang đã chọn
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 7ea3ca941c..d77c8f6425 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1839,6 +1839,15 @@
Tool 工具
Command 命令
Search tools and commands… 搜索工具和命令…
+
+# Accessible names for inputs that have no visible label.
+ Added text 已添加的文本
+ Link URL 链接 URL
+ Search tools and commands 搜索工具和命令
+ Text editing line 文本编辑行
+ Text to place 要放置的文本
+ Tooltip 提示
+ Words or phrases to redact 要密文的单词或短语
No matching tools 没有匹配的工具
All tools 所有工具
Read 阅读
@@ -2504,3 +2513,11 @@ animation effects Off 关
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today 今天
@plural {n} reply|{n} replies {n} 条回复
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools 页面工具
+ Insert pages from a file after the selection… 在所选内容后插入文件中的页面…
+ Rotate the selected pages counterclockwise 逆时针旋转所选页面
+ Rotate the selected pages clockwise 顺时针旋转所选页面
+ Extract the selected pages… 提取所选页面…
+ Delete the selected pages 删除所选页面
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index b34cb787ca..ce3b939f1d 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1783,6 +1783,15 @@
Tool 工具
Command 指令
Search tools and commands… 搜尋工具與指令…
+
+# Accessible names for inputs that have no visible label.
+ Added text 已新增的文字
+ Link URL 連結 URL
+ Search tools and commands 搜尋工具與指令
+ Text editing line 文字編輯行
+ Text to place 要放置的文字
+ Tooltip 提示
+ Words or phrases to redact 要遮蔽的字詞或片語
No matching tools 找不到相符的工具
All tools 所有工具
Read 閱讀
@@ -2490,3 +2499,11 @@ animation effects Off 關
# Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)
Today 今天
@plural {n} reply|{n} replies {n} 則回覆
+
+# Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)
+ Page tools 頁面工具
+ Insert pages from a file after the selection… 在所選內容後插入檔案中的頁面…
+ Rotate the selected pages counterclockwise 逆時針旋轉所選頁面
+ Rotate the selected pages clockwise 順時針旋轉所選頁面
+ Extract the selected pages… 擷取所選頁面…
+ Delete the selected pages 刪除所選頁面
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index 79254afa2f..5ad5425e8d 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -20,7 +20,7 @@ pub fn exists(name: &str) -> bool {
white_icons().contains(name)
}
-fn source(name: &str) -> egui::ImageSource<'static> {
+pub(crate) fn source(name: &str) -> egui::ImageSource<'static> {
// PdfCraft caches an unknown name under the resolved fallback name.
white_icons().source(white_icons().canonical_name(name).unwrap_or("square"))
}
diff --git a/crates/ui-egui/src/js_ui.rs b/crates/ui-egui/src/js_ui.rs
index 49611293ac..84aa706576 100644
--- a/crates/ui-egui/src/js_ui.rs
+++ b/crates/ui-egui/src/js_ui.rs
@@ -77,9 +77,6 @@ impl PdfCraftApp {
};
// Show/Hide: a panel already showing closes.
self.right = (self.right != Some(panel)).then_some(panel);
- if self.right.is_some() {
- self.pending_panel_reveals.push(crate::docking::Panel::Inspector);
- }
}
Request::Focus(_) | Request::Beep | Request::Reset(_) => {}
}
@@ -289,24 +286,66 @@ pub(crate) const PREFERENCES_BUTTON_ROW: f32 = 52.0;
/// leaves 173 pt): a taller floor would push OK off the screen again.
pub(crate) const PREFERENCES_MIN_SCROLL: f32 = 60.0;
+/// Whether the interface can draw a language picker's native name. On the web the browser's glyph
+/// rasterizer draws scripts no embedded face has, so the native names stay; on native, ask the
+/// fonts this build installed (including an installed fallback face, unless system fonts are off).
+fn picker_text_is_drawable(ui: &egui::Ui, text: &str) -> bool {
+ #[cfg(target_arch = "wasm32")]
+ {
+ let _ = (ui, text);
+ true
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ ui.fonts_mut(|fonts| fonts.has_glyphs(&egui::FontId::proportional(13.0), text))
+ }
+}
+
+/// The date picker's displayed name. Its languages are the interface languages, so it uses the
+/// same drawable-name fallback: a native name whose script this build has no face for would
+/// otherwise abort under egui 0.37's `MissingGlyphPolicy::Panic` (for example Hindi without a
+/// Devanagari face and installed system fonts turned off).
+fn date_language_picker_name(l: &pdfcraft_engine::dates::DateLanguage, drawable: impl FnOnce(&str) -> bool) -> &'static str {
+ match crate::i18n::Lang::from_code(l.code) {
+ Some(language) => language.picker_name(drawable),
+ None => l.name,
+ }
+}
+
/// Preferences: interface language and size, appearance, identity and JavaScript. Drawn in a scroll
/// area; [`preferences_buttons`] goes below it, outside the scroll, so OK is always in reach.
pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
ui.label(egui::RichText::new(tl!("Preferences")).font(theme::semibold(18.0)));
ui.horizontal(|ui| {
- ui.label(tl!("Interface language"));
- let selected = crate::i18n::Lang::from_code(&app.language).map_or(tl!("Auto"), crate::i18n::Lang::name);
+ let label = ui.label(tl!("Interface language"));
+ // A native name is only drawn when these fonts can draw it; otherwise the English name
+ // keeps the list readable instead of aborting on a missing glyph (for example Hindi
+ // without a Devanagari face, and installed system fonts turned off).
+ let (selected, picker) = {
+ let drawable = |text: &str| picker_text_is_drawable(ui, text);
+ let selected = crate::i18n::Lang::from_code(&app.language)
+ .map_or_else(|| tl!("Auto").to_owned(), |language| language.picker_name(drawable).to_owned());
+ let picker = crate::i18n::Lang::for_picker_by(|language| language.picker_name(drawable))
+ .into_iter()
+ .map(|language| (language, language.picker_name(drawable)))
+ .collect::>();
+ (selected, picker)
+ };
let before = app.language.clone();
- egui::ComboBox::from_id_salt("interface-language").selected_text(selected).show_ui(ui, |ui| {
- if ui.selectable_value(&mut app.language, crate::i18n::AUTO.to_string(), tl!("Auto")).clicked() {
- ui.close();
- }
- for language in crate::i18n::Lang::for_picker() {
- if ui.selectable_value(&mut app.language, language.code().to_string(), language.name()).clicked() {
+ egui::ComboBox::from_id_salt("interface-language")
+ .selected_text(selected)
+ .show_ui(ui, |ui| {
+ if ui.selectable_value(&mut app.language, crate::i18n::AUTO.to_string(), tl!("Auto")).clicked() {
ui.close();
}
- }
- });
+ for (language, name) in &picker {
+ if ui.selectable_value(&mut app.language, language.code().to_string(), *name).clicked() {
+ ui.close();
+ }
+ }
+ })
+ .response
+ .labelled_by(label.id);
// Relabel the rest of this dialog in the new language right away, not next frame.
if app.language != before {
crate::i18n::set_current(crate::i18n::Lang::from_pref(&app.language));
@@ -314,24 +353,28 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
});
ui.horizontal(|ui| {
use crate::ui_scale;
- ui.label(tl!("Interface size"));
+ let label = ui.label(tl!("Interface size"));
// Auto shows the size it draws at: the display's scale times the system's text scale.
let native = ui.ctx().native_pixels_per_point().unwrap_or(1.0);
let auto_percent = ui_scale::percent(ui_scale::drawn(None, app.system_text_scale, native));
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &auto_percent.to_string())]);
let selected = app.ui_scale.map_or_else(|| auto.clone(), |f| format!("{}%", ui_scale::percent(f)));
- egui::ComboBox::from_id_salt("interface-size").selected_text(selected).show_ui(ui, |ui| {
- if ui.selectable_value(&mut app.ui_scale, None, auto).clicked() {
- ui.close();
- }
- for p in ui_scale::PRESETS {
- let factor = f32::from(p) / 100.0;
- if ui.selectable_label(app.ui_scale.is_some_and(|f| ui_scale::percent(f) == u32::from(p)), format!("{p}%")).clicked() {
- app.ui_scale = Some(factor);
+ egui::ComboBox::from_id_salt("interface-size")
+ .selected_text(selected)
+ .show_ui(ui, |ui| {
+ if ui.selectable_value(&mut app.ui_scale, None, auto).clicked() {
ui.close();
}
- }
- });
+ for p in ui_scale::PRESETS {
+ let factor = f32::from(p) / 100.0;
+ if ui.selectable_label(app.ui_scale.is_some_and(|f| ui_scale::percent(f) == u32::from(p)), format!("{p}%")).clicked() {
+ app.ui_scale = Some(factor);
+ ui.close();
+ }
+ }
+ })
+ .response
+ .labelled_by(label.id);
});
ui.label(
egui::RichText::new(tl!("Auto follows the system's text size. Pages always render at the display's full resolution."))
@@ -340,16 +383,12 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
);
ui.horizontal(|ui| {
ui.label(tl!("Tools panel side"));
- let right = app.docking.tools_on_right();
- if ui.selectable_label(!right, tl!("Left")).clicked()
- && let Err(error) = app.docking.set_tools_on_right(false)
- {
- app.notify(error);
+ let right = app.side_panels.tools_on_right();
+ if ui.selectable_label(!right, tl!("Left")).clicked() {
+ app.side_panels.tools_side = crate::side_panels::ToolsSide::Left;
}
- if ui.selectable_label(right, tl!("Right")).clicked()
- && let Err(error) = app.docking.set_tools_on_right(true)
- {
- app.notify(error);
+ if ui.selectable_label(right, tl!("Right")).clicked() {
+ app.side_panels.tools_side = crate::side_panels::ToolsSide::Right;
}
});
ui.add_space(8.0);
@@ -444,38 +483,42 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
// is app-wide: every open document follows it, and documents open with it.
ui.label(egui::RichText::new(tl!("Reading colours")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
- ui.label(tl!("Replace document colours"));
+ let label = ui.label(tl!("Replace document colours"));
let mode = app.reading_colors.mode_name();
- egui::ComboBox::from_id_salt("reading-colors").selected_text(tl!(reading_mode_label(mode))).show_ui(ui, |ui| {
- for (m, label) in [
- ("off", "Off"),
- ("black-on-white", "Black on white"),
- ("white-on-black", "White on black"),
- ("yellow-on-black", "Yellow on black"),
- ("green-on-black", "Green on black"),
- ("custom", "Custom"),
- ] {
- if ui.selectable_label(mode == m, tl!(label)).clicked() {
- match m {
- "off" => app.set_reading_colors(pdfcraft_render::ReadingColors::default()),
- "custom" => {
- // Custom starts from the colours already chosen, or black on white.
- let colors = app.reading_colors.params.map_or(pdfcraft_render::ReadingColors::BLACK_ON_WHITE, |params| {
- pdfcraft_render::ReadingColors { params: Some(params) }
- });
- app.set_reading_colors(colors);
- }
- // `parse` knows these names; a preset comes with its own flags.
- preset => {
- if let Ok(colors) = pdfcraft_render::ReadingColors::parse(preset, None, None, None, None) {
+ egui::ComboBox::from_id_salt("reading-colors")
+ .selected_text(tl!(reading_mode_label(mode)))
+ .show_ui(ui, |ui| {
+ for (m, label) in [
+ ("off", "Off"),
+ ("black-on-white", "Black on white"),
+ ("white-on-black", "White on black"),
+ ("yellow-on-black", "Yellow on black"),
+ ("green-on-black", "Green on black"),
+ ("custom", "Custom"),
+ ] {
+ if ui.selectable_label(mode == m, tl!(label)).clicked() {
+ match m {
+ "off" => app.set_reading_colors(pdfcraft_render::ReadingColors::default()),
+ "custom" => {
+ // Custom starts from the colours already chosen, or black on white.
+ let colors = app.reading_colors.params.map_or(pdfcraft_render::ReadingColors::BLACK_ON_WHITE, |params| {
+ pdfcraft_render::ReadingColors { params: Some(params) }
+ });
app.set_reading_colors(colors);
}
+ // `parse` knows these names; a preset comes with its own flags.
+ preset => {
+ if let Ok(colors) = pdfcraft_render::ReadingColors::parse(preset, None, None, None, None) {
+ app.set_reading_colors(colors);
+ }
+ }
}
+ ui.close();
}
- ui.close();
}
- }
- });
+ })
+ .response
+ .labelled_by(label.id);
});
if app.reading_colors.params.is_some() {
let mut changed = false;
@@ -595,10 +638,20 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
}
ui.horizontal(|ui| {
let label = ui.label(tl!("Language"));
- let interface = crate::i18n::current().name();
- let follow = crate::i18n::fmt(tl!("Same as interface ({language})"), &[("language", interface)]);
- let current = app.session.date_language().map(str::to_string);
- let selected = DATE_LANGUAGES.iter().find(|l| current.as_deref() == Some(l.code)).map_or(follow.clone(), |l| l.name.to_string());
+ // Build every label before the combo box mutably borrows `ui`, with the same drawable
+ // fallback the interface language picker uses.
+ let (follow, selected, current, names) = {
+ let drawable = |text: &str| picker_text_is_drawable(ui, text);
+ let interface = crate::i18n::current().picker_name(drawable);
+ let follow = crate::i18n::fmt(tl!("Same as interface ({language})"), &[("language", interface)]);
+ let current = app.session.date_language().map(str::to_string);
+ let selected = DATE_LANGUAGES
+ .iter()
+ .find(|l| current.as_deref() == Some(l.code))
+ .map_or_else(|| follow.clone(), |l| date_language_picker_name(l, drawable).to_string());
+ let names = DATE_LANGUAGES.iter().map(|l| (l, date_language_picker_name(l, drawable))).collect::>();
+ (follow, selected, current, names)
+ };
egui::ComboBox::from_id_salt("date-language")
.selected_text(selected)
.width(240.0)
@@ -606,9 +659,8 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
if ui.selectable_label(current.is_none(), follow).clicked() && app.session.set_date_language(None).is_ok() {
ui.close();
}
- for l in &DATE_LANGUAGES {
- if ui.selectable_label(current.as_deref() == Some(l.code), l.name).clicked()
- && app.session.set_date_language(Some(l.code)).is_ok()
+ for (l, name) in &names {
+ if ui.selectable_label(current.as_deref() == Some(l.code), *name).clicked() && app.session.set_date_language(Some(l.code)).is_ok()
{
ui.close();
}
@@ -626,3 +678,21 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
.color(t.text_muted),
);
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn date_language_names_fall_back_when_the_native_name_cannot_be_drawn() {
+ let date_language = |code: &str| pdfcraft_engine::dates::DATE_LANGUAGES.iter().find(|l| l.code == code).expect("date language");
+ let hindi = date_language("hi");
+ assert_eq!(date_language_picker_name(hindi, |_| true), hindi.name, "the native name is kept when it can be drawn");
+ assert_eq!(date_language_picker_name(hindi, |_| false), "Hindi", "no Devanagari face: show the English name");
+ let chinese = date_language("zh-hans");
+ assert_eq!(date_language_picker_name(chinese, |_| false), "Simplified Chinese");
+ for language in &pdfcraft_engine::dates::DATE_LANGUAGES {
+ assert!(!date_language_picker_name(language, |_| false).is_empty(), "{}", language.code);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 17049388bd..79c0fc6033 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -9,6 +9,8 @@
// The settings object in `persist` is one `json!` literal past the default limit of 128.
#![recursion_limit = "256"]
+use crate::control::Host as _;
+
/// Whether `a` and `b` name the same file: equal, or equal once made absolute against the
/// current directory (links are not resolved, as in `last_session`).
pub(crate) fn same_file(a: &str, b: &str) -> bool {
@@ -42,7 +44,6 @@ mod image_pick;
mod tags_ui;
pub use combine_grid::ThumbState as CombineThumb;
mod combine_ui;
-pub mod docking;
pub use combine_ui::{Columns as CombineColumns, CombineView, Lock as CombineLock, SortKey};
mod camera_ui;
mod commands;
@@ -65,6 +66,7 @@ mod measure_ui;
mod ocr_ui;
mod optimize_ui;
mod search_ui;
+pub mod side_panels;
mod sign_ui;
mod stamps_ui;
mod standards_ui;
@@ -202,7 +204,7 @@ pub enum LeftPanel {
}
/// Right-hand panels, opened from the rail.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum RightPanel {
Comments,
Bookmarks,
@@ -281,8 +283,8 @@ struct GridDrop {
/// Dropped on the Pages panel (its gap decides where they go), not the page grid.
panel: bool,
files: Vec,
- /// When to stop waiting for the pointer (egui time, seconds).
- deadline: f64,
+ /// When to stop waiting for the pointer (monotonic: `logic` may run without a UI pass).
+ deadline: web_time::Instant,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -624,8 +626,8 @@ pub struct RecentFile {
}
pub struct PdfCraftApp {
- pub docking: docking::Workspace,
- pub(crate) pending_panel_reveals: Vec,
+ /// Tools side and pane widths; which panes are open is `left_open` and `right`.
+ pub side_panels: side_panels::SidePanels,
pub session: Session,
pub views: Vec,
pub(crate) closed_tabs: Vec,
@@ -648,6 +650,8 @@ pub struct PdfCraftApp {
pub left: LeftPanel,
pub left_open: bool,
pub right: Option,
+ /// The side panel F4 reopens: the one open last.
+ pub(crate) last_right: RightPanel,
/// The right panel that was open when the user switched to Read mode, which starts with the
/// panes closed; leaving Read mode brings it back unless the user opened or closed a pane in
/// Read mode meanwhile.
@@ -923,7 +927,7 @@ pub struct PdfCraftApp {
/// Entries left by a previous session, offered in the Recovery dialog.
pub recoverable: Vec,
recovery_keys: std::collections::HashMap,
- last_autosave: f64,
+ last_autosave: Option,
allow_quit: bool,
/// Shortcuts pressed while a text field had the keyboard, run on the next frame (see
/// `registry_shortcuts`).
@@ -1094,7 +1098,7 @@ pub enum OpenOutcome {
}
impl PdfCraftApp {
- /// A new app with no documents open and every setting at its default.
+ /// Construct an application with the default session, panels, theme and control state.
pub fn new() -> Self {
Self {
session: Session::new(),
@@ -1108,10 +1112,10 @@ impl PdfCraftApp {
date_format_draft: None,
mode_override: None,
left: LeftPanel::AllTools,
- docking: docking::Workspace::default(),
- pending_panel_reveals: Vec::new(),
+ side_panels: Default::default(),
left_open: true,
right: None,
+ last_right: RightPanel::Comments,
right_before_read: None,
comments_panel_closed: false,
right_panel_closed: false,
@@ -1261,7 +1265,7 @@ impl PdfCraftApp {
recovery: None,
recoverable: Vec::new(),
recovery_keys: Default::default(),
- last_autosave: 0.0,
+ last_autosave: None,
allow_quit: false,
deferred_commands: Vec::new(),
dialog_seen: None,
@@ -1727,7 +1731,7 @@ impl PdfCraftApp {
// Where there is no telling where the pointer is during the drag, its place arrives
// with the first move after the drop.
ctx.request_repaint();
- self.grid_drop = Some(GridDrop { doc: id, panel, files, deadline: ctx.input(|i| i.time) + 1.0 });
+ self.grid_drop = Some(GridDrop { doc: id, panel, files, deadline: web_time::Instant::now() + std::time::Duration::from_secs(1) });
}
Vec::new()
}
@@ -1751,7 +1755,7 @@ impl PdfCraftApp {
let Some(view) = self.active.and_then(|i| self.views.get_mut(i)) else { return };
let gap = match if panel { view.panel_gap } else { view.grid_gap } {
Some(gap) => gap,
- None if ctx.input(|i| i.time) >= deadline => usize::MAX,
+ None if web_time::Instant::now() >= deadline => usize::MAX,
None => return ctx.request_repaint(),
};
view.insert_at = Some(gap);
@@ -2477,7 +2481,6 @@ impl PdfCraftApp {
pub(crate) fn reveal_tools(&mut self) {
self.left_open = true;
- self.pending_panel_reveals.push(docking::Panel::Tools);
}
/// Enter a tool from the catalogue, Home, palette or control channel. Organize is a
@@ -2586,9 +2589,6 @@ impl PdfCraftApp {
if self.right.is_none() {
self.right = before;
}
- if self.right.is_some() {
- self.pending_panel_reveals.push(docking::Panel::Inspector);
- }
}
}
@@ -2610,17 +2610,21 @@ impl PdfCraftApp {
self.right_panel_closed = true;
}
self.right = panel;
- if panel.is_some() {
- self.pending_panel_reveals.push(docking::Panel::Inspector);
+ if let Some(panel) = panel {
+ self.last_right = panel;
}
}
+ /// F4: closes the side panel, or reopens the one open last.
+ pub(crate) fn toggle_side_panel(&mut self) {
+ self.choose_right_panel(if self.right.is_some() { None } else { Some(self.last_right) });
+ }
+
/// Serialize the user's persistent state (recent files, theme). Local only.
pub fn persist(&self) -> String {
let trusted: Vec = self.session.trusted_certificates().iter().map(pdfcraft_engine::sign::x509::to_pem).collect();
let mut v = serde_json::json!({
- "docking": self.docking,
- "docking_left_open": self.left_open,
+ "side_panels": self.side_panels.to_json(self.left_open),
"docking_right": self.right,
"recent": self.recent,
"reopen_last_session": self.reopen_last_session,
@@ -2697,14 +2701,13 @@ impl PdfCraftApp {
/// Restore state written by `persist`. Unknown or malformed data is ignored.
pub fn restore(&mut self, json: &str) {
let Ok(v) = serde_json::from_str::(json) else { return };
- if let Some(saved) = v.get("docking")
- && let Ok(workspace) = serde_json::from_value::(saved.clone())
- && workspace.validate().is_ok()
- {
- self.docking = workspace;
- self.left_open =
- v.get("docking_left_open").and_then(serde_json::Value::as_bool).unwrap_or(self.docking.layout.contains(&docking::Panel::Tools));
- self.right = v.get("docking_right").and_then(|value| serde_json::from_value(value.clone()).ok()).flatten();
+ let panels = side_panels::restore(&v);
+ self.side_panels = panels.panels;
+ if let Some(open) = panels.tools_open {
+ self.left_open = open;
+ }
+ if let Some(right) = v.get("docking_right") {
+ self.right = serde_json::from_value(right.clone()).ok().flatten().filter(|_| !panels.side_closed);
}
self.combine_columns = combine_ui::Columns::from_json(&v["combine_columns"]);
if let Some(view) = v["combine_view"].as_str().and_then(combine_ui::CombineView::parse) {
@@ -3068,11 +3071,13 @@ impl PdfCraftApp {
_ => return Err("always-default-view must be on or off".into()),
};
}
- ("tools-side", _) => self.docking.set_tools_on_right(match value {
- "left" => false,
- "right" => true,
- _ => return Err("tools-side must be left or right".into()),
- })?,
+ ("tools-side", _) => {
+ self.side_panels.tools_side = match value {
+ "left" => side_panels::ToolsSide::Left,
+ "right" => side_panels::ToolsSide::Right,
+ _ => return Err("tools-side must be left or right".into()),
+ }
+ }
("organize", Some(v)) => {
if value == "off" {
v.organize = false;
@@ -3260,12 +3265,6 @@ impl PdfCraftApp {
}
(other, _) => return Err(format!("unknown option {other}")),
}
- if key == "panel" && self.right.is_some() {
- self.pending_panel_reveals.push(docking::Panel::Inspector);
- }
- if key == "left" && self.left_open {
- self.pending_panel_reveals.push(docking::Panel::Tools);
- }
Ok(())
}
@@ -3456,6 +3455,60 @@ impl PdfCraftApp {
}
}
+/// Root-level panel salts whose 0.36 persisted state key changed in 0.37.
+///
+/// The shared rail and side panes now own their state. The legacy `rail` and
+/// `read_right_panel` entries are inert; the former `rail-nav` footer is no longer migrated.
+const PANEL_SALTS: [&str; 4] = ["tab_strip", "mode_bar", "rail", "read_right_panel"];
+
+/// Copy persisted 0.36 panel sizes to 0.37's parent-scope key, once, before the first panel.
+///
+/// 0.36 stored [`egui::PanelState`] under the panel's own `Id::unique(salt)`; 0.37 derives it
+/// from the parent `Ui`'s scope plus an `IdSalt`. A missing copy would reset a width the user
+/// chose. The old entry is left untouched, so rolling back to 0.36 still finds it.
+fn migrate_panel_state(ui: &egui::Ui) {
+ if ui.ctx().viewport_id() != egui::ViewportId::ROOT {
+ return;
+ }
+ for salt in PANEL_SALTS {
+ migrate_panel_state_from(ui, salt);
+ }
+}
+
+/// Copy one 0.36 panel's state to the key derived from this exact parent `Ui`.
+///
+/// The parent must be the `Ui` the panel is shown in (for a nested panel, the panel's content
+/// `Ui`), because 0.37's key includes that `Ui`'s scope.
+pub(crate) fn migrate_panel_state_from(ui: &egui::Ui, salt: &str) {
+ let old = egui::Id::unique(salt);
+ let new = ui.scope_id().with_salt(egui::IdSalt::new(salt));
+ if old == new || egui::PanelState::load(ui.ctx(), new).is_some() {
+ return;
+ }
+ if let Some(state) = egui::PanelState::load(ui.ctx(), old) {
+ ui.ctx().data_mut(|data| data.insert_persisted(new, state));
+ log::debug!("migrated panel {salt} state {:?}", state.size());
+ }
+}
+
+impl PdfCraftApp {
+ /// The parts of [`eframe::App::raw_input_hook`] that must run before egui's input hooks:
+ /// publish this pass's input-target generation to the control plugin, and hand the wheel
+ /// input to the reduced-motion reader.
+ ///
+ /// A test host that drives the app without eframe's raw hook can call this first, so its
+ /// frame ordering matches production instead of hiding focus-change bugs.
+ #[doc(hidden)]
+ pub fn prepare_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
+ // The control plugin's input hook runs next: give it this pass's input generation.
+ if let Some(control) = &self.control {
+ control.set_epoch(self.input_epoch());
+ }
+ // Before egui reads this frame's wheel input.
+ self.scroll_speed.apply(ctx, raw);
+ }
+}
+
impl eframe::App for PdfCraftApp {
/// While files are dragged over the window the system sends no pointer moves, so egui
/// would keep the place the pointer entered at: tell it where the pointer really is, so the
@@ -3463,8 +3516,7 @@ impl eframe::App for PdfCraftApp {
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// The button's release a window move or resize kept from egui.
window_controls::release_after_desktop_grab(ctx, raw);
- // Before egui reads this frame's wheel input.
- self.scroll_speed.apply(ctx, raw);
+ self.prepare_raw_input(ctx, raw);
if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() {
return;
}
@@ -3524,8 +3576,8 @@ impl eframe::App for PdfCraftApp {
self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some();
// Also done in `raw_input_hook`, before input; here for hosts that don't call the hook.
self.scroll_speed.set_line_speed(ctx);
- // Before anything reads this frame's wheel input or draws, and with the line speed just set.
- self.motion.begin_pass(ctx, self.animation_effects);
+ // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase:
+ // `logic` also runs alone while hidden, where the input events and time are stale.
// Before taking this frame's drop: the grid must be drawn once with the pointer where
// the files were let go before the gap is read.
self.finish_grid_drop(ctx);
@@ -3609,9 +3661,9 @@ impl eframe::App for PdfCraftApp {
}
self.guard_quit(ctx);
// macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136).
+ #[cfg(target_os = "macos")]
craft_quit::on_close_request(ctx);
- let now = ctx.input(|i| i.time);
- self.autosave_tick(ctx, now);
+ self.autosave_tick(ctx, web_time::Instant::now());
// Reload documents whose files a build rewrote (#431).
#[cfg(not(target_arch = "wasm32"))]
self.watch_files();
@@ -3661,11 +3713,17 @@ impl eframe::App for PdfCraftApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
i18n::set_current(i18n::Lang::from_pref(&self.language));
+ // A language change switches stock chrome between LTR and RTL before anything is drawn.
+ theme::sync_direction(&ctx);
// Fonts registered via set_fonts only take effect next frame; named families would panic now.
if !self.fonts_ready {
ctx.request_repaint();
return;
}
+ // Before any widget reads this frame's wheel input or draws.
+ self.motion.begin_pass(&ctx, self.animation_effects);
+ // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state.
+ migrate_panel_state(ui);
for view in &mut self.views {
view.begin_render_frame();
}
@@ -3698,6 +3756,10 @@ impl eframe::App for PdfCraftApp {
self.show_progress(&ctx);
widgets::toast(self, &ctx);
self.finish_render_frame(&ctx);
+ if let Some(mut control) = self.control.take() {
+ control.finish_frame(&ctx, self);
+ self.control = Some(control);
+ }
return;
}
self.sync_window_frame(&ctx);
@@ -3706,27 +3768,16 @@ impl eframe::App for PdfCraftApp {
}
chrome::tab_strip(self, ui);
chrome::mode_bar(self, ui);
- if self.active.is_some() {
- chrome::right_rail(self, ui);
- // Read mode hides the tools, not the navigation panes: the rail stays visible
- // there, so its buttons (Bookmarks, Page thumbnails, ...) must open their panels.
- // Outside Read mode the docking workspace draws the inspector.
- if self.mode == Mode::Read && self.right.is_some() {
- egui::Panel::right("read_right_panel")
- .resizable(true)
- .default_size(330.0)
- .size_range(260.0..=520.0)
- .frame(egui::Frame::NONE)
- .show(ui, |ui| panels::right_panel(self, ui));
- }
- }
// Whichever way another tab came to the front, it shows instead of the expanded view.
if self.all_tools_full && self.all_tools_tab != self.shown_tab() {
self.all_tools_full = false;
}
+ side_panels::show(self, ui);
let t = theme::Tokens::get(&ctx);
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| {
- if self.mode == Mode::Read {
+ if self.mode == Mode::AllTools && self.all_tools_full {
+ all_tools_ui::show(self, ui);
+ } else {
match self.active {
None if self.combine_showing() => combine_ui::page(self, ui),
None => home::show(self, ui),
@@ -3735,10 +3786,6 @@ impl eframe::App for PdfCraftApp {
None => canvas::document_area(self, index, ui),
},
}
- } else if self.mode == Mode::AllTools && self.all_tools_full {
- all_tools_ui::show(self, ui);
- } else {
- docking::show(self, ui);
}
});
self.process_pending_edits();
@@ -3747,6 +3794,11 @@ impl eframe::App for PdfCraftApp {
self.show_progress(&ctx);
widgets::toast(self, &ctx);
self.finish_render_frame(&ctx);
+ // Screenshots are issued only after a settled pass that really drew the window.
+ if let Some(mut control) = self.control.take() {
+ control.finish_frame(&ctx, self);
+ self.control = Some(control);
+ }
}
}
@@ -3776,3 +3828,75 @@ impl PdfCraftApp {
}
}
}
+
+#[cfg(test)]
+mod panel_migration_tests {
+ use super::*;
+
+ fn state(width: f32) -> egui::PanelState {
+ egui::PanelState { outer_rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(width, 900.0)) }
+ }
+
+ /// 0.36 stored a panel's persisted size under `Id::unique(salt)`. 0.37 derives the key from
+ /// the root `Ui`'s scope; the upgrade must carry the chosen width over, not reset it.
+ #[test]
+ fn upgrade_from_036_panel_memory_keeps_width() {
+ let ctx = egui::Context::default();
+ let old = egui::Id::unique("rail");
+ ctx.data_mut(|d| d.insert_persisted(old, state(287.0)));
+ let mut migrated = None;
+ let mut new_id = None;
+ let output = ctx.run_ui(egui::RawInput::default(), |ui| {
+ migrate_panel_state(ui);
+ new_id = Some(ui.scope_id().with_salt(egui::IdSalt::new("rail")));
+ migrated = egui::PanelState::load(ui.ctx(), new_id.expect("an id"));
+ });
+ output.drop_without_applying_deltas();
+ let migrated = migrated.expect("the 0.36 panel width migrates to the 0.37 key");
+ assert!((migrated.size().x - 287.0).abs() <= 1.0, "width survives: {:?}", migrated.size());
+ assert_eq!(new_id.unwrap(), ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail")));
+ assert!(egui::PanelState::load(&ctx, old).is_some(), "the old key stays for rollback");
+ }
+
+ /// A synthetic nested panel is keyed from its own parent `Ui`, not the root.
+ /// Migrating it at the root would silently miss its 0.36 state; the fixture uses
+ /// legacy rail names but does not model the current shared rail implementation.
+ #[test]
+ fn nested_panel_state_migrates_from_its_actual_parent_ui() {
+ let ctx = egui::Context::default();
+ let old = egui::Id::unique("rail-nav");
+ ctx.data_mut(|d| d.insert_persisted(old, state(140.0)));
+ let mut nested_id = None;
+ let mut migrated = None;
+ let output = ctx.run_ui(egui::RawInput::default(), |ui| {
+ egui::Panel::right("rail").resizable(false).exact_size(48.0).show(ui, |ui| {
+ migrate_panel_state_from(ui, "rail-nav");
+ // The key egui will use for the nested panel shown in this same Ui.
+ let key = ui.scope_id().with_salt(egui::IdSalt::new("rail-nav"));
+ nested_id = Some(key);
+ migrated = egui::PanelState::load(ui.ctx(), key);
+ egui::Panel::bottom("rail-nav").resizable(false).show(ui, |_ui| {});
+ });
+ });
+ output.drop_without_applying_deltas();
+ let migrated = migrated.expect("the nested 0.36 state migrates to its parent-scoped key");
+ assert_eq!(migrated.size().x, 140.0);
+ assert_ne!(nested_id.unwrap(), ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail-nav")), "the nested key is not the root key");
+ }
+
+ /// The one-time copy must never overwrite state a 0.37 run has already stored.
+ #[test]
+ fn migration_does_not_replace_a_037_panel_state() {
+ let ctx = egui::Context::default();
+ let old = egui::Id::unique("rail");
+ let new = ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail"));
+ ctx.data_mut(|d| {
+ d.insert_persisted(old, state(287.0));
+ d.insert_persisted(new, state(412.0));
+ });
+ let output = ctx.run_ui(egui::RawInput::default(), |ui| migrate_panel_state(ui));
+ output.drop_without_applying_deltas();
+ let kept = egui::PanelState::load(&ctx, new).expect("the 0.37 state");
+ assert_eq!(kept.size().x, 412.0);
+ }
+}
diff --git a/crates/ui-egui/src/link_ui.rs b/crates/ui-egui/src/link_ui.rs
index 446de39fc0..f7768912dd 100644
--- a/crates/ui-egui/src/link_ui.rs
+++ b/crates/ui-egui/src/link_ui.rs
@@ -291,7 +291,7 @@ pub(crate) fn body(ui: &mut egui::Ui, d: &mut LinkDraft, pages: usize, t: &Token
ui.add_enabled_ui(d.web, |ui| {
ui.horizontal(|ui| {
ui.add_space(24.0);
- ui.add(crate::widgets::line(&mut d.url).desired_width(360.0).hint_text("https://example.org"));
+ ui.add(crate::widgets::line(&mut d.url).desired_width(360.0).hint_text("https://example.org")).accessible_name(tl!("Link URL"));
});
});
widgets::radio_value(ui, &mut d.web, false, tl!("Go to a page view"));
diff --git a/crates/ui-egui/src/measure_ui.rs b/crates/ui-egui/src/measure_ui.rs
index 00dad4bd5f..79670ad304 100644
--- a/crates/ui-egui/src/measure_ui.rs
+++ b/crates/ui-egui/src/measure_ui.rs
@@ -353,6 +353,7 @@ fn finish(state: &mut MeasureView, pending: &mut Option, doc: &Document, p
pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
egui::ScrollArea::vertical().id_salt("measure-panel").show(ui, |ui| panel_body(app, ui, t));
}
+/// Draw the measurement panel: tool selection, scale calibration, snapping and the current reading.
fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
crate::widgets::begin_dialog(ui);
let Some((index, id)) = app.active_ids() else {
@@ -406,8 +407,8 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
ui.label(tl!("Click the first point to begin."));
}
ui.horizontal(|ui| {
- ui.label(tl!("Label"));
- ui.add(crate::widgets::line(&mut state.label).desired_width(130.0).char_limit(128));
+ let label = ui.label(tl!("Label"));
+ ui.add(crate::widgets::line(&mut state.label).desired_width(130.0).char_limit(128)).labelled_by(label.id);
});
ui.separator();
ui.add(widgets::checkbox(&mut state.snap_enabled, tl!("Snap to drawing")));
@@ -429,7 +430,7 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
ui.horizontal(|ui| {
ui.label(tl!("Drawing scale")).on_hover_text(tl!("Applying a scale switches units to m / mm."));
let typed = ui.add(crate::widgets::line(&mut state.ratio_text).hint_text("1:100").desired_width(56.0).char_limit(16));
- typed.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, true, tl!("Scale")));
+ typed.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, tl!("Scale")));
state.ratio_dirty |= typed.changed();
if typed.lost_focus() && std::mem::take(&mut state.ratio_dirty) {
match parse_ratio(&state.ratio_text) {
@@ -459,8 +460,8 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
ui.add(egui::DragValue::new(&mut state.real_distance).range(0.000001..=1e12));
});
ui.horizontal(|ui| {
- ui.label(tl!("Unit"));
- ui.add(crate::widgets::line(&mut state.unit).desired_width(64.0).char_limit(12));
+ let unit = ui.label(tl!("Unit"));
+ ui.add(crate::widgets::line(&mut state.unit).desired_width(64.0).char_limit(12)).labelled_by(unit.id);
ui.add(egui::DragValue::new(&mut state.precision).range(0..=6).prefix(format!("{} ", tl!("Decimals"))));
});
// A hand edit of the fields leaves the 1:N field showing the old ratio: say the new one.
@@ -480,8 +481,8 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
}
}
ui.horizontal(|ui| {
- ui.label(tl!("Viewport"));
- ui.add(crate::widgets::line(&mut state.name).desired_width(130.0).char_limit(128));
+ let viewport = ui.label(tl!("Viewport"));
+ ui.add(crate::widgets::line(&mut state.name).desired_width(130.0).char_limit(128)).labelled_by(viewport.id);
});
let apply = ui.add_enabled(doc.allows_annotation(), egui::Button::new(tl!("Apply scale"))).clicked();
if let Some(error) = &state.error {
diff --git a/crates/ui-egui/src/motion.rs b/crates/ui-egui/src/motion.rs
index 934fc06188..d95d205b0f 100644
--- a/crates/ui-egui/src/motion.rs
+++ b/crates/ui-egui/src/motion.rs
@@ -88,11 +88,19 @@ pub struct Motion {
/// egui's own animation time and scroll animation, kept while they are changed here.
egui_times: Option<(f32, ScrollAnimation)>,
wheel: WheelReader,
+ /// This frame's wheel motion, read on its first pass and reused on later passes.
+ ///
+ /// egui empties `RawInput` between the passes of a multi-pass frame, so reading the wheel
+ /// again in a later pass sees nothing. Only the first pass is handed the motion (a scroll
+ /// area keeps the offset it moved to, a view keeps the zoom it set); later passes are handed
+ /// no scroll and a unit zoom, explicitly.
+ frame: Option<(u64, WheelMotion)>,
}
impl Default for Motion {
+ /// Start motion handling with animations enabled and no desktop preference sampled yet.
fn default() -> Self {
- Self { reduced: false, source: None, asked_at: f64::NEG_INFINITY, egui_times: None, wheel: WheelReader::default() }
+ Self { reduced: false, source: None, asked_at: f64::NEG_INFINITY, egui_times: None, wheel: WheelReader::default(), frame: None }
}
}
@@ -114,13 +122,36 @@ impl Motion {
if animate {
// A gesture begun while easing is egui's to finish.
self.wheel = WheelReader::default();
+ self.frame = None;
return;
}
let options = ctx.options(|o| o.input_options);
- let motion = ctx.input(|i| self.wheel.read(&i.events, i.viewport_rect().height(), &options));
- ctx.input_mut(|i| i.smooth_scroll_delta = motion.scroll);
+ // One frame may run several passes (`request_discard`). Only the first pass has this
+ // frame's events, and only it may hand the wheel on: a scroll area applies the delta to
+ // its persisted offset, and a view multiplies the zoom into its persisted zoom, so
+ // replaying either would apply it twice. egui also rebuilds `smooth_scroll_delta` and
+ // its zoom factor from its retained wheel state every pass, so later passes must be
+ // given zero scroll and a unit zoom explicitly. A missing zoom entry would not do: it
+ // would fall back to egui's rebuilt factor.
+ let frame = ctx.cumulative_frame_nr();
+ let first_pass = match self.frame {
+ Some((read_in, _)) => read_in != frame,
+ None => true,
+ };
+ let motion = match self.frame {
+ Some((read_in, motion)) if read_in == frame => motion,
+ _ => {
+ let motion = ctx.input(|i| self.wheel.read(&i.events, i.viewport_rect().height(), &options));
+ self.frame = Some((frame, motion));
+ motion
+ }
+ };
+ let (scroll, zoom) = if first_pass { (motion.scroll, motion.zoom) } else { (Vec2::ZERO, 1.0) };
+ ctx.input_mut(|i| i.smooth_scroll_delta = scroll);
let pass = ctx.cumulative_pass_nr();
- ctx.data_mut(|d| d.insert_temp(zoom_id(), (pass, motion.zoom)));
+ ctx.data_mut(|d| d.insert_temp(zoom_id(), (pass, zoom)));
+ // Existing kinetic scrolling remains owned by egui; gating wheel input does not
+ // suppress a scroll area's per-pass advancement of retained velocity.
}
/// egui's animations, and its scrolling to a place, take no time unless the window is to
@@ -148,8 +179,9 @@ pub(crate) fn animated(ctx: &egui::Context) -> bool {
ctx.global_style().animation_time > 0.0
}
+/// Return the stable egui id holding the last wheel-zoom input state.
fn zoom_id() -> egui::Id {
- egui::Id::new("pdfcraft-motion-wheel-zoom")
+ egui::Id::unique("pdfcraft-motion-wheel-zoom")
}
/// This pass's zoom factor from a pinch or ⌘/Ctrl with the wheel (1.0 for none): egui's
@@ -194,7 +226,7 @@ impl WheelReader {
let mut modifiers = self.touch.unwrap_or_default();
for event in events {
match event {
- Event::MouseWheel { unit, delta: step, phase, modifiers: latest } => match phase {
+ Event::MouseWheel { unit, delta: step, phase, modifiers: latest, .. } => match phase {
TouchPhase::Start => {
self.touch = Some(*latest);
modifiers = *latest;
@@ -256,7 +288,7 @@ mod tests {
use std::rc::Rc;
fn wheel(unit: MouseWheelUnit, delta: Vec2, phase: TouchPhase, modifiers: Modifiers) -> Event {
- Event::MouseWheel { unit, delta, phase, modifiers }
+ Event::MouseWheel { unit, delta, phase, modifiers, source: egui::MouseWheelSource::Unknown }
}
fn notch(dy: f32, modifiers: Modifiers) -> Event {
@@ -507,6 +539,104 @@ mod tests {
});
}
+ /// With animation effects off, a real scroll area moves by one wheel step whether the frame
+ /// runs one pass or two (a `request_discard` from a sizing pass): the scroll area already
+ /// applied and stored the step in the first pass, so a later pass must not apply it again,
+ /// and must not replay the frame's raw wheel events either.
+ #[test]
+ fn two_pass_scroll_area_applies_one_wheel_step_like_a_single_pass() {
+ fn run(two_passes: bool) -> (Vec, Vec) {
+ let ctx = egui::Context::default();
+ let mut motion = Motion { reduced: true, ..Default::default() };
+ let mut offsets = Vec::new();
+ let mut wheel_events = Vec::new();
+ let raw = egui::RawInput {
+ time: Some(0.1),
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 300.0))),
+ events: vec![egui::Event::PointerMoved(egui::pos2(50.0, 50.0)), notch(-1.0, Modifiers::NONE)],
+ ..Default::default()
+ };
+ let output = ctx.run_ui(raw, |ui| {
+ motion.begin_pass(ui.ctx(), AnimationEffects::System);
+ wheel_events.push(ui.input(|i| i.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count()));
+ // Taller than the 300-point viewport, so one step stays far from the scroll
+ // limit and a doubled step could not be hidden by clamping.
+ let out = egui::ScrollArea::vertical().id_salt("motion-two-pass-scroll").auto_shrink([false, false]).show(ui, |ui| {
+ ui.set_min_size(egui::vec2(100.0, 3000.0));
+ });
+ offsets.push(out.state.unclamped_offset());
+ if two_passes && ui.ctx().current_pass_index() == 0 {
+ ui.ctx().request_discard("motion two-pass scroll regression");
+ }
+ });
+ output.drop_without_applying_deltas();
+ (offsets, wheel_events)
+ }
+
+ let (single, single_events) = run(false);
+ let (two, two_events) = run(true);
+
+ assert_eq!(single.len(), 1, "one frame, one pass");
+ assert_eq!(two.len(), 2, "the frame really ran two passes");
+ assert_eq!(single_events, vec![1], "one wheel event reaches the first pass");
+ assert_eq!(two_events, vec![1, 0], "raw wheel events are not replayed in the later pass");
+
+ let step = single[0].y;
+ assert!(step > 0.0, "the wheel step scrolled: {single:?}");
+ assert!((two[0].y - step).abs() < 0.01, "the first pass applies the whole step: single={step}, two-pass={two:?}");
+ assert!((two[1].y - step).abs() < 0.01, "the presented pass must not apply the same step again: single={step}, two-pass={two:?}");
+ }
+
+ /// With animation effects off, ctrl/⌘-wheel and pinch zoom reach a view's persisted zoom
+ /// once, whether the frame runs one pass or two (a `request_discard` from a sizing pass):
+ /// multiplying an accumulator by each pass's factor gives the single step either way. A
+ /// later pass gets a unit factor explicitly, and a frame with no wheel input resets to it.
+ #[test]
+ fn two_pass_zoom_applies_one_step_like_a_single_pass() {
+ /// One frame's `zoom_delta` readings, one per pass.
+ fn frame(ctx: &egui::Context, motion: &mut Motion, time: f64, events: Vec, two_passes: bool) -> Vec {
+ let raw = egui::RawInput {
+ time: Some(time),
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 300.0))),
+ events,
+ ..Default::default()
+ };
+ let mut zooms = Vec::new();
+ let output = ctx.run_ui(raw, |ui| {
+ motion.begin_pass(ui.ctx(), AnimationEffects::System);
+ zooms.push(zoom_delta(ui.ctx()));
+ if two_passes && ui.ctx().current_pass_index() == 0 {
+ ui.ctx().request_discard("motion two-pass zoom regression");
+ }
+ });
+ output.drop_without_applying_deltas();
+ zooms
+ }
+
+ let line = egui::InputOptions::default().line_scroll_speed;
+ let ctrl_step = (egui::InputOptions::default().scroll_zoom_speed * line).exp();
+ for (name, events, step) in [("ctrl-wheel", vec![notch(1.0, Modifiers::COMMAND)], ctrl_step), ("pinch", vec![Event::Zoom(1.5)], 1.5)] {
+ assert!((step - 1.0).abs() > 0.01, "{name}: the factor is nontrivial: {step}");
+ let single = {
+ let ctx = egui::Context::default();
+ let mut motion = Motion { reduced: true, ..Default::default() };
+ frame(&ctx, &mut motion, 0.1, events.clone(), false)
+ };
+ let ctx = egui::Context::default();
+ let mut motion = Motion { reduced: true, ..Default::default() };
+ let two = frame(&ctx, &mut motion, 0.1, events, true);
+ assert_eq!(single.len(), 1, "{name}: one frame, one pass: {single:?}");
+ assert_eq!(two.len(), 2, "{name}: the frame really ran two passes: {two:?}");
+ let product = |zooms: &[f32]| zooms.iter().product::();
+ assert!((product(&single) - step).abs() < 1e-5, "{name}: one pass applies the step: {single:?}");
+ assert!((product(&two) - step).abs() < 1e-5, "{name}: two passes apply it once: {two:?}");
+ assert!((two[1] - 1.0).abs() < 1e-6, "{name}: a later pass zooms by nothing: {two:?}");
+ // The next frame's wheel reading starts over; the two-pass frame's factor is gone.
+ let after = frame(&ctx, &mut motion, 0.1 + 1.0 / 60.0, Vec::new(), false);
+ assert_eq!(after, vec![1.0], "{name}: the cached factor does not survive the frame");
+ }
+ }
+
#[test]
fn the_system_is_asked_now_and_then_and_no_answer_changes_nothing() {
let ctx = egui::Context::default();
diff --git a/crates/ui-egui/src/object_ui.rs b/crates/ui-egui/src/object_ui.rs
index 8d7d64e47c..d495116c6c 100644
--- a/crates/ui-egui/src/object_ui.rs
+++ b/crates/ui-egui/src/object_ui.rs
@@ -36,6 +36,12 @@ struct Gesture {
}
impl ObjectSelection {
+ /// Clear any object-selection gesture and the page it was blocking.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ self.gesture = None;
+ self.blocked_page = None;
+ }
+
pub fn count(&self) -> usize {
self.selected.len()
}
diff --git a/crates/ui-egui/src/organize_panel.rs b/crates/ui-egui/src/organize_panel.rs
index b02d118012..338f64bc14 100644
--- a/crates/ui-egui/src/organize_panel.rs
+++ b/crates/ui-egui/src/organize_panel.rs
@@ -195,7 +195,7 @@ enum Availability {
fn row(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str, availability: Availability, menu: bool) -> egui::Response {
let ready = availability == Availability::Ready && ui.is_enabled();
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), if ready { Sense::click() } else { Sense::hover() });
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ready, label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ready, label));
let press = theme::Press::track(ui, &resp);
if ready {
press.wash(ui, rect, 6, false);
diff --git a/crates/ui-egui/src/page_pointer.rs b/crates/ui-egui/src/page_pointer.rs
index ebb81ab5fa..a6a318c1fd 100644
--- a/crates/ui-egui/src/page_pointer.rs
+++ b/crates/ui-egui/src/page_pointer.rs
@@ -144,7 +144,7 @@ mod tests {
let (_, resp) = ui.allocate_exact_size(PAGES.size(), Sense::click_and_drag());
seen = PagePointer::read(ui, &resp, modal);
if area {
- egui::Area::new(egui::Id::new("over")).fixed_pos(OVER.min).show(ui.ctx(), |ui| {
+ egui::Area::new(egui::Id::unique("over")).fixed_pos(OVER.min).show(ui.ctx(), |ui| {
ui.allocate_exact_size(OVER.size(), Sense::hover());
});
}
diff --git a/crates/ui-egui/src/page_selection_ui.rs b/crates/ui-egui/src/page_selection_ui.rs
index 0907232f7a..eb97b16b09 100644
--- a/crates/ui-egui/src/page_selection_ui.rs
+++ b/crates/ui-egui/src/page_selection_ui.rs
@@ -96,7 +96,7 @@ impl PageSelectionInput {
.char_limit(16_384)
.hint_text(current.saturating_add(1).to_string()),
);
- field.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), label));
+ field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label));
commit = ui.is_enabled() && !cancel && field.lost_focus();
let pick = crate::icons::button(ui, "chevron-down", 26.0, false, tl!("Select pages"));
chosen = egui::Popup::menu(&pick).show(menu).and_then(|r| r.inner);
diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs
index 4f4197927a..99174a4eba 100644
--- a/crates/ui-egui/src/palette.rs
+++ b/crates/ui-egui/src/palette.rs
@@ -19,6 +19,11 @@ struct Hit {
/// Where `needle` (folded with [`pdfcraft_render::text::fold_case`]) matches `hay`, for ranking.
fn score(hay: &str, needle: &str) -> Option {
+ score_for_direction(hay, needle, crate::i18n::current().rtl())
+}
+
+/// Rank logical text, accepting reordered query words for right-to-left locales.
+fn score_for_direction(hay: &str, needle: &str, rtl: bool) -> Option {
if needle.is_empty() {
return Some(0);
}
@@ -26,10 +31,9 @@ fn score(hay: &str, needle: &str) -> Option {
if let Some(p) = h.find(needle) {
return Some(p);
}
- // A right-to-left language's labels are in display order (their words run the other way)
- // while the query is in typing order, so several words match one by one.
- if crate::i18n::current().rtl() && needle.contains(char::is_whitespace) {
- let first = needle.split_whitespace().map(|word| h.find(word)).try_fold(usize::MAX, |first, p| p.map(|p| first.min(p)));
+ // Match the all-tools search: RTL queries may name the same words in another order.
+ if rtl && needle.contains(char::is_whitespace) {
+ let first = needle.split_whitespace().try_fold(usize::MAX, |first, word| h.find(word).map(|at| first.min(at)));
if let Some(first) = first {
return Some(first);
}
@@ -39,8 +43,9 @@ fn score(hay: &str, needle: &str) -> Option {
needle.chars().all(|c| it.any(|x| x == c)).then_some(100)
}
+/// Draw the command palette and dispatch the chosen command or tool group.
pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
- let palette_rect_id = egui::Id::new("palette_rect");
+ let palette_rect_id = egui::Id::unique("palette_rect");
if !app.palette_open {
return;
}
@@ -111,8 +116,8 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
hits.truncate(12);
let (down, up) = ctx.input(|i| (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp)));
let selected = ctx.data_mut(|data| {
- let id = egui::Id::new("palette_selected");
- let query_id = egui::Id::new("palette_selected_query");
+ let id = egui::Id::unique("palette_selected");
+ let query_id = egui::Id::unique("palette_selected_query");
let previous_query = data.get_temp::(query_id);
let selected =
if previous_query.as_deref() == Some(&q) { data.get_temp::(id).unwrap_or(0) } else { 0 }.min(hits.len().saturating_sub(1));
@@ -143,7 +148,7 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
return;
}
let mut chosen: Option<(Option<&'static str>, Option<&'static str>)> = None;
- let area_response = egui::Area::new(egui::Id::new("palette"))
+ let area_response = egui::Area::new(egui::Id::unique("palette"))
.order(egui::Order::Foreground)
.pivot(Align2::CENTER_TOP)
.fixed_pos(egui::pos2(screen.center().x, screen.top() + 96.0))
@@ -152,13 +157,15 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
ui.set_width(560.0);
ui.horizontal(|ui| {
ui.add(icons::image("search", 18.0, t.text_muted));
- let r = ui.add(
- egui::TextEdit::singleline(&mut app.palette_query)
- .hint_text(tl!("Search tools and commands…"))
- .frame(egui::Frame::NONE)
- .font(theme::regular(15.0))
- .desired_width(f32::INFINITY),
- );
+ let r = ui
+ .add(
+ egui::TextEdit::singleline(&mut app.palette_query)
+ .hint_text(tl!("Search tools and commands…"))
+ .frame(egui::Frame::NONE)
+ .font(theme::regular(15.0))
+ .desired_width(f32::INFINITY),
+ )
+ .accessible_name(tl!("Search tools and commands"));
// Enter runs the selected hit while the field is focused or relinquishing focus.
if (r.has_focus() || r.lost_focus())
&& ui.input(|i| i.key_pressed(egui::Key::Enter))
@@ -181,7 +188,7 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
// Display is translated; matching above already considered both languages.
let shown = crate::i18n::command_label(&h.label);
let shown_detail = tl!(&h.detail).to_string();
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, h.ready, &shown));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, h.ready, &shown));
let fg = if h.ready { t.text } else { t.text_faint };
let detail_font = theme::regular(12.0);
let detail_max = (rect.width() * 0.42).clamp(0.0, 220.0);
@@ -226,9 +233,20 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
#[cfg(test)]
mod search {
- use super::score;
+ use super::{score, score_for_direction};
use pdfcraft_render::text::fold_case;
+ /// Word-order tolerance is RTL-only and still requires every requested word.
+ #[test]
+ fn rtl_palette_queries_accept_reordered_words_without_reversing_text() {
+ let label = "تنظيم الصفحات";
+ assert_eq!(score_for_direction(label, &fold_case("الصفحات تنظيم"), true), Some(0));
+ assert_eq!(score_for_direction(label, &fold_case("تنظيم الصفحات"), true), Some(0));
+ assert_eq!(score_for_direction(label, &fold_case("الصفحات مفقود"), true), None);
+ assert_eq!(score_for_direction(label, &fold_case("الصفحات تنظيم"), false), None);
+ assert_eq!(score_for_direction("Organize Pages", &fold_case("Pages Organize"), false), None);
+ }
+
#[test]
fn commands_match_in_any_case_with_turkish_i() {
assert_eq!(score("İçe aktar", &fold_case("içe")), Some(0));
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index f043a1e999..bcc4123f25 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -108,9 +108,10 @@ fn row_label(ui: &mut egui::Ui, text: &str, font: egui::FontId, color: Color32,
elided
}
+/// Draw one tool-group row with its icon, label, badge and availability hint.
fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(g.label)));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label)));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
let body = rect.translate(press.offset());
@@ -155,6 +156,7 @@ fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup) -> egui::Response {
theme::hand(resp).on_hover_text(tip)
}
+/// Draw the detail view for one tool group, dispatching its commands and tool-specific panels.
fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static ToolGroup) {
if g.id == "edit" {
edit_panel(app, ui, t, g);
@@ -215,7 +217,7 @@ fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static
continue;
}
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(item.label)));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(item.label)));
let ready = item.availability == Availability::Ready;
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
@@ -363,7 +365,7 @@ fn edit_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static
widgets::section_title(ui, tl!("Add content"));
let content: Vec<_> =
g.sections.iter().filter(|s| s.title == "Add content").flat_map(|s| s.items.iter()).filter(|i| i.command != "edit.edit_text").collect();
- let more_id = egui::Id::new("edit_panel_more");
+ let more_id = egui::Id::unique("edit_panel_more");
let more = ui.data(|d| d.get_temp::(more_id)).unwrap_or(false);
let shown = if more { content.len() } else { EDIT_CONTENT_SHOWN.min(content.len()) };
for i in content.iter().take(shown) {
@@ -436,7 +438,7 @@ fn actions_menu(app: &PdfCraftApp, ui: &egui::Ui, resp: &egui::Response, item: &
/// item is muted and says when it ships when hovered.
fn edit_row(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str, availability: Availability) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
let body = rect.translate(press.offset());
@@ -467,7 +469,7 @@ fn stamp_palette(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
for kind in StampKind::ALL.into_iter().filter(|k| k.group() == group) {
let active = app.quick_tool == crate::QuickTool::Stamp(kind);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, kind.label()));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, kind.label()));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, active);
let body = rect.translate(press.offset());
@@ -654,6 +656,7 @@ pub(crate) enum Nav {
Flash(usize, [f32; 4]),
}
+/// Draw the selected right-hand panel and apply its navigation, layer, bookmark or edit actions.
pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Some((index, id)) = app.active_ids() else { return };
@@ -730,6 +733,11 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
if icons::button(ui, "x", 26.0, false, tl!("Close")).clicked() {
close = true;
}
+ if panel == RightPanel::Pages
+ && let Some(c) = page_tools(ui, !modal && view.panel_drag.is_none() && bm_editable)
+ {
+ panel_command = Some(c);
+ }
// Right to left: close, "…", filter, search (Acrobat's order left to right).
if panel == RightPanel::Comments {
panel_command = crate::comments_panel::header_controls(ui, info, view, doc.comments_hidden());
@@ -782,7 +790,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
});
});
ui.add_space(6.0);
- let search_id = egui::Id::new(("bookmark_search", id.0));
+ let search_id = egui::Id::unique(("bookmark_search", id.0));
let mut bookmark_query = ui.data(|d| d.get_temp::(search_id)).unwrap_or_default();
if panel == RightPanel::Bookmarks && !info.outline.is_empty() {
ui.horizontal(|ui| {
@@ -858,7 +866,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
for (li, l) in info.layers.iter().enumerate() {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, l.visible, &l.name));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, l.visible, &l.name));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
let body = rect.translate(press.offset());
@@ -1191,13 +1199,14 @@ fn title_format(item: &OutlineItem, depth: usize, t: &Tokens) -> egui::TextForma
egui::TextFormat { font_id, color, italics: item.italic, ..Default::default() }
}
+/// Draw one bookmark row with expansion, inline rename and the editable context menu.
fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineItem, path: &[usize], siblings: usize, cx: &mut OutlineCtx<'_>) {
if cx.searching && !cx.matches.contains(path) {
return;
}
let depth = path.len() - 1;
let indent = depth as f32 * 16.0;
- let id = ui.id().with(("outline", path));
+ let id = ui.scope_id().with(("outline", path));
if let Some(levels) = cx.expand {
ui.data_mut(|d| d.insert_temp(id, depth < levels));
}
@@ -1253,7 +1262,7 @@ fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineIte
let galley = ui.fonts_mut(|f| f.layout_job(job));
let h = (galley.size().y + 12.0).max(28.0);
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &item.title));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &item.title));
theme::Press::track(ui, &resp).wash(ui, rect, 6, false);
let x0 = rect.left() + indent;
if !item.children.is_empty() {
@@ -1335,6 +1344,38 @@ fn outline_item(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, item: &OutlineIte
}
}
+/// Page tools in the Pages panel's header (#4415): a menu, as Bookmark options is in its panel,
+/// to insert a blank page or pages from a file, rotate, extract and delete. Each runs its
+/// command on the selected pages (the current page when none is), so it does what Pages ▸ …
+/// does; the items say so, apart from the thumbnails' own menu. `enabled` is false while the
+/// document may not be assembled or a dialog is open. Returns the command a click asks for.
+fn page_tools(ui: &mut egui::Ui, enabled: bool) -> Option<&'static str> {
+ let tools: [(&'static str, &str); 6] = [
+ ("page.insert_blank", tl!("Insert a blank page after the selection")),
+ ("page.insert", tl!("Insert pages from a file after the selection…")),
+ ("page.rotate_ccw", tl!("Rotate the selected pages counterclockwise")),
+ ("page.rotate", tl!("Rotate the selected pages clockwise")),
+ ("page.extract", tl!("Extract the selected pages…")),
+ ("page.delete", tl!("Delete the selected pages")),
+ ];
+ let mut picked = None;
+ ui.add_enabled_ui(enabled, |ui| {
+ let more = icons::button(ui, "ellipsis", 26.0, false, tl!("Page tools"));
+ egui::Popup::menu(&more).show(|ui| {
+ ui.set_min_width(260.0);
+ for (id, label) in tools {
+ let Some(spec) = pdfcraft_engine::commands::command(id) else { continue };
+ let item = egui::Button::image_and_text(icons::image(spec.icon, 16.0, ui.visuals().text_color()), label);
+ if ui.add(item).clicked() {
+ picked = Some(id);
+ ui.close();
+ }
+ }
+ });
+ });
+ picked
+}
+
/// Size controls stay above the scroll area, so they remain reachable on long documents.
fn thumbnail_size(ui: &mut egui::Ui, t: &Tokens, view: &mut crate::DocView, enabled: bool) {
let before = view.thumbnail_zoom();
@@ -1441,7 +1482,7 @@ fn pages(ui: &mut egui::Ui, t: &Tokens, info: &DocInfo, view: &mut crate::DocVie
}
let info = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);
let picked = view.selected.contains(&i);
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, picked, info.clone()));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, picked, info.clone()));
// The current page keeps its heavier border; picked pages share its fill.
let selected = i == view.current;
let press = theme::Press::track(ui, &resp);
@@ -1685,7 +1726,7 @@ fn fields(
FieldKind::Unknown => "square",
};
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, selected, &f.name));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &f.name));
// A row scrolled out of view still takes clicks and keyboard focus, but isn't drawn:
// laying out every row of a large form each frame took a tenth of a second a frame.
let visible = ui.is_rect_visible(rect);
@@ -1712,8 +1753,8 @@ fn fields(
for (r, icon, earlier, tip) in
[(up, "chevron-up", true, tl!("Earlier in tab order")), (down, "chevron-down", false, tl!("Later in tab order"))]
{
- let b = ui.interact(r, ui.id().with((&f.name, earlier)), Sense::click());
- b.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{tip}: {}", f.name)));
+ let b = ui.interact(r, ui.scope_id().with((&f.name, earlier)), Sense::click());
+ b.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{tip}: {}", f.name)));
if visible {
let bpress = theme::Press::track(ui, &b);
bpress.wash(ui, r, 4, false);
diff --git a/crates/ui-egui/src/prepare.rs b/crates/ui-egui/src/prepare.rs
index 9f58f5ea5e..2635693676 100644
--- a/crates/ui-egui/src/prepare.rs
+++ b/crates/ui-egui/src/prepare.rs
@@ -151,6 +151,13 @@ pub struct PrepareView {
}
impl PrepareView {
+ /// Cancel a preparation marquee without injecting the terminal pointer release that Escape does.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ cancel_marquee(self);
+ // Unlike Escape, control cancellation never injects a terminal pointer release.
+ self.ignore_release = false;
+ }
+
/// Unique field names: selecting several widgets of one radio group still edits one field.
pub fn names(&self) -> Vec {
let mut names = Vec::new();
@@ -1371,6 +1378,7 @@ const SEPARATORS: [&str; 5] = ["1,234.56", "1234.56", "1.234,56", "1234,56", "1'
const NEGATIVES: [&str; 4] = ["-1,234.01", "1,234.01 (red)", "(1,234.01)", "(1,234.01) (red)"];
const SPECIALS: [&str; 5] = ["Zip Code", "Zip Code + 4", "Phone Number", "Social Security Number", "Arbitrary Mask"];
+/// Draw the field-format editor for the selected category and its options.
fn format_tab(ui: &mut egui::Ui, d: &mut FieldDraft, t: &crate::theme::Tokens) {
let cat = category(&d.format);
let mut picked = cat;
@@ -1483,8 +1491,8 @@ fn format_tab(ui: &mut egui::Ui, d: &mut FieldDraft, t: &crate::theme::Tokens) {
ui.selectable_value(p, pr.to_string(), pr);
}
});
- ui.label(tl!("Custom:"));
- ui.add(crate::widgets::line(p).desired_width(120.0));
+ let custom = ui.label(tl!("Custom:"));
+ ui.add(crate::widgets::line(p).desired_width(120.0)).labelled_by(custom.id);
});
}
Format::Special(n) => {
@@ -1508,8 +1516,8 @@ fn format_tab(ui: &mut egui::Ui, d: &mut FieldDraft, t: &crate::theme::Tokens) {
}
});
ui.horizontal(|ui| {
- ui.label(tl!("Mask:"));
- ui.add(crate::widgets::line(m).desired_width(160.0));
+ let mask = ui.label(tl!("Mask:"));
+ ui.add(crate::widgets::line(m).desired_width(160.0)).labelled_by(mask.id);
});
ui.label(egui::RichText::new(tl!("9 digit, A letter, O letter or digit, X any character")).small().color(t.text_faint));
if idx < 4 {
diff --git a/crates/ui-egui/src/print_ui.rs b/crates/ui-egui/src/print_ui.rs
index fcc8d89d97..5bf8737fcc 100644
--- a/crates/ui-egui/src/print_ui.rs
+++ b/crates/ui-egui/src/print_ui.rs
@@ -300,7 +300,7 @@ pub(crate) struct PrintTasks {
fn listed_printers() -> Vec {
#[cfg(target_arch = "wasm32")]
{
- vec![spool::Printer { name: crate::web_print::BROWSER_PRINTER.to_string(), default: true, two_sided: None }]
+ vec![spool::Printer { name: crate::web_print::BROWSER_PRINTER.to_string(), default: true, two_sided: None, description: String::new() }]
}
#[cfg(not(target_arch = "wasm32"))]
{
@@ -894,15 +894,20 @@ fn driver_options_panel(ui: &mut egui::Ui, d: &mut PrintDraft, t: &Tokens) {
}
egui::Grid::new(("driver-group", n)).num_columns(2).spacing([10.0, 4.0]).show(ui, |ui| {
for o in chunk {
- ui.label(&o.label);
let current = choices.get(&o.key).cloned().unwrap_or_else(|| o.default.clone());
let label_of = |c: &str| o.choices.iter().find(|(k, _)| k == c).map_or_else(|| c.to_string(), |(_, l)| l.clone());
let mut pick = current.clone();
- egui::ComboBox::from_id_salt(("driver-option", &o.key)).selected_text(label_of(¤t)).width(200.0).show_ui(ui, |ui| {
- for (k, l) in &o.choices {
- ui.selectable_value(&mut pick, k.clone(), l.as_str());
- }
- });
+ let option_label = ui.label(&o.label);
+ egui::ComboBox::from_id_salt(("driver-option", &o.key))
+ .selected_text(label_of(¤t))
+ .width(200.0)
+ .show_ui(ui, |ui| {
+ for (k, l) in &o.choices {
+ ui.selectable_value(&mut pick, k.clone(), l.as_str());
+ }
+ })
+ .response
+ .labelled_by(option_label.id);
if pick != current {
if pick == o.default {
choices.remove(&o.key);
@@ -918,13 +923,19 @@ fn driver_options_panel(ui: &mut egui::Ui, d: &mut PrintDraft, t: &Tokens) {
});
}
-fn combo(ui: &mut egui::Ui, id: &str, value: &mut T, choices: &[(T, &str)], width: f32) {
+/// Draw a combo box whose accessible name does not depend on the selected value.
+fn combo(ui: &mut egui::Ui, id: &str, name: &str, value: &mut T, choices: &[(T, &str)], width: f32) {
let shown = choices.iter().find(|c| c.0 == *value).map_or("", |c| c.1);
- egui::ComboBox::from_id_salt(id).selected_text(shown).width(width).show_ui(ui, |ui| {
- for (v, label) in choices {
- ui.selectable_value(value, *v, *label);
- }
- });
+ egui::ComboBox::from_id_salt(id)
+ .selected_text(shown)
+ .width(width)
+ .show_ui(ui, |ui| {
+ for (v, label) in choices {
+ ui.selectable_value(value, *v, *label);
+ }
+ })
+ .response
+ .accessible_name(name);
}
/// Draw the dialog. `thumb` gives a page's thumbnail texture when there is one. Returns
@@ -948,7 +959,7 @@ pub(crate) fn body(
ui.vertical(|ui| {
ui.set_width(470.0);
egui::Grid::new("print-top").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {
- ui.label(tl!("Printer:"));
+ let printer_caption = ui.label(tl!("Printer:"));
let before = d.printer.clone();
// The browser's print dialog sets copies, two-sided printing and colour itself.
let browser = d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER);
@@ -976,7 +987,9 @@ pub(crate) fn body(
if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() {
d.printer_picked = true;
}
- });
+ })
+ .response
+ .labelled_by(printer_caption.id);
let tip = if spool::HAS_PRINTER_PREFERENCES {
tl!("Opens the printer driver's preferences. They are saved for every print from this computer; the copies, two-sided, grayscale and paper chosen here still apply.")
} else {
@@ -1017,10 +1030,10 @@ pub(crate) fn body(
);
ui.end_row();
}
- ui.label(tl!("Copies:"));
+ let copies_label = ui.label(tl!("Copies:"));
ui.add_enabled_ui(!browser, |ui| {
ui.horizontal(|ui| {
- ui.add(egui::DragValue::new(&mut d.copies).range(1..=999));
+ ui.add(egui::DragValue::new(&mut d.copies).range(1..=999)).labelled_by(copies_label.id);
ui.add(widgets::checkbox(&mut d.collate, tl!("Collate")));
ui.add(widgets::checkbox(&mut d.grayscale, tl!("Print in grayscale")));
});
@@ -1034,6 +1047,7 @@ pub(crate) fn body(
combo(
ui,
"duplex",
+ tl!("Two-sided:"),
&mut d.duplex,
&[
(None, tl!("Printer default")),
@@ -1046,14 +1060,16 @@ pub(crate) fn body(
});
ui.end_row();
}
- ui.label(tl!("Paper:"));
+ let paper_label = ui.label(tl!("Paper:"));
let paper_name = PAPERS.get(d.paper).map_or("US Letter", |p| p.0);
let before = d.paper;
egui::ComboBox::from_id_salt("paper").selected_text(tl!(paper_name)).width(260.0).show_ui(ui, |ui| {
for (i, (name, _)) in PAPERS.iter().enumerate() {
ui.selectable_value(&mut d.paper, i, tl!(name));
}
- });
+ })
+ .response
+ .labelled_by(paper_label.id);
// Label stock gets the label layout (cut, turned upright, fitted).
if d.paper != before && d.paper == print::LABEL_PAPER {
d.paper_before_label = Some(before);
@@ -1104,11 +1120,11 @@ pub(crate) fn body(
ui.horizontal(|ui| {
widgets::radio_value(ui, &mut d.which, Which::All, tl!("All"));
widgets::radio_value(ui, &mut d.which, Which::Current, tl!("Current page"));
- widgets::radio_value(ui, &mut d.which, Which::Range, tl!("Pages"));
+ let pages = widgets::radio_value(ui, &mut d.which, Which::Range, tl!("Pages"));
let r = ui.add_enabled(
d.which == Which::Range,
crate::widgets::line(&mut d.range).hint_text(format!("1-{}", sizes.len())).desired_width(110.0),
- );
+ ).labelled_by(pages.id);
if r.gained_focus() {
d.which = Which::Range;
}
@@ -1123,6 +1139,7 @@ pub(crate) fn body(
combo(
ui,
"subset",
+ tl!("More options:"),
&mut d.subset,
&[(Subset::All, tl!("All pages in range")), (Subset::Odd, tl!("Odd pages only")), (Subset::Even, tl!("Even pages only"))],
150.0,
@@ -1157,7 +1174,8 @@ pub(crate) fn body(
if ui.add(widgets::radio(custom, tl!("Custom scale:"))).clicked() {
d.size = SizeMode::Custom(d.custom_scale);
}
- ui.add_enabled(custom, egui::DragValue::new(&mut d.custom_scale).range(1.0..=1000.0).suffix(" %"));
+ ui.add_enabled(custom, egui::DragValue::new(&mut d.custom_scale).range(1.0..=1000.0).suffix(" %"))
+ .accessible_name(tl!("Custom scale"));
});
}
Handling::Label => {
@@ -1170,21 +1188,22 @@ pub(crate) fn body(
}
Handling::Poster => {
ui.horizontal(|ui| {
- ui.label(tl!("Tile scale:"));
- ui.add(egui::DragValue::new(&mut d.poster_scale).range(10.0..=1000.0).suffix(" %"));
- ui.label(tl!("Overlap:"));
- ui.add(egui::DragValue::new(&mut d.overlap).range(0.0..=144.0).suffix(" pt"));
+ let scale_label = ui.label(tl!("Tile scale:"));
+ ui.add(egui::DragValue::new(&mut d.poster_scale).range(10.0..=1000.0).suffix(" %")).labelled_by(scale_label.id);
+ let overlap_label = ui.label(tl!("Overlap:"));
+ ui.add(egui::DragValue::new(&mut d.overlap).range(0.0..=144.0).suffix(" pt")).labelled_by(overlap_label.id);
ui.add(widgets::checkbox(&mut d.cut_marks, tl!("Cut marks")));
});
}
Handling::Multiple => {
ui.horizontal(|ui| {
ui.label(tl!("Pages per sheet:"));
- combo(ui, "per-sheet", &mut d.per_sheet, &[(2, "2"), (4, "4"), (6, "6"), (9, "9"), (16, "16")], 60.0);
+ combo(ui, "per-sheet", tl!("Pages per sheet:"), &mut d.per_sheet, &[(2, "2"), (4, "4"), (6, "6"), (9, "9"), (16, "16")], 60.0);
ui.label(tl!("Page order:"));
combo(
ui,
"order",
+ tl!("Page order:"),
&mut d.order,
&[
(PageOrder::Horizontal, tl!("Horizontal")),
@@ -1212,6 +1231,7 @@ pub(crate) fn body(
combo(
ui,
"booklet",
+ tl!("Booklet subset:"),
&mut d.booklet_subset,
&[
(BookletSubset::BothSides, tl!("Both sides")),
@@ -1221,7 +1241,7 @@ pub(crate) fn body(
130.0,
);
ui.label(tl!("Binding:"));
- combo(ui, "binding", &mut d.binding, &[(Binding::Left, tl!("Left")), (Binding::Right, tl!("Right"))], 80.0);
+ combo(ui, "binding", tl!("Binding:"), &mut d.binding, &[(Binding::Left, tl!("Left")), (Binding::Right, tl!("Right"))], 80.0);
});
}
}
@@ -1237,6 +1257,7 @@ pub(crate) fn body(
combo(
ui,
"content",
+ tl!("Comments & Forms"),
&mut d.content,
&[
(Content::Document, tl!("Document")),
@@ -1257,7 +1278,7 @@ pub(crate) fn body(
ui.add_enabled_ui(d.as_image, |ui| {
ui.label(tl!("Resolution:"));
let mut dpi = d.dpi.round() as u32;
- combo(ui, "print-dpi", &mut dpi, &[(150, "150 dpi"), (300, "300 dpi"), (600, "600 dpi")], 100.0);
+ combo(ui, "print-dpi", tl!("Resolution:"), &mut dpi, &[(150, "150 dpi"), (300, "300 dpi"), (600, "600 dpi")], 100.0);
d.dpi = f64::from(dpi);
});
});
diff --git a/crates/ui-egui/src/protect.rs b/crates/ui-egui/src/protect.rs
index fb48c369de..959877de64 100644
--- a/crates/ui-egui/src/protect.rs
+++ b/crates/ui-egui/src/protect.rs
@@ -86,7 +86,7 @@ fn radio(ui: &mut egui::Ui, t: &Tokens, on: bool, label: &str) -> egui::Response
}
ui.painter().text(egui::pos2(rect.left() + 26.0, rect.center().y), egui::Align2::LEFT_CENTER, tl!(label), theme::regular(14.0), t.text);
let info = tl!(label).to_string();
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, true, on, info.clone()));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, info.clone()));
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}
diff --git a/crates/ui-egui/src/recovery.rs b/crates/ui-egui/src/recovery.rs
index 128e576043..71759c4599 100644
--- a/crates/ui-egui/src/recovery.rs
+++ b/crates/ui-egui/src/recovery.rs
@@ -311,22 +311,32 @@ impl PdfCraftApp {
}
}
- /// Autosave when the interval has passed (called every frame).
- pub(crate) fn autosave_tick(&mut self, ctx: &egui::Context, now: f64) {
+ /// Autosave when the interval has passed (called by `logic`, which also runs while hidden).
+ ///
+ /// The deadline is monotonic (`web_time::Instant`): egui's input clock does not advance
+ /// during a hidden `run_logic`, so using it would stall autosave or restart its interval.
+ pub(crate) fn autosave_tick(&mut self, ctx: &egui::Context, now: web_time::Instant) {
if self.recovery.is_none() {
return;
}
- if now - self.last_autosave >= AUTOSAVE_SECS {
- self.last_autosave = now;
+ // The first tick starts the interval, as the old zero clock did: it does not snapshot
+ // immediately just because no deadline had been recorded yet.
+ let Some(last) = self.last_autosave else {
+ self.last_autosave = Some(now);
+ if self.session.has_pending_autosave() {
+ ctx.request_repaint_after(std::time::Duration::from_secs_f64(AUTOSAVE_SECS));
+ }
+ return;
+ };
+ if now.duration_since(last).as_secs_f64() >= AUTOSAVE_SECS {
+ self.last_autosave = Some(now);
self.autosave_now();
}
// An idle native window has no input-driven frames. Wake it at the existing
// autosave deadline, without keeping clean or already-snapshotted documents awake.
if self.session.has_pending_autosave() {
- let remaining = (self.last_autosave + AUTOSAVE_SECS - now).clamp(0.0, AUTOSAVE_SECS);
- if let Ok(delay) = std::time::Duration::try_from_secs_f64(remaining) {
- ctx.request_repaint_after(delay);
- }
+ let next = self.last_autosave.unwrap_or(now) + std::time::Duration::from_secs_f64(AUTOSAVE_SECS);
+ ctx.request_repaint_after(next.saturating_duration_since(now));
}
}
@@ -469,8 +479,8 @@ mod idle_tests {
assert_eq!(distinct.len(), 200);
}
- fn frame(app: &mut PdfCraftApp, ctx: &egui::Context, now: f64) -> Duration {
- let mut out = ctx.run_ui(egui::RawInput { time: Some(now), ..Default::default() }, |ui| {
+ fn frame(app: &mut PdfCraftApp, ctx: &egui::Context, now: web_time::Instant) -> Duration {
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
app.autosave_tick(ui.ctx(), now);
});
// Headless timer test: acknowledge texture uploads without a GPU backend.
@@ -478,6 +488,8 @@ mod idle_tests {
out.viewport_output[&egui::ViewportId::ROOT].repaint_delay
}
+ /// Check that an idle dirty document schedules a bounded write and autosaves without input, then stops
+ /// waking the window.
#[test]
fn idle_dirty_document_requests_its_deadline_and_writes_without_input() {
let dir = TestDir::new();
@@ -487,22 +499,26 @@ mod idle_tests {
let bytes = app.session.create_blank(200.0, 300.0, 1).unwrap();
let id = app.session.open_new("Untitled.pdf", bytes).unwrap();
let ctx = egui::Context::default();
+ let base = web_time::Instant::now();
+ frame(&mut app, &ctx, base);
let mut delay = Duration::ZERO;
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 15.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(15));
}
assert!(delay > Duration::ZERO && delay <= Duration::from_secs(45), "idle deadline: {delay:?}");
assert!(store.list().is_empty());
- frame(&mut app, &ctx, 60.0);
+ frame(&mut app, &ctx, base + Duration::from_secs(60));
assert_eq!(store.list().len(), 1, "timer frame writes the snapshot without input");
assert!(app.session.get(id).unwrap().dirty, "autosave does not mark the document saved");
assert!(!app.session.has_pending_autosave());
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 61.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(61));
}
assert_eq!(delay, Duration::MAX, "unchanged snapshot needs no periodic wake");
}
+ /// Check that an edit after autosave schedules the next deadline, keeps the old snapshot until then, and
+ /// replaces it on time.
#[test]
fn second_edit_after_autosave_schedules_next_deadline_and_updates_snapshot() {
let dir = TestDir::new();
@@ -512,7 +528,9 @@ mod idle_tests {
let bytes = app.session.create_blank(200.0, 300.0, 1).unwrap();
let id = app.session.open_new("Untitled.pdf", bytes).unwrap();
let ctx = egui::Context::default();
- frame(&mut app, &ctx, 60.0);
+ let base = web_time::Instant::now();
+ frame(&mut app, &ctx, base);
+ frame(&mut app, &ctx, base + Duration::from_secs(60));
let entries = store.list();
assert_eq!(entries.len(), 1);
let key = entries[0].key.clone();
@@ -520,20 +538,20 @@ mod idle_tests {
assert!(!app.session.has_pending_autosave());
let mut delay = Duration::ZERO;
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 61.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(61));
}
assert_eq!(delay, Duration::MAX);
app.session.apply(id, pdfcraft_engine::Edit::SetInfo { key: "Title".into(), value: "Second edit".into() }).unwrap();
assert!(app.session.has_pending_autosave());
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 75.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(75));
}
assert!(delay > Duration::ZERO && delay <= Duration::from_secs(45), "second edit wakes by 120 seconds: {delay:?}");
assert_eq!(store.read(&key).unwrap(), first, "editing does not overwrite the snapshot before its deadline");
- frame(&mut app, &ctx, 119.0);
+ frame(&mut app, &ctx, base + Duration::from_secs(119));
assert_eq!(store.read(&key).unwrap(), first);
- frame(&mut app, &ctx, 120.0);
+ frame(&mut app, &ctx, base + Duration::from_secs(120));
let entries = store.list();
assert_eq!(entries.len(), 1, "the same document replaces its existing snapshot");
assert_eq!(entries[0].key, key);
@@ -545,11 +563,12 @@ mod idle_tests {
assert!(app.session.get(id).unwrap().dirty);
assert!(!app.session.has_pending_autosave());
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 121.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(121));
}
assert_eq!(delay, Duration::MAX, "the second snapshot also lets the window sleep");
}
+ /// Check that a clean document and a document with recovery disabled never schedule an autosave.
#[test]
fn clean_documents_and_disabled_recovery_do_not_schedule_autosave() {
for recovery_enabled in [false, true] {
@@ -565,9 +584,10 @@ mod idle_tests {
app.session.open_new("Unsaved.pdf", bytes).unwrap();
}
let ctx = egui::Context::default();
+ let base = web_time::Instant::now();
let mut delay = Duration::ZERO;
for _ in 0..4 {
- delay = frame(&mut app, &ctx, 15.0);
+ delay = frame(&mut app, &ctx, base + Duration::from_secs(15));
}
assert_eq!(delay, Duration::MAX);
}
diff --git a/crates/ui-egui/src/redact_ui.rs b/crates/ui-egui/src/redact_ui.rs
index 8a48b3f690..6a5bee7ea4 100644
--- a/crates/ui-egui/src/redact_ui.rs
+++ b/crates/ui-egui/src/redact_ui.rs
@@ -388,7 +388,7 @@ pub(crate) fn search_body(ui: &mut egui::Ui, d: &mut SearchDraft, t: &Tokens) ->
widgets::radio_value(ui, &mut d.mode, SearchMode::Phrase, tl!("Single word or phrase"));
let mut enter = false;
ui.add_enabled_ui(d.mode == SearchMode::Phrase, |ui| {
- let r = ui.add(crate::widgets::line(&mut d.text).hint_text(tl!("Text to find")).desired_width(380.0));
+ let r = ui.add(crate::widgets::line(&mut d.text).hint_text(tl!("Text to find")).desired_width(380.0)).accessible_name(tl!("Text to find"));
enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
});
ui.add_space(6.0);
@@ -396,7 +396,8 @@ pub(crate) fn search_body(ui: &mut egui::Ui, d: &mut SearchDraft, t: &Tokens) ->
let mut import = false;
ui.add_enabled_ui(d.mode == SearchMode::Words, |ui| {
egui::ScrollArea::vertical().id_salt("redact-words").max_height(120.0).show(ui, |ui| {
- ui.add(egui::TextEdit::multiline(&mut d.words).hint_text(tl!("One word or phrase per line")).desired_width(380.0).desired_rows(4));
+ ui.add(egui::TextEdit::multiline(&mut d.words).hint_text(tl!("One word or phrase per line")).desired_width(380.0).desired_rows(4))
+ .accessible_name(tl!("Words or phrases to redact"));
});
ui.horizontal(|ui| {
import = ui.button(tl!("Import list…")).clicked();
diff --git a/crates/ui-egui/src/scroll_speed.rs b/crates/ui-egui/src/scroll_speed.rs
index e5a2b453f4..ebb6a34c41 100644
--- a/crates/ui-egui/src/scroll_speed.rs
+++ b/crates/ui-egui/src/scroll_speed.rs
@@ -90,7 +90,13 @@ mod tests {
fn wheel(unit: egui::MouseWheelUnit, dy: f32, command: bool) -> egui::Event {
let modifiers = egui::Modifiers { command, ..egui::Modifiers::NONE };
- egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers }
+ egui::Event::MouseWheel {
+ unit,
+ delta: egui::vec2(0.0, dy),
+ phase: egui::TouchPhase::Move,
+ modifiers,
+ source: egui::MouseWheelSource::Unknown,
+ }
}
#[test]
diff --git a/crates/ui-egui/src/search_ui.rs b/crates/ui-egui/src/search_ui.rs
index 630ca898dc..85a9b46052 100644
--- a/crates/ui-egui/src/search_ui.rs
+++ b/crates/ui-egui/src/search_ui.rs
@@ -11,6 +11,7 @@ use crate::widgets;
/// Glyphs of context shown on each side of a match.
const CONTEXT: usize = 36;
+/// Draw the Search panel with its query, options, progress and clickable result excerpts.
pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: usize) {
crate::widgets::begin_dialog(ui);
let searched = view.texts.len() + view.text_failed.len();
@@ -18,7 +19,8 @@ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: us
find.in_panel = true;
let l = ui.label(egui::RichText::new(tl!("What word or phrase would you like to search for?")).color(t.text_muted));
let r = ui
- .add(crate::widgets::line(&mut find.query).id(egui::Id::new("search-panel-input")).hint_text(tl!("Search")).desired_width(f32::INFINITY))
+ .add(crate::widgets::line(&mut find.query).id(egui::Id::unique("search-panel-input")).hint_text(tl!("Search")).desired_width(f32::INFINITY))
+ .accessible_name(tl!("Search"))
.labelled_by(l.id);
if find.focus {
r.request_focus();
diff --git a/crates/ui-egui/src/side_panels.rs b/crates/ui-egui/src/side_panels.rs
new file mode 100644
index 0000000000..71c3baa648
--- /dev/null
+++ b/crates/ui-egui/src/side_panels.rs
@@ -0,0 +1,522 @@
+//! The side panels around the page: the Tools pane, the rail and the open side panel
+//! ([`crate::RightPanel`]), drawn with craft-ui task panes ([`craft_ui::panes`]).
+//!
+//! On the right, outermost first: the rail, the Tools pane when Preferences ▸ Tools panel side is
+//! Right, then the side panel, then the page. Panes are docked only; their widths are resizable
+//! and saved with the preferences.
+
+use std::ops::RangeInclusive;
+
+use craft_ui::panes::{Edge, PaneContent, PaneHost, PaneLabels, PaneRequest, PaneState, SidePolicy};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::{Mode, PdfCraftApp};
+
+/// Default width of the Tools pane.
+pub const TOOLS_WIDTH: f32 = 272.0;
+/// Default width of the side panel.
+pub const SIDE_WIDTH: f32 = 330.0;
+const TOOLS_RANGE: RangeInclusive = 240.0..=520.0;
+const SIDE_RANGE: RangeInclusive = 260.0..=520.0;
+/// Version of the saved `side_panels` value.
+const VERSION: u64 = 1;
+/// Deepest split tree the old layout migration walks; the old renderer allowed far fewer.
+const MAX_DEPTH: usize = 32;
+
+/// The two panes [`PaneHost`] draws.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Pane {
+ Tools,
+ /// The open [`crate::RightPanel`].
+ Side,
+}
+
+impl Pane {
+ pub fn parse(id: &str) -> Option {
+ match id {
+ "tools" => Some(Self::Tools),
+ "side" => Some(Self::Side),
+ _ => None,
+ }
+ }
+
+ fn range(self) -> RangeInclusive {
+ match self {
+ Self::Tools => TOOLS_RANGE,
+ Self::Side => SIDE_RANGE,
+ }
+ }
+}
+
+/// Preferences ▸ Tools panel side.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ToolsSide {
+ #[default]
+ Left,
+ Right,
+}
+
+/// The saved side panel layout. Which side panel is open stays in `PdfCraftApp::right` and the
+/// Tools pane's open state in `PdfCraftApp::left_open`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SidePanels {
+ /// The one setting that places the Tools pane; [`SidePanels::tools_edge`] is its only reader
+ /// in the layout.
+ pub tools_side: ToolsSide,
+ pub tools_width: f32,
+ pub side_width: f32,
+}
+
+impl Default for SidePanels {
+ fn default() -> Self {
+ Self { tools_side: ToolsSide::Left, tools_width: TOOLS_WIDTH, side_width: SIDE_WIDTH }
+ }
+}
+
+/// A width from settings or automation: finite, within the pane's limits.
+fn clamp_width(pane: Pane, width: f64) -> Option {
+ let range = pane.range();
+ width.is_finite().then(|| (width as f32).clamp(*range.start(), *range.end()))
+}
+
+/// What [`restore`] read from the saved preferences.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Restored {
+ pub panels: SidePanels,
+ /// `None`: not saved; keep the default.
+ pub tools_open: Option,
+ /// An old layout had the side panel closed.
+ pub side_closed: bool,
+}
+
+impl SidePanels {
+ pub fn tools_on_right(&self) -> bool {
+ self.tools_side == ToolsSide::Right
+ }
+
+ fn tools_edge(&self) -> Edge {
+ match self.tools_side {
+ ToolsSide::Left => Edge::Start,
+ ToolsSide::Right => Edge::End,
+ }
+ }
+
+ pub fn width(&self, pane: Pane) -> f32 {
+ match pane {
+ Pane::Tools => self.tools_width,
+ Pane::Side => self.side_width,
+ }
+ }
+
+ fn set_width(&mut self, pane: Pane, width: f32) {
+ let Some(width) = clamp_width(pane, f64::from(width)) else { return };
+ match pane {
+ Pane::Tools => self.tools_width = width,
+ Pane::Side => self.side_width = width,
+ }
+ }
+
+ /// The saved value (`side_panels` in the preferences).
+ pub fn to_json(&self, tools_open: bool) -> Value {
+ json!({
+ "version": VERSION,
+ "tools_side": self.tools_side,
+ "tools_open": tools_open,
+ "tools_width": self.tools_width,
+ "side_width": self.side_width,
+ })
+ }
+}
+
+/// Reads the side panel layout from saved preferences: `side_panels`, else the old `docking`
+/// value, else the defaults. Nothing in it is an error: a malformed or unknown value gives the
+/// defaults.
+pub fn restore(saved: &Value) -> Restored {
+ let defaults = Restored { panels: SidePanels::default(), tools_open: None, side_closed: false };
+ if let Some(value) = saved.get("side_panels") {
+ if value.get("version").and_then(Value::as_u64) != Some(VERSION) {
+ return defaults;
+ }
+ let mut panels = SidePanels::default();
+ if let Some(side) = value.get("tools_side").and_then(|v| serde_json::from_value::(v.clone()).ok()) {
+ panels.tools_side = side;
+ }
+ if let Some(width) = value.get("tools_width").and_then(Value::as_f64).and_then(|w| clamp_width(Pane::Tools, w)) {
+ panels.tools_width = width;
+ }
+ if let Some(width) = value.get("side_width").and_then(Value::as_f64).and_then(|w| clamp_width(Pane::Side, w)) {
+ panels.side_width = width;
+ }
+ return Restored { panels, tools_open: value.get("tools_open").and_then(Value::as_bool), side_closed: false };
+ }
+ let Some(mut restored) = saved.get("docking").and_then(migrate) else { return defaults };
+ if let Some(open) = saved.get("docking_left_open").and_then(Value::as_bool) {
+ restored.tools_open = Some(open);
+ }
+ restored
+}
+
+/// Where the old docking tree held a panel.
+struct Found {
+ /// The panel's group held only it: a tab group or stack of its own.
+ alone: bool,
+ /// The innermost split around the panel's own group.
+ split: Option,
+}
+
+struct Split {
+ horizontal: bool,
+ /// The panel is in the split's second (right or bottom) child.
+ second: bool,
+ /// The split's fixed size, when it is the panel's side.
+ size: Option,
+}
+
+/// The pixel size of `size` (`{"FixedFirst": w}` or `{"FixedSecond": w}`) when it fixes the side
+/// the panel is on.
+fn fixed_size(size: Option<&Value>, second: bool) -> Option {
+ let key = if second { "FixedSecond" } else { "FixedFirst" };
+ size?.get(key)?.as_f64()
+}
+
+fn group_ids(node: &Value) -> Option> {
+ if let Some(tabs) = node.get("Tabs") {
+ return Some(tabs.get("panels")?.as_array()?.iter().filter_map(Value::as_str).collect());
+ }
+ let entries = node.get("Stack")?.get("entries")?.as_array()?;
+ Some(entries.iter().filter_map(|entry| entry.get("panel")?.as_str()).collect())
+}
+
+fn find(node: &Value, panel: &str, depth: usize) -> Option {
+ if depth > MAX_DEPTH {
+ return None;
+ }
+ if let Some(ids) = group_ids(node) {
+ return ids.contains(&panel).then(|| Found { alone: ids.iter().all(|id| *id == panel), split: None });
+ }
+ let split = node.get("Split")?;
+ for (key, second) in [("first", false), ("second", true)] {
+ if let Some(mut found) = split.get(key).and_then(|child| find(child, panel, depth + 1)) {
+ // A panel sharing its group was placed by its group, not by a split.
+ if found.alone && found.split.is_none() {
+ let horizontal = split.get("axis").and_then(Value::as_str) == Some("Horizontal");
+ found.split = Some(Split { horizontal, second, size: fixed_size(split.get("size"), second) });
+ }
+ return Some(found);
+ }
+ }
+ None
+}
+
+/// The old layout's saved place of a closed panel: whether it was on the right and its width.
+fn hidden_place<'a>(old: &'a Value, panel: &str) -> Option<&'a Value> {
+ old.get("hidden")?.as_array()?.iter().find_map(|entry| {
+ let pair = entry.as_array()?;
+ (pair.first()?.as_str()? == panel).then(|| pair.get(1)).flatten()
+ })
+}
+
+fn floating_contains(old: &Value, panel: &str) -> bool {
+ old.get("layout").and_then(|l| l.get("floating")).and_then(Value::as_array).is_some_and(|groups| {
+ groups.iter().any(|group| group.get("panels").and_then(Value::as_array).is_some_and(|ids| ids.iter().any(|id| id.as_str() == Some(panel))))
+ })
+}
+
+/// A panel of the old layout: on the right edge, open, and its width where the layout stated it
+/// in points. A floating or tabbed panel counts as on the left, as the old Tools side reading did.
+fn old_panel(old: &Value, panel: &str) -> (bool, bool, Option) {
+ let root = old.get("layout").and_then(|l| l.get("root"));
+ if let Some(found) = root.and_then(|root| find(root, panel, 0)) {
+ return match found.split {
+ Some(split) if split.horizontal => (split.second, true, split.size),
+ _ => (false, true, None),
+ };
+ }
+ if floating_contains(old, panel) {
+ return (false, true, None);
+ }
+ let Some(place) = hidden_place(old, panel) else { return (false, false, None) };
+ let right = place.get("placement").and_then(|p| p.get("Split")).and_then(Value::as_str) == Some("Right");
+ let left = place.get("placement").and_then(|p| p.get("Split")).and_then(Value::as_str) == Some("Left");
+ let size = if right || left { fixed_size(place.get("size"), right) } else { None };
+ (right, false, size)
+}
+
+/// Reads the old docking layout (craft-ui's `Workspace`) as plain JSON. `None` when it has no
+/// document view, which the old layout always held.
+fn migrate(old: &Value) -> Option {
+ find(old.get("layout")?.get("root")?, "canvas", 0)?;
+ let mut panels = SidePanels::default();
+ let (tools_right, tools_open, tools_width) = old_panel(old, "tools");
+ let (_, side_open, side_width) = old_panel(old, "inspector");
+ if tools_right {
+ panels.tools_side = ToolsSide::Right;
+ }
+ if let Some(width) = tools_width.and_then(|w| clamp_width(Pane::Tools, w)) {
+ panels.tools_width = width;
+ }
+ if let Some(width) = side_width.and_then(|w| clamp_width(Pane::Side, w)) {
+ panels.side_width = width;
+ }
+ Some(Restored { panels, tools_open: Some(tools_open), side_closed: !side_open })
+}
+
+/// What `ui.panel` and `ui.state` report.
+pub fn state(app: &PdfCraftApp) -> Value {
+ let panels = &app.side_panels;
+ json!({
+ "tools_side": panels.tools_side,
+ "tools_open": app.left_open,
+ "tools_width": panels.tools_width,
+ "side_open": app.right.is_some(),
+ "side_panel": app.right.map(|r| format!("{r:?}")),
+ "side_width": panels.side_width,
+ })
+}
+
+/// `ui.panel {panel, open?, width?}` and `ui.dock.reset` (`reset`).
+pub fn command(app: &mut PdfCraftApp, reset: bool, params: &Value) -> Result {
+ if reset {
+ app.side_panels = SidePanels::default();
+ app.left_open = true;
+ return Ok(json!({ "side_panels": state(app) }));
+ }
+ let pane = Pane::parse(params.get("panel").and_then(Value::as_str).ok_or("panel must be \"tools\" or \"side\"")?)
+ .ok_or("panel must be \"tools\" or \"side\"")?;
+ let open = match params.get("open") {
+ None | Some(Value::Null) => None,
+ Some(value) => Some(value.as_bool().ok_or("open must be a boolean")?),
+ };
+ let width = match params.get("width") {
+ None | Some(Value::Null) => None,
+ Some(value) => Some(value.as_f64().and_then(|w| clamp_width(pane, w)).ok_or("width must be a finite number")?),
+ };
+ if let Some(width) = width {
+ app.side_panels.set_width(pane, width);
+ }
+ match (pane, open) {
+ (Pane::Tools, Some(open)) => app.left_open = open,
+ (Pane::Side, Some(true)) if app.right.is_none() => app.toggle_side_panel(),
+ (Pane::Side, Some(false)) if app.right.is_some() => app.choose_right_panel(None),
+ _ => {}
+ }
+ Ok(json!({ "side_panels": state(app) }))
+}
+
+struct Content<'a> {
+ app: &'a mut PdfCraftApp,
+}
+
+impl PaneContent for Content<'_> {
+ fn title(&self, pane: &Pane) -> String {
+ crate::i18n::t(match pane {
+ Pane::Tools => "Tools",
+ Pane::Side => "Inspector",
+ })
+ .to_owned()
+ }
+
+ fn body(&mut self, ui: &mut egui::Ui, pane: &Pane) {
+ match pane {
+ Pane::Tools => crate::panels::left_panel(self.app, ui),
+ Pane::Side => {
+ ui.data_mut(|data| data.insert_temp(egui::Id::unique("pdfcraft-inspector-body"), ui.max_rect()));
+ crate::panels::right_panel(self.app, ui);
+ }
+ }
+ }
+
+ fn default_state(&self, pane: &Pane) -> PaneState {
+ state_of(&self.app.side_panels, *pane)
+ }
+
+ fn size_range(&self, pane: &Pane) -> RangeInclusive {
+ pane.range()
+ }
+
+ fn movable(&self, _pane: &Pane) -> bool {
+ false
+ }
+
+ fn title_bar(&self, _pane: &Pane) -> bool {
+ // Both panels draw their own header and Close.
+ false
+ }
+}
+
+fn state_of(panels: &SidePanels, pane: Pane) -> PaneState {
+ let edge = match pane {
+ Pane::Tools => panels.tools_edge(),
+ Pane::Side => Edge::End,
+ };
+ PaneState::docked(edge, panels.width(pane))
+}
+
+/// The panes that show this frame, outermost first on a shared edge.
+fn open_panes(app: &PdfCraftApp) -> Vec {
+ let mut open = Vec::new();
+ // Read mode hides the tools, not the navigation panes.
+ if app.left_open && app.mode != Mode::Read {
+ open.push(Pane::Tools);
+ }
+ // Home and Combine files have no side panel; the choice is kept for the next document.
+ if app.active.is_some() && app.right.is_some() {
+ open.push(Pane::Side);
+ }
+ open
+}
+
+/// Draws the rail and the open panes. Call after the top bars and before the central panel.
+pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
+ if let Some(panel) = app.right {
+ app.last_right = panel;
+ }
+ // The rail first: it is the outermost panel on the right.
+ if app.active.is_some() {
+ crate::chrome::right_rail(app, ui);
+ }
+ // The expanded All tools view covers the panes.
+ if app.mode == Mode::AllTools && app.all_tools_full {
+ return;
+ }
+ let open = open_panes(app);
+ if open.is_empty() {
+ return;
+ }
+ let t = crate::theme::Tokens::get(ui.ctx());
+ let labels = PaneLabels { resize: crate::i18n::t("Resize panels").to_owned(), ..PaneLabels::default() };
+ let panels = app.side_panels;
+ // Columns: both panes may share the right edge, Tools outermost, as `open` lists them.
+ let output = PaneHost::new(egui::Id::unique("pdfcraft-side-panels"))
+ .policy(SidePolicy::Columns)
+ .f6(false)
+ .labels(labels)
+ .frame(egui::Frame::NONE.fill(t.panel))
+ .body_margin(egui::Margin::ZERO)
+ .show(ui, &open, |pane| Some(state_of(&panels, *pane)), &mut Content { app });
+ for request in output.requests {
+ match request {
+ PaneRequest::Resize(pane, width) => app.side_panels.set_width(pane, width),
+ PaneRequest::Close(Pane::Tools) => app.left_open = false,
+ PaneRequest::Close(Pane::Side) => app.choose_right_panel(None),
+ _ => {}
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tabs(panels: &[&str]) -> Value {
+ json!({"Tabs": {"panels": panels, "active": 0}})
+ }
+
+ fn split(size: Value, first: Value, second: Value) -> Value {
+ json!({"Split": {"axis": "Horizontal", "size": size, "first": first, "second": second}})
+ }
+
+ fn workspace(root: Value, floating: Value, hidden: Value) -> Value {
+ json!({"docking": {"layout": {"root": root, "floating": floating}, "hidden": hidden}})
+ }
+
+ /// The old default layout, as craft-ui 5c874d5 serialized it.
+ fn docked(tools: f64, inspector: f64) -> Value {
+ workspace(
+ split(json!({"FixedFirst": tools}), tabs(&["tools"]), split(json!({"FixedSecond": inspector}), tabs(&["canvas"]), tabs(&["inspector"]))),
+ json!([]),
+ json!([]),
+ )
+ }
+
+ #[test]
+ fn docked_default_keeps_widths() {
+ let restored = restore(&docked(300.0, 400.0));
+ assert_eq!(restored.panels, SidePanels { tools_side: ToolsSide::Left, tools_width: 300.0, side_width: 400.0 });
+ assert_eq!((restored.tools_open, restored.side_closed), (Some(true), false));
+ }
+
+ #[test]
+ fn tools_on_the_right_moves_right() {
+ // `set_tools_on_right` put Tools to the right of the Inspector.
+ let old = workspace(
+ split(json!({"FixedSecond": 330.0}), tabs(&["canvas"]), split(json!({"FixedSecond": 290.0}), tabs(&["inspector"]), tabs(&["tools"]))),
+ json!([]),
+ json!([]),
+ );
+ let restored = restore(&old);
+ assert_eq!(restored.panels.tools_side, ToolsSide::Right);
+ assert_eq!(restored.panels.tools_width, 290.0);
+ // The Inspector's own split fixes Tools' width, not its.
+ assert_eq!(restored.panels.side_width, SIDE_WIDTH);
+ }
+
+ #[test]
+ fn floated_tools_docks_left_and_stays_open() {
+ let old = workspace(
+ split(json!({"FixedSecond": 360.0}), tabs(&["canvas"]), tabs(&["inspector"])),
+ json!([{"panels": ["tools"], "active": 0, "rect": [10.0, 20.0, 300.0, 400.0]}]),
+ json!([]),
+ );
+ let restored = restore(&old);
+ assert_eq!(restored.panels, SidePanels { tools_side: ToolsSide::Left, tools_width: TOOLS_WIDTH, side_width: 360.0 });
+ assert_eq!((restored.tools_open, restored.side_closed), (Some(true), false));
+ }
+
+ #[test]
+ fn tools_tabbed_with_the_inspector_docks_both() {
+ let old = workspace(split(json!({"FixedSecond": 350.0}), tabs(&["canvas"]), tabs(&["inspector", "tools"])), json!([]), json!([]));
+ let restored = restore(&old);
+ assert_eq!(restored.panels.tools_side, ToolsSide::Left);
+ assert_eq!((restored.panels.tools_width, restored.panels.side_width), (TOOLS_WIDTH, SIDE_WIDTH));
+ assert_eq!((restored.tools_open, restored.side_closed), (Some(true), false));
+ }
+
+ #[test]
+ fn a_hidden_inspector_stays_closed_and_hidden_tools_keeps_its_side() {
+ let old = workspace(
+ tabs(&["canvas"]),
+ json!([]),
+ json!([
+ ["inspector", {"floating": null, "anchor": "canvas", "placement": {"Split": "Right"}, "size": {"FixedSecond": 380.0}, "stack": null, "sibling": ["canvas"]}],
+ ["tools", {"floating": null, "anchor": "canvas", "placement": {"Split": "Right"}, "size": {"FixedSecond": 250.0}, "stack": null, "sibling": ["canvas"]}]
+ ]),
+ );
+ let restored = restore(&old);
+ assert_eq!(restored.panels, SidePanels { tools_side: ToolsSide::Right, tools_width: 250.0, side_width: 380.0 });
+ assert_eq!((restored.tools_open, restored.side_closed), (Some(false), true));
+ }
+
+ #[test]
+ fn malformed_values_give_the_defaults() {
+ let defaults = Restored { panels: SidePanels::default(), tools_open: None, side_closed: false };
+ for saved in [
+ json!({"docking": "not a layout"}),
+ json!({"docking": {"layout": [1, 2]}}),
+ json!({"docking": {"layout": {"root": {"Split": {"axis": 3, "size": {"FixedFirst": "wide"}, "first": null}}}}}),
+ json!({"side_panels": {"version": 2, "tools_side": "right"}}),
+ json!({"side_panels": "right"}),
+ ] {
+ let restored = restore(&saved);
+ assert_eq!(restored, defaults, "{saved}");
+ }
+ // Non-finite and out-of-range widths fall back or clamp; an unknown side keeps Left.
+ let restored = restore(&json!({"side_panels": {"version": 1, "tools_side": "up", "tools_width": 9000.0, "side_width": "x"}}));
+ assert_eq!(restored.panels, SidePanels { tools_side: ToolsSide::Left, tools_width: 520.0, side_width: SIDE_WIDTH });
+ // Deep trees are cut off rather than walked.
+ let mut deep = tabs(&["tools"]);
+ for _ in 0..200 {
+ deep = split(json!({"Ratio": 0.5}), tabs(&["canvas"]), deep);
+ }
+ assert_eq!(restore(&workspace(deep, json!([]), json!([]))).panels.tools_side, ToolsSide::Left);
+ }
+
+ #[test]
+ fn saved_value_round_trips() {
+ let panels = SidePanels { tools_side: ToolsSide::Right, tools_width: 300.0, side_width: 410.0 };
+ let restored = restore(&json!({ "side_panels": panels.to_json(false) }));
+ assert_eq!(restored, Restored { panels, tools_open: Some(false), side_closed: false });
+ }
+}
diff --git a/crates/ui-egui/src/sign_ui.rs b/crates/ui-egui/src/sign_ui.rs
index b7d9a136d8..ba1a18d5d0 100644
--- a/crates/ui-egui/src/sign_ui.rs
+++ b/crates/ui-egui/src/sign_ui.rs
@@ -751,6 +751,7 @@ fn error(ui: &mut egui::Ui, err: &Option) {
}
}
+/// Draw the digital-ID chooser, including unusable certificates and removal confirmation.
fn choose(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
title(ui, "Sign with a Digital ID");
ui.label(tl!("Choose the digital ID that you want to use for signing:"));
@@ -763,7 +764,7 @@ fn choose(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
let selected = d.selected == Some(i);
let usable = e.unusable.is_none();
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 52.0), egui::Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, usable, selected, &e.name));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, usable, selected, &e.name));
let fill = if selected {
t.accent_soft
} else if resp.hovered() && usable {
diff --git a/crates/ui-egui/src/system_fonts.rs b/crates/ui-egui/src/system_fonts.rs
index 383dc1e7a9..971683887a 100644
--- a/crates/ui-egui/src/system_fonts.rs
+++ b/crates/ui-egui/src/system_fonts.rs
@@ -503,6 +503,8 @@ mod tests {
std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0")
}
+ /// Check that the first readable fallback candidate wins, so reversing the preference list reverses the
+ /// chosen face.
#[test]
fn the_first_readable_candidate_wins_not_the_last() {
// List order *is* the preference, so a loader that scanned back-to-front would pick a
@@ -517,9 +519,9 @@ mod tests {
let size = |p: &Path| std::fs::metadata(p).expect("bundled face").len();
assert_ne!(size(&inter), size(&mono), "the two fixtures must be tellable apart");
let first = script_fallback(&[inter.clone(), mono.clone()], 'A').expect("Inter covers 'A'");
- assert_eq!(first.font.len() as u64, size(&inter), "the first readable candidate must win");
+ assert_eq!(first.bytes().len() as u64, size(&inter), "the first readable candidate must win");
let reversed = script_fallback(&[mono.clone(), inter], 'A').expect("JetBrains Mono covers 'A'");
- assert_eq!(reversed.font.len() as u64, size(&mono), "reversing the list must reverse the pick");
+ assert_eq!(reversed.bytes().len() as u64, size(&mono), "reversing the list must reverse the pick");
}
#[test]
@@ -663,7 +665,7 @@ mod tests {
// them, as this list produces.
let direct = script_fallback(&devanagari_candidates(), DEVANAGARI_PROBE).expect("the list above resolves");
let cached = devanagari_fallback().expect("devanagari_fallback() resolves where these faces are installed");
- assert_eq!(cached.font.len(), direct.font.len(), "devanagari_fallback() must load the face this list points at, not another script's");
+ assert_eq!(cached.bytes().len(), direct.bytes().len(), "devanagari_fallback() must load the face this list points at, not another script's");
assert_eq!(cached.index, direct.index, "and the same face within that file");
// The advertised last resort is the biggest file on the list and reaches its target through
// a compatibility symlink in `/Library/Fonts`, a folder installers and users may modify — so
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 442cd6d8e1..d9ba466b42 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -3,7 +3,7 @@
use std::sync::Arc;
-use egui::epaint::text::{FontTweak, HintingTarget, SmoothHinting};
+use egui::epaint::text::{FallbackAlign, FontTweak, HintingTarget, SmoothHinting};
use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Rect, Response, Stroke, Vec2, Visuals};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
@@ -122,8 +122,9 @@ impl Tokens {
}
}
+ /// Return the cached theme tokens, falling back to the light palette before the first apply.
pub fn get(ctx: &egui::Context) -> Self {
- ctx.data(|d| d.get_temp::(egui::Id::new("pdfcraft-theme"))).unwrap_or_else(|| Self::for_kind(ThemeKind::Light))
+ ctx.data(|d| d.get_temp::(egui::Id::unique("pdfcraft-theme"))).unwrap_or_else(|| Self::for_kind(ThemeKind::Light))
}
pub fn dark(&self) -> bool {
@@ -230,14 +231,34 @@ pub const SYSTEM_HEBREW_FALLBACK: &str = "system-hebrew-fallback";
/// The name of the installed Hangul (Korean) face [`installed_font_definitions`] may add.
pub const SYSTEM_HANGUL_FALLBACK: &str = "system-hangul-fallback";
+/// Which installed face an interface language needs, given whether the build embeds a `Hans`
+/// face.
+///
+/// A bundled `Hans` face serves Simplified Chinese, so the installed face stays last there. It
+/// cannot serve Traditional Chinese: a Traditional interface keeps an installed `Hant` face
+/// before the Japanese faces even when a Simplified-only face is embedded, or Traditional-only
+/// characters would fall through to a Japanese face first.
+#[cfg(not(target_arch = "wasm32"))]
+fn installed_fallback_need(cjk: CjkPreference, has_embedded_hans: bool) -> crate::system_fonts::Need {
+ use crate::system_fonts::Need;
+ match cjk {
+ CjkPreference::SimplifiedChinese if has_embedded_hans => Need::Other,
+ CjkPreference::SimplifiedChinese => Need::Hans,
+ CjkPreference::TraditionalChinese => Need::Hant,
+ CjkPreference::Default => Need::Other,
+ }
+}
+
/// What [`install_fonts_for`] installs: [`font_definitions_for`], then, on desktop, one face
/// already installed on this machine. It only draws characters no embedded face has.
///
-/// - In a Chinese interface built without a `Hans` craft-fonts face (every release so far,
-/// #826), it is a Chinese system face (Microsoft YaHei, PingFang, …), placed before the
-/// Japanese craft-fonts faces: they lack hundreds of the catalog's characters (欢, 导, 签, …),
-/// and one line drawn from two faces with different vertical metrics would not sit on one
-/// baseline.
+/// - In a Simplified Chinese interface built without an embedded `Hans` face (#826), it is a
+/// Simplified Chinese system face (Microsoft YaHei, PingFang SC, …), placed before the Japanese
+/// craft-fonts faces: they lack hundreds of the catalog's characters (欢, 导, 签, …), and one
+/// line drawn from two faces with different vertical metrics would not sit on one baseline.
+/// - A Traditional Chinese interface always uses an installed `Hant` face before the Japanese
+/// faces, even when a Simplified-only `Hans` face is embedded: that face cannot supply
+/// Traditional-only characters (說, 體, …).
/// - Otherwise it is the last fallback of every family (an Arabic file name in a build without
/// craft-fonts).
///
@@ -268,12 +289,7 @@ pub fn installed_font_definitions(cjk: CjkPreference) -> FontDefinitions {
stack.push(name.to_owned());
}
}
- let need = match cjk {
- _ if !pdfcraft_fonts::ui_chinese_fonts().is_empty() => Need::Other,
- CjkPreference::SimplifiedChinese => Need::Hans,
- CjkPreference::TraditionalChinese => Need::Hant,
- CjkPreference::Default => Need::Other,
- };
+ let need = installed_fallback_need(cjk, !pdfcraft_fonts::ui_chinese_fonts().is_empty());
if let Some(data) = fallback(need) {
fonts.font_data.insert(SYSTEM_FALLBACK.to_owned(), data);
let japanese: Vec = pdfcraft_fonts::ui_japanese_fonts().iter().map(|f| f.name()).collect();
@@ -323,37 +339,14 @@ fn primary_font_tweak(platform: FontPolicyPlatform, name: &str) -> FontTweak {
tweak
}
-/// A face's vertical metrics in em, as egui reads them: skrifa's ascent, descent (negative) and
-/// line gap at the default location. `None` when the face doesn't parse.
-fn vertical_metrics(bytes: &[u8], index: u32) -> Option<[f32; 3]> {
- use skrifa::MetadataProvider as _;
- let font = skrifa::FontRef::from_index(bytes, index).ok()?;
- let m = font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
- let em = f32::from(m.units_per_em);
- let metrics = [m.ascent / em, m.descent / em, m.leading / em];
- (em > 0.0 && metrics.iter().all(|v| v.is_finite())).then_some(metrics)
-}
-
-/// How far below the primary face's baseline egui draws a fallback face's, in em of the font size
-/// (negative: above). egui centres the fallback's line box (ascent − descent + gap) on the
-/// primary's rather than lining up their baselines, so the baseline moves by half the difference
-/// of ascent + descent, less half the difference of the line gaps (epaint `text_layout`).
-fn baseline_drop(primary: [f32; 3], fallback: [f32; 3]) -> f32 {
- let [pa, pd, pg] = primary;
- let [a, d, g] = fallback;
- ((a + d) - (pa + pd) + pg - g) / 2.0
-}
-
-/// `data` with its glyphs moved onto Inter's baseline (#1676). Without this, Chinese next to Latin
-/// in one label sits higher or lower than the Latin by a few percent of the font size, depending on
-/// the installed Chinese face (PingFang, Microsoft JhengHei, SimSun…). Inter is the first face of
-/// every proportional family; the monospace family's JetBrains Mono differs from it by 0.004 em,
-/// well under a pixel. A face that doesn't parse is left as it is (egui will skip it anyway).
+/// `data` with its glyphs placed on the row's baseline (#1676). epaint 0.37 otherwise centres a
+/// fallback face's line box on the primary's, so Chinese next to Latin in one label sits higher or
+/// lower than the Latin by a few percent of the font size, depending on the installed or embedded
+/// face (PingFang, Microsoft JhengHei, LXGW WenKai Lite…). `FallbackAlign::Baseline` makes epaint
+/// position every face's glyphs from the primary face's ascent, which is exactly the existing
+/// baseline-alignment intent without metric-derived offsets that go stale across egui versions.
pub(crate) fn on_interface_baseline(mut data: FontData) -> FontData {
- let primary = vertical_metrics(pdfcraft_fonts::INTER_REGULAR, 0);
- if let (Some(primary), Some(fallback)) = (primary, vertical_metrics(&data.font, data.index)) {
- data.tweak.y_offset_factor = -baseline_drop(primary, fallback);
- }
+ data.tweak.fallback_align = FallbackAlign::Baseline;
data
}
@@ -429,13 +422,15 @@ pub fn semibold(size: f32) -> FontId {
FontId::new(size, FontFamily::Name("semibold".into()))
}
+/// Install the palette, widget styling, text sizes and right-to-left flag for the chosen theme.
pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
// Keep the native window inherited. A concrete egui theme pins macOS's
// NSWindow appearance and prevents winit from delivering ThemeChanged.
// Our saved choice owns the palette; both egui branches receive it below.
ctx.set_theme(egui::ThemePreference::System);
+ let rtl = crate::i18n::current().rtl();
let t = Tokens::for_kind(kind);
- ctx.data_mut(|d| d.insert_temp(egui::Id::new("pdfcraft-theme"), t));
+ ctx.data_mut(|d| d.insert_temp(egui::Id::unique("pdfcraft-theme"), t));
let mut v = if t.dark() { Visuals::dark() } else { Visuals::light() };
v.panel_fill = t.panel;
v.window_fill = t.card;
@@ -477,6 +472,9 @@ pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
}
ctx.set_visuals(v);
ctx.global_style_mut(|s| {
+ // RTL languages mirror stock chrome (menus, combo boxes, scroll bars, headers).
+ // Labels still get their paragraph direction explicitly from `bidi::ui_direction`.
+ s.right_to_left = rtl;
s.spacing.item_spacing = egui::vec2(8.0, 6.0);
s.spacing.button_padding = egui::vec2(10.0, 5.0);
s.spacing.menu_margin = egui::Margin::same(6);
@@ -493,6 +491,30 @@ pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
let style = ctx.global_style();
ctx.set_style_of(egui::Theme::Light, style.clone());
ctx.set_style_of(egui::Theme::Dark, style);
+ ctx.data_mut(|d| d.insert_temp(direction_key(), rtl));
+}
+
+/// Return the stable egui id holding the current right-to-left style flag.
+fn direction_key() -> egui::Id {
+ egui::Id::unique("pdfcraft-style-right-to-left")
+}
+
+/// Keep stock egui chrome's direction in step with the drawing language, after a language
+/// change as well as at startup. Setting a flag on both concrete themes is cheap; this avoids
+/// rebuilding the whole visuals and font state every frame.
+pub fn sync_direction(ctx: &egui::Context) {
+ let rtl = crate::i18n::current().rtl();
+ let changed = ctx.data_mut(|d| {
+ if d.get_temp::(direction_key()) == Some(rtl) {
+ false
+ } else {
+ d.insert_temp(direction_key(), rtl);
+ true
+ }
+ });
+ if changed {
+ ctx.all_styles_mut(|s| s.right_to_left = rtl);
+ }
}
/// WCAG 2 contrast ratio between two opaque colours.
@@ -520,6 +542,21 @@ pub fn readable(color: Color32, background: Color32, text: Color32) -> Color32 {
mod tests {
use super::*;
+ /// Arabic and Kurdish switch stock chrome to mirror from the right; English switches it
+ /// back. This is the `Style::right_to_left` half of the explicit RTL policy.
+ #[test]
+ fn arabic_chrome_is_right_to_left_after_the_language_changes() {
+ let previous = crate::i18n::current();
+ let ctx = egui::Context::default();
+ crate::i18n::set_current(crate::i18n::Lang::from_code("ar").expect("registered language"));
+ apply(&ctx, ThemeKind::Light);
+ assert!(ctx.global_style().right_to_left);
+ crate::i18n::set_current(crate::i18n::Lang::EN);
+ sync_direction(&ctx);
+ assert!(!ctx.global_style().right_to_left);
+ crate::i18n::set_current(previous);
+ }
+
/// #3193: a bookmark's own colour is kept where it reads on the panel, and moved towards the
/// theme's text colour where it doesn't (dark blue on the dark panel), never past it.
#[test]
@@ -641,18 +678,16 @@ mod tests {
)
}
- /// The baseline of each glyph of `text` laid out by egui at `size` points, in points from the
- /// top of the row: its position plus its face's `y_offset_factor`, as epaint draws it.
+ /// The y position of each glyph of `text` laid out by egui at `size` points, in points from
+ /// the top of the row.
fn baselines(fallback: FontData, size: f32, text: &str) -> Vec {
- let factor = fallback.tweak.y_offset_factor;
let mut defs = FontDefinitions::empty();
defs.font_data.insert("Inter".into(), Arc::new(FontData::from_static(pdfcraft_fonts::INTER_REGULAR)));
defs.font_data.insert("fallback".into(), Arc::new(fallback));
defs.families.insert(FontFamily::Proportional, vec!["Inter".into(), "fallback".into()]);
let mut fonts = Fonts::new(TextOptions::default(), defs);
let g = galley(&mut fonts, FontFamily::Proportional, size, 1.0, text);
- let inter_has = |c: char| c.is_ascii();
- g.rows[0].glyphs.iter().map(|gl| gl.pos.y + if inter_has(gl.chr) { 0.0 } else { size * factor }).collect()
+ g.rows[0].glyphs.iter().map(|gl| gl.pos.y).collect()
}
#[test]
@@ -664,14 +699,23 @@ mod tests {
// As egui lays it out by itself, DŽ sits ~4 pt off H's baseline: the bug (#1676).
let raw = baselines(FontData::from_static(dancing), size, "HDŽ");
assert!((raw[1] - raw[0]).abs() > 3.0, "the test fonts must differ: {raw:?}");
- let drop = baseline_drop(vertical_metrics(pdfcraft_fonts::INTER_REGULAR, 0).unwrap(), vertical_metrics(dancing, 0).unwrap());
- assert!((raw[1] - raw[0] - size * drop).abs() <= 1.0, "baseline_drop predicts egui: {raw:?} vs {drop}");
- // On the interface baseline, to the pixel.
+ // `FallbackAlign::Baseline` puts every face on the same baseline, to the pixel.
let aligned = baselines(on_interface_baseline(FontData::from_static(dancing)), size, "HDŽ");
assert!((aligned[1] - aligned[0]).abs() <= 1.0, "{aligned:?}");
- // A face that doesn't parse is left alone rather than guessed at.
- assert_eq!(on_interface_baseline(FontData::from_static(b"not a font")).tweak, FontTweak::default());
- assert_eq!(vertical_metrics(b"", 0), None);
+ assert_eq!(on_interface_baseline(FontData::from_static(dancing)).tweak.fallback_align, FallbackAlign::Baseline);
+ }
+
+ /// The policy only exists on native platforms (`installed_font_definitions` has no installed
+ /// faces on wasm), so the test must not use it in a wasm test build.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn traditional_chinese_keeps_an_installed_face_when_hans_is_embedded() {
+ use crate::system_fonts::Need;
+ assert_eq!(installed_fallback_need(CjkPreference::SimplifiedChinese, true), Need::Other);
+ assert_eq!(installed_fallback_need(CjkPreference::SimplifiedChinese, false), Need::Hans);
+ assert_eq!(installed_fallback_need(CjkPreference::TraditionalChinese, true), Need::Hant);
+ assert_eq!(installed_fallback_need(CjkPreference::TraditionalChinese, false), Need::Hant);
+ assert_eq!(installed_fallback_need(CjkPreference::Default, true), Need::Other);
}
#[test]
diff --git a/crates/ui-egui/src/wheel_boost.rs b/crates/ui-egui/src/wheel_boost.rs
index b9d474565e..10ccbbbaa7 100644
--- a/crates/ui-egui/src/wheel_boost.rs
+++ b/crates/ui-egui/src/wheel_boost.rs
@@ -313,11 +313,23 @@ mod tests {
}
fn wheel(unit: egui::MouseWheelUnit, dx: f32, dy: f32) -> egui::Event {
- egui::Event::MouseWheel { unit, delta: egui::vec2(dx, dy), phase: egui::TouchPhase::Move, modifiers: egui::Modifiers::NONE }
+ egui::Event::MouseWheel {
+ unit,
+ delta: egui::vec2(dx, dy),
+ phase: egui::TouchPhase::Move,
+ modifiers: egui::Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
+ }
}
fn shifted(unit: egui::MouseWheelUnit, dx: f32, dy: f32) -> egui::Event {
- egui::Event::MouseWheel { unit, delta: egui::vec2(dx, dy), phase: egui::TouchPhase::Move, modifiers: egui::Modifiers::SHIFT }
+ egui::Event::MouseWheel {
+ unit,
+ delta: egui::vec2(dx, dy),
+ phase: egui::TouchPhase::Move,
+ modifiers: egui::Modifiers::SHIFT,
+ source: egui::MouseWheelSource::Unknown,
+ }
}
#[test]
@@ -379,6 +391,7 @@ mod tests {
assert_eq!(input.page, egui::vec2(-1.0, 0.0));
}
+ /// Check that NaN, zero, negative or infinite scales and non-wheel events add nothing.
#[test]
fn invalid_scales_and_events_contribute_nothing() {
use egui::MouseWheelUnit::Line;
@@ -386,8 +399,13 @@ mod tests {
let input = accumulate(&[wheel(Line, 0.0, -1.0)], bad, false);
assert_eq!(input.line, egui::Vec2::ZERO, "line scale {bad}");
}
- let zoom =
- egui::Event::MouseWheel { unit: Line, delta: egui::vec2(0.0, -1.0), phase: egui::TouchPhase::Move, modifiers: egui::Modifiers::COMMAND };
+ let zoom = egui::Event::MouseWheel {
+ unit: Line,
+ delta: egui::vec2(0.0, -1.0),
+ phase: egui::TouchPhase::Move,
+ modifiers: egui::Modifiers::COMMAND,
+ source: egui::MouseWheelSource::Unknown,
+ };
let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let input = accumulate(&[zoom, key, wheel(Line, 0.0, f32::NAN)], 100.0, false);
assert_eq!(input, FrameInput::default());
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 2d1f639965..01cab03314 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -27,12 +27,12 @@ fn dialog_frame(ctx: &egui::Context) -> egui::Frame {
/// A modal with the card fill, a 10-point corner and room around its contents.
pub fn modal(ctx: &egui::Context, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Modal {
- egui::Modal::new(egui::Id::new(id)).frame(dialog_frame(ctx))
+ egui::Modal::new(egui::Id::unique(id)).frame(dialog_frame(ctx))
}
/// Show [`modal`], outline its controls, and remember the card rect for layout checks.
pub fn show_modal(ctx: &egui::Context, id: &str, content: impl FnOnce(&mut egui::Ui) -> R) -> egui::ModalResponse {
- let stored = egui::Id::new(id);
+ let stored = egui::Id::unique(id);
modal(ctx, id).show(ctx, |ui| {
begin_dialog(ui);
let inner = content(ui);
@@ -111,7 +111,7 @@ pub fn mode_tab(ui: &mut egui::Ui, label: &str, active: bool) -> Response {
let font = if active { theme::semibold(13.5) } else { theme::medium(13.5) };
let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);
let (rect, resp) = ui.allocate_exact_size(vec2(w + 22.0, 48.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), active, label));
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), active, label));
let press = theme::Press::track(ui, &resp);
let well = rect.shrink2(vec2(2.0, 9.0));
if active {
@@ -140,21 +140,26 @@ pub fn pill_button(ui: &mut egui::Ui, label: &str, primary: bool) -> Response {
pub fn pill_button_marked(ui: &mut egui::Ui, label: &str, primary: bool, marked: bool) -> Response {
let t = Tokens::get(ui.ctx());
let font = theme::medium(12.5);
- let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);
+ let text_color = if primary { Color32::WHITE } else { t.text };
+ // Dialog buttons are translated UI text: an explicit RTL base keeps an Arabic label right
+ // to left even when its first strong character is Latin or a placeholder.
+ let label_galley = crate::bidi::layout_ui(ui, label.to_owned(), font, text_color);
+ let w = label_galley.size().x;
let (rect, resp) = ui.allocate_exact_size(vec2(w + 26.0, 28.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
let press = theme::Press::track(ui, &resp);
- let (fill, stroke, text) = if primary {
- (press.fill(t.accent, t.accent_text, t.accent.lerp_to_gamma(Color32::BLACK, 0.22)), Stroke::NONE, Color32::WHITE)
+ let (fill, stroke) = if primary {
+ (press.fill(t.accent, t.accent_text, t.accent.lerp_to_gamma(Color32::BLACK, 0.22)), Stroke::NONE)
} else {
- (press.fill(t.card, t.hover, t.pressed), Stroke::new(1.0, t.border), t.text)
+ (press.fill(t.card, t.hover, t.pressed), Stroke::new(1.0, t.border))
};
ui.painter().rect(rect, CornerRadius::same(14), fill, stroke, egui::StrokeKind::Inside);
if marked {
resp.request_focus();
ui.painter().rect_stroke(rect.expand(2.0), CornerRadius::same(16), Stroke::new(2.0, t.accent), egui::StrokeKind::Outside);
}
- ui.painter().text(rect.translate(press.offset()).center(), Align2::CENTER_CENTER, label, font, text);
+ let body = rect.translate(press.offset());
+ ui.painter().galley(body.center() - label_galley.size() / 2.0, label_galley, text_color);
theme::hand(resp)
}
@@ -167,14 +172,15 @@ pub fn ghost_button(ui: &mut egui::Ui, icon: &str, label: &str) -> Response {
pub fn ghost_button_sized(ui: &mut egui::Ui, icon: &str, label: &str, height: f32) -> Response {
let t = Tokens::get(ui.ctx());
let font = theme::medium(13.0);
- let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);
+ let label_galley = crate::bidi::layout_ui(ui, label.to_owned(), font, t.text);
+ let w = label_galley.size().x;
let (rect, resp) = ui.allocate_exact_size(vec2(w + 38.0, height), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
let press = theme::Press::track(ui, &resp);
press.wash(ui, rect, 6, false);
let body = rect.translate(press.offset());
icons::paint(ui, Rect::from_min_size(body.min + vec2(6.0, (height - 18.0) / 2.0), vec2(18.0, 18.0)), icon, 17.0, t.icon);
- ui.painter().text(body.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, label, font, t.text);
+ ui.painter().galley(body.left_center() + vec2(30.0, -label_galley.size().y / 2.0), label_galley, t.text);
theme::hand(resp)
}
@@ -182,7 +188,7 @@ pub fn ghost_button_sized(ui: &mut egui::Ui, icon: &str, label: &str, height: f3
pub fn search_box(ui: &mut egui::Ui, placeholder: &str, width: f32) -> Response {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(width, 32.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), placeholder));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), placeholder));
let press = theme::Press::track(ui, &resp);
let fill = press.fill(t.field, t.hover, t.pressed);
let edge = t.border.lerp_to_gamma(t.text_muted, press.hover * 0.35);
@@ -197,6 +203,7 @@ pub fn search_box(ui: &mut egui::Ui, placeholder: &str, width: f32) -> Response
let text_left = (rect.left() + 34.0).min(text_right);
let text_rect = Rect::from_min_max(egui::pos2(text_left, rect.top()), egui::pos2(text_right, rect.bottom()));
let mut job = egui::text::LayoutJob::simple_singleline(placeholder.to_owned(), theme::regular(13.0), t.text_faint);
+ job.direction = crate::bidi::ui_direction();
job.wrap = egui::text::TextWrapping { max_width: text_rect.width(), max_rows: 1, break_anywhere: true, ..Default::default() };
let text = ui.fonts_mut(|f| f.layout_job(job));
let elided = text.elided;
@@ -280,11 +287,20 @@ fn toggle<'a>(widget: impl egui::Widget + 'a, radius: Option) -> impl egui::
}
}
+/// Draw a panel section heading with explicit paragraph direction and letter spacing.
pub fn section_title(ui: &mut egui::Ui, text: &str) {
let t = Tokens::get(ui.ctx());
ui.add_space(10.0);
// Section titles across every panel go through here, so one translation point covers them.
- ui.label(egui::RichText::new(crate::i18n::upper_label(text)).font(theme::semibold(10.5)).color(t.text_faint).extra_letter_spacing(0.6));
+ // The paragraph direction is explicit: an Arabic title beginning with Latin or a placeholder
+ // must not inherit a left-to-right base from its first strong character.
+ let mut job = egui::text::LayoutJob::simple(crate::i18n::upper_label(text), theme::semibold(10.5), t.text_faint, ui.available_width().max(0.0));
+ job.direction = crate::bidi::ui_direction();
+ if let Some(section) = job.sections.first_mut() {
+ section.format.extra_letter_spacing = 0.6;
+ }
+ let galley = ui.painter().layout_job(job);
+ ui.add(egui::Label::new(egui::WidgetText::Galley(galley)).selectable(false));
ui.add_space(2.0);
}
@@ -292,12 +308,35 @@ pub fn section_title(ui: &mut egui::Ui, text: &str) {
/// at most `max_width` wide: a long file name or path stays inside its row (#425).
pub fn row_text(ui: &egui::Ui, pos: egui::Pos2, text: impl Into, font: egui::FontId, color: Color32, max_width: f32) {
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), font, color);
+ // A file name or path: an Arabic name keeps its extension at the visual end, as in the tab.
+ job.direction = egui::epaint::text::TextDirection::LeftToRight;
job.wrap = egui::text::TextWrapping::truncate_at_width(max_width.max(0.0));
let galley = ui.painter().layout_job(job);
let rect = Align2::LEFT_CENTER.anchor_size(pos, galley.size());
ui.painter().galley(rect.min, galley, color);
}
+/// A wrapping label for a file name or folder path, laid out explicitly left to right so an
+/// Arabic name keeps `.pdf` at the end. The accessibility name is the logical text.
+pub fn label_ltr(ui: &mut egui::Ui, text: impl Into, font: egui::FontId, color: Color32) -> Response {
+ let mut job = egui::text::LayoutJob::simple(text.into(), font, color, ui.available_width().max(0.0));
+ job.direction = egui::epaint::text::TextDirection::LeftToRight;
+ let galley = ui.painter().layout_job(job);
+ ui.add(egui::Label::new(egui::WidgetText::Galley(galley)).selectable(false))
+}
+
+/// [`label_ltr`] for one table row: the name is cut with an ellipsis instead of wrapping onto a
+/// second row. The logical text remains the accessibility name.
+pub fn label_ltr_truncated(ui: &mut egui::Ui, text: impl Into, font: egui::FontId, color: Color32) -> Response {
+ let text = text.into();
+ let width = ui.available_width().max(0.0);
+ let mut job = egui::text::LayoutJob::simple_singleline(text, font, color);
+ job.direction = egui::epaint::text::TextDirection::LeftToRight;
+ job.wrap = egui::text::TextWrapping::truncate_at_width(width);
+ let galley = ui.painter().layout_job(job);
+ ui.add(egui::Label::new(egui::WidgetText::Galley(galley)).selectable(false))
+}
+
/// Text wrapped to the available width, for text people write (comments, replies). A paragraph
/// in a right-to-left script (Persian, Arabic, Hebrew) reads right to left and sits against the
/// right edge ([`crate::bidi::wrap`]); text without one is an ordinary wrapping label.
@@ -312,11 +351,11 @@ pub fn wrapped_text(ui: &mut egui::Ui, text: &str, font: egui::FontId, color: Co
}
let width = ui.available_width().max(1.0);
let lines = wrapped_lines(ui, text, &font, width, truncate);
- let galleys: Vec<_> = lines.iter().map(|line| (line.rtl, ui.painter().layout_no_wrap(line.text.clone(), font.clone(), color))).collect();
+ let galleys: Vec<_> = lines.iter().map(|line| (line.rtl, wrapped_line_galley(ui, line, &font, color))).collect();
let height = galleys.iter().map(|(_, g)| g.size().y).sum();
let (rect, resp) = ui.allocate_exact_size(vec2(width, height), Sense::hover());
// Painted text only: the accessibility name keeps the logical order.
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, text));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text));
let mut y = rect.top();
for (rtl, galley) in galleys {
let x = if rtl { rect.right() - galley.size().x } else { rect.left() };
@@ -327,6 +366,15 @@ pub fn wrapped_text(ui: &mut egui::Ui, text: &str, font: egui::FontId, color: Co
resp
}
+/// One wrapped line laid out with its own paragraph direction. A line beginning with a Latin
+/// word inside a right-to-left comment is still part of that paragraph, so its base direction
+/// must stay right to left; `Auto` would follow the Latin word instead.
+fn wrapped_line_galley(ui: &egui::Ui, line: &crate::bidi::Line, font: &egui::FontId, color: Color32) -> std::sync::Arc {
+ let mut job = egui::text::LayoutJob::simple_singleline(line.text.clone(), font.clone(), color);
+ job.direction = if line.rtl { egui::epaint::text::TextDirection::RightToLeft } else { egui::epaint::text::TextDirection::LeftToRight };
+ ui.painter().layout_job(job)
+}
+
const ELLIPSIS: &str = "\u{2026}";
/// Wrapped right-to-left text kept between frames. Wrapping measures many candidate lines, so
@@ -351,7 +399,7 @@ fn wrapped_lines(ui: &egui::Ui, text: &str, font: &egui::FontId, width: f32, tru
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(text, font, width.to_bits(), ui.ctx().pixels_per_point().to_bits(), truncate).hash(&mut hasher);
let key = hasher.finish();
- let cache_id = egui::Id::new("pdfcraft-rtl-wrap-cache");
+ let cache_id = egui::Id::unique("pdfcraft-rtl-wrap-cache");
if let Some(hit) = ui.ctx().data_mut(|d| d.get_temp_mut_or_default::(cache_id).lines.get(&key).cloned()) {
return hit;
}
@@ -368,12 +416,9 @@ fn wrapped_lines(ui: &egui::Ui, text: &str, font: &egui::FontId, width: f32, tru
if truncate && (lines.len() > 1 || cut) {
lines.truncate(1);
if let Some(line) = lines.first_mut() {
- // The ellipsis goes where the line's reading ends: the left of a right-to-left line.
- if line.rtl {
- line.text.insert_str(0, ELLIPSIS);
- } else {
- line.text.push_str(ELLIPSIS);
- }
+ // The ellipsis goes where the line's reading ends, in logical text: epaint places it
+ // on the left for a right-to-left line and on the right for a left-to-right one.
+ line.text.push_str(ELLIPSIS);
}
}
let lines: std::sync::Arc<[crate::bidi::Line]> = lines.into();
@@ -400,9 +445,9 @@ pub fn toast(app: &mut PdfCraftApp, ctx: &egui::Context) {
let t = Tokens::get(ctx);
let screen = ctx.content_rect();
// Above the progress notice while a job runs.
- let card = if app.progress_notice.is_some() { ctx.data(|d| d.get_temp::(egui::Id::new(PROGRESS_HEIGHT))).unwrap_or(0.0) } else { 0.0 };
+ let card = if app.progress_notice.is_some() { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) } else { 0.0 };
let lift = if card > 0.0 { 28.0 + card + 10.0 } else { 28.0 };
- egui::Area::new(egui::Id::new("toast"))
+ egui::Area::new(egui::Id::unique("toast"))
.order(egui::Order::Tooltip)
.pivot(Align2::CENTER_BOTTOM)
.fixed_pos(screen.center_bottom() - vec2(0.0, lift))
@@ -455,10 +500,10 @@ pub fn progress_notice(app: &PdfCraftApp, ctx: &egui::Context) -> bool {
};
let fraction = if p.fraction.is_finite() { p.fraction.clamp(0.0, 1.0) } else { 0.0 };
let animated = crate::motion::animated(ctx);
- let shown = ctx.animate_value_with_time(egui::Id::new("progress-notice-bar"), fraction, if animated { 0.3 } else { 0.0 });
+ let shown = ctx.animate_value_with_time(egui::Id::unique("progress-notice-bar"), fraction, if animated { 0.3 } else { 0.0 });
let now = ctx.input(|i| i.time);
let mut cancel = false;
- let area = egui::Area::new(egui::Id::new("progress-notice"))
+ let area = egui::Area::new(egui::Id::unique("progress-notice"))
.order(egui::Order::Tooltip)
.pivot(Align2::CENTER_BOTTOM)
.fixed_pos(screen.center_bottom() - vec2(0.0, 28.0))
@@ -476,7 +521,7 @@ pub fn progress_notice(app: &PdfCraftApp, ctx: &egui::Context) -> bool {
let (track, resp) = ui.allocate_exact_size(vec2(width, 6.0), Sense::hover());
// The label above names the job; the bar carries the percentage.
resp.widget_info(|| {
- let mut info = egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator);
+ let mut info = egui::WidgetInfo::new(egui::Role::ProgressIndicator);
info.value = Some(f64::from(fraction) * 100.0);
info
});
@@ -506,7 +551,7 @@ pub fn progress_notice(app: &PdfCraftApp, ctx: &egui::Context) -> bool {
}
});
});
- ctx.data_mut(|d| d.insert_temp(egui::Id::new(PROGRESS_HEIGHT), area.response.rect.height()));
+ ctx.data_mut(|d| d.insert_temp(egui::Id::unique(PROGRESS_HEIGHT), area.response.rect.height()));
ctx.request_repaint_after(std::time::Duration::from_millis(33));
cancel
}
@@ -555,10 +600,10 @@ pub fn split_pill(ui: &mut egui::Ui, icon: &str, label: &str, more: &str) -> (Re
let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);
let (rect, _) = ui.allocate_exact_size(vec2(w + 46.0 + 28.0, 30.0), Sense::hover());
let (main_rect, more_rect) = rect.split_left_right_at_x(rect.right() - 28.0);
- let main = ui.interact(main_rect, ui.id().with(("split-pill", label)), Sense::click());
- let arrow = ui.interact(more_rect, ui.id().with(("split-pill-more", label)), Sense::click());
- main.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
- arrow.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), more));
+ let main = ui.interact(main_rect, ui.scope_id().with(("split-pill", label)), Sense::click());
+ let arrow = ui.interact(more_rect, ui.scope_id().with(("split-pill-more", label)), Sense::click());
+ main.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
+ arrow.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), more));
let radius = CornerRadius::same(15);
ui.painter().rect(rect, radius, t.card, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
let left = CornerRadius { nw: 15, sw: 15, ne: 0, se: 0 };
@@ -586,7 +631,7 @@ pub fn icon_pill(ui: &mut egui::Ui, icon: &str, label: &str, primary: bool) -> R
let font = theme::medium(12.5);
let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), t.text).size().x);
let (rect, resp) = ui.allocate_exact_size(vec2(w + 46.0, 30.0), Sense::click());
- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
let press = theme::Press::track(ui, &resp);
let (fill, stroke, text) = if primary {
(press.fill(t.accent, t.accent_text, t.accent.lerp_to_gamma(Color32::BLACK, 0.22)), Stroke::NONE, Color32::WHITE)
@@ -710,7 +755,7 @@ mod tests {
);
output.drop_without_applying_deltas();
}
- ctx.memory(|memory| memory.area_rect(egui::Id::new("toast")).unwrap())
+ ctx.memory(|memory| memory.area_rect(egui::Id::unique("toast")).unwrap())
}
#[test]
@@ -761,7 +806,7 @@ mod tests {
let ctx = egui::Context::default();
ctx.set_fonts(theme::font_definitions());
let cache_len =
- |ctx: &egui::Context| ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::new("pdfcraft-rtl-wrap-cache")).lines.len());
+ |ctx: &egui::Context| ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("pdfcraft-rtl-wrap-cache")).lines.len());
let persian = "این یک نظر طولانی به زبان فارسی است که باید در چند خط شکسته شود";
let long = persian.repeat(2_000);
let mut first = None;
@@ -775,7 +820,7 @@ mod tests {
first = Some(lines);
let collapsed = wrapped_lines(ui, &long, &theme::regular(13.0), 120.0, true);
assert_eq!(collapsed.len(), 1);
- assert!(collapsed[0].text.starts_with(ELLIPSIS), "{:?}", collapsed[0].text);
+ assert!(collapsed[0].text.ends_with(ELLIPSIS), "{:?}", collapsed[0].text);
})
.drop_without_applying_deltas();
}
@@ -789,6 +834,61 @@ mod tests {
assert!(cache_len(&ctx) <= WRAP_CACHE_MAX, "bounded: {}", cache_len(&ctx));
}
+ /// Comment lines reach epaint in logical order. A mixed Persian/Latin comment preordered by
+ /// `bidi::wrap` would be reordered a second time by egui 0.37; the old display-order text is
+ /// distinctly different, so this fails if the preordering comes back.
+ #[test]
+ fn rtl_comment_lines_stay_logical_for_epaint() {
+ let mixed = "این نظر PDF درباره فایل است";
+ let ctx = egui::Context::default();
+ ctx.set_fonts(theme::font_definitions());
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ let lines = wrapped_lines(ui, mixed, &theme::regular(13.0), 1000.0, false);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].text, mixed, "epaint needs reading order, not display order");
+ assert!(lines[0].rtl);
+ // Truncation appends the ellipsis logically; the line still starts with its first word.
+ let cut = wrapped_lines(ui, mixed, &theme::regular(13.0), 60.0, true);
+ assert_eq!(cut.len(), 1);
+ assert!(cut[0].text.starts_with("این"), "{:?}", cut[0].text);
+ assert!(cut[0].text.ends_with(ELLIPSIS), "{:?}", cut[0].text);
+ // The galley keeps logical text, so inspect positioned glyphs to prove that the
+ // visible ellipsis is at the left-hand reading end after epaint's bidi layout.
+ let galley = ui.painter().layout_no_wrap(cut[0].text.clone(), theme::regular(13.0), Color32::WHITE);
+ let row = &galley.rows[0];
+ let ellipsis_x = row.glyphs.iter().find(|glyph| glyph.chr == '\u{2026}').expect("ellipsis glyph").pos.x;
+ assert!(
+ row.glyphs.iter().filter(|glyph| glyph.chr != '\u{2026}' && !glyph.chr.is_whitespace()).all(|glyph| glyph.pos.x > ellipsis_x),
+ "RTL truncation must place the ellipsis to the left: {:?}",
+ row.glyphs
+ );
+ })
+ .drop_without_applying_deltas();
+ }
+
+ /// A wrapped line keeps its paragraph's direction. The second line here starts with a
+ /// Latin word, but belongs to a right-to-left comment: `Auto` would shape it left to right
+ /// and put `PDF` at the visual left. Assert the actual painted positions instead.
+ #[test]
+ fn wrapped_rtl_line_starting_with_latin_keeps_its_rtl_base() {
+ if pdfcraft_fonts::ui_arabic_fonts().is_empty() {
+ return;
+ }
+ let ctx = egui::Context::default();
+ ctx.set_fonts(theme::font_definitions());
+ ctx.run_ui(egui::RawInput::default(), |ui| {
+ let line = crate::bidi::Line { text: "PDF درباره فایل است".to_owned(), rtl: true };
+ let galley = wrapped_line_galley(ui, &line, &theme::regular(13.0), Color32::WHITE);
+ assert_eq!(galley.job.direction, egui::epaint::text::TextDirection::RightToLeft);
+ let positions: Vec<_> = galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x))).collect();
+ let p = positions.iter().find(|(c, _)| *c == 'P').map(|(_, x)| *x).expect("a Latin P");
+ let rightmost_arabic = positions.iter().filter(|(c, _)| crate::bidi::has_rtl(&c.to_string())).map(|(_, x)| *x).fold(f32::MIN, f32::max);
+ assert!(p > rightmost_arabic, "the line stays right to left: {positions:?}");
+ })
+ .drop_without_applying_deltas();
+ }
+
+ /// Check right-aligned wrapping and a single collapsed line whose logical text ends with an ellipsis.
#[test]
fn rtl_comment_wraps_against_the_right_edge() {
let persian = "این یک نظر طولانی به زبان فارسی است که باید در چند خط شکسته شود";
@@ -805,7 +905,7 @@ mod tests {
// Collapsed: one line, its ellipsis on the left where right-to-left reading ends.
let collapsed = wrapped_shapes(persian, true);
assert_eq!(collapsed.len(), 1);
- assert!(collapsed[0].2.starts_with('\u{2026}'), "{collapsed:?}");
+ assert!(collapsed[0].2.ends_with('\u{2026}'), "the galley retains logical text: {collapsed:?}");
// Text without right-to-left script is a plain label, as before.
let latin = wrapped_shapes("A short note", false);
assert_eq!(latin.len(), 1);
diff --git a/crates/ui-egui/src/window_controls.rs b/crates/ui-egui/src/window_controls.rs
index 70df814222..9965d46ec1 100644
--- a/crates/ui-egui/src/window_controls.rs
+++ b/crates/ui-egui/src/window_controls.rs
@@ -96,7 +96,7 @@ pub fn buttons(ui: &mut egui::Ui, buttons: &[Button]) {
Button::Close => tl!("Close"),
};
let (rect, response) = ui.allocate_exact_size(Vec2::splat(BUTTON), Sense::click());
- response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label));
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let response = response.on_hover_text(label);
if ui.is_rect_visible(rect) {
paint(ui.painter(), rect, button, maximized, &t, &response);
@@ -203,7 +203,7 @@ pub fn resize_edges(ctx: &egui::Context) {
}
let screen = ctx.content_rect();
let t = Tokens::get(ctx);
- egui::Area::new(egui::Id::new("window_resize_edges"))
+ egui::Area::new(egui::Id::unique("window_resize_edges"))
.order(egui::Order::Foreground)
.fixed_pos(screen.min)
.pivot(Align2::LEFT_TOP)
@@ -214,7 +214,7 @@ pub fn resize_edges(ctx: &egui::Context) {
if rect.width() <= 0.0 || rect.height() <= 0.0 {
continue;
}
- let response = ui.interact(rect, ui.id().with(("edge", n)), Sense::drag()).on_hover_cursor(cursor(direction));
+ let response = ui.interact(rect, ui.scope_id().with(("edge", n)), Sense::drag()).on_hover_cursor(cursor(direction));
// Sensing only drags, a drag starts on the press itself.
if response.drag_started() {
desktop_grab(ui.ctx(), egui::ViewportCommand::BeginResize(direction));
@@ -231,8 +231,9 @@ pub fn resize_edges(ctx: &egui::Context) {
});
}
+/// Return the stable egui id for desktop window-grab state.
fn grab_id() -> egui::Id {
- egui::Id::new("window_controls_desktop_grab")
+ egui::Id::unique("window_controls_desktop_grab")
}
/// Hand the pointer to the desktop to move or resize the window. On Wayland the compositor keeps
diff --git a/crates/ui-egui/tests/it/actions.rs b/crates/ui-egui/tests/it/actions.rs
index 8e5f37cf08..a78de3481a 100644
--- a/crates/ui-egui/tests/it/actions.rs
+++ b/crates/ui-egui/tests/it/actions.rs
@@ -1,12 +1,30 @@
//! Action Wizard in the real shell (egui_kittest): run a built-in action on files, create an
//! action, and remember it.
+use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use pdfcraft_engine::Session;
use pdfcraft_engine::actions::Step;
use pdfcraft_ui_egui::PdfCraftApp;
+/// The Action Wizard's name, description and step-argument boxes are named by their labels.
+#[test]
+fn action_editor_inputs_have_accessible_names() {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app
+ });
+ h.run_steps(2);
+ assert!(h.state_mut().execute("actions.wizard"));
+ h.run_steps(2);
+ h.get_by_label("New Action…").click();
+ h.run_steps(2);
+ h.get_by_role_and_label(Role::TextInput, "Action name:");
+ h.get_by_role_and_label(Role::TextInput, "Description:");
+}
+
#[test]
fn run_and_create_actions() {
let dir = std::env::temp_dir().join(format!("pdfcraft-actions-ui-{}", std::process::id()));
diff --git a/crates/ui-egui/tests/it/attachment_row.rs b/crates/ui-egui/tests/it/attachment_row.rs
index 1a66723bb9..c52b2892e0 100644
--- a/crates/ui-egui/tests/it/attachment_row.rs
+++ b/crates/ui-egui/tests/it/attachment_row.rs
@@ -127,22 +127,23 @@ fn the_right_click_menu_opens_saves_and_deletes() {
assert_eq!((count(&h, "Save attachment…"), count(&h, "Open in a new tab"), count(&h, "Delete attachment")), (3, 1, 3));
h.key_press(egui::Key::Escape);
h.run_steps(3);
- // The PDF's menu: Save writes the PDF, not the text file whose row comes last.
+ // Scope actions to the menu: egui nests it under its row in the accessibility tree.
+ // Save writes the PDF, not the text file whose row comes last.
right_click(&mut h, "inner.pdf");
assert_eq!(count(&h, "Open in a new tab"), 2, "the PDF's menu offers Open");
h.state_mut().pick_override = Some(vec![target.to_string_lossy().into_owned()]);
- h.get_all_by_label("Save attachment…").last().unwrap().click();
+ h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Save attachment…").click();
h.run_steps(3);
assert_eq!(std::fs::read(&target).unwrap(), INNER, "Save from inner.pdf's menu");
right_click(&mut h, "inner.pdf");
- h.get_all_by_label("Open in a new tab").last().unwrap().click();
+ h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Open in a new tab").click();
h.run_steps(3);
assert_eq!(h.state().views.len(), 2, "Open from the menu");
h.state_mut().active = Some(0);
h.run_steps(3);
// Delete from inner.pdf's menu leaves notes.txt, whose row's button would delete itself.
right_click(&mut h, "inner.pdf");
- h.get_all_by_label("Delete attachment").last().unwrap().click();
+ h.get_by_role(egui::accesskit::Role::Menu).get_by_label("Delete attachment").click();
h.run_steps(3);
let s = h.state();
let doc = s.session.get(s.views[0].id).unwrap();
diff --git a/crates/ui-egui/tests/it/bookmarks.rs b/crates/ui-egui/tests/it/bookmarks.rs
index be8c5151bb..415067ad33 100644
--- a/crates/ui-egui/tests/it/bookmarks.rs
+++ b/crates/ui-egui/tests/it/bookmarks.rs
@@ -101,7 +101,7 @@ fn new_rename_reorder_indent_delete_and_undo() {
/// The side panel's width as egui keeps it from one frame to the next.
fn panel_width(h: &Harness<'static, PdfCraftApp>) -> f32 {
- h.ctx.data(|data| data.get_temp::(egui::Id::new("pdfcraft-inspector-body"))).expect("the inspector body is shown").width()
+ h.ctx.data(|data| data.get_temp::(egui::Id::unique("pdfcraft-inspector-body"))).expect("the inspector body is shown").width()
}
#[test]
@@ -290,8 +290,8 @@ fn style_and_colour_from_the_bookmark_menu() {
let submenu = |h: &mut Harness<'static, PdfCraftApp>, menu: &str, item: &str| {
h.get_by_label("Intro").click_secondary();
h.run_steps(2);
- // A submenu's button carries its arrow.
- h.get_by_label(&format!("{menu} ⏵")).click();
+ // The submenu arrow is painted as an atom; the accessible name is the menu title.
+ h.get_by_label(menu).click();
h.run_steps(2);
h.get_by_label(item).click();
h.run_steps(3);
diff --git a/crates/ui-egui/tests/it/combine_grid.rs b/crates/ui-egui/tests/it/combine_grid.rs
index 4ed7b5778e..c6f2e3e721 100644
--- a/crates/ui-egui/tests/it/combine_grid.rs
+++ b/crates/ui-egui/tests/it/combine_grid.rs
@@ -180,6 +180,17 @@ fn ready(t: &CombineThumb) -> bool {
matches!(t, CombineThumb::Ready { .. })
}
+/// Wait for a modal opened by an action to be laid out and present in the accessibility tree.
+/// A newly shown modal needs a pass of its own; the action's frame only sets its state.
+fn wait_for_label(h: &mut Harness<'static, PdfCraftApp>, label: &str) {
+ for _ in 0..30 {
+ if h.query_by_label(label).is_some() {
+ return;
+ }
+ h.run_steps(1);
+ }
+}
+
/// Press, move in steps and release, as a user drags.
fn drag(h: &mut Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2) {
h.hover_at(from);
@@ -691,6 +702,7 @@ fn a_card_dragged_to_the_bottom_edge_scrolls_the_grid_and_still_drops() {
assert_eq!(order.get(at + 1), Some(&target_name), "dropped before {target_name}: {order:?}");
}
+/// Check that right-clicking a locked card selects that card and offers Unlock for it.
#[test]
fn a_locked_card_offers_unlock_on_a_right_click() {
let mut h = grid_of(vec![("one.pdf", fixture(1)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0));
@@ -699,6 +711,7 @@ fn a_locked_card_offers_unlock_on_a_right_click() {
// The menu's item comes after the toolbar's button of the same name.
h.get_all_by_label("Unlock…").last().unwrap().click();
h.run_steps(2);
+ wait_for_label(&mut h, "Unlock secret.pdf");
h.get_by_label("Unlock secret.pdf");
assert_eq!(h.state().combine_selection(), [1], "the card right-clicked is the one unlocked");
}
@@ -716,6 +729,7 @@ fn ctrl_wheel(h: &mut Harness<'static, PdfCraftApp>, at: Pos2, dy: f32) {
delta: vec2(0.0, dy),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::COMMAND,
+ source: egui::MouseWheelSource::Unknown,
});
h.run_steps(3);
}
@@ -833,6 +847,8 @@ fn ctrl_keys_and_ctrl_wheel_size_the_cards_and_leave_the_window_alone() {
assert_eq!(h.state().combine_zoom, now);
}
+/// Check that wheel zoom keeps the card under the pointer fixed and never blanks its thumbnail while a
+/// sharper render arrives.
#[test]
fn zooming_keeps_the_card_under_the_pointer_in_place_and_thumbnails_never_go_blank() {
let files: Vec<(String, Vec)> = (0..40).map(|i| (format!("f{i:02}.pdf"), fixture(1))).collect();
@@ -845,6 +861,7 @@ fn zooming_keeps_the_card_under_the_pointer_in_place_and_thumbnails_never_go_bla
delta: vec2(0.0, -300.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
});
h.run_steps(6);
// A card fully in view, below the toolbar, with its thumbnail drawn.
@@ -866,6 +883,7 @@ fn zooming_keeps_the_card_under_the_pointer_in_place_and_thumbnails_never_go_bla
delta: vec2(0.0, 120.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::COMMAND,
+ source: egui::MouseWheelSource::Unknown,
});
// The wheel zooms smoothly over several frames; in every one the card stays put.
let mut zooms = Vec::new();
@@ -976,6 +994,7 @@ fn scrolled_grid(dy: f32) -> (Harness<'static, PdfCraftApp>, f32) {
delta: vec2(0.0, -dy),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
});
h.run_steps(8);
(h, top)
@@ -1012,6 +1031,7 @@ fn zooming_from_the_toolbar_while_scrolled_keeps_the_top_cards_in_place() {
}
}
+/// Check that zooming out at the bottom keeps the last card in place without leaving a gap below it.
#[test]
fn zooming_out_at_the_bottom_leaves_no_gap_below_the_last_card() {
let (mut h, _) = scrolled_grid(20_000.0);
@@ -1024,6 +1044,7 @@ fn zooming_out_at_the_bottom_leaves_no_gap_below_the_last_card() {
delta: vec2(0.0, -20_000.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
});
h.run_steps(8);
let bottom = card(&h, "f39.pdf").bottom();
@@ -1598,13 +1619,16 @@ fn a_page_cards_magnifier_opens_the_preview_on_that_page() {
h.get_by_label("Preview").click();
h.run_steps(2);
assert_eq!(h.state().combine_preview().map(|p| (p.0, p.1)), Some(("b.pdf".to_string(), 3)));
+ wait_for_label(&mut h, "Page 3 of 3");
h.get_by_label("Page 3 of 3");
- // A page card's own actions: Collapse, Remove page, Preview (its file can't be removed from
- // it); nothing is selected yet, so no "Remove b.pdf" anywhere.
- h.get_by_label("Remove page");
+ // The preview is modal: the card's actions are not drawn behind it.
+ assert!(h.query_by_label("Remove page").is_none(), "the preview covers the page card's actions");
h.key_press(Key::Escape);
h.run_steps(2);
+ // A page card's own actions: Collapse, Remove page, Preview (its file can't be removed from
+ // it); nothing is selected yet, so no "Remove b.pdf" anywhere.
hover_card(&mut h, &page_card(4, "b.pdf"));
+ h.get_by_label("Remove page");
h.get_by_label("Collapse");
assert!(h.query_by_label("Remove b.pdf").is_none());
// Space on a page card that has the keyboard: that page too.
@@ -1615,6 +1639,7 @@ fn a_page_cards_magnifier_opens_the_preview_on_that_page() {
h.key_press(Key::Space);
h.run_steps(2);
assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0), "page 1, the second the file adds");
+ wait_for_label(&mut h, "Page 2 of 3");
h.get_by_label("Page 2 of 3");
}
@@ -1651,6 +1676,7 @@ fn collapsing_brings_the_files_card_into_view() {
delta: vec2(0.0, -120.0),
phase: egui::TouchPhase::Move,
modifiers: Modifiers::NONE,
+ source: egui::MouseWheelSource::Unknown,
});
h.run_steps(3);
}
diff --git a/crates/ui-egui/tests/it/commands.rs b/crates/ui-egui/tests/it/commands.rs
index 6f10288612..ff82820148 100644
--- a/crates/ui-egui/tests/it/commands.rs
+++ b/crates/ui-egui/tests/it/commands.rs
@@ -293,12 +293,13 @@ fn palette_arrow_keys_select_results_and_enter_runs_the_selection() {
assert_eq!(app.session.get(app.views[0].id).unwrap().info.pages[0].rotation, 270);
}
+/// Check that choosing Delete pages from the Pages menu reduces the document page count.
#[test]
fn the_pages_menu_comes_from_the_registry() {
let mut h = harness();
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("Pages ⏵").hover();
+ h.get_by_label("Pages").hover();
h.run_steps(3);
h.get_by_label_contains("Delete pages").click();
h.run_steps(3);
@@ -306,6 +307,8 @@ fn the_pages_menu_comes_from_the_registry() {
assert_eq!(app.session.get(app.views[0].id).unwrap().info.pages.len(), 2);
}
+/// Check that Open Recent lists a recorded file and opens it in a new active tab without replacing the
+/// original.
#[test]
fn the_open_recent_menu_lists_files_and_opens_one() {
let dir = std::env::temp_dir().join(format!("pdfcraft-recent-{}", std::process::id()));
@@ -326,9 +329,9 @@ fn the_open_recent_menu_lists_files_and_opens_one() {
h.run_steps(4);
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("File ⏵").hover();
+ h.get_by_label("File").hover();
h.run_steps(3);
- h.get_by_label("Open Recent ⏵").hover();
+ h.get_by_label("Open Recent").hover();
h.run_steps(3);
let original = h.state().views[0].id;
h.get_by_label_contains("recent.pdf").click();
@@ -341,12 +344,13 @@ fn the_open_recent_menu_lists_files_and_opens_one() {
assert_eq!(app.session.get(original).unwrap().bytes.as_slice(), fixture(3).as_slice());
}
+/// Check that Open Recent is disabled while no file has been opened.
#[test]
fn the_open_recent_menu_is_disabled_while_the_list_is_empty() {
let mut h = harness();
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("File ⏵").hover();
+ h.get_by_label("File").hover();
h.run_steps(3);
assert!(
h.query_by(|n| n.label().as_deref() == Some("Open Recent") && n.is_disabled()).is_some(),
@@ -358,6 +362,7 @@ fn recent_file(name: &str) -> pdfcraft_ui_egui::RecentFile {
pdfcraft_ui_egui::RecentFile { name: name.into(), path: format!("/nowhere/{name}"), pages: 1, size: 0 }
}
+/// Check that Clear Recent Files empties the list and disables Open Recent.
#[test]
fn clear_recent_files_at_the_foot_of_open_recent_empties_the_list() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
@@ -370,16 +375,16 @@ fn clear_recent_files_at_the_foot_of_open_recent_empties_the_list() {
h.run_steps(4);
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("File ⏵").hover();
+ h.get_by_label("File").hover();
h.run_steps(3);
- h.get_by_label("Open Recent ⏵").hover();
+ h.get_by_label("Open Recent").hover();
h.run_steps(3);
h.get_by_label("Clear Recent Files").click();
h.run_steps(3);
assert!(h.state().recent.is_empty(), "the list is empty");
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("File ⏵").hover();
+ h.get_by_label("File").hover();
h.run_steps(3);
assert!(h.query_by(|n| n.label().as_deref() == Some("Open Recent") && n.is_disabled()).is_some(), "and Open Recent is disabled");
}
@@ -459,7 +464,7 @@ fn view_menu(os: OperatingSystem) -> Harness<'static, PdfCraftApp> {
h.ctx.set_os(os);
h.get_by_label("Menu").click();
h.run_steps(2);
- h.get_by_label("View ⏵").hover();
+ h.get_by_label("View").hover();
h.run_steps(3);
h
}
@@ -530,6 +535,8 @@ fn the_about_dialog_shows_the_running_version() {
h.get_by_label_contains(&format!("Version {}", env!("CARGO_PKG_VERSION")));
}
+/// Check that the quit shortcut needs exact platform modifiers and that unsaved work opens the save prompt
+/// instead of closing.
#[test]
fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() {
for (os, modifiers) in [
@@ -550,6 +557,9 @@ fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() {
let closes = h.output().viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::Close));
assert_eq!(closes, should_close, "{os:?}, extra={extra:?}, dirty={dirty}");
if dirty {
+ // The save prompt is a modal laid out after the key pass; let that pass settle
+ // before looking it up.
+ h.run_steps(2);
h.get_by_label("Cancel").click();
h.run_steps(2);
assert_eq!(h.state().views.len(), 1);
diff --git a/crates/ui-egui/tests/it/comments.rs b/crates/ui-egui/tests/it/comments.rs
index d516330dd7..3a3169576c 100644
--- a/crates/ui-egui/tests/it/comments.rs
+++ b/crates/ui-egui/tests/it/comments.rs
@@ -1,6 +1,7 @@
//! Commenting in the real shell (egui_kittest): tools, gestures, selection, the composer and
//! the Comments panel.
+use egui::accesskit::Role;
use egui::{Pos2, pos2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
@@ -542,7 +543,7 @@ fn selected_text_replace_action_opens_replacement_composer() {
h.run_steps(3);
h.get_by_label("Replace text").click();
h.run_steps(2);
- h.get_by_label("Replacement text");
+ h.get_by_role_and_label(Role::MultilineTextInput, "Replacement text");
assert!(h.state().views[0].selected_text().is_none());
}
@@ -1052,7 +1053,7 @@ fn the_panel_posts_comments_and_replies() {
/// The side panel's width as egui keeps it from one frame to the next.
fn panel_width(h: &Harness<'static, PdfCraftApp>) -> f32 {
- h.ctx.data(|data| data.get_temp::(egui::Id::new("pdfcraft-inspector-body"))).expect("the inspector body is shown").width()
+ h.ctx.data(|data| data.get_temp::(egui::Id::unique("pdfcraft-inspector-body"))).expect("the inspector body is shown").width()
}
#[test]
diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs
index 7099ece40b..e18c7bf47a 100644
--- a/crates/ui-egui/tests/it/control.rs
+++ b/crates/ui-egui/tests/it/control.rs
@@ -4,7 +4,7 @@
use std::sync::{Arc, Mutex};
use egui_kittest::Harness;
-use egui_kittest::kittest::{NodeT, Queryable};
+use egui_kittest::kittest::Queryable;
use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind};
use pdfcraft_ui_egui::PdfCraftApp;
use pdfcraft_ui_egui::control::{ControlClient, Reply};
@@ -88,6 +88,14 @@ fn ok(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, pa
call(h, c, method, params).unwrap_or_else(|e| panic!("{method}: {e}"))
}
+/// Let the next real frames run after a control setting that changes the interface fonts or
+/// opens a modal. `ui.set` answers in the input pass, and a font change discards the pass that
+/// applies it, so the modal's labels are not in the accessibility tree until those frames have
+/// been laid out.
+fn settle(h: &mut Harness<'static, PdfCraftApp>) {
+ h.run_steps(3);
+}
+
#[test]
fn comment_pin_is_reported_and_persistent() {
let (mut h, c) = harness();
@@ -162,6 +170,9 @@ fn control_resize_reports_observed_dimensions_and_rejects_invalid_sizes() {
assert_eq!(state["documents"][0]["dirty"], false);
}
+/// Kittest calls only `App::logic` and `App::ui`, not eframe's `raw_input_hook`, so this checks
+/// the widget tree and key handling but not the production focus-generation ordering. The
+/// `production_*` tests above drive `prepare_raw_input` first and cover that ordering.
#[test]
fn control_focus_traverses_real_widgets_and_keyboard_activates() {
let (mut h, c) = harness();
@@ -183,6 +194,55 @@ fn control_focus_traverses_real_widgets_and_keyboard_activates() {
assert_eq!(state["documents"][0]["dirty"], false);
}
+/// A frame driven in production order: eframe's raw input hook runs before egui's input hooks, so
+/// the control plugin sees the focus/dialog generation produced by the previous UI pass. The
+/// kittest harness does not call `raw_input_hook`, which otherwise hides focus-change bugs.
+fn production_step(h: &mut Harness<'static, PdfCraftApp>) {
+ let ctx = h.ctx.clone();
+ let mut raw = std::mem::take(h.input_mut());
+ h.state_mut().prepare_raw_input(&ctx, &mut raw);
+ *h.input_mut() = raw;
+ h.step();
+}
+
+fn call_production(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Reply {
+ let rx = c.send(method, params);
+ for _ in 0..30 {
+ production_step(h);
+ if let Ok(r) = rx.try_recv() {
+ return r;
+ }
+ }
+ panic!("{method}: no reply after 30 production-ordered frames");
+}
+
+#[test]
+fn production_key_release_survives_the_focus_change_its_press_causes() {
+ let (mut h, c) = harness();
+ ok(&mut h, &c, "ui.focus", json!({"label": "Convert"}));
+ let reply = call_production(&mut h, &c, "ui.key", json!({"key": "Tab"}));
+ reply.unwrap_or_else(|e| panic!("a Tab press that moves focus must not leave its release unapplied: {e}"));
+ let sign = ok(&mut h, &c, "ui.inspect", json!({"query": "E-Sign", "role": "Button"}));
+ assert!(sign["widgets"].as_array().unwrap().iter().any(|w| w["label"] == "E-Sign" && w["focused"] == true), "focus moved on the press: {sign}");
+ assert!(!h.ctx.input(|i| i.keys_down.contains(&egui::Key::Tab)), "the release reached egui: no stuck Tab");
+}
+
+#[test]
+fn production_drag_releases_the_button_after_the_press_moves_focus() {
+ let (mut h, c) = harness_pages(2);
+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddBookmark { parent: vec![], index: 0, title: "Target".into(), page: 0, left: None, top: None });
+ ok(&mut h, &c, "ui.set", json!({"key": "panel", "value": "bookmarks"}));
+ let field = ok(&mut h, &c, "ui.inspect", json!({"query": "Search", "role": "TextInput"}));
+ let rect = field["widgets"][0]["rect"].as_array().expect("the search field has a rect");
+ let (x0, y0, x1, y1) = (rect[0].as_f64().unwrap(), rect[1].as_f64().unwrap(), rect[2].as_f64().unwrap(), rect[3].as_f64().unwrap());
+ let start = json!([x0 + 8.0, (y0 + y1) / 2.0]);
+ let end = json!([x1 - 8.0, (y0 + y1) / 2.0]);
+ call_production(&mut h, &c, "ui.drag", json!({"from": start, "to": end, "steps": 3}))
+ .unwrap_or_else(|e| panic!("the press's focus change must not cancel its moves and release: {e}"));
+ assert!(!h.ctx.input(|i| i.pointer.button_down(egui::PointerButton::Primary)), "the pointer button was released");
+ assert_eq!(h.ctx.input(|i| i.modifiers), egui::Modifiers::NONE, "no modifier is left held");
+}
+
#[test]
fn control_button_focus_preserves_document_undo_redo_shortcuts() {
let (mut h, c) = harness_pages(2);
@@ -209,7 +269,7 @@ fn control_text_focus_retains_text_undo_ownership() {
ok(&mut h, &c, "ui.focus", json!({"id": widgets["widgets"][0]["id"]}));
assert!(h.ctx.text_edit_focused());
ok(&mut h, &c, "ui.type", json!({"text": "target"}));
- let search_id = egui::Id::new(("bookmark_search", h.state().views[0].id.0));
+ let search_id = egui::Id::unique(("bookmark_search", h.state().views[0].id.0));
assert_eq!(h.ctx.data(|d| d.get_temp::(search_id)).as_deref(), Some("target"));
ok(&mut h, &c, "ui.key", json!({"key": "Z", "modifiers": ["command"]}));
assert_eq!(h.ctx.data(|d| d.get_temp::