From 5f07da441978ccdc8dcc98501e3996562ec8db56 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 09:33:03 +0530 Subject: [PATCH 01/15] ui: modernize preferences dialog with card-based layout - Replace cluttered settings list with clean, modular card containers - Integrate interactive real-time search box flush with card boundary - Combine page display and continuous scrolling into a unified segmented pill - Enable smooth scrolling with dedicated animation duration - Enhance vertical scrollbar spacing and layout geometry - Update unit and integration tests across layout, appearance, and theme - Credit @Combiler01 in contributors/people.toml --- contributors/people.toml | 3 + crates/ui-egui/src/dialogs.rs | 17 +- crates/ui-egui/src/dialogs/appearance.rs | 26 +- crates/ui-egui/src/dialogs/preferences.rs | 783 ++++++++++++++++++ crates/ui-egui/src/workflows/js_ui.rs | 443 +--------- crates/ui-egui/tests/it/preferences_layout.rs | 95 +++ crates/ui-egui/tests/it/theme.rs | 6 +- 7 files changed, 911 insertions(+), 462 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/preferences.rs diff --git a/contributors/people.toml b/contributors/people.toml index a5a47f5c52..fecfb68c90 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -180,3 +180,6 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true + +[people.Combiler01] +sync_github_name = true diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 42bed83657..2e2457fbbf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -14,6 +14,7 @@ pub(super) mod credits; pub(super) mod marks_ui; pub(super) mod pageboxes; pub(super) mod palette; +pub(super) mod preferences; mod prompts; pub(super) mod protect; pub(super) mod standards_ui; @@ -127,6 +128,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) { Dialog::Properties(_) => 640.0, Dialog::Print => 820.0, Dialog::FieldProps | Dialog::BulkFieldProps => 600.0, + Dialog::Preferences => 610.0, Dialog::About => 780.0, Dialog::PinTool => 540.0, _ => 520.0, @@ -1356,10 +1358,11 @@ fn dialog_signature(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) /// `Dialog::Preferences` content. Returns `false` when it has its own buttons and no footer is wanted. fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool { + ui.set_width(610.0); let t = Tokens::get(ui.ctx()); // The settings outgrow a short window: scroll them rather than run off the screen. // The OK row stays below the scroll, in reach however far the settings are scrolled. - let max = (ui.ctx().content_rect().height() - 120.0 - crate::js_ui::PREFERENCES_BUTTON_ROW).max(crate::js_ui::PREFERENCES_MIN_SCROLL); + let max = (ui.ctx().content_rect().height() - 120.0 - preferences::PREFERENCES_BUTTON_ROW).max(preferences::PREFERENCES_MIN_SCROLL); // A scroll area starts from the room the dialog offers it, and a modal offers more // each frame for the first few, so with OK outside the scroll the dialog would grow // over those frames. Asking for the full height as the least it may scroll in @@ -1368,9 +1371,17 @@ fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pendin // cards and other full-width rows (#3557). ui.scope(|ui| { ui.spacing_mut().scroll.floating = false; - egui::ScrollArea::vertical().max_height(max).min_scrolled_height(max).show(ui, |ui| crate::js_ui::preferences_body(ui, app, &t)); + ui.spacing_mut().scroll.bar_inner_margin = 14.0; + ui.spacing_mut().scroll.bar_outer_margin = 2.0; + ui.style_mut().scroll_animation = egui::style::ScrollAnimation::duration(0.25); + egui::ScrollArea::vertical() + .id_salt("preferences-dialog-scroll") + .max_height(max) + .min_scrolled_height(max) + .animated(true) + .show(ui, |ui| preferences::preferences_body(ui, app, &t)); }); - req.close = crate::js_ui::preferences_buttons(ui); + req.close = preferences::preferences_buttons(ui); false } diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 48ad0cb31c..135337aaba 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -5,7 +5,6 @@ use egui::{Rect, RichText, pos2, vec2}; use crate::PdfCraftApp; use crate::theme::{self, ThemeKind, ThemePreference, Tokens}; -use crate::widgets; /// The themes each card offers. One of each today; a new theme is one more row here. pub const LIGHT_THEMES: &[(ThemeKind, &str)] = &[(ThemeKind::Light, "Light gray")]; @@ -82,9 +81,10 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { } } -/// One theme card: its title, Active when it is what shows now, a preview of the chosen theme -/// and a radio row per theme. Returns true when the card or one of its radio rows was clicked. +/// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme. +/// Returns true when the card was clicked. fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool { + let mut title_clicked = false; let inner = egui::Frame::new() .fill(t.card) .stroke(egui::Stroke::new(1.0, if active { t.accent } else { t.border })) @@ -93,7 +93,8 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The .show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { - ui.label(RichText::new(title).font(theme::semibold(12.5)).color(t.text)); + let resp = ui.label(RichText::new(title).font(theme::semibold(12.5)).color(t.text)); + title_clicked = resp.interact(egui::Sense::click()).clicked(); if active { ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); } @@ -101,17 +102,10 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The ui.add_space(4.0); let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); preview(ui, shown, ui.available_width()); - ui.add_space(4.0); - let mut clicked = false; - for (kind, label) in themes { - // One theme per card today, so it is always the chosen one. - clicked |= ui.add(widgets::radio(*kind == shown, tl!(label))).clicked(); - } - clicked }); - // The whole card picks its theme, not just the radio row. + // The whole card picks its theme. let whole = inner.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); - inner.inner || whole.clicked() + title_clicked || whole.clicked() } /// The Appearance section of Preferences. @@ -175,7 +169,6 @@ mod tests { ); h.run(); assert!(h.query_by_label("Light theme").is_some() && h.query_by_label("Dark theme").is_some()); - assert!(h.query_by_label("Light gray").is_some() && h.query_by_label("Dark gray").is_some()); assert_eq!(h.query_all_by_label("Active").count(), 1); if let Ok(path) = std::env::var("PDFCRAFT_APPEARANCE_SHOT") { h.render().unwrap().save(path).unwrap(); @@ -200,7 +193,7 @@ mod tests { assert_eq!(h.state().theme_preference, ThemePreference::System); } - /// Clicking a theme card, or its radio row, picks that theme, not only the mode combo box. + /// Clicking a theme card picks that theme, not only the mode combo box. #[test] fn clicking_a_theme_card_picks_that_theme() { let mut app = PdfCraftApp::new(); @@ -219,10 +212,9 @@ mod tests { app, ); h.run(); - h.get_by_label("Dark gray").click(); + h.get_by_label("Dark theme").click(); h.run(); assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Dark, ThemeKind::Dark)); - // The card's title is not a widget of its own: the click lands on the card. h.get_by_label("Light theme").click(); h.run(); assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Light, ThemeKind::Light)); diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs new file mode 100644 index 0000000000..4147417277 --- /dev/null +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -0,0 +1,783 @@ +//! Preferences dialog: card-based settings interface organized into clean, modular cards +//! with segmented pill controls and real-time search filtering. + +use egui::{Color32, CornerRadius, Margin, Rect, RichText, Sense, Stroke, pos2, vec2}; + +use crate::PdfCraftApp; +use crate::canvas::{Fit, PageLayout}; +use crate::motion::AnimationEffects; +use crate::scroll_speed::ScrollSpeed; +use crate::side_panels::ToolsSide; +use crate::theme::{self, ThemeKind, Tokens}; +use crate::units::Unit; +use crate::widgets::{self, icons}; + +/// The height the Preferences dialog keeps below its scrolling settings for the buttons row. +pub(crate) const PREFERENCES_BUTTON_ROW: f32 = 52.0; + +/// The least height the scrolling settings are given in very small windows. +pub(crate) const PREFERENCES_MIN_SCROLL: f32 = 60.0; + +/// A segmented pill control for mutually exclusive choices. +/// +/// Draws a rounded container with options inside. The active option is highlighted +/// with the accent colour. Emits AccessKit RadioButton widget info with the option's label. +pub fn segmented_pill_choice(ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str)]) -> bool { + let with_a11y: Vec<(T, &str, &str)> = options.iter().map(|&(v, l)| (v, l, l)).collect(); + segmented_pill_choice_a11y(ui, t, current, &with_a11y) +} + +/// A segmented pill selection bar with separate accessibility labels. +pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)]) -> bool { + let mut changed = false; + egui::Frame::new() + .fill(t.field) + .stroke(Stroke::new(1.0, t.border)) + .corner_radius(CornerRadius::same(14)) + .inner_margin(Margin::symmetric(2, 2)) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.horizontal(|ui| { + for &(value, label, a11y_label) in options { + let is_active = *current == value; + let font = theme::medium(12.0); + let text_color = if is_active { Color32::WHITE } else { t.text }; + 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 + 18.0, 24.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, is_active, a11y_label)); + + if is_active { + ui.painter().rect(rect, CornerRadius::same(12), t.accent, Stroke::NONE, egui::StrokeKind::Inside); + } else { + let press = theme::Press::track(ui, &resp); + let fill = press.fill(Color32::TRANSPARENT, t.hover, t.pressed); + ui.painter().rect(rect, CornerRadius::same(12), fill, Stroke::NONE, egui::StrokeKind::Inside); + } + ui.painter().galley(rect.center() - label_galley.size() / 2.0, label_galley, text_color); + + let resp = theme::hand(resp); + if resp.clicked() && *current != value { + *current = value; + changed = true; + } + } + }); + }); + changed +} + +/// An independent toggle pill button (e.g. for standalone toggles). +#[allow(dead_code)] +pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { + let mut changed = false; + let is_active = *active; + let font = theme::medium(12.0); + let text_color = if is_active { Color32::WHITE } else { t.text }; + 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 + 20.0, 26.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, is_active, label)); + + let (fill, stroke) = if is_active { + (t.accent, Stroke::NONE) + } else { + let press = theme::Press::track(ui, &resp); + (press.fill(t.field, t.hover, t.pressed), Stroke::new(1.0, t.border)) + }; + ui.painter().rect(rect, CornerRadius::same(13), fill, stroke, egui::StrokeKind::Inside); + ui.painter().galley(rect.center() - label_galley.size() / 2.0, label_galley, text_color); + + let resp = theme::hand(resp); + if resp.clicked() { + *active = !*active; + changed = true; + } + changed +} + +/// A standard card container for a Preferences section. +/// Groups related settings with clean margins, subtle border and rounded corners. +pub fn preference_card(ui: &mut egui::Ui, t: &Tokens, title: &str, icon: Option<&str>, content: impl FnOnce(&mut egui::Ui) -> R) -> R { + let card_fill = if t.kind == ThemeKind::Light { Color32::from_rgb(0xF7, 0xF8, 0xFA) } else { Color32::from_rgb(0x24, 0x24, 0x28) }; + egui::Frame::new() + .fill(card_fill) + .stroke(Stroke::new(1.0, t.border)) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(14, 12)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if let Some(ic) = icon { + ui.add(icons::image(ic, 16.0, t.accent)); + } + ui.label(RichText::new(title).font(theme::semibold(13.5)).color(t.text)); + }); + ui.add_space(8.0); + content(ui) + }) + .inner +} + +fn matches_search(query: &str, title: &str, keywords: &[&str]) -> bool { + let q = query.trim().to_lowercase(); + if q.is_empty() { + return true; + } + title.to_lowercase().contains(&q) || keywords.iter().any(|k| k.to_lowercase().contains(&q)) +} + +/// Whether the interface can draw a language picker's native name. +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. +pub(crate) 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, + } +} + +/// Interactive search box widget at the top of Preferences. +fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, rect: Rect) { + let stroke = Stroke::new(1.0, t.border); + ui.painter().rect(rect, CornerRadius::same(15), t.field, stroke, egui::StrokeKind::Inside); + + // Magnifying glass icon: 14pt icon centered vertically at (rect.min.x + 16, rect.center().y) + let icon_rect = Rect::from_center_size(pos2(rect.min.x + 16.0, rect.center().y), vec2(14.0, 14.0)); + icons::paint(ui, icon_rect, "search", 14.0, t.text_muted); + + let clear_w = if query.is_empty() { 12.0 } else { 30.0 }; + let edit_rect = Rect::from_min_max(pos2(rect.min.x + 28.0, rect.min.y), pos2(rect.max.x - clear_w, rect.max.y)); + let mut child_ui = ui.new_child(egui::UiBuilder::new().max_rect(edit_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + let edit = child_ui.add( + egui::TextEdit::singleline(query) + .hint_text(tl!("Search settings…")) + .frame(egui::Frame::NONE) + .align(egui::Align2::LEFT_CENTER) + .desired_width(edit_rect.width()), + ); + edit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, tl!("Search settings…"))); + + if !query.is_empty() { + let clear_rect = Rect::from_center_size(pos2(rect.max.x - 16.0, rect.center().y), vec2(16.0, 16.0)); + let clear_resp = ui.interact(clear_rect, ui.auto_id_with("clear_search"), Sense::click()); + clear_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Clear search"))); + icons::paint(ui, clear_rect, "x", 12.0, if clear_resp.hovered() { t.text } else { t.text_muted }); + if clear_resp.clicked() { + query.clear(); + } + } + + if edit.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + query.clear(); + } +} + +/// The body of the Preferences dialog with card layout and search filtering. +pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + let search_id = egui::Id::unique("pdfcraft_preferences_search_query"); + let mut query: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); + + // Top Header: Title on the left, Search bar on the right. + // Allocate the full available width so the search bar aligns flush with the card boxes below. + let full_w = ui.available_width(); + let header_h = 30.0; + let (header_rect, _) = ui.allocate_exact_size(vec2(full_w, header_h), Sense::hover()); + + // Title on the left, vertically centered in the header row: + let title_rect = Rect::from_min_max(header_rect.min, pos2(header_rect.min.x + 240.0, header_rect.max.y)); + let mut title_ui = ui.new_child(egui::UiBuilder::new().max_rect(title_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + title_ui.label(RichText::new(tl!("Preferences")).font(theme::semibold(18.0)).color(t.text)); + + // Search bar on the right, right edge flush with the card box boundary: + let search_w = 210.0; + let search_rect = Rect::from_min_max(pos2(header_rect.max.x - search_w, header_rect.min.y), header_rect.max); + let before = query.clone(); + preference_search_box_at(ui, t, &mut query, search_rect); + if query != before { + ui.data_mut(|d| d.insert_temp(search_id, query.clone())); + } + + ui.add_space(10.0); + + let mut matches_count = 0; + + // Card 1: General & Interface + let kw1 = &[ + "general", + "interface", + "language", + "size", + "tools", + "panel", + "side", + "animation", + "motion", + "reopen", + "session", + "restore", + "reload", + "recent", + "title", + ]; + let title1 = tl!("General & Interface"); + if matches_search(&query, title1, kw1) { + matches_count += 1; + preference_card(ui, t, title1, Some("settings"), |ui| { + card_general(ui, app, t); + }); + ui.add_space(12.0); + } + + // Card 2: Appearance & Theme + let kw2 = &["appearance", "theme", "dark", "light", "shadow", "edge", "highlight", "field", "reading", "colors", "colours", "custom", "contrast"]; + let title2 = tl_ctx!("theme", "Appearance"); + if matches_search(&query, title2, kw2) { + matches_count += 1; + preference_card(ui, t, title2, Some("sun"), |ui| { + card_appearance(ui, app, t); + }); + ui.add_space(12.0); + } + + // Card 3: Documents and View + let kw3 = + &["documents", "view", "workspace", "mode", "page", "display", "continuous", "scrolling", "gaps", "zoom", "fit", "units", "scroll", "speed"]; + let title3 = tl!("Documents and view"); + if matches_search(&query, title3, kw3) { + matches_count += 1; + preference_card(ui, t, title3, Some("file-text"), |ui| { + card_documents_and_view(ui, app, t); + }); + ui.add_space(12.0); + } + + // Card 4: Comment + let kw4 = &["comment", "comments", "identity", "name", "author", "preview", "hover", "highlight"]; + let title4 = tl!("Comment"); + if matches_search(&query, title4, kw4) { + matches_count += 1; + preference_card(ui, t, title4, Some("message-square-text"), |ui| { + card_identity(ui, app, t); + }); + ui.add_space(12.0); + } + + // Card 5: Fill & Sign + let kw5 = &["fill", "sign", "flatten", "date", "format", "pattern", "today", "language", "token"]; + let title5 = tl!("Fill & Sign"); + if matches_search(&query, title5, kw5) { + matches_count += 1; + preference_card(ui, t, title5, Some("pen-tool"), |ui| { + card_fill_and_sign(ui, app, t); + }); + ui.add_space(12.0); + } + + // Card 6: JavaScript + let kw6 = &["javascript", "js", "scripts", "sandbox", "security", "acrobat"]; + let title6 = "JavaScript"; + if matches_search(&query, title6, kw6) { + matches_count += 1; + preference_card(ui, t, title6, Some("code-xml"), |ui| { + card_javascript(ui, app, t); + }); + ui.add_space(12.0); + } + + // Empty search state when nothing matches + if matches_count == 0 { + ui.add_space(30.0); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover()); + icons::paint(ui, rect, "search", 32.0, t.text_muted); + ui.add_space(8.0); + ui.label(RichText::new(format!("No settings match \"{query}\"")).font(theme::medium(14.0)).color(t.text_muted)); + ui.add_space(10.0); + if widgets::pill_button(ui, tl!("Clear search"), false).clicked() { + ui.data_mut(|d| d.insert_temp(search_id, String::new())); + ui.ctx().request_repaint(); + } + }); + } +} + +/// Content for Card 1: General & Interface +fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + ui.horizontal(|ui| { + let label = ui.label(tl!("Interface language")); + 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(); + craft_ui::ComboBox::from_id_salt("interface-language") + .selected_text(selected) + .width(160.0) + .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); + if app.language != before { + crate::i18n::set_current(crate::i18n::Lang::from_pref(&app.language)); + } + + ui.add_space(16.0); + use crate::ui_scale; + let label_size = ui.label(tl!("Interface size")); + 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))); + craft_ui::ComboBox::from_id_salt("interface-size") + .selected_text(selected) + .width(130.0) + .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_size.id); + }); + ui.label( + RichText::new(tl!("Auto follows the system's text size. Pages always render at the display's full resolution.")).small().color(t.text_muted), + ); + ui.add_space(6.0); + + ui.horizontal(|ui| { + ui.label(tl!("Tools panel side")); + let right = app.side_panels.tools_on_right(); + let mut side = if right { ToolsSide::Right } else { ToolsSide::Left }; + if segmented_pill_choice(ui, t, &mut side, &[(ToolsSide::Left, tl!("Left")), (ToolsSide::Right, tl!("Right"))]) { + app.side_panels.tools_side = side; + } + + ui.add_space(16.0); + ui.label(tl!("Navigation rail side")); + let rail_right = app.side_panels.rail_on_right(); + let mut rside = if rail_right { ToolsSide::Right } else { ToolsSide::Left }; + if segmented_pill_choice_a11y( + ui, + t, + &mut rside, + &[(ToolsSide::Left, tl!("Left"), tl!("Navigation rail on left")), (ToolsSide::Right, tl!("Right"), tl!("Navigation rail on right"))], + ) { + app.side_panels.rail_side = rside; + } + }); + ui.add_space(6.0); + + ui.horizontal(|ui| { + ui.label(tl!("Animation effects")); + segmented_pill_choice( + ui, + t, + &mut app.animation_effects, + &[ + (AnimationEffects::System, tl_ctx!("animation effects", AnimationEffects::System.label())), + (AnimationEffects::On, tl_ctx!("animation effects", AnimationEffects::On.label())), + (AnimationEffects::Off, tl_ctx!("animation effects", AnimationEffects::Off.label())), + ], + ); + }); + ui.add_space(6.0); + + #[cfg(not(target_arch = "wasm32"))] + ui.add(widgets::checkbox(&mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed"))); + #[cfg(not(target_arch = "wasm32"))] + ui.add(widgets::checkbox(&mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again"))); + #[cfg(not(target_arch = "wasm32"))] + ui.add(widgets::checkbox(&mut app.reload_changed_files, tl!("Reload documents when their files change on disk"))); + ui.add(widgets::checkbox(&mut app.show_secured_notice, tl!("Show a notice when a document is secured"))); + + #[cfg(not(target_arch = "wasm32"))] + { + ui.horizontal(|ui| { + let label = ui.label(tl!("Recent files to keep")); + ui.add(egui::DragValue::new(&mut app.recent_limit).range(0..=crate::RECENT_FILES_MAX)).labelled_by(label.id); + }); + ui.label(RichText::new(tl!("Lowering this forgets the oldest files. At 0 there is no list.")).small().color(t.text_muted)); + } + + if app.window_controls.is_some() { + ui.add(widgets::checkbox(&mut app.system_title_bar, tl!("Use system title bar"))).on_hover_text(tl!( + "Show a basic title bar for the window buttons instead of the tab strip. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme." + )); + } +} + +/// Content for Card 2: Appearance & Theme +fn card_appearance(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + if ui.add(widgets::checkbox(&mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"))).changed() { + ui.ctx().request_repaint(); + } + ui.add_space(4.0); + crate::appearance::preferences_section(ui, app, t); + ui.add_space(8.0); + reading_colours_section(ui, app, t); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DisplayModeChoice { + Single, + TwoUp, + Continuous, +} + +/// Content for Card 3: Documents and View +fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + ui.horizontal(|ui| { + ui.label(tl!("Default workspace mode")); + segmented_pill_choice( + ui, + t, + &mut app.default_mode, + &[ + (crate::Mode::AllTools, tl!("All tools")), + (crate::Mode::Read, tl!("Read")), + (crate::Mode::Edit, tl!("Edit")), + (crate::Mode::Convert, tl!("Convert")), + (crate::Mode::Sign, tl!("E-Sign")), + ], + ); + }); + ui.label( + RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session.")) + .small() + .color(t.text_muted), + ); + ui.add_space(6.0); + + let defaults = &mut app.view_defaults; + ui.horizontal(|ui| { + ui.label(tl!("Default page display")); + let mut display_choice = if defaults.continuous { + DisplayModeChoice::Continuous + } else if defaults.layout == PageLayout::TwoUp { + DisplayModeChoice::TwoUp + } else { + DisplayModeChoice::Single + }; + if segmented_pill_choice( + ui, + t, + &mut display_choice, + &[ + (DisplayModeChoice::Single, tl!("Single page")), + (DisplayModeChoice::TwoUp, tl!("Two-page view")), + (DisplayModeChoice::Continuous, tl!("Continuous scrolling")), + ], + ) { + match display_choice { + DisplayModeChoice::Single => { + defaults.layout = PageLayout::Single; + defaults.continuous = false; + } + DisplayModeChoice::TwoUp => { + defaults.layout = PageLayout::TwoUp; + defaults.continuous = false; + } + DisplayModeChoice::Continuous => { + defaults.layout = PageLayout::Single; + defaults.continuous = true; + } + } + } + }); + ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages"))); + ui.label(RichText::new(tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged.")).small().color(t.text_muted)); + ui.add_space(6.0); + + ui.horizontal(|ui| { + ui.label(tl!("Default zoom")); + segmented_pill_choice( + ui, + t, + &mut defaults.fit, + &[(Fit::Width, tl!("Fit to width")), (Fit::Page, tl!("Zoom to page level")), (Fit::None, tl!("Custom"))], + ); + let mut percent = defaults.zoom * 100.0; + if ui.add(egui::DragValue::new(&mut percent).range(8.0..=6400.0).max_decimals(0).suffix("%")).changed() { + (defaults.fit, defaults.zoom) = (Fit::None, percent / 100.0); + } + }); + ui.label( + RichText::new(tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages.")) + .small() + .color(t.text_muted), + ); + ui.add(widgets::checkbox(&mut app.always_default_view, tl!("Always use my default zoom and page layout"))); + ui.add_space(6.0); + + ui.horizontal(|ui| { + ui.label(tl!("Units")); + segmented_pill_choice( + ui, + t, + &mut app.units, + &[ + (Unit::Inches, Unit::Inches.label()), + (Unit::Millimetres, Unit::Millimetres.label()), + (Unit::Centimetres, Unit::Centimetres.label()), + (Unit::Points, Unit::Points.label()), + ], + ); + }); + ui.label(RichText::new(tl!("For page sizes and margins.")).small().color(t.text_muted)); + ui.add_space(6.0); + + ui.horizontal(|ui| { + ui.label(tl!("Scroll speed (mouse wheel and arrow keys)")); + segmented_pill_choice( + ui, + t, + &mut app.scroll_speed, + &[ + (ScrollSpeed::Slow, tl_ctx!("scroll speed", ScrollSpeed::Slow.label())), + (ScrollSpeed::Normal, tl_ctx!("scroll speed", ScrollSpeed::Normal.label())), + (ScrollSpeed::Fast, tl_ctx!("scroll speed", ScrollSpeed::Fast.label())), + ], + ); + }); +} + +/// Content for Card 4: Identity +fn card_identity(ui: &mut egui::Ui, app: &mut PdfCraftApp, _t: &Tokens) { + ui.horizontal(|ui| { + let label = ui.label(tl!("Name on new comments")); + ui.add(crate::widgets::line(&mut app.comment_prefs.author).desired_width(240.0).char_limit(crate::MAX_AUTHOR_CHARS)).labelled_by(label.id); + }); + ui.add(widgets::checkbox(&mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text"))); +} + +/// Content for Card 5: Fill & Sign +fn card_fill_and_sign(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving"))); + ui.label(RichText::new(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")).small().color(t.text_muted)); + ui.add_space(8.0); + date_format(ui, app, t); +} + +/// Content for Card 6: JavaScript +fn card_javascript(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + let mut on = app.session.javascript(); + if ui.add(widgets::checkbox(&mut on, tl!("Enable Acrobat JavaScript"))).changed() { + app.session.set_javascript(on); + } + ui.label( + RichText::new(tl!( + "Scripts run in a sandbox without file or network access. A script that asks to open a web page needs your permission first. With JavaScript off, Acrobat's standard format, validate and calculate functions still work." + )) + .small() + .color(t.text_muted), + ); +} + +/// Preferences dialog buttons: Cancel and OK on the right. Returns true to close. +pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool { + ui.add_space(10.0); + let mut close = false; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::pill_button(ui, tl!("OK"), true).clicked() { + close = true; + } + if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { + close = true; + } + }); + }); + close +} + +/// Fill & Sign date pattern and date language picker. +fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + use pdfcraft_engine::dates::{DATE_FORMATS, DATE_LANGUAGES, MAX_DATE_FORMAT_CHARS}; + ui.label(RichText::new(tl!("Date format")).font(theme::semibold(12.5))); + let sample = |app: &PdfCraftApp, f: &str| format!("{} {f}", app.date_text(Some(f)).unwrap_or_default()); + ui.horizontal(|ui| { + let label = ui.label(tl!("Fill & Sign dates")); + let current = app.session.date_format().to_string(); + let selected = if DATE_FORMATS.contains(¤t.as_str()) { sample(app, ¤t) } else { tl!("Custom").to_string() }; + craft_ui::ComboBox::from_id_salt("date-format") + .selected_text(selected) + .width(240.0) + .show_ui(ui, |ui| { + for f in DATE_FORMATS { + if ui.selectable_label(current == f, sample(app, f)).clicked() && app.session.set_date_format(f).is_ok() { + app.date_format_draft = None; + ui.close(); + } + } + }) + .response + .labelled_by(label.id); + }); + ui.horizontal(|ui| { + let label = ui.label(tl!("Pattern")); + let mut text = app.date_format_draft.clone().unwrap_or_else(|| app.session.date_format().to_string()); + let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0).char_limit(MAX_DATE_FORMAT_CHARS)).labelled_by(label.id); + if edit.changed() { + let _ = app.session.set_date_format(&text); + app.date_format_draft = Some(text.clone()); + } + if !edit.has_focus() && pdfcraft_engine::dates::check_date_format(&text).is_ok() { + app.date_format_draft = None; + } + match app.date_text(Some(&text)) { + Ok(today) => ui.label(RichText::new(crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)])).color(t.text_muted)), + Err(e) => ui.label(RichText::new(e).color(Color32::from_rgb(0xD1, 0x3B, 0x3B))), + }; + }); + let bad = app.date_text(None).map(|today| pdfcraft_engine::dates::unwritable(&today)).unwrap_or_default(); + if !bad.is_empty() { + ui.label( + RichText::new(crate::i18n::fmt( + tl!( + "{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy." + ), + &[("chars", &bad)], + )) + .color(Color32::from_rgb(0xD1, 0x3B, 0x3B)), + ); + } + ui.horizontal(|ui| { + let label = ui.label(tl!("Language")); + 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) + }; + craft_ui::ComboBox::from_id_salt("date-language") + .selected_text(selected) + .width(240.0) + .show_ui(ui, |ui| { + if ui.selectable_label(current.is_none(), follow).clicked() && app.session.set_date_language(None).is_ok() { + ui.close(); + } + 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(); + } + } + }) + .response + .labelled_by(label.id); + }); + ui.label( + RichText::new(crate::i18n::fmt( + tl!("yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is."), + &[("escape", "\\")], + )) + .small() + .color(t.text_muted), + ); +} + +/// Reading colours settings: presets, preview and custom replacement options. +fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + ui.label(RichText::new(tl!("Reading colours")).font(theme::semibold(13.0))); + let mode = app.reading_colors.mode_name(); + ui.horizontal_wrapped(|ui| { + for (name, label, colors) in [ + ("off", "Off", pdfcraft_render::ReadingColors::default()), + ("black-on-white", "Black on white", pdfcraft_render::ReadingColors::BLACK_ON_WHITE), + ("white-on-black", "White on black", pdfcraft_render::ReadingColors::WHITE_ON_BLACK), + ("yellow-on-black", "Yellow on black", pdfcraft_render::ReadingColors::YELLOW_ON_BLACK), + ("green-on-black", "Green on black", pdfcraft_render::ReadingColors::GREEN_ON_BLACK), + ] { + let params = colors.params.unwrap_or(pdfcraft_render::ReadingParams { + text: [0, 0, 0], + background: [255, 255, 255], + only_black: false, + line_art: true, + }); + ui.vertical(|ui| { + ui.set_width(100.0); + let sample = RichText::new("Aa").size(20.0).color(Color32::from_rgb(params.text[0], params.text[1], params.text[2])); + let button = egui::Button::new(sample) + .fill(Color32::from_rgb(params.background[0], params.background[1], params.background[2])) + .min_size(vec2(90.0, 40.0)) + .stroke(Stroke::new(if mode == name { 2.0 } else { 1.0 }, if mode == name { t.accent } else { t.border })); + let response = ui.add(button); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, mode == name, tl!(label))); + if response.clicked() { + app.set_reading_colors(colors); + } + ui.label(tl!(label)); + }); + } + }); + ui.add_space(4.0); + if let Some(params) = app.reading_colors.params { + let text = Color32::from_rgb(params.text[0], params.text[1], params.text[2]); + let background = Color32::from_rgb(params.background[0], params.background[1], params.background[2]); + egui::Frame::new().fill(background).inner_margin(12.0).corner_radius(CornerRadius::same(6)).show(ui, |ui| { + ui.set_min_width((ui.available_width() - 24.0).max(0.0)); + ui.label(RichText::new(tl!("Reading colours")).size(16.0).color(text)); + ui.label(RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).color(text)); + }); + } else { + ui.label(tl!("Original")); + } + egui::CollapsingHeader::new(tl!("Custom")).default_open(mode == "custom").show(ui, |ui| { + let mut colors = if app.reading_colors.params.is_some() { app.reading_colors } else { pdfcraft_render::ReadingColors::BLACK_ON_WHITE }; + let mut changed = false; + if let Some(params) = colors.params.as_mut() { + ui.horizontal(|ui| { + let text = ui.label(tl!("Text")); + changed |= ui.color_edit_button_srgb(&mut params.text).labelled_by(text.id).changed(); + let background = ui.label(tl!("Page background")); + changed |= ui.color_edit_button_srgb(&mut params.background).labelled_by(background.id).changed(); + }); + changed |= ui.add(crate::widgets::checkbox(&mut params.only_black, tl!("Only change the colour of black text or line art"))).changed(); + changed |= ui.add(crate::widgets::checkbox(&mut params.line_art, tl!("Change the colour of line art as well as text"))).changed(); + } + if changed { + app.set_reading_colors(colors); + } + }); + ui.label(RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).small().color(t.text_muted)); +} diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 70c3f775e9..0a9b07764c 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -316,445 +316,10 @@ pub(crate) fn document_js_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok close } -/// The height the Preferences dialog keeps below its scrolling settings for the OK row: the -/// button, and the space above it. -pub(crate) const PREFERENCES_BUTTON_ROW: f32 = 52.0; - -/// The least height the scrolling settings are given. The dialog around them takes about 80 more, -/// so this still fits the smallest window (520 pt) at the largest interface size (300%, which -/// 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.label(egui::RichText::new(tl!("Appearance")).font(theme::semibold(13.0))); - if ui.add(widgets::checkbox(&mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"))).changed() { - ui.ctx().request_repaint(); - } - ui.horizontal(|ui| { - 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(); - craft_ui::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)); - } - }); - ui.horizontal(|ui| { - use crate::ui_scale; - 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))); - craft_ui::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.")) - .small() - .color(t.text_muted), - ); - ui.horizontal(|ui| { - ui.label(tl!("Tools panel side")); - 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() { - app.side_panels.tools_side = crate::side_panels::ToolsSide::Right; - } - }); - ui.horizontal(|ui| { - ui.label(tl!("Navigation rail side")); - let right = app.side_panels.rail_on_right(); - let left_btn = ui.selectable_label(!right, tl!("Left")); - left_btn.widget_info(|| { - egui::WidgetInfo::selected(egui::Role::Button, true, !right, format!("{}: {}", tl!("Navigation rail side"), tl!("Left"))) - }); - if left_btn.clicked() { - app.side_panels.rail_side = crate::side_panels::ToolsSide::Left; - } - let right_btn = ui.selectable_label(right, tl!("Right")); - right_btn.widget_info(|| { - egui::WidgetInfo::selected(egui::Role::Button, true, right, format!("{}: {}", tl!("Navigation rail side"), tl!("Right"))) - }); - if right_btn.clicked() { - app.side_panels.rail_side = crate::side_panels::ToolsSide::Right; - } - }); - ui.add_space(8.0); - crate::appearance::preferences_section(ui, app, t); - ui.add_space(8.0); - reading_colours_section(ui, app, t); - ui.add_space(8.0); - ui.label(egui::RichText::new(tl!("Documents and view")).font(theme::semibold(13.0))); - ui.horizontal(|ui| { - ui.label(tl!("Default workspace mode")); - for (mode, label) in [ - (crate::Mode::AllTools, "All tools"), - (crate::Mode::Read, "Read"), - (crate::Mode::Edit, "Edit"), - (crate::Mode::Convert, "Convert"), - (crate::Mode::Sign, "E-Sign"), - ] { - widgets::radio_value(ui, &mut app.default_mode, mode, tl!(label)); - } - }); - ui.label( - egui::RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session.")) - .small() - .color(t.text_muted), - ); - let defaults = &mut app.view_defaults; - ui.horizontal(|ui| { - ui.label(tl!("Default page display")); - for l in crate::canvas::PageLayout::ORDER { - widgets::radio_value(ui, &mut defaults.layout, l, tl!(l.label())); - } - ui.add(widgets::checkbox(&mut defaults.continuous, tl!("Continuous scrolling"))); - }); - ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages"))); - ui.label(egui::RichText::new(tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged.")).small().color(t.text_muted)); - ui.horizontal(|ui| { - use crate::canvas::Fit; - ui.label(tl!("Default zoom")); - widgets::radio_value(ui, &mut defaults.fit, Fit::Width, tl!("Fit to width")); - widgets::radio_value(ui, &mut defaults.fit, Fit::Page, tl!("Zoom to page level")); - widgets::radio_value(ui, &mut defaults.fit, Fit::None, tl!("Custom")); - // Editing the percentage selects Custom. - let mut percent = defaults.zoom * 100.0; - if ui.add(egui::DragValue::new(&mut percent).range(8.0..=6400.0).max_decimals(0).suffix("%")).changed() { - (defaults.fit, defaults.zoom) = (Fit::None, percent / 100.0); - } - }); - ui.label( - egui::RichText::new(tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages.")) - .small() - .color(t.text_muted), - ); - ui.add(widgets::checkbox(&mut app.always_default_view, tl!("Always use my default zoom and page layout"))); - ui.horizontal(|ui| { - ui.label(tl!("Units")); - for u in crate::units::Unit::ALL { - widgets::radio_value(ui, &mut app.units, u, u.label()); - } - }); - ui.label(egui::RichText::new(tl!("For page sizes and margins.")).small().color(t.text_muted)); - // The web build has no file paths to list. - #[cfg(not(target_arch = "wasm32"))] - { - ui.horizontal(|ui| { - let label = ui.label(tl!("Recent files to keep")); - ui.add(egui::DragValue::new(&mut app.recent_limit).range(0..=crate::RECENT_FILES_MAX)).labelled_by(label.id); - }); - ui.label(egui::RichText::new(tl!("Lowering this forgets the oldest files. At 0 there is no list.")).small().color(t.text_muted)); - } - // The web build has no file paths to reopen. - #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed"))); - // Acrobat's "Restore last view settings when reopening documents" (#1767). - #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again"))); - // The web build has no files on disk to watch. - #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.reload_changed_files, tl!("Reload documents when their files change on disk"))); - // The notice's "Don't show again" turns this off (#4035); the restrictions stay either way. - ui.add(widgets::checkbox(&mut app.show_secured_notice, tl!("Show a notice when a document is secured"))); - ui.horizontal(|ui| { - ui.label(tl!("Scroll speed (mouse wheel and arrow keys)")); - for speed in crate::scroll_speed::ScrollSpeed::ALL { - widgets::radio_value(ui, &mut app.scroll_speed, speed, tl_ctx!("scroll speed", speed.label())); - } - }); - // Whether anything animates, the wheel's scrolling and zooming included; left alone it - // follows the system's animation setting. - ui.horizontal(|ui| { - ui.label(tl!("Animation effects")); - for choice in crate::motion::AnimationEffects::ALL { - widgets::radio_value(ui, &mut app.animation_effects, choice, tl_ctx!("animation effects", choice.label())); - } - }); - // Only where the app draws the title bar (GNOME on Wayland); elsewhere the desktop draws it. - if app.window_controls.is_some() { - ui.add(widgets::checkbox(&mut app.system_title_bar, tl!("Use system title bar"))) - .on_hover_text(tl!("Show a basic title bar for the window buttons instead of the tab strip. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme.")); - } - ui.add_space(8.0); - // Identity: the author of new comments (Acrobat: Preferences ▸ Identity). - ui.label(egui::RichText::new(tl!("Identity")).font(theme::semibold(13.0))); - ui.horizontal(|ui| { - let label = ui.label(tl!("Name on new comments")); - ui.add(crate::widgets::line(&mut app.comment_prefs.author).desired_width(220.0).char_limit(crate::MAX_AUTHOR_CHARS)).labelled_by(label.id); - }); - ui.add(widgets::checkbox(&mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text"))); - ui.add_space(8.0); - ui.label(egui::RichText::new(tl!("Fill & Sign")).font(theme::semibold(13.0))); - ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving"))); - ui.label( - egui::RichText::new(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")).small().color(t.text_muted), - ); - ui.add_space(8.0); - date_format(ui, app, t); - ui.add_space(8.0); - ui.label(egui::RichText::new("JavaScript").font(theme::semibold(13.0))); - egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| { - ui.set_width(ui.available_width()); - let mut on = app.session.javascript(); - if ui.add(widgets::checkbox(&mut on, tl!("Enable Acrobat JavaScript"))).changed() { - app.session.set_javascript(on); - } - ui.label( - egui::RichText::new(tl!("Scripts run in a sandbox without file or network access. A script that asks to open a web page needs your permission first. With JavaScript off, Acrobat's standard format, validate and calculate functions still work.")) - .small() - .color(t.text_muted), - ); - }); -} - -/// The Preferences dialog's OK row. Returns `true` to close. -pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool { - ui.add_space(10.0); - buttons(ui, tl!("OK"), &[]).is_some() -} - -/// Preferences ▸ Date format: a preset, or any pattern typed in, for Fill & Sign dates, and the -/// language of its month and weekday names. A valid pattern applies as it's typed; an invalid -/// one stays in the box with the reason, and the last valid one stays in use. -fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - use pdfcraft_engine::dates::{DATE_FORMATS, DATE_LANGUAGES, MAX_DATE_FORMAT_CHARS}; - ui.label(egui::RichText::new(tl!("Date format")).font(theme::semibold(13.0))); - let sample = |app: &PdfCraftApp, f: &str| format!("{} {f}", app.date_text(Some(f)).unwrap_or_default()); - ui.horizontal(|ui| { - let label = ui.label(tl!("Fill & Sign dates")); - let current = app.session.date_format().to_string(); - let selected = if DATE_FORMATS.contains(¤t.as_str()) { sample(app, ¤t) } else { tl!("Custom").to_string() }; - craft_ui::ComboBox::from_id_salt("date-format") - .selected_text(selected) - .width(240.0) - .show_ui(ui, |ui| { - for f in DATE_FORMATS { - if ui.selectable_label(current == f, sample(app, f)).clicked() && app.session.set_date_format(f).is_ok() { - app.date_format_draft = None; - ui.close(); - } - } - }) - .response - .labelled_by(label.id); - }); - ui.horizontal(|ui| { - let label = ui.label(tl!("Pattern")); - let mut text = app.date_format_draft.clone().unwrap_or_else(|| app.session.date_format().to_string()); - let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0).char_limit(MAX_DATE_FORMAT_CHARS)).labelled_by(label.id); - // The box keeps the text as typed (a trailing space included) while it has focus; the - // setting takes the trimmed pattern whenever it's valid. - if edit.changed() { - let _ = app.session.set_date_format(&text); - app.date_format_draft = Some(text.clone()); - } - if !edit.has_focus() && pdfcraft_engine::dates::check_date_format(&text).is_ok() { - app.date_format_draft = None; - } - match app.date_text(Some(&text)) { - Ok(today) => ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)])).color(t.text_muted)), - // The engine's reason, in English. - Err(e) => ui.label(egui::RichText::new(e).color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B))), - }; - }); - // Fill & Sign refuses a date it would save as "?"; say so before anyone tries. - let bad = app.date_text(None).map(|today| pdfcraft_engine::dates::unwritable(&today)).unwrap_or_default(); - if !bad.is_empty() { - ui.label( - egui::RichText::new(crate::i18n::fmt( - tl!( - "{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy." - ), - &[("chars", &bad)], - )) - .color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B)), - ); - } - ui.horizontal(|ui| { - let label = ui.label(tl!("Language")); - // 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) - }; - craft_ui::ComboBox::from_id_salt("date-language") - .selected_text(selected) - .width(240.0) - .show_ui(ui, |ui| { - if ui.selectable_label(current.is_none(), follow).clicked() && app.session.set_date_language(None).is_ok() { - ui.close(); - } - 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(); - } - } - }) - .response - .labelled_by(label.id); - }); - ui.label( - egui::RichText::new(crate::i18n::fmt( - tl!("yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is."), - &[("escape", "\\")], - )) - .small() - .color(t.text_muted), - ); -} - -fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - // Reading colours (Acrobat: Replace Document Colors): solid text and line-art paints are - // remapped while rendering, and the page clears to the background colour. The preference - // 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))); - let mode = app.reading_colors.mode_name(); - ui.horizontal_wrapped(|ui| { - for (name, label, colors) in [ - ("off", "Off", pdfcraft_render::ReadingColors::default()), - ("black-on-white", "Black on white", pdfcraft_render::ReadingColors::BLACK_ON_WHITE), - ("white-on-black", "White on black", pdfcraft_render::ReadingColors::WHITE_ON_BLACK), - ("yellow-on-black", "Yellow on black", pdfcraft_render::ReadingColors::YELLOW_ON_BLACK), - ("green-on-black", "Green on black", pdfcraft_render::ReadingColors::GREEN_ON_BLACK), - ] { - let params = colors.params.unwrap_or(pdfcraft_render::ReadingParams { - text: [0, 0, 0], - background: [255, 255, 255], - only_black: false, - line_art: true, - }); - ui.vertical(|ui| { - ui.set_width(104.0); - let sample = egui::RichText::new("Aa").size(22.0).color(egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2])); - let button = egui::Button::new(sample) - .fill(egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2])) - .min_size(egui::vec2(94.0, 44.0)) - .stroke(egui::Stroke::new(if mode == name { 2.0 } else { 1.0 }, if mode == name { t.accent } else { t.border })); - let response = ui.add(button); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, mode == name, tl!(label))); - if response.clicked() { - app.set_reading_colors(colors); - } - ui.label(tl!(label)); - }); - } - }); - ui.add_space(8.0); - if let Some(params) = app.reading_colors.params { - let text = egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2]); - let background = egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2]); - egui::Frame::new().fill(background).inner_margin(16.0).show(ui, |ui| { - ui.set_min_width((ui.available_width() - 32.0).max(0.0)); - ui.label(egui::RichText::new(tl!("Reading colours")).size(18.0).color(text)); - ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).color(text)); - }); - } else { - ui.label(tl!("Original")); - } - egui::CollapsingHeader::new(tl!("Custom")).default_open(mode == "custom").show(ui, |ui| { - let mut colors = if app.reading_colors.params.is_some() { app.reading_colors } else { pdfcraft_render::ReadingColors::BLACK_ON_WHITE }; - let mut changed = false; - if let Some(params) = colors.params.as_mut() { - ui.horizontal(|ui| { - let text = ui.label(tl!("Text")); - changed |= ui.color_edit_button_srgb(&mut params.text).labelled_by(text.id).changed(); - let background = ui.label(tl!("Page background")); - changed |= ui.color_edit_button_srgb(&mut params.background).labelled_by(background.id).changed(); - }); - changed |= ui.add(crate::widgets::checkbox(&mut params.only_black, tl!("Only change the colour of black text or line art"))).changed(); - changed |= ui.add(crate::widgets::checkbox(&mut params.line_art, tl!("Change the colour of line art as well as text"))).changed(); - } - if changed { - app.set_reading_colors(colors); - } - }); - ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).small().color(t.text_muted)); - ui.add_space(8.0); -} +#[expect(unused_imports, reason = "re-exported for tests and backward compatibility")] +pub(crate) use crate::dialogs::preferences::{ + PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, +}; #[cfg(test)] mod tests { diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index 1ebe06b7a0..a20d786965 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -102,3 +102,98 @@ fn a_very_tall_window_does_not_leave_a_blank_gap_above_ok() { assert!(on_screen(ok, 2600.0) && on_screen(last, 2600.0), "{last:?} {ok:?}"); assert!(ok.min.y - last.max.y < 120.0, "a gap of {} pt between the last setting and OK", ok.min.y - last.max.y); } + +#[test] +fn segmented_pill_controls_switch_modes_and_layouts() { + let mut h = harness(900.0); + // Switch workspace mode via segmented pill + h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").scroll_to_me(); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").click(); + h.run_steps(2); + assert_eq!(h.state().default_mode, pdfcraft_ui_egui::Mode::Convert); + + // Switch page layout via segmented pill + h.get_by_label("Two-page view").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Two-page view").click(); + h.run_steps(2); + assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp); + + // Switch continuous scrolling pill + let continuous_before = h.state().view_defaults.continuous; + h.get_by_label("Continuous scrolling").click(); + h.run_steps(2); + assert_eq!(h.state().view_defaults.continuous, !continuous_before); + + // Switch to single page mode + h.get_by_label("Single page").click(); + h.run_steps(2); + assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::Single); + assert!(!h.state().view_defaults.continuous); + + // Switch tools panel side via segmented pill + h.get_by_label("Left").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Left").click(); + h.run_steps(2); + assert_eq!(h.state().side_panels.tools_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left); + + // Switch measurement units via segmented pill + h.get_by_label("pt").scroll_to_me(); + h.run_steps(3); + h.get_by_label("pt").click(); + h.run_steps(2); + assert_eq!(h.state().units, pdfcraft_ui_egui::units::Unit::Points); +} + +#[test] +fn cancel_button_closes_preferences_dialog() { + let mut h = harness(900.0); + assert!(h.state().dialog.is_some()); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().dialog.is_none()); +} + +#[test] +fn search_settings_filters_cards_in_real_time() { + let mut h = harness(900.0); + // Initially all card titles exist + assert!(h.query_by_label("General & Interface").is_some()); + assert!(h.query_by_label("Comment").is_some()); + assert!(h.query_by_label("JavaScript").is_some()); + + // Type in search box to filter to JavaScript card + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click(); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("javascript"); + h.run_steps(3); + + // JavaScript card is visible, General & Interface is filtered out + assert!(h.query_by_label("JavaScript").is_some()); + assert!(h.query_by_label("General & Interface").is_none()); + + // Clearing search shows everything again + h.get_by_label("Clear search").click(); + h.run_steps(3); + assert!(h.query_by_label("General & Interface").is_some()); + assert!(h.query_by_label("Comment").is_some()); + assert!(h.query_by_label("JavaScript").is_some()); +} + +#[test] +fn preferences_dialog_scrollbar_spacing_and_controls() { + let h = harness(600.0); + let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect(); + let search = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").rect(); + let ok = h.get_by_label("OK").rect(); + let cancel = h.get_by_label("Cancel").rect(); + assert!(cancel.min.x < ok.min.x); + assert!(on_screen(ok, 600.0)); + assert!(on_screen(cancel, 600.0)); + // Header title and search box are vertically aligned + assert!((title.center().y - search.center().y).abs() <= 2.0); + // Search box right edge is aligned within the dialog + assert!(search.max.x <= ok.max.x); +} diff --git a/crates/ui-egui/tests/it/theme.rs b/crates/ui-egui/tests/it/theme.rs index a02c5c05ca..1f2709cd56 100644 --- a/crates/ui-egui/tests/it/theme.rs +++ b/crates/ui-egui/tests/it/theme.rs @@ -242,11 +242,11 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { assert_theme(&h, ThemePreference::System, ThemeKind::Dark); assert_eq!(mode_shown(&h), "Use system setting"); - // The OS is dark: the Dark card's radio row picks Dark, and the combo box says so. + // The OS is dark: the Dark card picks Dark, and the combo box says so. // The cards sit below the fold of the Preferences scroll area at this window size. - h.get_by_label("Dark gray").scroll_to_me(); + h.get_by_label("Dark theme").scroll_to_me(); h.run_steps(3); - h.get_by_label("Dark gray").click(); + h.get_by_label("Dark theme").click(); h.run_steps(3); assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); assert_eq!(mode_shown(&h), "Dark"); From f035218cb47e414ccc649c59229315bab8d89f0b Mon Sep 17 00:00:00 2001 From: Elarionus <29511515+Elarionus@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:49:10 -0800 Subject: [PATCH 02/15] fix(ui): don't check recent files on the UI thread at startup (#5682) (#5692) * fix(ui): don't check recent files on the UI thread at startup (#5682) Restoring settings dropped recent files whose files no longer exist by asking the file system about each one on the UI thread, before the first frame. On a network mount that has stopped answering (davfs2 in the report) that call blocks in the kernel, so the window never appears. Settings now keep every recent entry when they load. Once the window is up, a worker checks the restored paths and each frame drops the ones it has found gone. An entry it hasn't reached, or can't tell about (the mount answers with an error), stays listed. A worker stuck on a dead mount stays stuck, but nothing waits for it. This follows the pinned folders' worker. Fixes #5682 Co-Authored-By: Claude Opus 5.5 * Recent files: a file opened while the check is pending stays listed The worker's answer that a restored path is gone is out of date once the user opens that path; keep the new entry (CodeRabbit on #5692). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/files.rs | 1 + crates/ui-egui/src/app/prefs.rs | 6 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/persist.rs | 1 + crates/ui-egui/src/persist/recent_check.rs | 125 +++++++++++++++++++++ crates/ui-egui/tests/it/recent_files.rs | 33 ++++++ 7 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/persist/recent_check.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 43d0066e63..c326b479fe 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -144,6 +144,7 @@ impl PdfCraftApp { #[cfg(all(test, not(target_arch = "wasm32")))] open_prepare_gate: None, pinned: Default::default(), + recent_check: Default::default(), pinned_tools: Vec::new(), pin_tool_search: String::new(), toast: None, @@ -452,6 +453,7 @@ impl eframe::App for PdfCraftApp { } self.poll_pending_opens(); } + self.check_restored_recent(); // Chinese wants its own faces before the Japanese ones (one baseline per line). let cjk = theme::CjkPreference::for_language(lang.code()); if !self.styled { diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 29e6978461..9991047077 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -332,6 +332,7 @@ impl PdfCraftApp { #[cfg(target_os = "macos")] macos_association::repair(std::path::Path::new(&p)); self.recent.retain(|r| r.path != p); + self.recent_check.opened(&p); self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size }); self.recent.truncate(self.recent_limit); } diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 7bd8943774..7eddee0af0 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -182,9 +182,9 @@ impl PdfCraftApp { self.organize_zoom = zoom.clamp(*canvas::GRID_ZOOM_RANGE.start(), *canvas::GRID_ZOOM_RANGE.end()); } if let Ok(r) = serde_json::from_value::>(v["recent"].clone()) { - // Only keep entries whose files still exist. - #[cfg(not(target_arch = "wasm32"))] - let r: Vec = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect(); + // Entries whose files are gone leave once the window is up: asking here could block + // startup on a mount that has stopped answering (#5682). + self.recent_check.restored(r.iter().map(|f| f.path.clone()).collect()); self.recent = r; } // Nonsense keeps the limit it had; settings from before the limit have none. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fe0138f27f..c25dae98e3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -392,6 +392,8 @@ pub struct PdfCraftApp { open_prepare_gate: Option>, /// Folders pinned to Home, and what they held when last listed. pub pinned: folders_ui::PinnedFolders, + /// The recent files restored from settings, checked off the UI thread (#5682). + recent_check: persist::recent_check::RecentCheck, /// Tools pinned to Home, in user-defined order. pub pinned_tools: Vec, /// Search query for the Pin a tool selection dialog. diff --git a/crates/ui-egui/src/persist.rs b/crates/ui-egui/src/persist.rs index 32a8ec048d..20ccecdd3f 100644 --- a/crates/ui-egui/src/persist.rs +++ b/crates/ui-egui/src/persist.rs @@ -1,6 +1,7 @@ pub mod last_session; pub mod last_view; pub mod paper; +pub(crate) mod recent_check; pub(super) mod recovery; pub mod units; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/persist/recent_check.rs b/crates/ui-egui/src/persist/recent_check.rs new file mode 100644 index 0000000000..8c7db75f8b --- /dev/null +++ b/crates/ui-egui/src/persist/recent_check.rs @@ -0,0 +1,125 @@ +//! Recent files whose files are gone leave the list, without the window waiting to find out +//! (#5682). +//! +//! A recent file can be on a network or cloud mount that has stopped answering, where even +//! asking whether the file exists blocks in the kernel, and no timeout can cancel that. So +//! settings keep every recent entry when they load, and a worker asks about them once the window +//! is up; each frame only takes the answers it has so far. An entry the worker hasn't reached +//! yet, or can't tell about (the mount answers with an error), stays listed and can be opened or +//! removed by hand. A worker stuck on a dead mount stays stuck, but nothing waits for it. + +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::PdfCraftApp; + +/// The recent files restored from settings that haven't been checked yet, and the check under way. +#[derive(Debug, Default)] +pub struct RecentCheck { + /// Paths restored from settings, checked on the next frame. + unchecked: Vec, + /// The paths the worker has found gone so far; it adds to them as it goes. + gone: Option>>>, + /// Paths opened while a check was pending: the file is there now, whatever the worker found. + opened: Vec, +} + +impl RecentCheck { + /// Settings just restored these recent files: check them once the window is up. + pub(crate) fn restored(&mut self, paths: Vec) { + self.unchecked = paths; + } + + /// `path` was just opened: an answer the worker gives about it later is out of date. + pub(crate) fn opened(&mut self, path: &str) { + if self.gone.is_some() || !self.unchecked.is_empty() { + self.opened.push(path.to_string()); + } + } +} + +/// Whether `path` is known to be gone. Any other answer, an error included, keeps the entry. +fn gone(path: &str) -> bool { + matches!(std::fs::exists(path), Ok(false)) +} + +impl PdfCraftApp { + /// Start checking the recent files restored from settings, and drop the ones found gone so + /// far (called each frame). The check runs on a worker thread, inline in tests + /// ([`PdfCraftApp::run_inline`]). + pub(crate) fn check_restored_recent(&mut self) { + let paths = std::mem::take(&mut self.recent_check.unchecked); + // The web build's recent files aren't paths on a file system. + if !paths.is_empty() && !cfg!(target_arch = "wasm32") { + let slot = Arc::new(Mutex::new(Vec::new())); + let out = slot.clone(); + let ctx = self.ctx.clone(); + let work = move || { + for path in paths { + if gone(&path) { + out.lock().unwrap_or_else(PoisonError::into_inner).push(path); + if let Some(ctx) = &ctx { + ctx.request_repaint(); + } + } + } + }; + if self.run_inline { + work(); + } else if std::thread::Builder::new().name("pdfcraft-recent".into()).spawn(work).is_err() { + // No worker: the entries stay listed, as if the check hadn't reached them. + return; + } + self.recent_check.gone = Some(slot); + } + let Some(slot) = &self.recent_check.gone else { return }; + // Asked before taking, so a path the worker adds after this is taken on a later frame. + let finished = Arc::strong_count(slot) == 1; + let gone = std::mem::take(&mut *slot.lock().unwrap_or_else(PoisonError::into_inner)); + if !gone.is_empty() { + // A file opened since the check began is there, whatever the worker found earlier. + let opened = &self.recent_check.opened; + self.recent.retain(|r| !gone.contains(&r.path) || opened.contains(&r.path)); + } + // The worker has finished (or panicked) and everything it found is taken. + if finished { + self.recent_check.gone = None; + self.recent_check.opened.clear(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A file opened after the worker found it gone, but before that answer was taken, stays + /// listed (CodeRabbit on #5692). + #[test] + fn a_file_opened_while_the_check_is_pending_stays() { + let mut app = PdfCraftApp::new(); + app.recent = vec![crate::state::RecentFile { name: "a.pdf".into(), path: "/gone/a.pdf".into(), pages: 1, size: 0 }]; + // The worker's answer is waiting: it found the file gone. + app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()]))); + app.recent_check.opened("/gone/a.pdf"); + app.check_restored_recent(); + assert_eq!(app.recent.len(), 1, "the reopened file stays"); + assert!(app.recent_check.gone.is_none() && app.recent_check.opened.is_empty()); + // Without the open, the answer removes it. + app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()]))); + app.check_restored_recent(); + assert!(app.recent.is_empty()); + } + + #[test] + fn only_a_path_known_to_be_missing_is_gone() { + let dir = std::env::temp_dir().join(format!("pdfcraft-recent-check-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let here = dir.join("here.pdf"); + std::fs::write(&here, b"%PDF-1.7").unwrap(); + assert!(!gone(&here.to_string_lossy())); + assert!(gone(&dir.join("missing.pdf").to_string_lossy())); + // A path that can't be asked about (here: one with a NUL) is not known to be gone. + assert!(!gone("bad\0path.pdf")); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/ui-egui/tests/it/recent_files.rs b/crates/ui-egui/tests/it/recent_files.rs index b4eccfb10e..e3f7721d2f 100644 --- a/crates/ui-egui/tests/it/recent_files.rs +++ b/crates/ui-egui/tests/it/recent_files.rs @@ -221,6 +221,39 @@ fn the_limit_is_saved_and_restored_and_cuts_a_longer_list() { std::fs::remove_dir_all(&dir).unwrap(); } +/// #5682: restoring settings never asks the file system about recent files, which can block on a +/// mount that has stopped answering. A gone file leaves the list once frames run, and a file that +/// is there stays. +#[test] +fn restoring_settings_does_not_check_recent_files_and_a_frame_drops_the_gone_ones() { + let dir = std::env::temp_dir().join(format!("pdfcraft-recent-restore-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let here = dir.join("here.pdf"); + std::fs::write(&here, PDF).unwrap(); + let here = here.to_string_lossy().into_owned(); + let gone = dir.join("gone.pdf").to_string_lossy().into_owned(); + let entries: Vec = + [&here, &gone].iter().map(|p| RecentFile { name: "x.pdf".into(), path: (*p).clone(), pages: 1, size: 0 }).collect(); + let json = serde_json::json!({ "recent": entries }).to_string(); + + let mut restored = PdfCraftApp::new(); + restored.restore(&json); + let paths: Vec<&str> = restored.recent.iter().map(|r| r.path.as_str()).collect(); + assert_eq!(paths, [here.as_str(), gone.as_str()], "restoring keeps every entry without asking whether its file exists"); + + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.run_inline = true; + app.restore(&json); + app + }); + h.run_steps(2); + let paths: Vec<&str> = h.state().recent.iter().map(|r| r.path.as_str()).collect(); + assert_eq!(paths, [here.as_str()], "the gone file leaves once the window is up"); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_settings_file_can_not_ask_for_a_limit_that_is_not_one() { for (saved, want) in [ From 8faebd0d96eb158ade0eea4c6825fac6fc682319 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 05:49:14 +0100 Subject: [PATCH 03/15] Fix Matrix::invert rejecting valid matrices with a small scale (#5703) * Fix Matrix::invert rejecting valid matrices with a small scale Found while testing crates/content/src/lib.rs:732-735 (Matrix::invert) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * Matrix::invert: a matrix whose inverse overflows has none A subnormal determinant passes the relative check, and dividing by it overflows (CodeRabbit on #5703). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/content/src/lib.rs | 7 +++++-- crates/content/src/tests.rs | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs index c52916d332..4957f86861 100644 --- a/crates/content/src/lib.rs +++ b/crates/content/src/lib.rs @@ -730,11 +730,14 @@ impl Matrix { pub fn invert(&self) -> Option { let [a, b, c, d, e, f] = self.0; let det = a * d - b * c; - if det.abs() < 1e-12 || !det.is_finite() { + if det == 0.0 || !det.is_finite() || det.abs() <= 1e-12 * ((a * d).abs() + (b * c).abs()) { return None; } let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); - Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)])) + let inverse = [ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]; + // A determinant that underflows toward zero can still pass the relative check above, + // and dividing by it overflows: such a matrix has no usable inverse. + inverse.iter().all(|v| v.is_finite()).then_some(Matrix(inverse)) } /// The bounding box of a rectangle `[x0 y0 x1 y1]` after this transform. diff --git a/crates/content/src/tests.rs b/crates/content/src/tests.rs index c5c7a3aaac..9ac9297cd2 100644 --- a/crates/content/src/tests.rs +++ b/crates/content/src/tests.rs @@ -552,3 +552,17 @@ fn inline_images_end_where_the_renderer_ends_them() { assert_eq!((parsed.skipped, parsed.ambiguous_images), (0, 0), "{}", String::from_utf8_lossy(data)); } } + +#[test] +fn invert_accepts_small_scale_and_rejects_singular() { + let m = Matrix([1e-7, 0., 0., 1e-7, 0., 0.]); + let inv = m.invert().expect("a uniform 1e-7 scale is invertible"); + let id = m.then(&inv).0; + for (got, want) in id.iter().zip(Matrix::IDENTITY.0) { + assert!((got - want).abs() < 1e-9, "{id:?}"); + } + assert!(Matrix([1., 2., 2., 4., 0., 0.]).invert().is_none()); + assert!(Matrix([f64::NAN, 0., 0., 1., 0., 0.]).invert().is_none()); + // A subnormal scale passes the relative check but its inverse overflows (CodeRabbit on #5703). + assert!(Matrix([1e-310, 0., 0., 1., 0., 0.]).invert().is_none()); +} From d3384340a628bd728389eba71371fa6f7c9b0b4e Mon Sep 17 00:00:00 2001 From: AdrianTM Date: Sun, 1 Nov 2026 23:49:18 -0500 Subject: [PATCH 04/15] M7: make page-mark replacement transactional (#5657) (#5704) * M7: make page-mark replacement transactional (#5657) * ROADMAP: drop the header line (the log entry stays) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- ROADMAP.md | 3 + crates/edit/src/apply.rs | 32 +++- crates/edit/src/lib.rs | 5 + crates/edit/src/mark_transaction_tests.rs | 211 ++++++++++++++++++++++ crates/edit/src/place.rs | 27 ++- crates/edit/src/tests.rs | 3 + docs/roadmap.md | 5 +- parity/acrobat-features.toml | 12 +- 8 files changed, 287 insertions(+), 11 deletions(-) create mode 100644 crates/edit/src/mark_transaction_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 6e7140b909..a39d6f8b6c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -219,6 +219,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md ## Progress log +- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged. + - **2026-11-01 (M14, #5572):** Preferences ▸ Documents and view sets how many recent files to keep, from 0 to 50 with 12 by default. At 0 Home has no Recent section and File ▸ Open Recent is disabled. The list is cut when Preferences closes, so the number can pass through 0 on its way to another. - **2026-11-01 (M5/M14, customizable hotbar, freehand highlight, and moveable navigation rail):** Added Freehand-Highlight (`/Subtype /Ink`, `/IT /FreehandHighlight`, Multiply blending, 100 pt max line width) inside the standard Highlight flyout and headless `comment_add`; added a customizable floating or side-docked hotbar with a full-side chrome strip mode, settings gear icon anchored at the bar end, and 24–64 px sizing; and added Left/Right docking for the navigation rail (`rail_side`). Focused unit and integration tests pass across `annot`, `automation`, and `ui-egui`. Estimates unchanged. @@ -743,6 +745,7 @@ Newest first: the date, what moved, and the new overall estimate. | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. | | 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. | | 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. | | 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. | diff --git a/crates/edit/src/apply.rs b/crates/edit/src/apply.rs index ff570d5483..0d0213904b 100644 --- a/crates/edit/src/apply.rs +++ b/crates/edit/src/apply.rs @@ -7,9 +7,25 @@ use super::place::{ }; use super::{Document, EditError, Object, added, backdrop, helvetica_width}; +/// Commit one complete mark operation only after every selected page succeeds. The snapshot +/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table +/// and document metadata are copied. Dropping a failed stage also drops removed marks, changed +/// page/resources/backdrop dictionaries and new objects, including the allocation cursor. +fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) -> Result<(), EditError>) -> Result<(), EditError> { + let mut staged = doc.clone(); + apply(&mut staged)?; + *doc = staged; + Ok(()) +} + /// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on -/// those pages are removed first (Acrobat's Replace Existing). +/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic: +/// on error, the document (including earlier selected pages) is unchanged. pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { + apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx)) +} + +fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; if hf.text.iter().all(|t| t.trim().is_empty()) { @@ -121,8 +137,13 @@ pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, Ok(()) } -/// Add a text watermark to `pages`. +/// Add a text or picture watermark to `pages`. All selected pages, including mark replacement, +/// form one transaction; on error, the document is unchanged. pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> { + apply_mark_transaction(doc, |staged| add_watermark_in_place(staged, pages, wm, replace)) +} + +fn add_watermark_in_place(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; let text = wm.text.trim(); @@ -201,8 +222,13 @@ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replac /// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a /// white backdrop a page paints itself is replaced first, so the background shows (see -/// [`backdrop`]); a picture backdrop (a scan) still hides it. +/// [`backdrop`]); a picture backdrop (a scan) still hides it. All selected pages, including +/// replacement and backdrop edits, form one transaction; on error, the document is unchanged. pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> { + apply_mark_transaction(doc, |staged| add_background_in_place(staged, pages, bg, replace)) +} + +fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> { let all = page_list(doc); check(pages, all.len())?; if replace { diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index aa11617c14..44a6730acc 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -1,6 +1,11 @@ //! pdfcraft-edit — page content editing (L4). Today: page marks, Acrobat's Header & footer, //! Watermark, Background and Bates numbering (execution plan M7.6). //! +//! **Atomic page-mark operations.** Adding or replacing headers/footers, watermarks and backgrounds +//! stages the whole call on a document snapshot and commits only after every selected page succeeds. +//! An error preserves existing marks, content, resources, pending edits and allocated objects. The +//! snapshot shares original PDF bytes and unchanged objects; it copies the overlay table and metadata. +//! //! **How marks are stored.** Each mark is one content stream appended to (or, for content behind //! the page, inserted after the backgrounds at the start of) the page's `/Contents`, drawn in //! display space (after `/Rotate`) and wrapped in a marked-content artifact (§14.8.2.2) so diff --git a/crates/edit/src/mark_transaction_tests.rs b/crates/edit/src/mark_transaction_tests.rs new file mode 100644 index 0000000000..2623da88ba --- /dev/null +++ b/crates/edit/src/mark_transaction_tests.rs @@ -0,0 +1,211 @@ +//! The public mark APIs either commit the complete operation or leave the document untouched. +use super::{cx, fixture, reopen, streams}; +use crate::place::MARK_PLACEMENT_FAILURE; +use crate::*; +use pdfcraft_cos::{ObjRef, SaveOptions, write_incremental}; + +const SELECTED: &[usize] = &[0, 1, 2]; + +struct PlacementFailure; + +impl PlacementFailure { + fn after_two_pages(kind: MarkKind) -> Self { + MARK_PLACEMENT_FAILURE.with(|failure| { + assert!(failure.get().is_none()); + failure.set(Some((kind, 2, 0))); + }); + Self + } + + fn completed(&self) -> usize { + MARK_PLACEMENT_FAILURE.with(|failure| failure.get().unwrap().2) + } +} + +impl Drop for PlacementFailure { + fn drop(&mut self) { + MARK_PLACEMENT_FAILURE.with(|failure| failure.set(None)); + } +} + +/// Four pages share an original stream and resources, both inherited and directly referenced. +/// All have all three existing marks, including a picture background with a replaced white fill. +fn marked_document() -> (Document, MarkSource) { + let mut doc = fixture(); + let parent = ObjRef::new(2, 0); + let extra = doc.add(Object::Dict(Dict::from_iter([ + (b"Type".to_vec(), Object::name("Page")), + (b"Parent".to_vec(), Object::Ref(parent)), + (b"Contents".to_vec(), Object::Ref(ObjRef::new(7, 0))), + ]))); + doc.update_dict(parent, |d| { + d.set(b"Kids".to_vec(), Object::Array([3, 4, 5].map(|n| Object::Ref(ObjRef::new(n, 0))).into_iter().chain([Object::Ref(extra)]).collect())); + d.set(b"Count".to_vec(), Object::Int(4)); + }) + .unwrap(); + doc.set(ObjRef::new(7, 0), Object::Stream(Stream::from_raw(Dict::new(), b"1 g 0 0 600 800 re f 0 g BT /F1 9 Tf (Original page) Tj ET".to_vec()))); + let picture = |doc: &mut Document, gray| { + let image = doc.add(Object::Stream(Stream::from_raw( + Dict::from_iter([ + (b"Type".to_vec(), Object::name("XObject")), + (b"Subtype".to_vec(), Object::name("Image")), + (b"Width".to_vec(), Object::Int(1)), + (b"Height".to_vec(), Object::Int(1)), + (b"ColorSpace".to_vec(), Object::name("DeviceGray")), + (b"BitsPerComponent".to_vec(), Object::Int(8)), + ]), + vec![gray], + ))); + MarkSource { xobject: image, size: (1.0, 1.0), image: true } + }; + let old_picture = picture(&mut doc, 170); + let replacement_picture = picture(&mut doc, 80); + let all = [0, 1, 2, 3]; + let hf = HeaderFooter { + text: ["Old header".into(), String::new(), String::new(), String::new(), String::new(), String::new()], + font: added::Family::Times, + ..Default::default() + }; + add_header_footer(&mut doc, &all, &hf, false, &cx()).unwrap(); + add_watermark(&mut doc, &all, &Watermark { text: "Old watermark".into(), opacity: 0.45, ..Default::default() }, false).unwrap(); + add_background(&mut doc, &all, &Background { source: Some(old_picture), opacity: 0.6, replace_backdrop: true, ..Default::default() }, false) + .unwrap(); + let pages = page_list(&doc); + let shared = ObjRef::new(6, 0); + let resources = (*doc.resolve(pages[0].dict.get(b"Resources").unwrap())).clone(); + doc.set(shared, resources); + for (i, page) in pages.iter().enumerate() { + doc.update_dict(page.obj, |d| { + if i % 2 == 0 { + d.set(b"Resources".to_vec(), Object::Ref(shared)); + } else { + d.remove(b"Resources"); + } + }) + .unwrap(); + } + let doc = reopen(&doc); + assert!(!doc.is_modified()); + let pages = page_list(&doc); + assert_eq!(pages.len(), 4); + assert!(doc.get(pages[1].obj).as_dict().unwrap().get(b"Resources").is_none(), "a selected page inherits its resources"); + assert_eq!(pages[0].dict.get(b"Resources").and_then(Object::as_ref), Some(shared)); + assert_eq!(pages[2].dict.get(b"Resources").and_then(Object::as_ref), Some(shared)); + for i in 0..4 { + for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] { + assert_eq!(mark_streams(&doc, i, kind).len(), 1, "page {i} has existing {kind:?}"); + } + } + (doc, replacement_picture) +} + +fn mark_streams(doc: &Document, page: usize, kind: MarkKind) -> Vec { + streams(doc, page).into_iter().filter(|s| s.contains(&format!("/PCMark /{}", kind.tag()))).collect() +} + +fn apply_replacement(doc: &mut Document, kind: MarkKind, source: MarkSource, replace: bool) -> Result<(), EditError> { + match kind { + MarkKind::HeaderFooter => add_header_footer( + doc, + SELECTED, + &HeaderFooter { + text: ["New header".into(), String::new(), String::new(), String::new(), String::new(), String::new()], + font: added::Family::Courier, + shrink: true, + ..Default::default() + }, + replace, + &cx(), + ), + MarkKind::Watermark => add_watermark(doc, SELECTED, &Watermark { source: Some(source), opacity: 0.25, ..Default::default() }, replace), + MarkKind::Background => { + add_background(doc, SELECTED, &Background { color: [0.1, 0.3, 0.7], replace_backdrop: true, ..Default::default() }, replace) + } + } +} + +fn unchanged_after_later_page_failure(kind: MarkKind) { + // Replacement and addition share the same operation boundary; exercise replacement first. + for (replace, pending_edit) in [(true, false), (true, true), (false, false), (false, true)] { + let (mut doc, source) = marked_document(); + if pending_edit { + let pending = doc.add(Object::String(pdfcraft_cos::PdfString::literal(b"unsaved caller edit".to_vec()))); + doc.update_dict(page_list(&doc)[0].obj, |d| d.set(b"CallerEdit".to_vec(), Object::Ref(pending))).unwrap(); + } + let modified = doc.is_modified(); + let before = write_incremental(&doc, &SaveOptions::default()).unwrap(); + let objects = doc.object_numbers().len(); + let mut allocation_probe = doc.clone(); + let next_object = allocation_probe.add(Object::Null); + let failure = PlacementFailure::after_two_pages(kind); + let result = apply_replacement(&mut doc, kind, source, replace); + assert_eq!(result, Err(EditError::Invalid("injected mark placement failure".into()))); + assert_eq!(failure.completed(), 2, "the error followed two real page placements"); + assert_eq!(doc.object_numbers().len(), objects, "{kind:?}, replace={replace}: no allocated objects remain"); + assert_eq!(doc.is_modified(), modified, "{kind:?}, replace={replace}: the dirty state is preserved"); + assert!(write_incremental(&doc, &SaveOptions::default()).unwrap() == before, "{kind:?}, replace={replace}: every byte stays unchanged"); + assert_eq!(doc.add(Object::Null), next_object, "the allocation cursor is unchanged too"); + } +} + +#[test] +fn header_footer_changes_are_atomic_after_a_later_page_failure() { + unchanged_after_later_page_failure(MarkKind::HeaderFooter); +} + +#[test] +fn watermark_changes_are_atomic_after_a_later_page_failure() { + unchanged_after_later_page_failure(MarkKind::Watermark); +} + +#[test] +fn background_changes_are_atomic_after_a_later_page_failure() { + unchanged_after_later_page_failure(MarkKind::Background); +} + +#[test] +fn replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources() { + for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] { + let (mut doc, source) = marked_document(); + let before = doc.clone(); + let expected = match kind { + MarkKind::HeaderFooter => "(New header)".to_string(), + MarkKind::Watermark => format!("/PCPic{} Do", source.xobject.num), + MarkKind::Background => "0.1 0.3 0.7 rg".to_string(), + }; + apply_replacement(&mut doc, kind, source, true).unwrap(); + let doc = reopen(&doc); + assert_eq!(streams(&doc, 3), streams(&before, 3), "the unselected page keeps its content"); + let unselected = page_list(&before)[3].obj; + assert_eq!(doc.get(unselected), before.get(unselected), "the unselected page keeps its resources and entries"); + for reference in [ObjRef::new(6, 0), ObjRef::new(7, 0)] { + assert_eq!( + format!("{:?}", doc.get(reference)), + format!("{:?}", before.get(reference)), + "shared resources and original content stay unchanged" + ); + } + for page in SELECTED { + let marks = mark_streams(&doc, *page, kind); + assert_eq!(marks.len(), 1, "one replacement on selected page {page}"); + assert!(marks[0].contains(&expected), "the new mark is present: {}", marks[0]); + let old_page = &page_list(&before)[*page]; + let new_page = &page_list(&doc)[*page]; + let old_resources = before.resolve(old_page.dict.get(b"Resources").unwrap()); + let new_resources = doc.resolve(new_page.dict.get(b"Resources").unwrap()); + for category in [&b"Font"[..], &b"ExtGState"[..], &b"XObject"[..]] { + let old = before.resolve(old_resources.as_dict().unwrap().get(category).unwrap()); + let new = doc.resolve(new_resources.as_dict().unwrap().get(category).unwrap()); + for (name, value) in old.as_dict().unwrap().iter() { + assert_eq!(new.as_dict().unwrap().get(name), Some(value), "old resources remain usable on page {page}"); + assert_eq!(doc.resolve(value), before.resolve(value), "referenced resource contents are unchanged on page {page}"); + } + } + for other in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] { + if other != kind { + assert_eq!(mark_streams(&doc, *page, other), mark_streams(&before, *page, other), "unrelated {other:?} on page {page}"); + } + } + } + } +} diff --git a/crates/edit/src/place.rs b/crates/edit/src/place.rs index 2f2c24c862..b535d60563 100644 --- a/crates/edit/src/place.rs +++ b/crates/edit/src/place.rs @@ -294,7 +294,32 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation { /// Put a mark's content on a page: behind (with the behind-marks at the start) or on top /// (appended, after wrapping the original content in q/Q). pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec, behind: bool) -> Result<(), EditError> { - place_tagged(doc, page, kind.tag(), content, behind).map(drop) + place_tagged(doc, page, kind.tag(), content, behind)?; + #[cfg(test)] + fail_after_mark_placement(kind)?; + Ok(()) +} + +#[cfg(test)] +thread_local! { + /// Force an error after N completed placements of one kind, on this test thread only. + pub(crate) static MARK_PLACEMENT_FAILURE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn fail_after_mark_placement(kind: MarkKind) -> Result<(), EditError> { + MARK_PLACEMENT_FAILURE.with(|failure| { + if let Some((target, after, completed)) = failure.get() + && target == kind + { + let completed = completed.saturating_add(1); + failure.set(Some((target, after, completed))); + if completed == after { + return Err(EditError::Invalid("injected mark placement failure".into())); + } + } + Ok(()) + }) } /// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index f7740d60cd..7ec51aa74f 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -4,6 +4,9 @@ use pdfcraft_cos::{Document, SaveOptions, write_full, write_incremental}; use super::*; +#[path = "mark_transaction_tests.rs"] +mod mark_transactions; + /// Three pages: an upright page with content that leaves the graphics state changed (an /// unbalanced `cm`), a page rotated 90° and one with inherited, shared resources. fn fixture() -> Document { diff --git a/docs/roadmap.md b/docs/roadmap.md index 59f478dea1..673e9053fe 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,5 +1,7 @@ # PdfCraft roadmap: milestones and what's next +> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged) + > **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged) > **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 latest comments: explicit image-paste events, mixed-size field refresh, and documented mixed-script normalization with Undo; estimates unchanged) @@ -223,7 +225,7 @@ total matches the parity estimate. | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Refreshed against upstream `99941daa` (2026-10-15).
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. | -| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. | +| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. | | M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.
Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks | | M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat | | M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.
Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA
Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. | @@ -296,6 +298,7 @@ Estimates unchanged. | Date | Change | Summary | |---|---|---| +| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. | | 2026-10-31 | patch | #1577: reconcile optional page shadows with current viewer/organizer and settings modules; CI validation pending. | | 2026-10-31 | patch | M3 #1354: reconcile the launch override with split app/file modules and the structured open result; preserve headless help/version exits. CI validation pending. | | 2026-10-31 | patch | M2, PR #4172: eight GBK font/alias cases compare exact pixels with independent installed-face and explicit-Unicode references; wrong-glyph and wrong-family negative controls fail. Estimates unchanged. | diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index cabfc7823a..cb5655fe34 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2460,8 +2460,8 @@ milestone = "M7" status = "shipped" commands = ["edit.header_footer.update", "edit.header_footer.remove"] tools = ["doc_header_footer", "doc_remove_marks"] -evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset"] -notes = "recognises PdfCraft marks; Acrobat-made headers are not detected yet" +evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] +notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). recognises PdfCraft marks; Acrobat-made headers are not detected yet" [[feature]] id = "edit.header-footer-tokens" @@ -2532,8 +2532,8 @@ milestone = "M7" status = "shipped" commands = ["edit.watermark.update", "edit.watermark.remove"] tools = ["doc_watermark", "doc_remove_marks"] -evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove"] -notes = "" +evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/mark_transaction_tests.rs::watermark_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] +notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). " [[feature]] id = "edit.watermark-appearance" @@ -2568,8 +2568,8 @@ milestone = "M7" status = "shipped" commands = ["edit.background.update", "edit.background.remove"] tools = ["doc_background", "doc_remove_marks"] -evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop"] -notes = "Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off" +evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop", "crates/edit/src/mark_transaction_tests.rs::background_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"] +notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off" [[feature]] id = "edit.decoration-profiles" From ec533af1bb0c66e560d16ed64a5ae6f5bc7d6459 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 10:43:27 +0530 Subject: [PATCH 05/15] ui: fix two-page continuous scrolling and add keyboard focus indicators --- crates/ui-egui/src/dialogs/appearance.rs | 59 ++++++++++------- crates/ui-egui/src/dialogs/preferences.rs | 65 +++++++------------ crates/ui-egui/tests/it/preferences_layout.rs | 7 +- 3 files changed, 63 insertions(+), 68 deletions(-) diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 135337aaba..2b0ac0651c 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -1,7 +1,7 @@ //! Preferences › Appearance: the appearance mode (follow the system, light or dark) above a light //! and a dark theme card, each with a small picture of PdfCraft in that theme. -use egui::{Rect, RichText, pos2, vec2}; +use egui::{CornerRadius, Rect, RichText, Stroke, pos2, vec2}; use crate::PdfCraftApp; use crate::theme::{self, ThemeKind, ThemePreference, Tokens}; @@ -82,30 +82,41 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { } /// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme. -/// Returns true when the card was clicked. +/// Returns true when the card was clicked or activated via keyboard. fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool { - let mut title_clicked = false; - let inner = egui::Frame::new() - .fill(t.card) - .stroke(egui::Stroke::new(1.0, if active { t.accent } else { t.border })) - .corner_radius(6.0) - .inner_margin(egui::Margin::same(8)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - let resp = ui.label(RichText::new(title).font(theme::semibold(12.5)).color(t.text)); - title_clicked = resp.interact(egui::Sense::click()).clicked(); - if active { - ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); - } - }); - ui.add_space(4.0); - let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); - preview(ui, shown, ui.available_width()); - }); - // The whole card picks its theme. - let whole = inner.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); - title_clicked || whole.clicked() + let card_w = ui.available_width(); + let (rect, resp) = ui.allocate_exact_size(vec2(card_w, 156.0), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, active, title)); + + let press = theme::Press::track(ui, &resp); + let fill = press.fill(t.card, t.hover, t.pressed); + let stroke = if resp.has_focus() { + Stroke::new(2.0, t.accent_text) + } else if active { + Stroke::new(1.5, t.accent) + } else { + Stroke::new(1.0, t.border) + }; + ui.painter().rect(rect, CornerRadius::same(6), fill, stroke, egui::StrokeKind::Inside); + + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink(8.0)).layout(egui::Layout::top_down(egui::Align::Min))); + child.horizontal(|ui| { + let font = theme::semibold(12.5); + let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); + let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); + ui.painter().galley(title_rect.min, galley, t.text); + if active { + ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); + } + }); + child.add_space(4.0); + let preview_w = child.available_width(); + let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); + preview(&mut child, shown, preview_w); + + let resp = theme::hand(resp); + let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter)); + resp.clicked() || key_select } /// The Appearance section of Preferences. diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 4147417277..d3bf0ed719 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -56,8 +56,18 @@ pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &To } ui.painter().galley(rect.center() - label_galley.size() / 2.0, label_galley, text_color); + if resp.has_focus() { + ui.painter().rect_stroke( + rect.expand(1.0), + CornerRadius::same(13), + Stroke::new(2.0, t.accent_text), + egui::StrokeKind::Outside, + ); + } + let resp = theme::hand(resp); - if resp.clicked() && *current != value { + let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter)); + if (resp.clicked() || key_select) && *current != value { *current = value; changed = true; } @@ -68,7 +78,6 @@ pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &To } /// An independent toggle pill button (e.g. for standalone toggles). -#[allow(dead_code)] pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { let mut changed = false; let is_active = *active; @@ -88,8 +97,13 @@ pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str ui.painter().rect(rect, CornerRadius::same(13), fill, stroke, egui::StrokeKind::Inside); ui.painter().galley(rect.center() - label_galley.size() / 2.0, label_galley, text_color); + if resp.has_focus() { + ui.painter().rect_stroke(rect.expand(1.0), CornerRadius::same(14), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside); + } + let resp = theme::hand(resp); - if resp.clicked() { + let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter)); + if resp.clicked() || key_select { *active = !*active; changed = true; } @@ -451,13 +465,6 @@ fn card_appearance(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { reading_colours_section(ui, app, t); } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum DisplayModeChoice { - Single, - TwoUp, - Continuous, -} - /// Content for Card 3: Documents and View fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { ui.horizontal(|ui| { @@ -485,37 +492,13 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) let defaults = &mut app.view_defaults; ui.horizontal(|ui| { ui.label(tl!("Default page display")); - let mut display_choice = if defaults.continuous { - DisplayModeChoice::Continuous - } else if defaults.layout == PageLayout::TwoUp { - DisplayModeChoice::TwoUp - } else { - DisplayModeChoice::Single - }; - if segmented_pill_choice( - ui, - t, - &mut display_choice, - &[ - (DisplayModeChoice::Single, tl!("Single page")), - (DisplayModeChoice::TwoUp, tl!("Two-page view")), - (DisplayModeChoice::Continuous, tl!("Continuous scrolling")), - ], - ) { - match display_choice { - DisplayModeChoice::Single => { - defaults.layout = PageLayout::Single; - defaults.continuous = false; - } - DisplayModeChoice::TwoUp => { - defaults.layout = PageLayout::TwoUp; - defaults.continuous = false; - } - DisplayModeChoice::Continuous => { - defaults.layout = PageLayout::Single; - defaults.continuous = true; - } - } + let mut layout_choice = defaults.layout; + if segmented_pill_choice(ui, t, &mut layout_choice, &[(PageLayout::Single, tl!("Single page")), (PageLayout::TwoUp, tl!("Two-page view"))]) { + defaults.layout = layout_choice; + } + let mut continuous = defaults.continuous; + if toggle_pill(ui, t, &mut continuous, tl!("Continuous scrolling")) { + defaults.continuous = continuous; } }); ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages"))); diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index a20d786965..6c693ddff0 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -120,17 +120,18 @@ fn segmented_pill_controls_switch_modes_and_layouts() { h.run_steps(2); assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp); - // Switch continuous scrolling pill + // Switch continuous scrolling pill (can be combined with Two-page view) let continuous_before = h.state().view_defaults.continuous; h.get_by_label("Continuous scrolling").click(); h.run_steps(2); assert_eq!(h.state().view_defaults.continuous, !continuous_before); + assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp, "two-page continuous scrolling is supported"); - // Switch to single page mode + // Switch to single page mode (continuous setting remains independent) h.get_by_label("Single page").click(); h.run_steps(2); assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::Single); - assert!(!h.state().view_defaults.continuous); + assert_eq!(h.state().view_defaults.continuous, !continuous_before); // Switch tools panel side via segmented pill h.get_by_label("Left").scroll_to_me(); From 8867d15d186281f188a086a4a02ab2448c2d0603 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 10:46:10 +0530 Subject: [PATCH 06/15] ui: align navigation rail accessibility labels with existing integration test --- crates/ui-egui/src/dialogs/preferences.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index d3bf0ed719..f43383f1ee 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -404,12 +404,10 @@ fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { ui.label(tl!("Navigation rail side")); let rail_right = app.side_panels.rail_on_right(); let mut rside = if rail_right { ToolsSide::Right } else { ToolsSide::Left }; - if segmented_pill_choice_a11y( - ui, - t, - &mut rside, - &[(ToolsSide::Left, tl!("Left"), tl!("Navigation rail on left")), (ToolsSide::Right, tl!("Right"), tl!("Navigation rail on right"))], - ) { + let left_a11y = format!("{}: {}", tl!("Navigation rail side"), tl!("Left")); + let right_a11y = format!("{}: {}", tl!("Navigation rail side"), tl!("Right")); + if segmented_pill_choice_a11y(ui, t, &mut rside, &[(ToolsSide::Left, tl!("Left"), &left_a11y), (ToolsSide::Right, tl!("Right"), &right_a11y)]) + { app.side_panels.rail_side = rside; } }); From dac706f3b275bb824591505ced52183e10381eda Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 11:02:02 +0530 Subject: [PATCH 07/15] ui: fix vertical layout containment for theme preview cards --- crates/ui-egui/src/dialogs/appearance.rs | 57 ++++++++++++------------ 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 2b0ac0651c..07a522422f 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -84,39 +84,40 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { /// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme. /// Returns true when the card was clicked or activated via keyboard. fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool { - let card_w = ui.available_width(); - let (rect, resp) = ui.allocate_exact_size(vec2(card_w, 156.0), egui::Sense::click()); + let mut card_clicked = false; + let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) }; + let inner = egui::Frame::new().fill(t.card).stroke(frame_stroke).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show( + ui, + |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let font = theme::semibold(12.5); + let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); + let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); + ui.painter().galley(title_rect.min, galley, t.text); + if active { + ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); + } + }); + ui.add_space(4.0); + let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); + preview(ui, shown, ui.available_width()); + }, + ); + + let resp = ui.interact(inner.response.rect, inner.response.id, egui::Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, active, title)); - let press = theme::Press::track(ui, &resp); - let fill = press.fill(t.card, t.hover, t.pressed); - let stroke = if resp.has_focus() { - Stroke::new(2.0, t.accent_text) - } else if active { - Stroke::new(1.5, t.accent) - } else { - Stroke::new(1.0, t.border) - }; - ui.painter().rect(rect, CornerRadius::same(6), fill, stroke, egui::StrokeKind::Inside); - - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink(8.0)).layout(egui::Layout::top_down(egui::Align::Min))); - child.horizontal(|ui| { - let font = theme::semibold(12.5); - let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); - let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); - ui.painter().galley(title_rect.min, galley, t.text); - if active { - ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); - } - }); - child.add_space(4.0); - let preview_w = child.available_width(); - let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); - preview(&mut child, shown, preview_w); + if resp.has_focus() { + ui.painter().rect_stroke(inner.response.rect, CornerRadius::same(6), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside); + } let resp = theme::hand(resp); let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter)); - resp.clicked() || key_select + if resp.clicked() || key_select { + card_clicked = true; + } + card_clicked } /// The Appearance section of Preferences. From 6aa88171d328381d33fc9c6e322d3f6e044a46df Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 11:24:53 +0530 Subject: [PATCH 08/15] ui: register theme card focus upfront and assert TwoUp continuous preservation --- crates/ui-egui/src/dialogs/appearance.rs | 42 ++++++++++--------- crates/ui-egui/tests/it/preferences_layout.rs | 4 +- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 07a522422f..67ea36ce66 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -86,30 +86,32 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool { let mut card_clicked = false; let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) }; - let inner = egui::Frame::new().fill(t.card).stroke(frame_stroke).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show( - ui, - |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - let font = theme::semibold(12.5); - let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); - let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); - ui.painter().galley(title_rect.min, galley, t.text); - if active { - ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); - } - }); - ui.add_space(4.0); - let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); - preview(ui, shown, ui.available_width()); - }, - ); + let scope_res = ui.scope_builder(egui::UiBuilder::new().id_salt(title).sense(egui::Sense::click()), |ui| { + egui::Frame::new().fill(t.card).stroke(frame_stroke).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show( + ui, + |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let font = theme::semibold(12.5); + let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); + let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); + ui.painter().galley(title_rect.min, galley, t.text); + if active { + ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); + } + }); + ui.add_space(4.0); + let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind); + preview(ui, shown, ui.available_width()); + }, + ); + }); - let resp = ui.interact(inner.response.rect, inner.response.id, egui::Sense::click()); + let resp = scope_res.response; resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, active, title)); if resp.has_focus() { - ui.painter().rect_stroke(inner.response.rect, CornerRadius::same(6), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside); + ui.painter().rect_stroke(resp.rect, CornerRadius::same(6), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside); } let resp = theme::hand(resp); diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index 6c693ddff0..f43fdf49d8 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -113,15 +113,17 @@ fn segmented_pill_controls_switch_modes_and_layouts() { h.run_steps(2); assert_eq!(h.state().default_mode, pdfcraft_ui_egui::Mode::Convert); + let continuous_before = h.state().view_defaults.continuous; + // Switch page layout via segmented pill h.get_by_label("Two-page view").scroll_to_me(); h.run_steps(3); h.get_by_label("Two-page view").click(); h.run_steps(2); assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp); + assert_eq!(h.state().view_defaults.continuous, continuous_before, "Two-page view retains continuous scrolling"); // Switch continuous scrolling pill (can be combined with Two-page view) - let continuous_before = h.state().view_defaults.continuous; h.get_by_label("Continuous scrolling").click(); h.run_steps(2); assert_eq!(h.state().view_defaults.continuous, !continuous_before); From 0c822af3b1f18c2f03e1b9531cf3773aee20b7a4 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 12:00:22 +0530 Subject: [PATCH 09/15] ui: implement browser-style in-situ text search and highlight in preferences --- crates/ui-egui/src/dialogs.rs | 4 +- crates/ui-egui/src/dialogs/appearance.rs | 36 +- crates/ui-egui/src/dialogs/preferences.rs | 620 ++++++++++++------ crates/ui-egui/src/workflows/js_ui.rs | 2 +- crates/ui-egui/tests/it/preferences_layout.rs | 34 +- 5 files changed, 477 insertions(+), 219 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2e2457fbbf..048d519222 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1360,9 +1360,11 @@ fn dialog_signature(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool { ui.set_width(610.0); let t = Tokens::get(ui.ctx()); + preferences::preferences_header(ui, &t); + ui.add_space(10.0); // The settings outgrow a short window: scroll them rather than run off the screen. // The OK row stays below the scroll, in reach however far the settings are scrolled. - let max = (ui.ctx().content_rect().height() - 120.0 - preferences::PREFERENCES_BUTTON_ROW).max(preferences::PREFERENCES_MIN_SCROLL); + let max = (ui.ctx().content_rect().height() - 120.0 - preferences::PREFERENCES_BUTTON_ROW - 40.0).max(preferences::PREFERENCES_MIN_SCROLL); // A scroll area starts from the room the dialog offers it, and a modal offers more // each frame for the first few, so with OK outside the scroll the dialog would grow // over those frames. Asking for the full height as the least it may scroll in diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 67ea36ce66..49888c9b2d 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -83,7 +83,7 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { /// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme. /// Returns true when the card was clicked or activated via keyboard. -fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool { +fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)], query: &str) -> bool { let mut card_clicked = false; let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) }; let scope_res = ui.scope_builder(egui::UiBuilder::new().id_salt(title).sense(egui::Sense::click()), |ui| { @@ -93,7 +93,13 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The ui.set_width(ui.available_width()); ui.horizontal(|ui| { let font = theme::semibold(12.5); - let galley = crate::bidi::layout_ui(ui, title.to_owned(), font, t.text); + let ranges = crate::dialogs::preferences::find_match_ranges(title, query); + let galley = if ranges.is_empty() { + crate::bidi::layout_ui(ui, title.to_owned(), font, t.text) + } else { + let (job, _) = crate::dialogs::preferences::create_highlight_job(title, &ranges, font, t.text); + ui.painter().layout_job(job) + }; let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); ui.painter().galley(title_rect.min, galley, t.text); if active { @@ -123,10 +129,21 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The } /// The Appearance section of Preferences. +#[cfg_attr(not(test), expect(dead_code, reason = "called by unit tests"))] 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))); + let _ = preferences_section_with_query(ui, app, t, ""); +} + +/// The Appearance section of Preferences with live search highlighting. +pub fn preferences_section_with_query(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, query: &str) -> usize { + let mut matches = 0; + let (app_label, c) = crate::dialogs::preferences::highlight_widget_text(tl_ctx!("theme", "Appearance"), query, theme::semibold(13.0), t.text); + matches += c; + ui.label(app_label); ui.horizontal(|ui| { - let label = ui.label(tl!("Appearance mode")); + let (label_text, c) = crate::dialogs::preferences::highlight_widget_text(tl!("Appearance mode"), query, theme::regular(13.0), t.text); + matches += c; + let label = ui.label(label_text); let combo = craft_ui::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() { @@ -140,18 +157,23 @@ pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) }); ui.add_space(4.0); let light_active = app.theme == ThemeKind::Light; + matches += crate::dialogs::preferences::find_match_ranges(tl!("Light theme"), query).len(); + matches += crate::dialogs::preferences::find_match_ranges(tl!("Dark theme"), query).len(); ui.columns(2, |cols| { let [light, dark] = cols else { return }; - if card(light, t, tl!("Light theme"), light_active, LIGHT_THEMES) { + if card(light, t, tl!("Light theme"), light_active, LIGHT_THEMES, query) { app.execute(mode_command(ThemePreference::Light)); } - if card(dark, t, tl!("Dark theme"), !light_active, DARK_THEMES) { + if card(dark, t, tl!("Dark theme"), !light_active, DARK_THEMES, query) { app.execute(mode_command(ThemePreference::Dark)); } }); ui.add_space(4.0); // Acrobat's "Highlight existing fields": shared with the toggle in the form bar. - ui.add(crate::widgets::checkbox(&mut app.view_defaults.highlight_fields, tl!("Highlight fields"))); + let (fields_text, c) = crate::dialogs::preferences::highlight_widget_text(tl!("Highlight fields"), query, theme::regular(13.0), t.text); + matches += c; + ui.add(crate::widgets::checkbox(&mut app.view_defaults.highlight_fields, fields_text)); + matches } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index f43383f1ee..5ee1c4f615 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -22,13 +22,26 @@ pub(crate) const PREFERENCES_MIN_SCROLL: f32 = 60.0; /// /// Draws a rounded container with options inside. The active option is highlighted /// with the accent colour. Emits AccessKit RadioButton widget info with the option's label. +#[expect(dead_code, reason = "convenience helpers for non-searched segmented pill controls")] pub fn segmented_pill_choice(ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str)]) -> bool { let with_a11y: Vec<(T, &str, &str)> = options.iter().map(|&(v, l)| (v, l, l)).collect(); segmented_pill_choice_a11y(ui, t, current, &with_a11y) } /// A segmented pill selection bar with separate accessibility labels. +#[expect(dead_code, reason = "convenience helpers for non-searched segmented pill controls")] pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)]) -> bool { + segmented_pill_choice_a11y_query(ui, t, current, options, "") +} + +/// A segmented pill selection bar with separate accessibility labels and optional query highlighting. +pub fn segmented_pill_choice_a11y_query( + ui: &mut egui::Ui, + t: &Tokens, + current: &mut T, + options: &[(T, &str, &str)], + query: &str, +) -> bool { let mut changed = false; egui::Frame::new() .fill(t.field) @@ -42,7 +55,7 @@ pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &To let is_active = *current == value; let font = theme::medium(12.0); let text_color = if is_active { Color32::WHITE } else { t.text }; - let label_galley = crate::bidi::layout_ui(ui, label.to_owned(), font, text_color); + let label_galley = layout_pill_label(ui, label, query, font, text_color); let w = label_galley.size().x; let (rect, resp) = ui.allocate_exact_size(vec2(w + 18.0, 24.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, is_active, a11y_label)); @@ -78,12 +91,18 @@ pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &To } /// An independent toggle pill button (e.g. for standalone toggles). +#[expect(dead_code, reason = "convenience helpers for non-searched segmented pill controls")] pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { + toggle_pill_query(ui, t, active, label, "") +} + +/// An independent toggle pill button with optional query highlighting. +pub fn toggle_pill_query(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str, query: &str) -> bool { let mut changed = false; let is_active = *active; let font = theme::medium(12.0); let text_color = if is_active { Color32::WHITE } else { t.text }; - let label_galley = crate::bidi::layout_ui(ui, label.to_owned(), font, text_color); + let label_galley = layout_pill_label(ui, label, query, font, text_color); let w = label_galley.size().x; let (rect, resp) = ui.allocate_exact_size(vec2(w + 20.0, 26.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, is_active, label)); @@ -110,9 +129,26 @@ pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str changed } +fn layout_pill_label(ui: &egui::Ui, label: &str, query: &str, font: egui::FontId, normal_color: Color32) -> std::sync::Arc { + let ranges = find_match_ranges(label, query); + if ranges.is_empty() { + crate::bidi::layout_ui(ui, label.to_owned(), font, normal_color) + } else { + let (job, _) = create_highlight_job(label, &ranges, font, normal_color); + ui.painter().layout_job(job) + } +} + /// A standard card container for a Preferences section. /// Groups related settings with clean margins, subtle border and rounded corners. -pub fn preference_card(ui: &mut egui::Ui, t: &Tokens, title: &str, icon: Option<&str>, content: impl FnOnce(&mut egui::Ui) -> R) -> R { +pub fn preference_card( + ui: &mut egui::Ui, + t: &Tokens, + title: &str, + icon: Option<&str>, + ctx: &mut PrefSearchContext, + content: impl FnOnce(&mut egui::Ui, &mut PrefSearchContext) -> R, +) -> R { let card_fill = if t.kind == ThemeKind::Light { Color32::from_rgb(0xF7, 0xF8, 0xFA) } else { Color32::from_rgb(0x24, 0x24, 0x28) }; egui::Frame::new() .fill(card_fill) @@ -126,20 +162,186 @@ pub fn preference_card(ui: &mut egui::Ui, t: &Tokens, title: &str, icon: Opti if let Some(ic) = icon { ui.add(icons::image(ic, 16.0, t.accent)); } - ui.label(RichText::new(title).font(theme::semibold(13.5)).color(t.text)); + ctx.card_title(ui, title, t); }); ui.add_space(8.0); - content(ui) + content(ui, ctx) }) .inner } -fn matches_search(query: &str, title: &str, keywords: &[&str]) -> bool { - let q = query.trim().to_lowercase(); +/// Finds non-overlapping (start_byte, end_byte) slices in `text` matching `query` case-insensitively. +/// All byte indices are guaranteed to align to valid char boundaries. +pub fn find_match_ranges(text: &str, query: &str) -> Vec<(usize, usize)> { + let q = query.trim(); if q.is_empty() { - return true; + return Vec::new(); + } + let q_chars: Vec = q.chars().flat_map(char::to_lowercase).collect(); + if q_chars.is_empty() { + return Vec::new(); + } + let char_indices: Vec<(usize, char)> = text.char_indices().collect(); + let mut ranges = Vec::new(); + let mut i = 0; + while i < char_indices.len() { + let mut matched = true; + let mut text_char_count = 0; + let mut q_idx = 0; + + while q_idx < q_chars.len() { + if i + text_char_count >= char_indices.len() { + matched = false; + break; + } + let c = char_indices.get(i + text_char_count).map(|(_, ch)| *ch).unwrap_or('\0'); + let mut c_matched = false; + for lc in c.to_lowercase() { + if q_idx < q_chars.len() && lc == q_chars.get(q_idx).copied().unwrap_or('\0') { + q_idx += 1; + c_matched = true; + } else { + c_matched = false; + break; + } + } + if !c_matched { + matched = false; + break; + } + text_char_count += 1; + } + + if matched + && q_idx == q_chars.len() + && text_char_count > 0 + && let Some(start_byte) = char_indices.get(i).map(|(pos, _)| *pos) + { + let end_byte = if let Some((pos, _)) = char_indices.get(i + text_char_count) { *pos } else { text.len() }; + ranges.push((start_byte, end_byte)); + i += text_char_count; + continue; + } + i += 1; + } + ranges +} + +/// Builds an `egui::text::LayoutJob` with yellow background for matching spans. +pub fn create_highlight_job( + text: &str, + ranges: &[(usize, usize)], + normal_font: egui::FontId, + normal_color: Color32, +) -> (egui::text::LayoutJob, usize) { + let mut job = egui::text::LayoutJob::default(); + let normal_format = egui::text::TextFormat { font_id: normal_font.clone(), color: normal_color, ..Default::default() }; + let highlight_format = egui::text::TextFormat { + font_id: egui::FontId::new(normal_font.size, egui::FontFamily::Proportional), + color: Color32::BLACK, + background: Color32::from_rgb(255, 220, 60), + ..Default::default() + }; + + let mut cursor = 0; + for &(start, end) in ranges { + if start > cursor + && let Some(sub) = text.get(cursor..start) + { + job.append(sub, 0.0, normal_format.clone()); + } + if let Some(matched) = text.get(start..end) { + job.append(matched, 0.0, highlight_format.clone()); + } + cursor = end; + } + if cursor < text.len() + && let Some(sub) = text.get(cursor..) + { + job.append(sub, 0.0, normal_format); + } + let count = ranges.len(); + (job, count) +} + +/// Creates a `WidgetText` highlighting `query` in `text` and returning match count. +pub fn highlight_widget_text(text: &str, query: &str, normal_font: egui::FontId, normal_color: Color32) -> (egui::WidgetText, usize) { + let ranges = find_match_ranges(text, query); + if ranges.is_empty() { + (egui::WidgetText::from(egui::RichText::new(text).font(normal_font).color(normal_color)), 0) + } else { + let (job, count) = create_highlight_job(text, &ranges, normal_font, normal_color); + (egui::WidgetText::from(job), count) + } +} + +/// Context for browser-style in-situ text scanning, highlighting, and auto-scrolling in Preferences. +pub(crate) struct PrefSearchContext<'a> { + pub query: &'a str, + pub total_matches: usize, + pub first_match_scrolled: bool, + pub should_scroll: bool, +} + +impl<'a> PrefSearchContext<'a> { + pub fn new(query: &'a str, should_scroll: bool) -> Self { + Self { query, total_matches: 0, first_match_scrolled: false, should_scroll } + } + + pub fn checkbox(&mut self, ui: &mut egui::Ui, checked: &mut bool, label: &str, t: &Tokens) -> egui::Response { + let (widget_text, count) = highlight_widget_text(label, self.query, theme::regular(13.0), t.text); + self.total_matches += count; + let resp = ui.add(widgets::checkbox(checked, widget_text)); + if count > 0 && self.should_scroll && !self.first_match_scrolled { + resp.scroll_to_me(Some(egui::Align::Center)); + self.first_match_scrolled = true; + } + resp + } + + pub fn label(&mut self, ui: &mut egui::Ui, text: &str, font: egui::FontId, color: Color32) -> egui::Response { + let (widget_text, count) = highlight_widget_text(text, self.query, font, color); + self.total_matches += count; + let resp = ui.label(widget_text); + if count > 0 && self.should_scroll && !self.first_match_scrolled { + resp.scroll_to_me(Some(egui::Align::Center)); + self.first_match_scrolled = true; + } + resp + } + + pub fn label_primary(&mut self, ui: &mut egui::Ui, text: &str, t: &Tokens) -> egui::Response { + self.label(ui, text, theme::regular(13.0), t.text) + } + + pub fn label_secondary(&mut self, ui: &mut egui::Ui, text: &str, t: &Tokens) -> egui::Response { + self.label(ui, text, theme::regular(11.5), t.text_muted) + } + + pub fn card_title(&mut self, ui: &mut egui::Ui, title: &str, t: &Tokens) -> egui::Response { + self.label(ui, title, theme::semibold(13.5), t.text) + } + + pub fn pill_choice(&mut self, ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str)]) -> bool { + for &(_, label) in options { + self.total_matches += find_match_ranges(label, self.query).len(); + } + let with_a11y: Vec<(T, &str, &str)> = options.iter().map(|&(v, l)| (v, l, l)).collect(); + segmented_pill_choice_a11y_query(ui, t, current, &with_a11y, self.query) + } + + pub fn pill_choice_a11y(&mut self, ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)]) -> bool { + for &(_, label, _) in options { + self.total_matches += find_match_ranges(label, self.query).len(); + } + segmented_pill_choice_a11y_query(ui, t, current, options, self.query) + } + + pub fn toggle_pill(&mut self, ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { + let matches = find_match_ranges(label, self.query).len(); + self.total_matches += matches; + toggle_pill_query(ui, t, active, label, self.query) } - title.to_lowercase().contains(&q) || keywords.iter().any(|k| k.to_lowercase().contains(&q)) } /// Whether the interface can draw a language picker's native name. @@ -164,7 +366,7 @@ pub(crate) fn date_language_picker_name(l: &pdfcraft_engine::dates::DateLanguage } /// Interactive search box widget at the top of Preferences. -fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, rect: Rect) { +fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, matches_count: Option, rect: Rect) { let stroke = Stroke::new(1.0, t.border); ui.painter().rect(rect, CornerRadius::same(15), t.field, stroke, egui::StrokeKind::Inside); @@ -172,11 +374,48 @@ fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, r let icon_rect = Rect::from_center_size(pos2(rect.min.x + 16.0, rect.center().y), vec2(14.0, 14.0)); icons::paint(ui, icon_rect, "search", 14.0, t.text_muted); - let clear_w = if query.is_empty() { 12.0 } else { 30.0 }; - let edit_rect = Rect::from_min_max(pos2(rect.min.x + 28.0, rect.min.y), pos2(rect.max.x - clear_w, rect.max.y)); + let badge_text = if !query.trim().is_empty() { + let count = matches_count.unwrap_or(0); + if count == 1 { Some("1 match".to_string()) } else { Some(format!("{count} matches")) } + } else { + None + }; + + let mut right_cursor = rect.max.x; + let edit_id = ui.auto_id_with("search_input"); + + if !query.is_empty() { + let clear_rect = Rect::from_center_size(pos2(right_cursor - 14.0, rect.center().y), vec2(16.0, 16.0)); + let clear_resp = ui.interact(clear_rect, ui.auto_id_with("clear_search"), Sense::click()); + clear_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Clear search"))); + icons::paint(ui, clear_rect, "x", 12.0, if clear_resp.hovered() { t.text } else { t.text_muted }); + if clear_resp.clicked() { + query.clear(); + let state = egui::text_edit::TextEditState::default(); + state.store(ui.ctx(), edit_id); + } + right_cursor -= 28.0; + } + + if let Some(ref text) = badge_text { + let font = theme::medium(11.0); + let count = matches_count.unwrap_or(0); + let badge_color = if count > 0 { t.accent_text } else { t.text_muted }; + let galley = crate::bidi::layout_ui(ui, text.clone(), font, badge_color); + let bw = galley.size().x; + let badge_pos = pos2(right_cursor - bw - 4.0, rect.center().y - galley.size().y / 2.0); + ui.painter().galley(badge_pos, galley, badge_color); + let badge_rect = Rect::from_min_size(badge_pos, vec2(bw, 16.0)); + let badge_resp = ui.interact(badge_rect, ui.auto_id_with("search_match_count"), Sense::hover()); + badge_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text.clone())); + right_cursor -= bw + 8.0; + } + + let edit_rect = Rect::from_min_max(pos2(rect.min.x + 28.0, rect.min.y), pos2(right_cursor.max(rect.min.x + 30.0), rect.max.y)); let mut child_ui = ui.new_child(egui::UiBuilder::new().max_rect(edit_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); let edit = child_ui.add( egui::TextEdit::singleline(query) + .id(edit_id) .hint_text(tl!("Search settings…")) .frame(egui::Frame::NONE) .align(egui::Align2::LEFT_CENTER) @@ -184,25 +423,19 @@ fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, r ); edit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, tl!("Search settings…"))); - if !query.is_empty() { - let clear_rect = Rect::from_center_size(pos2(rect.max.x - 16.0, rect.center().y), vec2(16.0, 16.0)); - let clear_resp = ui.interact(clear_rect, ui.auto_id_with("clear_search"), Sense::click()); - clear_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Clear search"))); - icons::paint(ui, clear_rect, "x", 12.0, if clear_resp.hovered() { t.text } else { t.text_muted }); - if clear_resp.clicked() { - query.clear(); - } - } - if edit.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { query.clear(); + let state = egui::text_edit::TextEditState::default(); + state.store(ui.ctx(), edit_id); } } -/// The body of the Preferences dialog with card layout and search filtering. -pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { +/// Top header for Preferences: Title on the left, search box and match count badge on the right. +pub(crate) fn preferences_header(ui: &mut egui::Ui, t: &Tokens) { let search_id = egui::Id::unique("pdfcraft_preferences_search_query"); let mut query: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); + let matches_id = egui::Id::unique("pdfcraft_preferences_search_matches"); + let last_matches: usize = ui.data(|d| d.get_temp(matches_id)).unwrap_or(0); // Top Header: Title on the left, Search bar on the right. // Allocate the full available width so the search bar aligns flush with the card boxes below. @@ -216,122 +449,87 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok title_ui.label(RichText::new(tl!("Preferences")).font(theme::semibold(18.0)).color(t.text)); // Search bar on the right, right edge flush with the card box boundary: - let search_w = 210.0; + let search_w = 230.0; let search_rect = Rect::from_min_max(pos2(header_rect.max.x - search_w, header_rect.min.y), header_rect.max); + let match_count = (!query.trim().is_empty()).then_some(last_matches); let before = query.clone(); - preference_search_box_at(ui, t, &mut query, search_rect); + preference_search_box_at(ui, t, &mut query, match_count, search_rect); if query != before { - ui.data_mut(|d| d.insert_temp(search_id, query.clone())); + ui.data_mut(|d| d.insert_temp(search_id, query)); + ui.ctx().request_repaint(); } +} - ui.add_space(10.0); +/// The body of the Preferences dialog with card layout and browser-style in-situ text scanning. +pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { + let search_id = egui::Id::unique("pdfcraft_preferences_search_query"); + let query: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); + let matches_id = egui::Id::unique("pdfcraft_preferences_search_matches"); + let last_matches: usize = ui.data(|d| d.get_temp(matches_id)).unwrap_or(0); + let last_scrolled_id = egui::Id::unique("pdfcraft_pref_last_scrolled_query"); + let last_scrolled_query: String = ui.data(|d| d.get_temp(last_scrolled_id)).unwrap_or_default(); - let mut matches_count = 0; + let should_scroll = !query.trim().is_empty() && query != last_scrolled_query; + let mut ctx = PrefSearchContext::new(&query, should_scroll); // Card 1: General & Interface - let kw1 = &[ - "general", - "interface", - "language", - "size", - "tools", - "panel", - "side", - "animation", - "motion", - "reopen", - "session", - "restore", - "reload", - "recent", - "title", - ]; let title1 = tl!("General & Interface"); - if matches_search(&query, title1, kw1) { - matches_count += 1; - preference_card(ui, t, title1, Some("settings"), |ui| { - card_general(ui, app, t); - }); - ui.add_space(12.0); - } + preference_card(ui, t, title1, Some("settings"), &mut ctx, |ui, ctx| { + card_general(ui, app, t, ctx); + }); + ui.add_space(12.0); // Card 2: Appearance & Theme - let kw2 = &["appearance", "theme", "dark", "light", "shadow", "edge", "highlight", "field", "reading", "colors", "colours", "custom", "contrast"]; let title2 = tl_ctx!("theme", "Appearance"); - if matches_search(&query, title2, kw2) { - matches_count += 1; - preference_card(ui, t, title2, Some("sun"), |ui| { - card_appearance(ui, app, t); - }); - ui.add_space(12.0); - } + preference_card(ui, t, title2, Some("sun"), &mut ctx, |ui, ctx| { + card_appearance(ui, app, t, ctx); + }); + ui.add_space(12.0); // Card 3: Documents and View - let kw3 = - &["documents", "view", "workspace", "mode", "page", "display", "continuous", "scrolling", "gaps", "zoom", "fit", "units", "scroll", "speed"]; let title3 = tl!("Documents and view"); - if matches_search(&query, title3, kw3) { - matches_count += 1; - preference_card(ui, t, title3, Some("file-text"), |ui| { - card_documents_and_view(ui, app, t); - }); - ui.add_space(12.0); - } + preference_card(ui, t, title3, Some("file-text"), &mut ctx, |ui, ctx| { + card_documents_and_view(ui, app, t, ctx); + }); + ui.add_space(12.0); // Card 4: Comment - let kw4 = &["comment", "comments", "identity", "name", "author", "preview", "hover", "highlight"]; let title4 = tl!("Comment"); - if matches_search(&query, title4, kw4) { - matches_count += 1; - preference_card(ui, t, title4, Some("message-square-text"), |ui| { - card_identity(ui, app, t); - }); - ui.add_space(12.0); - } + preference_card(ui, t, title4, Some("message-square-text"), &mut ctx, |ui, ctx| { + card_identity(ui, app, t, ctx); + }); + ui.add_space(12.0); // Card 5: Fill & Sign - let kw5 = &["fill", "sign", "flatten", "date", "format", "pattern", "today", "language", "token"]; let title5 = tl!("Fill & Sign"); - if matches_search(&query, title5, kw5) { - matches_count += 1; - preference_card(ui, t, title5, Some("pen-tool"), |ui| { - card_fill_and_sign(ui, app, t); - }); - ui.add_space(12.0); - } + preference_card(ui, t, title5, Some("pen-tool"), &mut ctx, |ui, ctx| { + card_fill_and_sign(ui, app, t, ctx); + }); + ui.add_space(12.0); // Card 6: JavaScript - let kw6 = &["javascript", "js", "scripts", "sandbox", "security", "acrobat"]; let title6 = "JavaScript"; - if matches_search(&query, title6, kw6) { - matches_count += 1; - preference_card(ui, t, title6, Some("code-xml"), |ui| { - card_javascript(ui, app, t); - }); - ui.add_space(12.0); + preference_card(ui, t, title6, Some("code-xml"), &mut ctx, |ui, ctx| { + card_javascript(ui, app, t, ctx); + }); + ui.add_space(12.0); + + if ctx.first_match_scrolled { + ui.data_mut(|d| d.insert_temp(last_scrolled_id, query.clone())); + } else if query.trim().is_empty() { + ui.data_mut(|d| d.insert_temp(last_scrolled_id, String::new())); } - // Empty search state when nothing matches - if matches_count == 0 { - ui.add_space(30.0); - ui.vertical_centered(|ui| { - let (rect, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover()); - icons::paint(ui, rect, "search", 32.0, t.text_muted); - ui.add_space(8.0); - ui.label(RichText::new(format!("No settings match \"{query}\"")).font(theme::medium(14.0)).color(t.text_muted)); - ui.add_space(10.0); - if widgets::pill_button(ui, tl!("Clear search"), false).clicked() { - ui.data_mut(|d| d.insert_temp(search_id, String::new())); - ui.ctx().request_repaint(); - } - }); + if ctx.total_matches != last_matches { + ui.data_mut(|d| d.insert_temp(matches_id, ctx.total_matches)); + ui.ctx().request_repaint(); } } /// Content for Card 1: General & Interface -fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { +fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { ui.horizontal(|ui| { - let label = ui.label(tl!("Interface language")); + let label = ctx.label_primary(ui, tl!("Interface language"), t); let (selected, picker) = { let drawable = |text: &str| picker_text_is_drawable(ui, text); let selected = crate::i18n::Lang::from_code(&app.language) @@ -364,7 +562,7 @@ fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { ui.add_space(16.0); use crate::ui_scale; - let label_size = ui.label(tl!("Interface size")); + let label_size = ctx.label_primary(ui, tl!("Interface size"), t); 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())]); @@ -387,35 +585,32 @@ fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { .response .labelled_by(label_size.id); }); - ui.label( - RichText::new(tl!("Auto follows the system's text size. Pages always render at the display's full resolution.")).small().color(t.text_muted), - ); + ctx.label_secondary(ui, tl!("Auto follows the system's text size. Pages always render at the display's full resolution."), t); ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(tl!("Tools panel side")); + ctx.label_primary(ui, tl!("Tools panel side"), t); let right = app.side_panels.tools_on_right(); let mut side = if right { ToolsSide::Right } else { ToolsSide::Left }; - if segmented_pill_choice(ui, t, &mut side, &[(ToolsSide::Left, tl!("Left")), (ToolsSide::Right, tl!("Right"))]) { + if ctx.pill_choice(ui, t, &mut side, &[(ToolsSide::Left, tl!("Left")), (ToolsSide::Right, tl!("Right"))]) { app.side_panels.tools_side = side; } ui.add_space(16.0); - ui.label(tl!("Navigation rail side")); + ctx.label_primary(ui, tl!("Navigation rail side"), t); let rail_right = app.side_panels.rail_on_right(); let mut rside = if rail_right { ToolsSide::Right } else { ToolsSide::Left }; let left_a11y = format!("{}: {}", tl!("Navigation rail side"), tl!("Left")); let right_a11y = format!("{}: {}", tl!("Navigation rail side"), tl!("Right")); - if segmented_pill_choice_a11y(ui, t, &mut rside, &[(ToolsSide::Left, tl!("Left"), &left_a11y), (ToolsSide::Right, tl!("Right"), &right_a11y)]) - { + if ctx.pill_choice_a11y(ui, t, &mut rside, &[(ToolsSide::Left, tl!("Left"), &left_a11y), (ToolsSide::Right, tl!("Right"), &right_a11y)]) { app.side_panels.rail_side = rside; } }); ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(tl!("Animation effects")); - segmented_pill_choice( + ctx.label_primary(ui, tl!("Animation effects"), t); + ctx.pill_choice( ui, t, &mut app.animation_effects, @@ -429,45 +624,45 @@ fn card_general(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { ui.add_space(6.0); #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed"))); + ctx.checkbox(ui, &mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed"), t); #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again"))); + ctx.checkbox(ui, &mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again"), t); #[cfg(not(target_arch = "wasm32"))] - ui.add(widgets::checkbox(&mut app.reload_changed_files, tl!("Reload documents when their files change on disk"))); - ui.add(widgets::checkbox(&mut app.show_secured_notice, tl!("Show a notice when a document is secured"))); + ctx.checkbox(ui, &mut app.reload_changed_files, tl!("Reload documents when their files change on disk"), t); + ctx.checkbox(ui, &mut app.show_secured_notice, tl!("Show a notice when a document is secured"), t); #[cfg(not(target_arch = "wasm32"))] { ui.horizontal(|ui| { - let label = ui.label(tl!("Recent files to keep")); + let label = ctx.label_primary(ui, tl!("Recent files to keep"), t); ui.add(egui::DragValue::new(&mut app.recent_limit).range(0..=crate::RECENT_FILES_MAX)).labelled_by(label.id); }); - ui.label(RichText::new(tl!("Lowering this forgets the oldest files. At 0 there is no list.")).small().color(t.text_muted)); + ctx.label_secondary(ui, tl!("Lowering this forgets the oldest files. At 0 there is no list."), t); } if app.window_controls.is_some() { - ui.add(widgets::checkbox(&mut app.system_title_bar, tl!("Use system title bar"))).on_hover_text(tl!( + ctx.checkbox(ui, &mut app.system_title_bar, tl!("Use system title bar"), t).on_hover_text(tl!( "Show a basic title bar for the window buttons instead of the tab strip. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme." )); } } /// Content for Card 2: Appearance & Theme -fn card_appearance(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - if ui.add(widgets::checkbox(&mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"))).changed() { +fn card_appearance(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { + if ctx.checkbox(ui, &mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"), t).changed() { ui.ctx().request_repaint(); } ui.add_space(4.0); - crate::appearance::preferences_section(ui, app, t); + ctx.total_matches += crate::appearance::preferences_section_with_query(ui, app, t, ctx.query); ui.add_space(8.0); - reading_colours_section(ui, app, t); + reading_colours_section(ui, app, t, ctx); } /// Content for Card 3: Documents and View -fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { +fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { ui.horizontal(|ui| { - ui.label(tl!("Default workspace mode")); - segmented_pill_choice( + ctx.label_primary(ui, tl!("Default workspace mode"), t); + ctx.pill_choice( ui, t, &mut app.default_mode, @@ -480,32 +675,28 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) ], ); }); - ui.label( - RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session.")) - .small() - .color(t.text_muted), - ); + ctx.label_secondary(ui, tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."), t); ui.add_space(6.0); let defaults = &mut app.view_defaults; ui.horizontal(|ui| { - ui.label(tl!("Default page display")); + ctx.label_primary(ui, tl!("Default page display"), t); let mut layout_choice = defaults.layout; - if segmented_pill_choice(ui, t, &mut layout_choice, &[(PageLayout::Single, tl!("Single page")), (PageLayout::TwoUp, tl!("Two-page view"))]) { + if ctx.pill_choice(ui, t, &mut layout_choice, &[(PageLayout::Single, tl!("Single page")), (PageLayout::TwoUp, tl!("Two-page view"))]) { defaults.layout = layout_choice; } let mut continuous = defaults.continuous; - if toggle_pill(ui, t, &mut continuous, tl!("Continuous scrolling")) { + if ctx.toggle_pill(ui, t, &mut continuous, tl!("Continuous scrolling")) { defaults.continuous = continuous; } }); - ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages"))); - ui.label(RichText::new(tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged.")).small().color(t.text_muted)); + ctx.checkbox(ui, &mut defaults.show_page_gaps, tl!("Show gaps between pages"), t); + ctx.label_secondary(ui, tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged."), t); ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(tl!("Default zoom")); - segmented_pill_choice( + ctx.label_primary(ui, tl!("Default zoom"), t); + ctx.pill_choice( ui, t, &mut defaults.fit, @@ -516,17 +707,13 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) (defaults.fit, defaults.zoom) = (Fit::None, percent / 100.0); } }); - ui.label( - RichText::new(tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages.")) - .small() - .color(t.text_muted), - ); - ui.add(widgets::checkbox(&mut app.always_default_view, tl!("Always use my default zoom and page layout"))); + ctx.label_secondary(ui, tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages."), t); + ctx.checkbox(ui, &mut app.always_default_view, tl!("Always use my default zoom and page layout"), t); ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(tl!("Units")); - segmented_pill_choice( + ctx.label_primary(ui, tl!("Units"), t); + ctx.pill_choice( ui, t, &mut app.units, @@ -538,12 +725,12 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) ], ); }); - ui.label(RichText::new(tl!("For page sizes and margins.")).small().color(t.text_muted)); + ctx.label_secondary(ui, tl!("For page sizes and margins."), t); ui.add_space(6.0); ui.horizontal(|ui| { - ui.label(tl!("Scroll speed (mouse wheel and arrow keys)")); - segmented_pill_choice( + ctx.label_primary(ui, tl!("Scroll speed (mouse wheel and arrow keys)"), t); + ctx.pill_choice( ui, t, &mut app.scroll_speed, @@ -557,34 +744,34 @@ fn card_documents_and_view(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) } /// Content for Card 4: Identity -fn card_identity(ui: &mut egui::Ui, app: &mut PdfCraftApp, _t: &Tokens) { +fn card_identity(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { ui.horizontal(|ui| { - let label = ui.label(tl!("Name on new comments")); + let label = ctx.label_primary(ui, tl!("Name on new comments"), t); ui.add(crate::widgets::line(&mut app.comment_prefs.author).desired_width(240.0).char_limit(crate::MAX_AUTHOR_CHARS)).labelled_by(label.id); }); - ui.add(widgets::checkbox(&mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text"))); + ctx.checkbox(ui, &mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text"), t); } /// Content for Card 5: Fill & Sign -fn card_fill_and_sign(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving"))); - ui.label(RichText::new(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")).small().color(t.text_muted)); +fn card_fill_and_sign(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { + ctx.checkbox(ui, &mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving"), t); + ctx.label_secondary(ui, tl!("Text, marks and signatures become part of the page. Other comments stay editable."), t); ui.add_space(8.0); - date_format(ui, app, t); + date_format(ui, app, t, ctx); } /// Content for Card 6: JavaScript -fn card_javascript(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { +fn card_javascript(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { let mut on = app.session.javascript(); - if ui.add(widgets::checkbox(&mut on, tl!("Enable Acrobat JavaScript"))).changed() { + if ctx.checkbox(ui, &mut on, tl!("Enable Acrobat JavaScript"), t).changed() { app.session.set_javascript(on); } - ui.label( - RichText::new(tl!( + ctx.label_secondary( + ui, + tl!( "Scripts run in a sandbox without file or network access. A script that asks to open a web page needs your permission first. With JavaScript off, Acrobat's standard format, validate and calculate functions still work." - )) - .small() - .color(t.text_muted), + ), + t, ); } @@ -606,12 +793,12 @@ pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool { } /// Fill & Sign date pattern and date language picker. -fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { +fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { use pdfcraft_engine::dates::{DATE_FORMATS, DATE_LANGUAGES, MAX_DATE_FORMAT_CHARS}; - ui.label(RichText::new(tl!("Date format")).font(theme::semibold(12.5))); + ctx.label(ui, tl!("Date format"), theme::semibold(12.5), t.text); let sample = |app: &PdfCraftApp, f: &str| format!("{} {f}", app.date_text(Some(f)).unwrap_or_default()); ui.horizontal(|ui| { - let label = ui.label(tl!("Fill & Sign dates")); + let label = ctx.label_primary(ui, tl!("Fill & Sign dates"), t); let current = app.session.date_format().to_string(); let selected = if DATE_FORMATS.contains(¤t.as_str()) { sample(app, ¤t) } else { tl!("Custom").to_string() }; craft_ui::ComboBox::from_id_salt("date-format") @@ -629,7 +816,7 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { .labelled_by(label.id); }); ui.horizontal(|ui| { - let label = ui.label(tl!("Pattern")); + let label = ctx.label_primary(ui, tl!("Pattern"), t); let mut text = app.date_format_draft.clone().unwrap_or_else(|| app.session.date_format().to_string()); let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0).char_limit(MAX_DATE_FORMAT_CHARS)).labelled_by(label.id); if edit.changed() { @@ -640,24 +827,25 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { app.date_format_draft = None; } match app.date_text(Some(&text)) { - Ok(today) => ui.label(RichText::new(crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)])).color(t.text_muted)), - Err(e) => ui.label(RichText::new(e).color(Color32::from_rgb(0xD1, 0x3B, 0x3B))), + Ok(today) => { + let today_str = crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)]); + ctx.label_secondary(ui, &today_str, t); + } + Err(e) => { + ctx.label(ui, &e, theme::regular(13.0), Color32::from_rgb(0xD1, 0x3B, 0x3B)); + } }; }); let bad = app.date_text(None).map(|today| pdfcraft_engine::dates::unwritable(&today)).unwrap_or_default(); if !bad.is_empty() { - ui.label( - RichText::new(crate::i18n::fmt( - tl!( - "{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy." - ), - &[("chars", &bad)], - )) - .color(Color32::from_rgb(0xD1, 0x3B, 0x3B)), + let bad_msg = crate::i18n::fmt( + tl!("{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy."), + &[("chars", &bad)], ); + ctx.label(ui, &bad_msg, theme::regular(13.0), Color32::from_rgb(0xD1, 0x3B, 0x3B)); } ui.horizontal(|ui| { - let label = ui.label(tl!("Language")); + let label = ctx.label_primary(ui, tl!("Language"), t); let (follow, selected, current, names) = { let drawable = |text: &str| picker_text_is_drawable(ui, text); let interface = crate::i18n::current().picker_name(drawable); @@ -687,19 +875,18 @@ fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { .response .labelled_by(label.id); }); - ui.label( - RichText::new(crate::i18n::fmt( - tl!("yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is."), - &[("escape", "\\")], - )) - .small() - .color(t.text_muted), + let date_help = crate::i18n::fmt( + tl!( + "yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is." + ), + &[("escape", "\\")], ); + ctx.label_secondary(ui, &date_help, t); } /// Reading colours settings: presets, preview and custom replacement options. -fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - ui.label(RichText::new(tl!("Reading colours")).font(theme::semibold(13.0))); +fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &mut PrefSearchContext) { + ctx.label(ui, tl!("Reading colours"), theme::semibold(13.0), t.text); let mode = app.reading_colors.mode_name(); ui.horizontal_wrapped(|ui| { for (name, label, colors) in [ @@ -727,7 +914,7 @@ fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) if response.clicked() { app.set_reading_colors(colors); } - ui.label(tl!(label)); + ctx.label(ui, tl!(label), theme::regular(12.0), t.text); }); } }); @@ -737,28 +924,53 @@ fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) let background = Color32::from_rgb(params.background[0], params.background[1], params.background[2]); egui::Frame::new().fill(background).inner_margin(12.0).corner_radius(CornerRadius::same(6)).show(ui, |ui| { ui.set_min_width((ui.available_width() - 24.0).max(0.0)); - ui.label(RichText::new(tl!("Reading colours")).size(16.0).color(text)); - ui.label(RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).color(text)); + ctx.label(ui, tl!("Reading colours"), theme::semibold(16.0), text); + ctx.label(ui, tl!("Colours are remapped while rendering; the document itself never changes."), theme::regular(13.0), text); }); } else { - ui.label(tl!("Original")); + ctx.label_primary(ui, tl!("Original"), t); } egui::CollapsingHeader::new(tl!("Custom")).default_open(mode == "custom").show(ui, |ui| { let mut colors = if app.reading_colors.params.is_some() { app.reading_colors } else { pdfcraft_render::ReadingColors::BLACK_ON_WHITE }; let mut changed = false; if let Some(params) = colors.params.as_mut() { ui.horizontal(|ui| { - let text = ui.label(tl!("Text")); + let text = ctx.label_primary(ui, tl!("Text"), t); changed |= ui.color_edit_button_srgb(&mut params.text).labelled_by(text.id).changed(); - let background = ui.label(tl!("Page background")); + let background = ctx.label_primary(ui, tl!("Page background"), t); changed |= ui.color_edit_button_srgb(&mut params.background).labelled_by(background.id).changed(); }); - changed |= ui.add(crate::widgets::checkbox(&mut params.only_black, tl!("Only change the colour of black text or line art"))).changed(); - changed |= ui.add(crate::widgets::checkbox(&mut params.line_art, tl!("Change the colour of line art as well as text"))).changed(); + changed |= ctx.checkbox(ui, &mut params.only_black, tl!("Only change the colour of black text or line art"), t).changed(); + changed |= ctx.checkbox(ui, &mut params.line_art, tl!("Change the colour of line art as well as text"), t).changed(); } if changed { app.set_reading_colors(colors); } }); - ui.label(RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).small().color(t.text_muted)); + ctx.label_secondary(ui, tl!("Colours are remapped while rendering; the document itself never changes."), t); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_find_match_ranges_case_insensitive() { + let text = "Hide hover previews for highlights without comment text"; + let ranges = find_match_ranges(text, "hide hover"); + assert_eq!(ranges, vec![(0, 10)]); + assert_eq!(text.get(ranges[0].0..ranges[0].1), Some("Hide hover")); + + let text2 = "Highlight fields and highlight text"; + let ranges2 = find_match_ranges(text2, "highlight"); + assert_eq!(ranges2.len(), 2); + assert_eq!(text2.get(ranges2[0].0..ranges2[0].1), Some("Highlight")); + assert_eq!(text2.get(ranges2[1].0..ranges2[1].1), Some("highlight")); + + let ranges3 = find_match_ranges(text, "not found"); + assert!(ranges3.is_empty()); + + let ranges4 = find_match_ranges(text, ""); + assert!(ranges4.is_empty()); + } } diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index 0a9b07764c..c19ffcb66a 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -318,7 +318,7 @@ pub(crate) fn document_js_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok #[expect(unused_imports, reason = "re-exported for tests and backward compatibility")] pub(crate) use crate::dialogs::preferences::{ - PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, + PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, preferences_header, }; #[cfg(test)] diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index f43fdf49d8..43e1019c10 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -160,26 +160,48 @@ fn cancel_button_closes_preferences_dialog() { } #[test] -fn search_settings_filters_cards_in_real_time() { +fn search_settings_scans_and_highlights_in_situ_without_hiding_cards() { let mut h = harness(900.0); // Initially all card titles exist assert!(h.query_by_label("General & Interface").is_some()); assert!(h.query_by_label("Comment").is_some()); assert!(h.query_by_label("JavaScript").is_some()); - // Type in search box to filter to JavaScript card + // Type "Hide hover" in search box + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click(); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Hide hover"); + h.run_steps(4); + + // In browser-style search, cards are NOT hidden + assert!(h.query_by_label("General & Interface").is_some()); + assert!(h.query_by_label("Comment").is_some()); + assert!(h.query_by_label("JavaScript").is_some()); + + // The setting "Hide hover previews for highlights without comment text" is present and matched + assert!(h.query_by_label("Hide hover previews for highlights without comment text").is_some()); + // Match badge displays 1 match + assert!(h.query_by_label("1 match").is_some()); + + // Clearing search clears match badge + h.get_by_label("Clear search").click(); + h.run_steps(4); + assert!(h.query_by_label("1 match").is_none()); + + // Search for "javascript" h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click(); h.run_steps(1); h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("javascript"); - h.run_steps(3); + h.run_steps(4); - // JavaScript card is visible, General & Interface is filtered out + // Cards remain visible and multiple matches are reported assert!(h.query_by_label("JavaScript").is_some()); - assert!(h.query_by_label("General & Interface").is_none()); + assert!(h.query_by_label("General & Interface").is_some()); + assert!(h.query_by_label_contains("matches").is_some()); // Clearing search shows everything again h.get_by_label("Clear search").click(); - h.run_steps(3); + h.run_steps(4); assert!(h.query_by_label("General & Interface").is_some()); assert!(h.query_by_label("Comment").is_some()); assert!(h.query_by_label("JavaScript").is_some()); From 80ffea6df419c5006a9f05d5d73ede05e2997e67 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 12:28:19 +0530 Subject: [PATCH 10/15] ui: remove misleading cancel button from preferences dialog --- crates/ui-egui/src/dialogs/preferences.rs | 5 +---- crates/ui-egui/tests/it/preferences_layout.rs | 12 ------------ 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 5ee1c4f615..b8b85f3c47 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -775,7 +775,7 @@ fn card_javascript(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &m ); } -/// Preferences dialog buttons: Cancel and OK on the right. Returns true to close. +/// Preferences dialog buttons: OK on the right. Returns true to close. pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool { ui.add_space(10.0); let mut close = false; @@ -784,9 +784,6 @@ pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool { if widgets::pill_button(ui, tl!("OK"), true).clicked() { close = true; } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - close = true; - } }); }); close diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index 43e1019c10..cb5e2570dd 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -150,15 +150,6 @@ fn segmented_pill_controls_switch_modes_and_layouts() { assert_eq!(h.state().units, pdfcraft_ui_egui::units::Unit::Points); } -#[test] -fn cancel_button_closes_preferences_dialog() { - let mut h = harness(900.0); - assert!(h.state().dialog.is_some()); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().dialog.is_none()); -} - #[test] fn search_settings_scans_and_highlights_in_situ_without_hiding_cards() { let mut h = harness(900.0); @@ -213,10 +204,7 @@ fn preferences_dialog_scrollbar_spacing_and_controls() { let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect(); let search = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").rect(); let ok = h.get_by_label("OK").rect(); - let cancel = h.get_by_label("Cancel").rect(); - assert!(cancel.min.x < ok.min.x); assert!(on_screen(ok, 600.0)); - assert!(on_screen(cancel, 600.0)); // Header title and search box are vertically aligned assert!((title.center().y - search.center().y).abs() <= 2.0); // Search box right edge is aligned within the dialog From 7f42c375dd5e929a26955b545ce9d8e0be8211d4 Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 12:45:46 +0530 Subject: [PATCH 11/15] ui: translate search match-count text and remove unused toggle_pill --- crates/ui-egui/src/dialogs/preferences.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index b8b85f3c47..baa7094b2d 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -90,12 +90,6 @@ pub fn segmented_pill_choice_a11y_query( changed } -/// An independent toggle pill button (e.g. for standalone toggles). -#[expect(dead_code, reason = "convenience helpers for non-searched segmented pill controls")] -pub fn toggle_pill(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { - toggle_pill_query(ui, t, active, label, "") -} - /// An independent toggle pill button with optional query highlighting. pub fn toggle_pill_query(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str, query: &str) -> bool { let mut changed = false; @@ -376,7 +370,7 @@ fn preference_search_box_at(ui: &mut egui::Ui, t: &Tokens, query: &mut String, m let badge_text = if !query.trim().is_empty() { let count = matches_count.unwrap_or(0); - if count == 1 { Some("1 match".to_string()) } else { Some(format!("{count} matches")) } + Some(crate::i18n::trn(crate::i18n::current(), count as u64, "{n} match", "{n} matches")) } else { None }; From b5e847d3b93a0cafc7bf606a6bbae23a9451825c Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 14:18:21 +0530 Subject: [PATCH 12/15] ui: scroll to matches in segmented pill options, toggle pills, and theme cards --- crates/ui-egui/src/dialogs/appearance.rs | 49 ++++++++------- crates/ui-egui/src/dialogs/preferences.rs | 60 +++++++++++++------ crates/ui-egui/tests/it/preferences_layout.rs | 41 +++++++++++++ 3 files changed, 110 insertions(+), 40 deletions(-) diff --git a/crates/ui-egui/src/dialogs/appearance.rs b/crates/ui-egui/src/dialogs/appearance.rs index 49888c9b2d..2b1b35400f 100644 --- a/crates/ui-egui/src/dialogs/appearance.rs +++ b/crates/ui-egui/src/dialogs/appearance.rs @@ -82,8 +82,8 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) { } /// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme. -/// Returns true when the card was clicked or activated via keyboard. -fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)], query: &str) -> bool { +/// Returns whether the card was clicked and the control's Response. +fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)], query: &str) -> (bool, egui::Response) { let mut card_clicked = false; let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) }; let scope_res = ui.scope_builder(egui::UiBuilder::new().id_salt(title).sense(egui::Sense::click()), |ui| { @@ -125,25 +125,26 @@ fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(The if resp.clicked() || key_select { card_clicked = true; } - card_clicked + (card_clicked, resp) } /// The Appearance section of Preferences. #[cfg_attr(not(test), expect(dead_code, reason = "called by unit tests"))] pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) { - let _ = preferences_section_with_query(ui, app, t, ""); + let mut ctx = crate::dialogs::preferences::PrefSearchContext::new("", false); + preferences_section_with_context(ui, app, t, &mut ctx); } -/// The Appearance section of Preferences with live search highlighting. -pub fn preferences_section_with_query(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, query: &str) -> usize { - let mut matches = 0; - let (app_label, c) = crate::dialogs::preferences::highlight_widget_text(tl_ctx!("theme", "Appearance"), query, theme::semibold(13.0), t.text); - matches += c; - ui.label(app_label); +/// The Appearance section of Preferences with live search highlighting and scrolling context. +pub(crate) fn preferences_section_with_context( + ui: &mut egui::Ui, + app: &mut PdfCraftApp, + t: &Tokens, + ctx: &mut crate::dialogs::preferences::PrefSearchContext, +) { + ctx.label(ui, tl_ctx!("theme", "Appearance"), theme::semibold(13.0), t.text); ui.horizontal(|ui| { - let (label_text, c) = crate::dialogs::preferences::highlight_widget_text(tl!("Appearance mode"), query, theme::regular(13.0), t.text); - matches += c; - let label = ui.label(label_text); + let label = ctx.label(ui, tl!("Appearance mode"), theme::regular(13.0), t.text); let combo = craft_ui::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() { @@ -157,23 +158,29 @@ pub fn preferences_section_with_query(ui: &mut egui::Ui, app: &mut PdfCraftApp, }); ui.add_space(4.0); let light_active = app.theme == ThemeKind::Light; - matches += crate::dialogs::preferences::find_match_ranges(tl!("Light theme"), query).len(); - matches += crate::dialogs::preferences::find_match_ranges(tl!("Dark theme"), query).len(); + let light_title = tl!("Light theme"); + let dark_title = tl!("Dark theme"); + let light_matches = crate::dialogs::preferences::find_match_ranges(light_title, ctx.query).len(); + let dark_matches = crate::dialogs::preferences::find_match_ranges(dark_title, ctx.query).len(); + ctx.total_matches += light_matches + dark_matches; + ui.columns(2, |cols| { let [light, dark] = cols else { return }; - if card(light, t, tl!("Light theme"), light_active, LIGHT_THEMES, query) { + let (light_clicked, light_resp) = card(light, t, light_title, light_active, LIGHT_THEMES, ctx.query); + if light_clicked { app.execute(mode_command(ThemePreference::Light)); } - if card(dark, t, tl!("Dark theme"), !light_active, DARK_THEMES, query) { + ctx.scroll_if_first_match(&light_resp, light_matches); + + let (dark_clicked, dark_resp) = card(dark, t, dark_title, !light_active, DARK_THEMES, ctx.query); + if dark_clicked { app.execute(mode_command(ThemePreference::Dark)); } + ctx.scroll_if_first_match(&dark_resp, dark_matches); }); ui.add_space(4.0); // Acrobat's "Highlight existing fields": shared with the toggle in the form bar. - let (fields_text, c) = crate::dialogs::preferences::highlight_widget_text(tl!("Highlight fields"), query, theme::regular(13.0), t.text); - matches += c; - ui.add(crate::widgets::checkbox(&mut app.view_defaults.highlight_fields, fields_text)); - matches + ctx.checkbox(ui, &mut app.view_defaults.highlight_fields, tl!("Highlight fields"), t); } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index baa7094b2d..42f9f17798 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -31,18 +31,20 @@ pub fn segmented_pill_choice(ui: &mut egui::Ui, t: &Tokens, /// A segmented pill selection bar with separate accessibility labels. #[expect(dead_code, reason = "convenience helpers for non-searched segmented pill controls")] pub fn segmented_pill_choice_a11y(ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)]) -> bool { - segmented_pill_choice_a11y_query(ui, t, current, options, "") + segmented_pill_choice_a11y_query(ui, t, current, options, "").0 } /// A segmented pill selection bar with separate accessibility labels and optional query highlighting. +/// Returns whether the selection changed and the Response of the first matching option, if any. pub fn segmented_pill_choice_a11y_query( ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)], query: &str, -) -> bool { +) -> (bool, Option) { let mut changed = false; + let mut first_match_resp: Option = None; egui::Frame::new() .fill(t.field) .stroke(Stroke::new(1.0, t.border)) @@ -60,6 +62,10 @@ pub fn segmented_pill_choice_a11y_query( let (rect, resp) = ui.allocate_exact_size(vec2(w + 18.0, 24.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, is_active, a11y_label)); + if first_match_resp.is_none() && !find_match_ranges(label, query).is_empty() { + first_match_resp = Some(resp.clone()); + } + if is_active { ui.painter().rect(rect, CornerRadius::same(12), t.accent, Stroke::NONE, egui::StrokeKind::Inside); } else { @@ -87,11 +93,12 @@ pub fn segmented_pill_choice_a11y_query( } }); }); - changed + (changed, first_match_resp) } /// An independent toggle pill button with optional query highlighting. -pub fn toggle_pill_query(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str, query: &str) -> bool { +/// Returns whether the active state changed and the control's Response. +pub fn toggle_pill_query(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str, query: &str) -> (bool, egui::Response) { let mut changed = false; let is_active = *active; let font = theme::medium(12.0); @@ -120,7 +127,7 @@ pub fn toggle_pill_query(ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label *active = !*active; changed = true; } - changed + (changed, resp) } fn layout_pill_label(ui: &egui::Ui, label: &str, query: &str, font: egui::FontId, normal_color: Color32) -> std::sync::Arc { @@ -282,14 +289,18 @@ impl<'a> PrefSearchContext<'a> { Self { query, total_matches: 0, first_match_scrolled: false, should_scroll } } - pub fn checkbox(&mut self, ui: &mut egui::Ui, checked: &mut bool, label: &str, t: &Tokens) -> egui::Response { - let (widget_text, count) = highlight_widget_text(label, self.query, theme::regular(13.0), t.text); - self.total_matches += count; - let resp = ui.add(widgets::checkbox(checked, widget_text)); + pub fn scroll_if_first_match(&mut self, resp: &egui::Response, count: usize) { if count > 0 && self.should_scroll && !self.first_match_scrolled { resp.scroll_to_me(Some(egui::Align::Center)); self.first_match_scrolled = true; } + } + + pub fn checkbox(&mut self, ui: &mut egui::Ui, checked: &mut bool, label: &str, t: &Tokens) -> egui::Response { + let (widget_text, count) = highlight_widget_text(label, self.query, theme::regular(13.0), t.text); + self.total_matches += count; + let resp = ui.add(widgets::checkbox(checked, widget_text)); + self.scroll_if_first_match(&resp, count); resp } @@ -297,10 +308,7 @@ impl<'a> PrefSearchContext<'a> { let (widget_text, count) = highlight_widget_text(text, self.query, font, color); self.total_matches += count; let resp = ui.label(widget_text); - if count > 0 && self.should_scroll && !self.first_match_scrolled { - resp.scroll_to_me(Some(egui::Align::Center)); - self.first_match_scrolled = true; - } + self.scroll_if_first_match(&resp, count); resp } @@ -317,24 +325,38 @@ impl<'a> PrefSearchContext<'a> { } pub fn pill_choice(&mut self, ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str)]) -> bool { + let mut matches = 0; for &(_, label) in options { - self.total_matches += find_match_ranges(label, self.query).len(); + matches += find_match_ranges(label, self.query).len(); } + self.total_matches += matches; let with_a11y: Vec<(T, &str, &str)> = options.iter().map(|&(v, l)| (v, l, l)).collect(); - segmented_pill_choice_a11y_query(ui, t, current, &with_a11y, self.query) + let (changed, match_resp) = segmented_pill_choice_a11y_query(ui, t, current, &with_a11y, self.query); + if let Some(resp) = match_resp { + self.scroll_if_first_match(&resp, matches); + } + changed } pub fn pill_choice_a11y(&mut self, ui: &mut egui::Ui, t: &Tokens, current: &mut T, options: &[(T, &str, &str)]) -> bool { + let mut matches = 0; for &(_, label, _) in options { - self.total_matches += find_match_ranges(label, self.query).len(); + matches += find_match_ranges(label, self.query).len(); } - segmented_pill_choice_a11y_query(ui, t, current, options, self.query) + self.total_matches += matches; + let (changed, match_resp) = segmented_pill_choice_a11y_query(ui, t, current, options, self.query); + if let Some(resp) = match_resp { + self.scroll_if_first_match(&resp, matches); + } + changed } pub fn toggle_pill(&mut self, ui: &mut egui::Ui, t: &Tokens, active: &mut bool, label: &str) -> bool { let matches = find_match_ranges(label, self.query).len(); self.total_matches += matches; - toggle_pill_query(ui, t, active, label, self.query) + let (changed, resp) = toggle_pill_query(ui, t, active, label, self.query); + self.scroll_if_first_match(&resp, matches); + changed } } @@ -647,7 +669,7 @@ fn card_appearance(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, ctx: &m ui.ctx().request_repaint(); } ui.add_space(4.0); - ctx.total_matches += crate::appearance::preferences_section_with_query(ui, app, t, ctx.query); + crate::appearance::preferences_section_with_context(ui, app, t, ctx); ui.add_space(8.0); reading_colours_section(ui, app, t, ctx); } diff --git a/crates/ui-egui/tests/it/preferences_layout.rs b/crates/ui-egui/tests/it/preferences_layout.rs index cb5e2570dd..e0a5d4e1cb 100644 --- a/crates/ui-egui/tests/it/preferences_layout.rs +++ b/crates/ui-egui/tests/it/preferences_layout.rs @@ -210,3 +210,44 @@ fn preferences_dialog_scrollbar_spacing_and_controls() { // Search box right edge is aligned within the dialog assert!(search.max.x <= ok.max.x); } + +#[test] +fn search_scrolls_option_only_and_theme_card_matches_into_visible_viewport() { + let mut h = harness(480.0); + let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect(); + let ok = h.get_by_label("OK").rect(); + + // "Two-page view" is an option in Card 3 (Documents and view). + // In a 480 pt window, it starts out below the visible scroll viewport. + let opt_before = h.get_by_label("Two-page view").rect(); + assert!(opt_before.min.y >= ok.min.y, "Two-page option starts out below the visible viewport: {opt_before:?} vs OK {ok:?}"); + + // Searching "Two-page" (which only occurs inside that segmented pill option) + // auto-scrolls the matching option into the visible viewport between title and OK. + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click(); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Two-page"); + h.run_steps(4); + + let opt_after = h.get_by_label("Two-page view").rect(); + assert!( + opt_after.min.y >= title.max.y && opt_after.max.y <= ok.min.y, + "Two-page option scrolled into visible scroll viewport: {opt_after:?} between title {title:?} and OK {ok:?}" + ); + + // Clear search and test a theme-card-only match + h.get_by_label("Clear search").click(); + h.run_steps(4); + + // Search for "Dark theme" (which occurs only in the dark theme card in Card 2). + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click(); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Dark theme"); + h.run_steps(4); + + let dark_card = h.get_by_label("Dark theme").rect(); + assert!( + dark_card.min.y >= title.max.y && dark_card.max.y <= ok.min.y, + "Dark theme card scrolled into visible viewport: {dark_card:?} between title {title:?} and OK {ok:?}" + ); +} From d266527b98b7f684aaa73339dbbb0e0f68be07cf Mon Sep 17 00:00:00 2001 From: Combiler01 Date: Mon, 2 Nov 2026 14:41:41 +0530 Subject: [PATCH 13/15] ui: fold dotted and dotless i in preferences text search --- crates/ui-egui/src/dialogs/preferences.rs | 59 ++++++++++++++++++----- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 42f9f17798..49609461d8 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -171,6 +171,20 @@ pub fn preference_card( .inner } +/// Folds a character for case-insensitive search, folding dotted/dotless i variants +/// ('I', 'i', 'İ', 'ı') to 'i', Greek sigmas to 'σ', and otherwise following `char::to_lowercase`. +fn fold_search_char(c: char, mut f: impl FnMut(char)) { + match c { + 'I' | 'i' | '\u{130}' | '\u{131}' => f('i'), + 'Σ' | 'σ' | 'ς' => f('σ'), + _ => { + for lc in c.to_lowercase() { + f(lc); + } + } + } +} + /// Finds non-overlapping (start_byte, end_byte) slices in `text` matching `query` case-insensitively. /// All byte indices are guaranteed to align to valid char boundaries. pub fn find_match_ranges(text: &str, query: &str) -> Vec<(usize, usize)> { @@ -178,7 +192,10 @@ pub fn find_match_ranges(text: &str, query: &str) -> Vec<(usize, usize)> { if q.is_empty() { return Vec::new(); } - let q_chars: Vec = q.chars().flat_map(char::to_lowercase).collect(); + let mut q_chars = Vec::new(); + for c in q.chars() { + fold_search_char(c, |ch| q_chars.push(ch)); + } if q_chars.is_empty() { return Vec::new(); } @@ -196,20 +213,19 @@ pub fn find_match_ranges(text: &str, query: &str) -> Vec<(usize, usize)> { break; } let c = char_indices.get(i + text_char_count).map(|(_, ch)| *ch).unwrap_or('\0'); - let mut c_matched = false; - for lc in c.to_lowercase() { - if q_idx < q_chars.len() && lc == q_chars.get(q_idx).copied().unwrap_or('\0') { - q_idx += 1; - c_matched = true; - } else { - c_matched = false; - break; + let mut c_folded = ['\0'; 4]; + let mut len = 0; + fold_search_char(c, |lc| { + if len < c_folded.len() { + c_folded[len] = lc; + len += 1; } - } - if !c_matched { + }); + if len == 0 || q_idx + len > q_chars.len() || q_chars.get(q_idx..q_idx + len) != Some(&c_folded[..len]) { matched = false; break; } + q_idx += len; text_char_count += 1; } @@ -986,4 +1002,25 @@ mod tests { let ranges4 = find_match_ranges(text, ""); assert!(ranges4.is_empty()); } + + #[test] + fn test_find_match_ranges_turkish_i() { + let text = "Doldur ve İmzala"; + let ranges = find_match_ranges(text, "imzala"); + assert_eq!(ranges.len(), 1); + assert_eq!(text.get(ranges[0].0..ranges[0].1), Some("İmzala")); + + let ranges2 = find_match_ranges(text, "İMZALA"); + assert_eq!(ranges2.len(), 1); + assert_eq!(text.get(ranges2[0].0..ranges2[0].1), Some("İmzala")); + + let text2 = "Doldur ve imzala"; + let ranges3 = find_match_ranges(text2, "İmzala"); + assert_eq!(ranges3.len(), 1); + assert_eq!(text2.get(ranges3[0].0..ranges3[0].1), Some("imzala")); + + let ranges4 = find_match_ranges(text, "ımzala"); + assert_eq!(ranges4.len(), 1); + assert_eq!(text.get(ranges4[0].0..ranges4[0].1), Some("İmzala")); + } } From 4a0b1dd158f4f8a73af1b2dc1e10f97dda576dc7 Mon Sep 17 00:00:00 2001 From: Hamza Naveed <45464935+Hamza0101@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:02:12 +0500 Subject: [PATCH 14/15] Repair scan: an object whose header names another generation is still found (#5580) (#5584) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * A rebuilt xref finds an object whose header names another generation (#5580) `poppler-85140-0.pdf` is 340 bytes with no cross-reference table, and the header of its one page reads `3 18446744073709551616 obj` while the page tree points at `3 0 R`. Before #427 the digits wrapped and 2^64 wrapped to exactly 0, so the header read as `3 0 obj` and the file opened by accident. Once an overflowing integer became a real, the object was unreachable and the file stopped opening at all, which `cargo xtask check` reports as a regression. The generation is not really the point. `3 99999 obj` with the same page tree is refused in exactly the same way on main -- the control for the new test fails on that row first, with "page 1 does not exist" -- so this is a mismatched generation in a rebuilt table, not an integer overflow. A table rebuilt by scanning the file has no revision history to tell two generations of an object apart, and a file that needs rebuilding references everything as `N 0 R` whatever its headers say. So, in the reconstruction path only: - a generation number that cannot be read is taken as 0, the value such a file's references use (`read_object_header`). A generation is at most 65,535 (ISO 32000-2 §7.5.4), so there is nothing to lose by it; - every scanned object is also filed under generation 0, with `or_insert` so a real `N 0 obj` is never displaced by the alias; - the object is read back behind the same lenient header, since reading it parses the header again and the strict identifier check rejected it (`read_repaired_body`, gated on `repaired`). Reading numbers anywhere else is unchanged, and a table read from the file's own xref keeps the exact identifier match. The scan already files objects found in object streams under generation 0, and cos's table parser already takes an unreadable generation as 0, so this follows what the code does elsewhere. The test covers generations 0, 99999 and 2^64 with no table and no `startxref`, and asserts the page is found at its own size. Its fixture is built in the test rather than taken from the corpus, so it holds without the pinned checkout. * The generation-0 stand-in is one key, not a second object Two consequences of filing a scanned object under generation 0 as well, both from review. `XRef::objects` walks the table's keys, so an object with a stand-in came out once per key: a document whose page tree cannot be read is recovered by looking for objects that are pages, and it reported the page twice. Enumeration now yields one object per location, after the sort it already does. Both keys stay for lookups; only this walk is deduplicated. And `or_insert` never replaces, so a later `3 1 obj` moved the exact `3 1` key to the later body while the `3 0` stand-in stayed on the earlier one -- `3 0 R` and `3 1 R` would then read different objects. The scan now tracks which generation-0 keys are stand-ins: a real `N 0 obj` takes the key and keeps it, and a later header for the same number replaces a stand-in. The tests check both through what comes out: page 2 must not exist for a single-page file recovered without a page tree, and with two `3 1 obj` headers the page comes back at the later body's 300x150 rather than the earlier 200x100. * M2: the repair scan keeps its place on a non-header, and an object stream's first member is enumerated (#5580) - read_object_header's lenient path works on a clone, so `42 3 0 obj` no longer costs the header after the stray number (CodeRabbit, minor). - XRef::objects deduplicates by location and object number: an object stream and its first member share (offset, 0) and are two objects (CodeRabbit, minor). - vendor/README.md: hayro-syntax patch (34) and its tests. Both new tests fail with their fix reverted. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/render/src/raster/tests.rs | 93 ++++++++++++++++++++++ vendor/README.md | 2 +- vendor/hayro-syntax/src/xref.rs | 125 +++++++++++++++++++++++++++++- 3 files changed, 217 insertions(+), 3 deletions(-) diff --git a/crates/render/src/raster/tests.rs b/crates/render/src/raster/tests.rs index 1c24408e1b..67b9c86906 100644 --- a/crates/render/src/raster/tests.rs +++ b/crates/render/src/raster/tests.rs @@ -8491,6 +8491,99 @@ mod devicen_inks; // patch 27). mod isolated_cmyk_groups; +/// The generation-0 stand-in a rebuilt table files an object under must not make the object a +/// second object: enumeration yielded it once per key, so a document recovered without a readable +/// page tree reported the page twice (noted in review of #5580). +/// +/// And a later header for the same object number replaces the stand-in, so `N 0 R` cannot be left +/// pointing at a body the exact key no longer names. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object() { + // No table, no `startxref`, and no readable page tree: the pages are recovered by looking for + // objects that are pages, which is where a doubled object shows up as a doubled page. + let pdf = "%PDF-1.4\n\ + 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\ + 3 99999 obj << /Type /Page /MediaBox [0 0 200 100] /Contents 4 0 R >> endobj\n\ + 4 0 obj << /Length 0 >> stream\n\nendstream endobj\n\ + trailer << /Root 1 0 R >>\n\ + %%EOF\n"; + let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default()); + let first = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false }); + assert!(first.error.is_none(), "the page is recovered: {:?}", first.error); + let second = r.render(RenderRequest { page: 1, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false }); + assert!(second.error.is_some(), "and it is one page, not two: page 2 must not exist"); + + // Two headers for object 3, the second the one the exact key names: the stand-in follows it. + // `(B)` is drawn by the later body, so the page that comes back says which one was read. + let twice = "%PDF-1.4\n\ + 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ + 3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 5 0 R >> endobj\n\ + 3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 150] /Contents 5 0 R >> endobj\n\ + 5 0 obj << /Length 0 >> stream\n\nendstream endobj\n\ + trailer << /Root 1 0 R >>\n\ + %%EOF\n"; + let mut r = PageRenderer::new(Arc::new(twice.to_string().into_bytes()), RenderConfig::default()); + let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false }); + assert!(page.error.is_none(), "the page is found: {:?}", page.error); + assert_eq!((page.width, page.height), (300, 150), "`3 0 R` reads the later body, as `3 1` does"); +} + +/// A file whose cross-reference table has to be rebuilt keeps an object whose header names a +/// generation the reference does not. +/// +/// `poppler-85140-0.pdf` is 340 bytes with no table at all, and its one page's header reads +/// `3 18446744073709551616 obj` while the page tree points at `3 0 R`. Before #427 the digits +/// wrapped, and 2^64 wrapped to exactly 0, so the header read as `3 0 obj` and the file opened by +/// accident; once an overflowing integer became a real the object was unreachable and the file +/// stopped opening at all, which `cargo xtask check` reports as a regression (#5580). +/// +/// A rebuilt table has no revision history to tell two generations of an object apart -- the scan +/// already files objects found in object streams under generation 0 -- so the object number is +/// what identifies one. A readable generation that simply is not the one referenced +/// (`3 99999 obj`) was lost the same way, and is covered here too. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_rebuilt_table_finds_an_object_whose_header_names_another_generation() { + for generation in [ + // The generation the reference names, which always worked. + "0", + // One that reads as an integer but is not the one referenced. + "99999", + // And one no generation may be: 2^64, which is what the reported file carries. A + // generation number is at most 65,535 (ISO 32000-2 §7.5.4). + "18446744073709551616", + ] { + // No table and no `startxref`, so the objects are recovered by scanning the file. + let pdf = format!( + "%PDF-1.4\n\ + 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ + 3 {generation} obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\ + trailer << /Root 1 0 R >>\n\ + %%EOF\n" + ); + let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default()); + let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false }); + assert!(page.error.is_none(), "generation {generation}: the page is found: {:?}", page.error); + assert_eq!((page.width, page.height), (200, 100), "generation {generation}: and it is the page's own size"); + } + + // A stray number before a header (`42 3 0 obj`) is not a header, and must not cost the one + // after it: the lenient read leaves the scan where it was when it fails (noted in review). + let pdf = "%PDF-1.4\n\ + 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ + 42 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\ + trailer << /Root 1 0 R >>\n\ + %%EOF\n"; + let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default()); + let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false }); + assert!(page.error.is_none(), "the header after a stray number is found: {:?}", page.error); + assert_eq!((page.width, page.height), (200, 100)); +} + /// #3109 / #3116: clipping-only text (`7 Tr`) installs a clip for subsequent painting /// but draws no pixels itself. #[test] diff --git a/vendor/README.md b/vendor/README.md index 3173659698..35cca11813 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -43,7 +43,7 @@ Other resource categories retain their existing parent-chain lookup. | hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated image whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (25) a tiling cell is drawn at the scale that makes one `/XStep` (`/YStep`) exactly the cell pixmap's whole number of pixels (`tiling_cell_pixels`, at least 1 and at most the cap), so the repeated pixmap puts cells at whole multiples of the step at any device scale; drawing at the unrounded scale repeated the cell up to half a pixel off at every step, and the error grew with distance from the pattern's origin (ISO 32000-2 8.7.3.1) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`), `raster::tests::a_turned_or_mirrored_minified_image_snaps_to_whole_pixels`, `rotated_image_snap::a_shrunk_image_on_a_turned_page_is_the_upright_render_turned` (`cargo test -p pdfcraft-render --test it`), `renderer::snap_tests::a_skew_that_moves_a_far_edge_is_not_snapped` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path`; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (25) `tiling_cell_placement::{far_cells_of_a_fill_sit_at_whole_steps, far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix, far_cells_of_a_stroke_sit_at_whole_steps, a_cell_pixmap_spans_exactly_one_step}` (`cargo test -p pdfcraft-render --test it`) | | hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`, `raster::tests::jbig2_halftone_grids_past_their_bound_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`); (5) `raster::tests::jbig2_regions_held_past_a_pages_bound_are_refused`, `jbig2_symbols_without_pixels_count_towards_a_pages_bound`, `jbig2_retained_contexts_count_towards_a_pages_bound`, `jbig2_huffman_tables_count_towards_a_pages_bound`, `jbig2_new_symbols_count_towards_a_pages_bound`, `jbig2_new_symbols_are_held_to_what_a_page_has_left`, `jbig2_pattern_dictionaries_count_towards_a_pages_bound`, and in the crate (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) `decode::symbol::tests::exported_symbols_are_counted_before_they_are_copied`, `tests::the_room_left_shrinks_as_segments_are_stored`; (6) `raster::tests::jbig2_segments_referring_to_too_many_symbols_are_refused`; (7) `raster::tests::jbig2_pattern_dictionaries_too_large_to_shift_still_draw`, `jbig2_shifted_patterns_never_refuse_an_image`; (8) `raster::tests::jbig2_huffman_tables_of_too_many_lines_are_refused`, `jbig2_streams_of_too_many_segments_are_refused`, `jbig2_streams_of_too_many_references_are_refused`, and in the crate `tests::the_segments_of_a_stream_and_its_globals_count_together`; (9) `raster::tests::jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them`, `tests::a_page_past_the_bounds_is_refused_when_opened`; (10) `raster::tests::jbig2_decoding_work_is_counted_item_by_item`; (12) `raster::tests::jbig2_placements_at_the_end_of_an_i32_draw_nothing` | | lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` | -| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax) | +| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260); (29) a `/JBIG2Globals` stream that is itself JBIG2 isn't decoded: globals are raw segments, and a chain of 16,000 such streams overflowed the stack, which aborts the process; (32) a group of array items read together (a tuple: an image's `/Decode`, `/W`, `/W2`, and a function's `/Domain`, `/Range`, `/Encode` and `/Decode`) can start with a reference: it was taken for the whole group and lost, which ended the array, so an image with `/Decode [7 0 R 0]` didn't draw and CID widths fell back to `/DW`; (33) an object that holds only a reference stands for what that names, stored on its own or in an object stream, up to 32 references: read as a number it was the reference's own object number, so a `/Decode` or `/W` entry naming such an object took a wrong value, and as anything else it was lost. Past 32, as any cycle goes, it reads as a missing object. An object stream isn't reached that way, as its checks are of the object named; reading its index counts against the 64 nested loads and reads its dictionary alone, as a chain of them, each with a member of the next for its `/N`, `/First` or `/Length`, ran out of stack; and a comment inside a reference counts as white space; (34) a table rebuilt by scanning the file (`fallback_xref_map`) finds an object by its number when its header names another generation, including one no generation may be (`3 18446744073709551616 obj` in `poppler-85140-0.pdf`, #5580): the header is read leniently only in that scan (`read_object_header`), the object is also filed under generation 0 unless a real `N 0 obj` holds that key (a later header for the number moves the stand-in), `XRef::get_with` matches by object number only in a repaired table, and `XRef::objects` yields each location once | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content`; (29) `raster::tests::jbig2_globals_that_are_jbig2_themselves_are_not_decoded`, `raster::tests::jbig2_globals_are_read`; (32) `raster::tests::a_decode_array_with_references_in_it_is_read`, `raster::tests::a_functions_arrays_can_start_with_a_reference` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret); (33) `raster::tests::a_reference_to_a_reference_is_what_it_names`, `raster::tests::a_decode_array_with_references_in_it_is_read` (pdfcraft-render), `font::cid::width_tests::a_width_group_can_start_with_a_reference` (hayro-interpret), `xref::tests::an_object_stream_isnt_reached_through_a_reference`, `xref::tests::a_chain_of_object_streams_ends_at_the_limit_of_nested_loads`, `xref::tests::a_chain_of_object_streams_takes_no_more_work_for_two_ways_on`, `xref::tests::a_reference_held_in_either_storage_is_followed`, `xref::tests::a_page_a_reference_is_held_to_is_found_once` (hayro-syntax); (34) `raster::tests::a_rebuilt_table_finds_an_object_whose_header_names_another_generation`, `raster::tests::a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object` (pdfcraft-render), `xref::tests::an_object_stream_and_its_first_member_are_both_enumerated` (hayro-syntax) | | winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open | | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate | diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs index 356bad6b15..d3ab7d324f 100644 --- a/vendor/hayro-syntax/src/xref.rs +++ b/vendor/hayro-syntax/src/xref.rs @@ -4,6 +4,7 @@ use crate::crypto::{DecryptionError, DecryptionTarget, Decryptor, get}; use crate::data::Data; use crate::metadata::Metadata; use crate::object::Name; +use crate::object::Number; use crate::object::ObjectIdentifier; use crate::object::Stream; use crate::object::dict::keys::{ @@ -80,6 +81,65 @@ pub(crate) fn fallback(data: PdfData, password: &[u8]) -> Option { } } +/// PdfCraft patch: an `N G obj` header for the repair scan, taking a generation number that +/// cannot be read as 0. +/// +/// A generation number is at most 65,535 (ISO 32000-2 §7.5.4), so `3 18446744073709551616 obj` is +/// malformed and [`ObjectIdentifier::read`] is right to refuse it everywhere else. This scan runs +/// only when a file's cross-reference table is unusable and its objects are being recovered by +/// reading the file, where refusing the header drops the object and whatever it holds (#5580). +/// Before #427 the digits wrapped, and 2^64 wrapped to exactly 0, which is the only reason such a +/// file used to open. +/// +/// Only here: reading numbers anywhere else is unchanged. +fn read_object_header<'a>(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option { + let mut strict = r.clone(); + if let Some(obj_id) = strict.read::(ctx) { + *r = strict; + return Some(obj_id); + } + // On a clone as well, so a header that isn't one leaves `r` where it was for the caller. + let mut lenient = r.clone(); + let obj_number = lenient.read_without_context::()?; + lenient.skip_white_spaces_and_comments(); + // Any number at all in the generation position, including one no generation may be. + lenient.skip::(false)?; + lenient.skip_white_spaces_and_comments(); + lenient.forward_tag(b"obj")?; + *r = lenient; + Some(ObjectIdentifier::new(obj_number, 0)) +} + +/// PdfCraft patch: the body of the object at `offset` whose `N G obj` header cannot be read +/// strictly, for a table rebuilt by scanning the file (#5580). The steps are +/// `IndirectObject::read`'s, with [`read_object_header`] in place of the strict identifier. +fn read_repaired_body<'a, T>( + data: &'a [u8], + offset: usize, + id: ObjectIdentifier, + ctx: &ReaderContext<'a>, +) -> Option +where + T: ObjectLike<'a>, +{ + let mut r = Reader::new(data); + r.jump(offset); + // The number is what identifies the object; the generation is what could not be read. + if read_object_header(&mut r, ctx)?.obj_number != id.obj_number { + return None; + } + let mut ctx = ctx.clone(); + if ctx.parent_chain_contains(&id) { + warn!("cycle detected in indirect object: {id:?}"); + + return None; + } + ctx.set_obj_number(id); + ctx.parent_chain_push(id); + r.skip_white_spaces_and_comments(); + r.read_with_context::(&ctx) +} + fn fallback_xref_map<'a>(data: &'a PdfData, password: &[u8]) -> (XrefMap, Option>) { fallback_xref_map_inner(data, ReaderContext::dummy(), true, password) } @@ -91,6 +151,10 @@ fn fallback_xref_map_inner<'a>( password: &[u8], ) -> (XrefMap, Option>) { let mut xref_map = FxHashMap::default(); + // PdfCraft patch: the generation-0 keys below that stand in for a header with another + // generation, so a later header can replace one while a real `N 0 obj` is never displaced + // (noted in review of #5580). + let mut aliases: rustc_hash::FxHashSet = rustc_hash::FxHashSet::default(); let mut trailer_dicts = vec![]; let mut root_ref = None; @@ -105,12 +169,32 @@ fn fallback_xref_map_inner<'a>( // First try to check if we have an object identifier. if r.peek_byte().is_some_and(|b: u8| b.is_ascii_digit()) { - if let Some(obj_id) = r.read::(&dummy_ctx) { + if let Some(obj_id) = read_object_header(&mut r, &dummy_ctx) { let mut cloned = r.clone(); // Check that the object following it is actually valid before inserting it. cloned.skip_white_spaces_and_comments(); if cloned.skip::>(false).is_some() { xref_map.insert(obj_id, EntryType::Normal(cur_pos)); + // PdfCraft patch: also reachable by object number alone, so a reference that + // names a different generation than the header still finds it. A rebuilt + // table has no revision history to tell two generations apart, and a file + // that needs rebuilding references everything as `N 0 R` whatever its headers + // say: `poppler-85140-0.pdf` has one page whose header reads + // `3 18446744073709551616 obj` with a page tree pointing at `3 0 R`, so the + // page was lost and the file did not open at all (#5580). `or_insert`, so a + // real `N 0 obj` is never displaced by this alias. + let by_number = ObjectIdentifier::new(obj_id.obj_number, 0); + if obj_id.gen_number == 0 { + // A real `N 0 obj`: it owns the key from here on, and the last one wins + // as every other entry does. + aliases.remove(&by_number); + } else if !xref_map.contains_key(&by_number) || aliases.contains(&by_number) { + // Stand in for it, and let a later header for the same number replace the + // stand-in -- the exact key moves on, so an alias left behind would send + // `N 0 R` to a body the exact key no longer names (noted in review). + xref_map.insert(by_number, EntryType::Normal(cur_pos)); + aliases.insert(by_number); + } last_obj_num = Some(obj_id); dummy_ctx.set_obj_number(obj_id); } @@ -498,6 +582,14 @@ impl XRef { // Try to yield in the order the objects appeared in the // PDF. elements.sort_by(|e1, e2| e1.1.cmp(&e2.1)); + // PdfCraft patch: one object per location. A rebuilt table can hold two keys for + // one object -- its own generation and the generation-0 stand-in (#5580) -- and + // enumeration yielded the object once for each, so a document recovered by + // `Pages::new_brute_force` reported the page twice (noted in review). Both keys + // stay for lookups; only this walk is deduplicated. The object number is part of + // the key: an object stream at (offset, 0) and its first member, also + // (offset, 0), are two objects. + elements.dedup_by(|a, b| a.1 == b.1 && a.0.obj_number == b.0.obj_number); let mut iter = elements.into_iter(); @@ -653,10 +745,27 @@ impl XRef { } if let Some(object) = r.read_with_context::>(&ctx) { - if object.id() == &id { + // PdfCraft patch: in a table rebuilt by scanning the file, the object number + // is what identifies an object. There is no revision history to tell two + // generations apart, the scan already files objects found in object streams + // under generation 0, and a malformed generation in a header would otherwise + // make the object unreadable through the reference that names it (#5580). A + // table read from the file's own xref keeps the exact match. + if object.id() == &id || (repaired && object.id().obj_number == id.obj_number) { return Some(Fetched::Object(object.get())); } } else { + // PdfCraft patch: the strict read of the header failed. In a table rebuilt by + // scanning the file that can be a generation number no generation may be -- + // `3 18446744073709551616 obj` -- and refusing it loses the object the + // reference names (#5580). The object number still has to be the one asked + // for; only an unreadable generation is tolerated, and only here. + if repaired + && let Some(object) = + read_repaired_body::(repr.data.get().as_ref(), offset, id, &ctx) + { + return Some(Fetched::Object(object)); + } // There is a valid object at the offset, it's just not of the type the caller // expected, which is fine. if r.skip::>>(false).is_some() { @@ -1734,6 +1843,18 @@ mod tests { } } + #[test] + fn an_object_stream_and_its_first_member_are_both_enumerated() { + // Both sit at (stream offset, 0) in `objects`' ordering; one object per location must + // not cost either of them. + let pdf = crate::Pdf::new(object_stream_fixture(false)).unwrap(); + let objects: Vec<_> = pdf.xref().objects().into_iter().collect(); + assert!(objects.iter().any(|o| matches!(o, Object::Stream(_)))); + assert!(objects.iter().any( + |o| matches!(o, Object::Dict(d) if d.get::(b"Marker") == Some(123)) + )); + } + #[test] fn recursive_object_stream_locations_fail_without_recursing() { let pdf = crate::Pdf::new(object_stream_fixture(true)).unwrap(); From d7dd1de647ee186d2161b2c464bdb8bb68f085fb Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:07:42 +0100 Subject: [PATCH 15/15] Reject '+' sign in page selection numbers (#5715) Found while testing crates/ui-egui/src/panels/page_selection_ui.rs:24-27 (parse, `number` closure) Co-authored-by: Claude Haiku 5.5 --- crates/ui-egui/src/panels/page_selection_ui.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/page_selection_ui.rs b/crates/ui-egui/src/panels/page_selection_ui.rs index eb97b16b09..deb811768e 100644 --- a/crates/ui-egui/src/panels/page_selection_ui.rs +++ b/crates/ui-egui/src/panels/page_selection_ui.rs @@ -22,7 +22,9 @@ pub(crate) fn parse(text: &str, count: usize) -> Result, PrintError> let mut pages = BTreeSet::new(); let mut budget = 1_000_000usize; let number = |token: &str| { - let n = token.trim().parse::().map_err(|_| PrintError::NotAPage(token.into()))?; + let t = token.trim(); + let n = + if t.bytes().all(|b| b.is_ascii_digit()) { t.parse::().ok() } else { None }.ok_or_else(|| PrintError::NotAPage(token.into()))?; if n == 0 || n > count { Err(PrintError::OutOfRange(n, count)) } else { Ok(n - 1) } }; for part in text.split([',', ';']).map(str::trim) { @@ -132,6 +134,13 @@ impl PageSelectionInput { mod tests { use super::*; + #[test] + fn plus_sign_is_not_a_page_number() { + for text in ["+3", "+2-4", "2-+4"] { + assert!(matches!(parse(text, 100), Err(PrintError::NotAPage(_))), "{text}"); + } + } + #[test] fn selection_ranges_are_sorted_unique_and_bounded() { let pages = parse("1,12,16-18,89,92,93,97,99", 100).unwrap();