From 5ed8fdb5246f32f21bbcbb4cd4454d2765dbd4b7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 22:50:02 -0500 Subject: [PATCH] print-tests: keep the port's PrintSection body, Rig print tests and count-based perf tests; production's printer picker, harness_with_printers and timing calibration go to the framework (F-P4) or stay cut --- crates/ui-egui/src/workflows/print_ui/body.rs | 661 ------------------ crates/ui-egui/tests/it/print.rs | 146 ---- crates/ui-egui/tests/perf.rs | 242 ------- 3 files changed, 1049 deletions(-) diff --git a/crates/ui-egui/src/workflows/print_ui/body.rs b/crates/ui-egui/src/workflows/print_ui/body.rs index afb3ba17a3..92d43414a3 100644 --- a/crates/ui-egui/src/workflows/print_ui/body.rs +++ b/crates/ui-egui/src/workflows/print_ui/body.rs @@ -439,7 +439,6 @@ fn advanced_section(d: &PrintDraft) -> PrintSection { .folded(d.as_image) } -<<<<<<< HEAD /// The values of every row the draft decides. pub(super) fn fields_from_draft(d: &PrintDraft) -> DialogFields { let mut f = DialogFields::new(); @@ -641,666 +640,6 @@ pub(super) fn draft_from_fields(d: &mut PrintDraft, f: &DialogFields, edited: &[ let typed = |n: f64| if n > 0.0 { n.to_string() } else { String::new() }; if on("custom_name") && let Some(t) = text("custom_name") -======= -/// A wide, searchable fleet list; filtering never changes the selected destination. -fn printer_picker(ui: &mut egui::Ui, d: &mut PrintDraft) -> egui::Response { - let filter_id = ui.make_persistent_id("printer-filter"); - // Keep the search only while the combo box renders its popup contents. - let previous_filter = ui.data(|data| data.get_temp::(filter_id)); - let opening = previous_filter.is_none(); - let mut filter = previous_filter.unwrap_or_default(); - let shown = match d.printer.as_deref() { - Some(p) => printer_label(p), - None if still_looking(d) => tl!("Looking for printers…").to_string(), - None => tl!("Save as PDF").to_string(), - }; - let screen = ui.ctx().content_rect(); - let width = 430.0_f32.min((screen.width() - 32.0).max(0.0)); - let height = 420.0_f32.min(screen.height() * 0.6); - let response = craft_ui::ComboBox::from_id_salt("printer") - .selected_text(&shown) - .width(260.0) - .truncate() - .height(height) - .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) - .show_ui(ui, |ui| { - ui.set_width(width); - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); - let search_label = ui.label(tl!("Search printers")); - let search = ui.add(widgets::line(&mut filter).desired_width(f32::INFINITY).char_limit(256)).labelled_by(search_label.id); - if opening { - search.request_focus(); - } - let query = pdfcraft_render::text::fold_case(filter.trim()); - if d.printers_loading { - ui.add_enabled(false, egui::Label::new(tl!("Looking for printers…"))); - } - // Keep the search and Save as PDF visible while the devices scroll. - // The popup's actual clip can be shorter than the requested height. - let footer_height = ui.spacing().interact_size.y + 4.0 * ui.spacing().item_spacing.y; - let list_height = (ui.clip_rect().bottom() - ui.cursor().top() - footer_height).clamp(0.0, height); - let mut list = egui::ScrollArea::vertical().id_salt("printer-results").max_height(list_height); - if search.changed() { - list = list.vertical_scroll_offset(0.0); - } - list.show(ui, |ui| { - let mut matched = false; - for p in &d.printers { - let name = printer_label(&p.name); - if !query.is_empty() && !pdfcraft_render::text::fold_case(&name).contains(&query) { - continue; - } - matched = true; - let label = if p.default && p.name != crate::web_print::BROWSER_PRINTER { - crate::i18n::fmt(tl!("{name} (default)"), &[("name", &name)]) - } else { - name - }; - let selected = d.printer.as_deref() == Some(p.name.as_str()); - let choice = ui.selectable_value(&mut d.printer, Some(p.name.clone()), label); - if opening && selected { - choice.scroll_to_me(Some(egui::Align::Center)); - } - if choice.clicked() { - d.printer_picked = true; - ui.close(); - } - } - if !matched && !query.is_empty() && !d.printers_loading { - ui.label(tl!("No printers match.")); - } - }); - ui.separator(); - // An explicit choice also protects PDF from a late default-printer refresh. - if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() { - d.printer_picked = true; - ui.close(); - } - }); - ui.data_mut(|data| { - if response.inner.is_some() { - data.insert_temp(filter_id, filter); - } else { - data.remove::(filter_id); - } - }); - response.response.on_hover_text(shown) -} - -/// Draw the dialog. `thumb` gives a page's thumbnail texture when there is one. Returns -/// (print, cancel). -pub(crate) fn body( - ui: &mut egui::Ui, - d: &mut PrintDraft, - t: &Tokens, - sizes: &[(f64, f64)], - labels: &[String], - thumb: &mut dyn FnMut(usize) -> Option, -) -> (bool, bool) { - ui.set_width(820.0); - ui.label(egui::RichText::new(tl!("Print")).font(theme::semibold(18.0))); - ui.add_space(8.0); - let settings = d.settings(sizes.len(), labels); - let laid = settings.as_ref().ok().map(|s| print::layout(sizes, s)); - // Creep within its field's range can still be too much for a thick booklet. - let too_much_creep = d.handling == Handling::Booklet && d.creep > 0.0 && matches!(laid, Some(Err(_))); - let sheets = laid.and_then(Result::ok).unwrap_or_default(); - d.sheet = d.sheet.min(sheets.len().saturating_sub(1)); - // Cap the settings+preview area to the screen's available height (#4252, #5317): - // on a short screen, or with the driver's own Properties… panel expanded below, this row can - // otherwise grow taller than the display and push the Print/Cancel buttons off both edges. - // The title and the button row stay outside, so they are always reachable. - // `viewport_rect()` is egui's own idea of the current viewport, kept from the latest - // `RawInput::screen_rect` it was handed — unlike reading `raw.screen_rect` directly, it - // does not go blank on a frame where the backend didn't resend it. - let screen_h = ui.ctx().input(|i| i.viewport_rect().height()); - let max_h = (screen_h - 220.0).max(300.0); - // The viewport is `max_h` itself, not what the modal offers this frame: when a different - // dialog was shown before, the shared modal remeasures from a height of zero (#5118) and - // offers less, which would size this area by the dialog shown before. `auto_shrink` still - // shrinks it to contents that fit. - egui::ScrollArea::vertical().max_height(max_h).min_scrolled_height(max_h).auto_shrink([false, true]).show(ui, |ui| { - ui.horizontal_top(|ui| { - // Settings. - ui.vertical(|ui| { - ui.set_width(470.0); - egui::Grid::new("print-top").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - let printer_caption = ui.label(tl!("Printer:")); - let before = d.printer.clone(); - // The browser's print dialog sets copies, two-sided printing and colour itself. - let browser = d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER); - ui.horizontal(|ui| { - printer_picker(ui, d).labelled_by(printer_caption.id); - let tip = if spool::HAS_PRINTER_PREFERENCES { - tl!("Opens the printer driver's preferences. They are saved for every print from this computer; the copies, two-sided, grayscale and paper chosen here still apply.") - } else { - tl!("The printer driver's own settings for this print: paper tray, paper type, finishing and more.") - }; - let properties = ui.add_enabled(d.printer.is_some() && !browser, egui::Button::new(tl!("Properties…"))).on_hover_text(tip); - if properties.clicked() - && let Some(p) = d.printer.clone() - { - if spool::HAS_PRINTER_PREFERENCES { - d.driver_error = spool::open_printer_preferences(&p).err().map(|e| e.to_string()); - } else { - if d.driver_options.as_ref().is_none_or(|(read_for, _)| *read_for != p) && d.driver_options_loading.as_deref() != Some(p.as_str()) { - // Read off the GUI thread (#1818): `poll_print` starts it next frame. - d.driver_options = None; - d.driver_choices.clear(); - d.driver_options_loading = Some(p.clone()); - d.read_options_for = Some(p); - } - d.show_driver_options = !d.show_driver_options; - } - } - }); - if d.printer != before { - d.printer_picked = true; - d.show_driver_options = false; - d.driver_error = None; - // What this printer was last printed with (#2001). - d.apply_setup(); - d.reset_unoverridden_custom_paper(); - d.apply_printer_papers(Vec::new()); - if let Some(p) = d.printer.clone() { - d.read_papers_for = Some(p); - } - } - ui.end_row(); - // The spooler answered with no printer at all (#160): say so, rather than - // leaving Save as PDF looking like the only thing PdfCraft can do. - if !d.printers_loading && d.printers.is_empty() { - ui.label(""); - ui.label( - egui::RichText::new(tl!("No printers were found. Check that the printer is installed and the print spooler is running, then open Print again.")) - .small() - .color(t.text_muted), - ); - ui.end_row(); - } - let copies_label = ui.label(tl!("Copies:")); - ui.add_enabled_ui(!browser, |ui| { - ui.horizontal(|ui| { - ui.add(egui::DragValue::new(&mut d.copies).range(1..=999)).labelled_by(copies_label.id); - ui.add(widgets::checkbox(&mut d.collate, tl!("Collate"))); - ui.add(widgets::checkbox(&mut d.grayscale, tl!("Print in grayscale"))); - }); - }); - ui.end_row(); - // A booklet decides two-sided itself (#2707), so the choice is hidden meanwhile, as - // in Acrobat's Print dialog; it is kept for the other layouts. - if d.handling != Handling::Booklet { - ui.label(tl!("Two-sided:")); - ui.add_enabled_ui(!browser, |ui| { - combo( - ui, - "duplex", - tl!("Two-sided:"), - &mut d.duplex, - &[ - (None, tl!("Printer default")), - (Some(spool::Duplex::Off), tl!("Off")), - (Some(spool::Duplex::LongEdge), tl!("Flip on long edge")), - (Some(spool::Duplex::ShortEdge), tl!("Flip on short edge")), - ], - 160.0, - ); - }); - ui.end_row(); - } - let paper_label = ui.label(tl!("Paper:")); - d.paper = d.paper.min(d.paper_count().saturating_sub(1)); - let before = d.paper; - let mut paper_clicked = false; - let detecting = d.papers_loading(); - ui.horizontal(|ui| { - // A standard size's name is translated; a custom paper keeps the name it was given. - let shown = if d.paper_is_custom() { d.paper_name().to_string() } else { tl!(&d.paper_name()).to_string() }; - craft_ui::ComboBox::from_id_salt("paper").selected_text(shown).width(180.0).show_ui(ui, |ui| { - if detecting { - ui.add_enabled(false, egui::Label::new(tl!("Detecting paper…"))); - } - for (i, (name, _)) in d.papers.iter().enumerate() { - if ui.selectable_value(&mut d.paper, i, tl!(name)).clicked() { - paper_clicked = true; - } - } - if !d.custom_papers.is_empty() { - ui.separator(); - } - for (i, p) in d.custom_papers.iter().enumerate() { - let label = format!("{} ({})", p.name, d.units.size(p.width, p.height)); - if ui.selectable_value(&mut d.paper, d.papers.len() + i, label).clicked() { - paper_clicked = true; - } - } - }) - .response - .labelled_by(paper_label.id); - if detecting { - ui.label(egui::RichText::new(tl!("Detecting…")).small().color(t.text_muted)); - } - if ui.button(tl!("Custom…")).on_hover_text(tl!("Add a paper size of your own to the list")).clicked() { - d.custom_new = match d.custom_new { - Some(_) => None, - None => Some((String::new(), String::new(), String::new())), - }; - } - if d.paper_is_custom() && ui.button(tl!("Remove")).on_hover_text(tl!("Take this paper size off the list")).clicked() { - d.remove_custom_paper(); - paper_clicked = true; - } - let page_setup_tip = if spool::HAS_PRINTER_PREFERENCES { - tl!("Selects paper size and orientation from the printer driver. For paper tray, print quality or other driver defaults, use Properties…") - } else { - tl!("Page setup dialog is not available on this system.") - }; - let page_setup = ui - .add_enabled(d.printer.is_some() && !browser && spool::HAS_PRINTER_PREFERENCES, egui::Button::new(tl!("Page Setup…"))) - .on_hover_text(page_setup_tip); - if page_setup.clicked() - && let Some(p) = d.printer.clone() - { - d.driver_error = None; - #[cfg(windows)] - let parent = winsafe::HWND::GetActiveWindow().map(|h| h.ptr() as isize); - #[cfg(not(windows))] - let parent = None; - match spool::show_printer_properties(&p, parent) { - Ok(Some((name, size))) => { - d.apply_driver_paper(name, size); - } - Ok(None) => {} - Err(e) => d.driver_error = Some(e.to_string()), - } - } - }); - if paper_clicked || d.paper != before { - d.paper_overridden = true; - } - // Label stock gets the label layout (cut, turned upright, fitted). - if paper_clicked && d.paper != before && d.paper == print::LABEL_PAPER && d.which != Which::Area { - d.paper_before_label = Some(before); - d.handling = Handling::Label; - d.sheet = 0; - } - ui.end_row(); - if d.custom_new.is_some() { - ui.label(""); - custom_paper_row(ui, d, t); - ui.end_row(); - } - }); - // Windows says which drivers can't print two-sided as they're asked; they keep their - // own setting, even when Two-sided is Off, and for a booklet's both sides. - if d.printer_two_sided() == Some(false) { - ui.label(egui::RichText::new(tl!("This printer's driver doesn't take two-sided settings from other programs, so its own setting applies. Change it in Properties…")).small().color(t.text_muted)); - } - if d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER) { - ui.label(egui::RichText::new(tl!("Copies, two-sided printing and colour are chosen in the browser's print dialog.")).small().color(t.text_muted)); - } - if let Some(e) = &d.driver_error { - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Couldn't open the printer's preferences: {e}"), &[("e", e)])).small().color(t.text_muted)); - } - if d.show_driver_options { - if d.driver_options.is_none() && d.driver_options_loading.is_some() { - ui.label(egui::RichText::new(tl!("Reading the printer's settings…")).small().color(t.text_muted)); - } else { - driver_options_panel(ui, d, t); - } - } - if let Some(&source) = sizes.get(d.current_page) { - ui.horizontal_wrapped(|ui| { - ui.label(crate::i18n::fmt(tl!("PDF page: {size}"), &[("size", &d.units.size(source.0, source.1))])); - let matched = d.matching_paper(source); - if ui.add_enabled(matched.is_some(), egui::Button::new(tl!("Match page at 100%"))).clicked() - && let Some(paper) = matched - { - d.paper = paper; - d.paper_overridden = true; - // A paper picked outright: nothing for leaving Label to give back. - d.paper_before_label = None; - d.handling = Handling::Size; - d.size = SizeMode::Actual; - d.orientation = Orientation::Auto; - d.sheet = 0; - } - }); - } - ui.add_space(6.0); - widgets::section_title(ui, tl!("Pages to Print")); - ui.horizontal(|ui| { - widgets::radio_value(ui, &mut d.which, Which::All, tl!("All")); - widgets::radio_value(ui, &mut d.which, Which::Current, tl!("Current page")); - let pages = widgets::radio_value(ui, &mut d.which, Which::Range, tl!("Pages")); - let r = ui.add_enabled( - d.which == Which::Range, - crate::widgets::line(&mut d.range).hint_text(format!("1-{}", sizes.len())).desired_width(110.0), - ).labelled_by(pages.id); - if r.gained_focus() { - d.which = Which::Range; - } - }); - // Offered only when an area was chosen with Snapshot (its menu's Print area…). - if let Some((page, a)) = d.area { - let label = crate::i18n::fmt( - tl!("Selected area (page {page}, {size})"), - &[("page", &(page + 1).to_string()), ("size", &d.units.size(a[2] - a[0], a[3] - a[1]))], - ); - if widgets::radio_value(ui, &mut d.which, Which::Area, label).clicked() { - // Leaving Label this way gives back the paper it replaced, as its tabs do. - d.set_handling(Handling::Size); - } - } - // Offered only when pages were picked before the dialog opened. - if !d.selected.is_empty() { - let label = format!("{} ({})", tl!("Selected pages"), d.selected.len()); - widgets::radio_value(ui, &mut d.which, Which::Selected, label); - } - ui.horizontal(|ui| { - ui.label(tl!("More options:")); - combo( - ui, - "subset", - tl!("More options:"), - &mut d.subset, - &[(Subset::All, tl!("All pages in range")), (Subset::Odd, tl!("Odd pages only")), (Subset::Even, tl!("Even pages only"))], - 150.0, - ); - ui.add(widgets::checkbox(&mut d.reverse, tl!("Reverse pages"))); - }); - ui.add_space(6.0); - widgets::section_title(ui, tl!("Page Sizing & Handling")); - ui.horizontal_wrapped(|ui| { - for (h, label) in [ - (Handling::Size, tl!("Size")), - (Handling::Poster, tl!("Poster")), - (Handling::Multiple, tl!("Multiple")), - (Handling::Booklet, tl!("Booklet")), - (Handling::Label, tl!("Label")), - ] { - // A selected area prints only with Size. - let offered = d.which != Which::Area || h == Handling::Size; - if ui.add_enabled_ui(offered, |ui| widgets::mode_tab(ui, label, d.handling == h)).inner.clicked() { - d.set_handling(h); - } - } - }); - ui.add_space(4.0); - match d.handling { - Handling::Size => { - ui.horizontal(|ui| { - widgets::radio_value(ui, &mut d.size, SizeMode::Fit, tl!("Fit")); - widgets::radio_value(ui, &mut d.size, SizeMode::Actual, tl!("Actual size")); - widgets::radio_value(ui, &mut d.size, SizeMode::Shrink, tl!("Shrink oversized pages")); - }); - ui.horizontal(|ui| { - let custom = matches!(d.size, SizeMode::Custom(_)); - if ui.add(widgets::radio(custom, tl!("Custom scale:"))).clicked() { - d.size = SizeMode::Custom(d.custom_scale); - } - ui.add_enabled(custom, egui::DragValue::new(&mut d.custom_scale).range(CUSTOM_SCALE).suffix(" %")) - .accessible_name(tl!("Custom scale")); - }); - } - Handling::Label => { - ui.add(widgets::checkbox(&mut d.label_flip, tl!("Turn upside down (180°)"))); - ui.label( - egui::RichText::new(tl!("Cuts each page to its printed area, turns it upright and fits it to the sheet without stretching. One label per sheet.")) - .small() - .color(t.text_muted), - ); - } - Handling::Poster => { - ui.horizontal(|ui| { - let scale_label = ui.label(tl!("Tile scale:")); - ui.add(egui::DragValue::new(&mut d.poster_scale).range(10.0..=1000.0).suffix(" %")).labelled_by(scale_label.id); - let overlap_label = ui.label(tl!("Overlap:")); - ui.add(egui::DragValue::new(&mut d.overlap).range(0.0..=144.0).suffix(" pt")).labelled_by(overlap_label.id); - ui.add(widgets::checkbox(&mut d.cut_marks, tl!("Cut marks"))); - }); - } - Handling::Multiple => { - let page_order = |ui: &mut egui::Ui, order: &mut PageOrder| { - ui.label(tl!("Page order:")); - combo( - ui, - "order", - tl!("Page order:"), - order, - &[ - (PageOrder::Horizontal, tl!("Horizontal")), - (PageOrder::HorizontalReversed, tl!("Horizontal reversed")), - (PageOrder::Vertical, tl!("Vertical")), - (PageOrder::VerticalReversed, tl!("Vertical reversed")), - (PageOrder::CutStack, tl!("Cut and stack")), - ], - 150.0, - ); - }; - ui.horizontal(|ui| { - ui.label(tl!("Pages per sheet:")); - // `None` is Custom: columns by rows, typed in. - let mut per_sheet = (!d.custom_grid).then_some(d.per_sheet); - combo( - ui, - "per-sheet", - tl!("Pages per sheet:"), - &mut per_sheet, - &[(Some(2), "2"), (Some(4), "4"), (Some(6), "6"), (Some(9), "9"), (Some(16), "16"), (None, tl!("Custom"))], - 70.0, - ); - d.custom_grid = per_sheet.is_none(); - if let Some(n) = per_sheet { - d.per_sheet = n; - page_order(ui, &mut d.order); - } else { - let max = print::MAX_GRID; - ui.add(egui::DragValue::new(&mut d.cols).range(1..=max)).accessible_name(tl!("Columns")); - ui.label(tl!("by")); - ui.add(egui::DragValue::new(&mut d.rows).range(1..=max)).accessible_name(tl!("Rows")); - } - }); - if d.custom_grid { - // The grid's fields take the room the page order had. - ui.horizontal(|ui| page_order(ui, &mut d.order)); - } - ui.horizontal(|ui| { - ui.add(widgets::checkbox(&mut d.border, tl!("Print page border"))); - ui.add(widgets::checkbox(&mut d.auto_rotate, tl!("Auto-rotate pages"))); - }); - if d.order == PageOrder::CutStack { - ui.label(tl!( - "Print single-sided. Keep the sheets in order, cut at the marks, then stack the piles left to right, top to bottom." - )); - } - } - Handling::Booklet => { - ui.horizontal(|ui| { - ui.label(tl!("Booklet subset:")); - combo( - ui, - "booklet", - tl!("Booklet subset:"), - &mut d.booklet_subset, - &[ - (BookletSubset::BothSides, tl!("Both sides")), - (BookletSubset::FrontOnly, tl!("Front side only")), - (BookletSubset::BackOnly, tl!("Back side only")), - ], - 130.0, - ); - ui.label(tl!("Binding:")); - combo(ui, "binding", tl!("Binding:"), &mut d.binding, &[(Binding::Left, tl!("Left")), (Binding::Right, tl!("Right"))], 80.0); - let creep_label = ui.label(tl!("Creep:")); - ui.add(egui::DragValue::new(&mut d.creep).range(0.0..=print::MAX_CREEP).speed(0.05).suffix(" pt")) - .labelled_by(creep_label.id) - .on_hover_text(tl!("Moves each sheet's pages toward the fold by this much more than the sheet outside it, so the margins match once the booklet is folded and trimmed.")); - }); - } - } - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.label(tl!("Orientation:")); - widgets::radio_value(ui, &mut d.orientation, Orientation::Auto, tl!("Auto portrait/landscape")); - widgets::radio_value(ui, &mut d.orientation, Orientation::Portrait, tl!("Portrait")); - widgets::radio_value(ui, &mut d.orientation, Orientation::Landscape, tl!("Landscape")); - }); - ui.add_space(6.0); - widgets::section_title(ui, tl!("Comments & Forms")); - combo( - ui, - "content", - tl!("Comments & Forms"), - &mut d.content, - &[ - (Content::Document, tl!("Document")), - (Content::DocumentAndMarkups, tl!("Document and markups")), - (Content::DocumentAndStamps, tl!("Document and stamps")), - (Content::FormFieldsOnly, tl!("Form fields only")), - ], - 220.0, - ); - // Advanced (Acrobat's Advanced Print Setup): print as image. Folded unless it is on. - ui.add_space(6.0); - egui::CollapsingHeader::new(egui::RichText::new(crate::i18n::upper_label("Advanced")).font(theme::semibold(10.5)).color(t.text_faint)) - .id_salt("print-advanced") - .default_open(d.as_image) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.add(widgets::checkbox(&mut d.as_image, tl!("Print as image"))); - ui.add_enabled_ui(d.as_image, |ui| { - ui.label(tl!("Resolution:")); - let mut dpi = d.dpi.round() as u32; - combo(ui, "print-dpi", tl!("Resolution:"), &mut dpi, &[(150, "150 dpi"), (300, "300 dpi"), (600, "600 dpi")], 100.0); - d.dpi = f64::from(dpi); - }); - }); - ui.label( - egui::RichText::new(tl!( - "Use it when a printer skips text, shading or transparency. The print is no longer searchable text; with Print in grayscale, the pictures are grey." - )) - .small() - .color(t.text_muted), - ); - }); - }); - ui.add_space(12.0); - // Preview. - ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - let (area, _) = ui.allocate_exact_size(vec2(PREVIEW_W, PREVIEW_H), egui::Sense::hover()); - ui.painter().rect_filled(area, 6.0, t.hover); - match (&settings, sheets.get(d.sheet)) { - (Err(e), _) => { - ui.put(area.shrink(16.0), egui::Label::new(egui::RichText::new(tl!(e)).color(t.text_muted)).wrap()); - } - (Ok(_), None) if too_much_creep => { - let msg = tl!("The creep moves the innermost sheet's pages too far for this many pages. Reduce Creep."); - ui.put(area.shrink(16.0), egui::Label::new(egui::RichText::new(msg).color(t.text_muted)).wrap()); - } - (Ok(_), Some(sheet)) => { - let k = (PREVIEW_BOX.0 / sheet.size.0 as f32).min(PREVIEW_BOX.1 / sheet.size.1 as f32); - let paper = Rect::from_center_size(area.center(), vec2(sheet.size.0 as f32 * k, sheet.size.1 as f32 * k)); - ui.painter().rect_filled(paper, 0.0, Color32::WHITE); - ui.painter().rect_stroke(paper, 0.0, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); - let to_screen = |x: f64, y: f64| -> Pos2 { pos2(paper.left() + x as f32 * k, paper.bottom() - y as f32 * k) }; - let painter = ui.painter().with_clip_rect(paper); - for pl in &sheet.placed { - let (dw, dh) = sizes[pl.page]; - let [x0, y0, x1, y1] = pl.clip; - let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| { - let (sx, sy) = pl.matrix.apply(x, y); - to_screen(sx, sy) - }); - // UVs of the visible part (texture y runs down from the page top). - let uv = |x: f64, y: f64| pos2((x / dw) as f32, (1.0 - y / dh) as f32); - let uvs = [uv(x0, y0), uv(x1, y0), uv(x1, y1), uv(x0, y1)]; - match thumb(pl.page) { - Some(tex) => { - let mut mesh = egui::Mesh::with_texture(tex); - for (p, u) in corners.iter().zip(uvs) { - mesh.vertices.push(egui::epaint::Vertex { - pos: *p, - uv: u, - color: if d.grayscale { Color32::from_gray(235) } else { Color32::WHITE }, - }); - } - mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); - painter.add(egui::Shape::mesh(mesh)); - } - None => { - painter.add(egui::Shape::convex_polygon( - corners.to_vec(), - Color32::from_gray(245), - Stroke::new(0.5, Color32::from_gray(180)), - )); - let c = corners.iter().fold(vec2(0.0, 0.0), |a, p| a + p.to_vec2()) / 4.0; - painter.text( - c.to_pos2(), - egui::Align2::CENTER_CENTER, - (pl.page + 1).to_string(), - theme::regular(11.0), - Color32::from_gray(120), - ); - } - } - } - for b in &sheet.borders { - painter.rect_stroke( - Rect::from_two_pos(to_screen(b[0], b[1]), to_screen(b[2], b[3])), - 0.0, - Stroke::new(0.6, Color32::BLACK), - egui::StrokeKind::Middle, - ); - } - for l in &sheet.lines { - painter.line_segment([to_screen(l[0], l[1]), to_screen(l[2], l[3])], Stroke::new(0.6, Color32::BLACK)); - } - } - _ => {} - } - ui.horizontal(|ui| { - let n = sheets.len(); - if ui.add_enabled(d.sheet > 0, egui::Button::new("‹")).on_hover_text(tl!("Previous sheet")).clicked() { - d.sheet -= 1; - } - ui.label(if n == 0 { - tl!("No sheets").to_string() - } else { - crate::i18n::fmt(tl!("Sheet {s} of {n}"), &[("s", &(d.sheet + 1).to_string()), ("n", &n.to_string())]) - }); - if ui.add_enabled(d.sheet + 1 < n, egui::Button::new("›")).on_hover_text(tl!("Next sheet")).clicked() { - d.sheet += 1; - } - }); - if let Some(s) = sheets.get(d.sheet) { - ui.label(egui::RichText::new(d.units.size(s.size.0, s.size.1)).small().color(t.text_muted)); - if d.handling == Handling::Size - && let Some(p) = s.placed.first() - { - let scale = p.matrix.0[0].hypot(p.matrix.0[1]) * 100.0; - ui.label(crate::i18n::fmt(tl!("PDF scale: {scale}%"), &[("scale", &format!("{scale:.2}"))])); - ui.label(egui::RichText::new(tl!("Printer paper and scaling may differ. Check driver settings.")).small().color(t.text_muted)); - if (scale - 100.0).abs() > 0.01 { - ui.label(egui::RichText::new(tl!("Drawing scale changes. Use Actual size for full-scale plans.")).small().color(t.text_muted)); - } - } - } - }); - }); - }); // end ScrollArea (#4252, #5317) - ui.add_space(12.0); - let (mut go, mut cancel) = (false, false); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let looking = still_looking(d); - let waiting_paper = d.papers_loading(); - let label = if d.printer.is_some() || looking { tl!("Print") } else { tl!("Save as PDF") }; - if ui - .add_enabled_ui(settings.is_ok() && !sheets.is_empty() && !looking && !waiting_paper, |ui| widgets::pill_button(ui, label, true)) - .inner - .clicked() ->>>>>>> upstream/main { *name = t.to_owned(); } diff --git a/crates/ui-egui/tests/it/print.rs b/crates/ui-egui/tests/it/print.rs index 1c8faffe01..f3cc6c058c 100644 --- a/crates/ui-egui/tests/it/print.rs +++ b/crates/ui-egui/tests/it/print.rs @@ -18,7 +18,6 @@ use serde_json::json; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; -<<<<<<< HEAD // PLAN: assumed `Host::builder(AppInfo).jobs(..).files(..).build()`, `PdfCraftApp::with_host(Arc, AppServices)`, // `AppServices::new(wake, intake, watch)` (q171, q184, q187), `FileIntake::new(Wake)`, `FileWatch::inline()`, the dialog's // listed `notes` (the note rows' keys) and `sheet`/`sheets` (the pager), `ScriptedFiles::failing_writes(path)` (F-4), @@ -282,151 +281,6 @@ fn list_printers(h: &mut Rig, names: &[&str]) { h.state_mut().printer_source = Some(Arc::new(move || listed.clone())); h.state_mut().printer_papers_source = Some(Arc::new(|_| Vec::new())); h.state_mut().default_paper_source = Some(Arc::new(|_| None)); -======= -/// Open a bundled synthetic form with the default print settings. -fn harness() -> Harness<'static, PdfCraftApp> { - harness_with_settings(None) -} - -/// Restore optional settings before opening the form and settling the shell frames. -fn harness_with_settings(settings: Option) -> Harness<'static, PdfCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - if let Some(json) = &settings { - app.restore(json); - } - app.open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); - app - }); - h.run_steps(4); - h -} - -/// A large synthetic fleet, independent of the host's installed printers. -fn harness_with_printers() -> (Harness<'static, PdfCraftApp>, String) { - use pdfcraft_engine::print::spool::Printer; - let mut h = harness(); - let last = "München Satellite 119 - Engineering floor 4 (network queue) - colour duplex device, Building North".to_string(); - let mut printers: Vec<_> = (0..119) - .map(|i| Printer { - name: format!("Office {i:03} - Engineering floor 4 (network queue)"), - description: String::new(), - default: i == 0, - two_sided: None, - }) - .collect(); - printers.push(Printer { name: last.clone(), description: String::new(), default: false, two_sided: None }); - h.state_mut().printer_source = Some(std::sync::Arc::new(move || printers.clone())); - assert!(h.state_mut().execute("print.dialog")); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while h.state().print_draft.printers_loading && std::time::Instant::now() < deadline { - h.run_steps(1); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(!h.state().print_draft.printers_loading); - h.run_steps(3); - (h, last) -} - -/// Searching folds names without selecting a device, and reopening restores the fleet. -#[test] -fn printer_picker_filters_a_large_fleet_without_changing_the_selection() { - let (mut h, last) = harness_with_printers(); - let initial = h.state().print_draft.printer.clone(); - h.get_by_value(initial.as_deref().unwrap()).click(); - h.run_steps(3); - let search = h.get_by_role_and_label(Role::TextInput, "Search printers"); - assert!(search.rect().width() > 350.0, "room for long device names"); - search.type_text(" MÜNCHEN satellite "); - h.run_steps(3); - assert_eq!(h.state().print_draft.printer, initial, "typing is not a printer choice"); - assert!(!h.state().print_draft.printer_picked); - assert!(h.query_by_label("Office 001 - Engineering floor 4 (network queue)").is_none()); - h.get_by_label(&last).click(); - h.run_steps(3); - assert_eq!(h.state().print_draft.printer.as_deref(), Some(last.as_str())); - assert!(h.state().print_draft.printer_picked); - assert!(h.query_by_role_and_label(Role::TextInput, "Search printers").is_none(), "choosing closes the popup"); - - // A fresh opening shows the whole fleet again, including a choice outside the old filter. - h.get_by_value(&last).click(); - h.run_steps(3); - h.get_by_label("Office 001 - Engineering floor 4 (network queue)").scroll_to_me(); - h.run_steps(4); - h.get_by_label("Office 001 - Engineering floor 4 (network queue)").click(); - h.run_steps(2); - assert_eq!(h.state().print_draft.printer.as_deref(), Some("Office 001 - Engineering floor 4 (network queue)")); -} - -/// PDF remains an explicit destination even when no physical device matches the search. -#[test] -fn printer_picker_keeps_save_as_pdf_available_when_the_filter_matches_nothing() { - let (mut h, _) = harness_with_printers(); - let initial = h.state().print_draft.printer.clone(); - h.get_by_value(initial.as_deref().unwrap()).click(); - h.run_steps(3); - // Clicking in the filter must not close the popup, unlike choosing a device. - h.get_by_role_and_label(Role::TextInput, "Search printers").click(); - h.run_steps(2); - h.get_by_role_and_label(Role::TextInput, "Search printers").type_text("no-such-printer"); - h.run_steps(3); - h.get_by_label("No printers match."); - assert_eq!(h.state().print_draft.printer, initial); - h.get_by_label("Save as PDF").click(); - h.run_steps(3); - assert_eq!(h.state().print_draft.printer, None); - assert!(h.state().print_draft.printer_picked); - assert!(h.query_by_role_and_label(Role::TextInput, "Search printers").is_none()); - assert_eq!(h.state().dialog, Some(Dialog::Print), "selecting PDF must not submit the job"); -} - -/// Scrolling and wrapped names must leave the pinned footer physically clickable. -#[test] -fn printer_picker_scrolls_long_names_without_losing_the_search_or_pdf_choice() { - let (mut h, last) = harness_with_printers(); - let size = egui::vec2(1024.0, 768.0); - h.set_size(size); - h.run_steps(4); - let initial = h.state().print_draft.printer.clone(); - h.get_by_value(initial.as_deref().unwrap()).click(); - h.run_steps(3); - let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); - let pdf = h.get_by_label("Save as PDF").rect(); - assert!(pdf.top() - search.bottom() > 200.0, "show more than a few device rows"); - h.get_by_label(&last).scroll_to_me(); - h.run_steps(5); - let row = h.get_by_label(&last).rect(); - assert!(row.left() >= 0.0 && row.right() <= size.x, "long names wrap within the viewport: {row:?}"); - let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); - let pdf = h.get_by_label("Save as PDF").rect(); - assert!(search.top() >= 0.0 && pdf.bottom() <= size.y, "search and PDF stay on screen"); - h.get_by_label(&last).click(); - h.run_steps(3); - assert_eq!(h.state().print_draft.printer.as_deref(), Some(last.as_str())); - h.get_by_value(&last).click(); - h.run_steps(3); - // Reopening must scroll to the selection itself; manual scrolling would mask a regression. - let search = h.get_by_role_and_label(Role::TextInput, "Search printers").rect(); - let row = h.get_by_label(&last).rect(); - let pdf = h.get_by_label("Save as PDF").rect(); - assert!( - row.top() >= search.bottom() && row.bottom() <= pdf.top(), - "the selected printer is visible on reopening: {row:?}, search {search:?}, PDF {pdf:?}" - ); - h.get_by_label("Save as PDF").click(); - h.run_steps(3); - assert_eq!(h.state().print_draft.printer, None, "the PDF row must be clickable with the full fleet shown"); -} - -/// The page-range field is labelled by the Pages radio button rather than floating unnamed. -#[test] -fn the_page_range_field_is_named_for_screen_readers() { - let mut h = harness(); - assert!(h.state_mut().execute("print.dialog")); - h.run_steps(3); - h.get_by_role_and_label(Role::TextInput, "Pages"); ->>>>>>> upstream/main } #[test] diff --git a/crates/ui-egui/tests/perf.rs b/crates/ui-egui/tests/perf.rs index d12b0e77fe..acdc4926d6 100644 --- a/crates/ui-egui/tests/perf.rs +++ b/crates/ui-egui/tests/perf.rs @@ -1,165 +1,13 @@ -<<<<<<< HEAD //! Work counts on a 500-page document (parity view.large-document-performance): scrolling and wheel frames build only //! the pages and rows in view, never the whole document. Each assertion is a relation between counts of the same //! script on a small and a large document, from the component runs the framework counts, so a slow or busy machine //! cannot fail it and a regression cannot hide behind a fast one. Rendering runs on worker threads and is not counted. -======= -//! The frame-time budget applies to a 500-page document (parity view.large-document-performance). -//! The budget scales with the measured duration of a fixed integer workload on slow machines. -//! Rendering runs on worker threads and is not part of the measurement. ->>>>>>> upstream/main use craft::pages::ui::view::GoTo; use craft::ui::testing::last_pass_runs; use egui_kittest::Harness; use pdfcraft_ui_egui::PdfCraftApp; -<<<<<<< HEAD -======= -/// The one-minute load average, where the OS reports it (macOS `vm.loadavg`, Linux -/// `/proc/loadavg`). -fn load_average() -> Option { - if let Ok(s) = std::fs::read_to_string("/proc/loadavg") { - return s.split_whitespace().next()?.parse().ok(); - } - let out = std::process::Command::new("sysctl").args(["-n", "vm.loadavg"]).output().ok()?; - String::from_utf8_lossy(&out.stdout).trim_matches(|c: char| c == '{' || c == '}' || c.is_whitespace()).split_whitespace().next()?.parse().ok() -} - -/// Frame budgets only mean something on a machine that isn't overcommitted: with the load -/// average above twice the core count (other builds running), skip and say so. -fn overloaded() -> bool { - let cores = std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get) as f64; - match load_average() { - Some(l) if l > 2.0 * cores => { - eprintln!("PERF skipped: load average {l:.0} on {cores} cores; frame budgets need a quiet machine"); - true - } - _ => false, - } -} - -/// The budget tests take turns: each starts render workers, and measuring one while another -/// runs would charge it for the other's work on a small CI machine. -static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -/// Base budget for debug builds. Calibration can increase it by at most three times. -const BUDGET: std::time::Duration = std::time::Duration::from_millis(40); -const CALIBRATION_REFERENCE: std::time::Duration = std::time::Duration::from_millis(17); - -fn budget_scale(calibration: std::time::Duration) -> f64 { - (calibration.as_secs_f64() / CALIBRATION_REFERENCE.as_secs_f64()).clamp(1.0, 3.0) -} - -#[test] -fn calibration_scales_slow_machines_without_exceeding_the_cap() { - assert_eq!(budget_scale(std::time::Duration::from_millis(8)), 1.0); - assert_eq!(budget_scale(std::time::Duration::from_millis(17)), 1.0); - assert_eq!(budget_scale(std::time::Duration::from_micros(42_500)), 2.5); - assert_eq!(budget_scale(std::time::Duration::from_millis(64)), 3.0); -} - -/// Measure 18 million integer updates, taking the fastest of three trials. -fn calibration_average() -> std::time::Duration { - let mut best = std::time::Duration::MAX; - for _ in 0..3 { - let mut value = std::hint::black_box(0x9e3779b97f4a7c15_u64); - let start = std::time::Instant::now(); - for _ in 0..18_000_000 { - value = value.wrapping_mul(0xd1342543de82ef95).rotate_left(17).wrapping_add(0x94d049bb133111eb); - } - std::hint::black_box(value); - best = best.min(start.elapsed()); - } - best -} - -/// A round's calibration: the faster of the runs before and after its frames. -fn round_calibration(before: std::time::Duration, after: std::time::Duration) -> std::time::Duration { - before.min(after) -} - -#[test] -fn contention_during_one_calibration_does_not_raise_the_budget() { - let quiet = std::time::Duration::from_millis(17); - let contended = std::time::Duration::from_millis(60); - assert_eq!(budget_scale(round_calibration(contended, quiet)), 1.0); - assert_eq!(budget_scale(round_calibration(quiet, contended)), 1.0); - assert_eq!(budget_scale(round_calibration(contended, contended)), 3.0); -} - -/// Run `step` for `frames` frames per round, with the integer workload as calibration. -fn best_average(label: &str, frames: usize, mut step: impl FnMut(usize)) -> (std::time::Duration, std::time::Duration) { - calibrated_rounds(label, calibration_average, || { - let start = std::time::Instant::now(); - let mut worst = std::time::Duration::ZERO; - for f in 0..frames { - let t = std::time::Instant::now(); - step(f); - worst = worst.max(t.elapsed()); - } - (start.elapsed() / frames as u32, worst) - }) -} - -/// Run `calibrate` just before and just after each round of frames, and set that round's budget from -/// the faster of the two. `frames` returns the round's average and worst frame. The lowest -/// average-to-budget ratio determines the result. Later rounds run only when the measured average -/// exceeds that round's calibrated budget. -fn calibrated_rounds( - label: &str, - mut calibrate: impl FnMut() -> std::time::Duration, - mut frames: impl FnMut() -> (std::time::Duration, std::time::Duration), -) -> (std::time::Duration, std::time::Duration) { - let mut best = std::time::Duration::MAX; - let mut best_budget = BUDGET; - let mut best_ratio = f64::INFINITY; - for round in 1..=3 { - let before = calibrate(); - let (avg, worst) = frames(); - let after = calibrate(); - let calibration = round_calibration(before, after); - let scale = budget_scale(calibration); - let budget = BUDGET.mul_f64(scale); - eprintln!( - "PERF {label} round {round}: calibration {before:?} before, {after:?} after, factor {scale:.2}, budget {budget:?}, avg frame {avg:?}, worst {worst:?}" - ); - let ratio = avg.as_secs_f64() / budget.as_secs_f64(); - if ratio < best_ratio { - best = avg; - best_budget = budget; - best_ratio = ratio; - } - if avg < budget { - break; - } - } - (best, best_budget) -} - -#[test] -fn the_returned_budget_is_the_selected_rounds_faster_calibration() { - let ms = std::time::Duration::from_millis; - let run = |calibrations: &[u64], averages: &[u64]| { - let mut calibrations = calibrations.iter().map(|&c| ms(c)); - let mut averages = averages.iter().map(|&a| ms(a)); - let result = calibrated_rounds( - "fixed", - || calibrations.next().expect("a calibration for each run"), - || (averages.next().expect("an average for each round"), ms(0)), - ); - assert!(calibrations.next().is_none() && averages.next().is_none(), "every planned round ran"); - result - }; - // Round 2 has the lowest ratio; contention after its frames, or before round 3's, leaves both at 40 ms. - assert_eq!(run(&[60, 60, 17, 60, 60, 17], &[130, 41, 50]), (ms(41), ms(40))); - // Every round contended: the selected round keeps its own raised budget. - assert_eq!(run(&[60, 60, 60, 60, 60, 60], &[130, 125, 140]), (ms(125), ms(120))); - // A round within its budget ends the run. - assert_eq!(run(&[60, 17], &[30]), (ms(30), ms(40))); -} - ->>>>>>> upstream/main /// `n` text pages with a few comments each, so panels and overlays have work to do. fn big(n: usize) -> Vec { let mut objs: Vec = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()]; @@ -282,23 +130,16 @@ fn a_folded_page_builds_no_comment_cards_and_an_open_one_builds_only_the_rows_in } assert_eq!(state.views[0].session.comments.panel.collapsed_pages, [0]); } -<<<<<<< HEAD let (folded, _) = most_work(&mut h, Some("CommentRow"), 6, |_, _| {}); assert_eq!(folded, 1, "a folded page builds only its heading row, no cards"); h.state_mut().views[0].session.comments.panel.collapsed_pages.clear(); let (open, _) = most_work(&mut h, Some("CommentRow"), 6, |_, _| {}); assert!(open > 0, "the open page builds the cards in view"); assert!(open < ROOTS, "{open} cards for {ROOTS} roots: only the rows in view are built"); -======= - // Folding removes card layout cost, so this measures filtering and thread lookup work. - let (avg, budget) = best_average("collapsed named comments", 30, |_| h.step()); - assert!(avg < budget, "collapsed comments: average frame {avg:?}, budget {budget:?}"); ->>>>>>> upstream/main } /// Jumping through a long document costs work for the pages in view only: the work at 500 pages is no more than at 50. #[test] -<<<<<<< HEAD fn jumping_through_pages_builds_only_the_pages_in_view() { let work = |n: usize| { let mut h = harness(big(n), &[]); @@ -308,34 +149,10 @@ fn jumping_through_pages_builds_only_the_pages_in_view() { assert!(small.0 > 0, "the frames build something"); assert!(large.0 <= small.0, "component runs in one frame: {} at 500 pages, {} at 50", large.0, small.0); assert!(large.1 <= small.1, "passes in one frame: {} at 500 pages, {} at 50", large.1, small.1); -======= -fn scrolling_a_500_page_document_stays_within_the_frame_budget() { - if overloaded() { - return; - } - let _turn = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let bytes = big(500); - let t0 = std::time::Instant::now(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("big.pdf", None, bytes).expect("opens"); - app - }); - h.run_steps(4); - eprintln!("PERF open {:?}", t0.elapsed()); - // Scroll through the document: 200 frames, jumping ~2 pages per frame. - let (avg, budget) = best_average("scroll", 200, |f| { - h.state_mut().views[0].goto = Some(((f * 5) / 2 % 500, 0.3)); - h.step(); - }); - assert!(avg < budget, "average frame {avg:?}, budget {budget:?}"); ->>>>>>> upstream/main } /// Wheel frames and the idle frames between them do not rebuild the pages of the whole document. #[test] -<<<<<<< HEAD fn wheel_frames_build_only_the_pages_in_view() { let work = |n: usize| { let mut h = harness(big(n), &[("left", "closed"), ("panel", "none"), ("layout", "continuous"), ("zoom", "200"), ("animation_effects", "on")]); @@ -377,65 +194,6 @@ fn panels_build_only_the_rows_in_view() { assert!(small > 0, "{panel}: the {row} rows are built"); } assert!(large <= small, "{panel}: {large} {row} runs in one frame at 500 pages, {small} at 50"); -======= -fn regular_wheel_input_on_500_pages_stays_within_the_frame_budget() { - if overloaded() { - return; - } - let _turn = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let bytes = big(500); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("wheel-budget.pdf", None, bytes).expect("opens"); - for (key, value) in [("left", "closed"), ("panel", "none"), ("layout", "continuous"), ("zoom", "200"), ("animation_effects", "on")] { - app.set_option(key, value).unwrap(); - } - app - }); - h.run_steps(8); - h.hover_at(h.state().views[0].viewport_rect().center()); - h.run_steps(2); - let start = h.state().views[0].current; - let (average, budget) = best_average("wheel input", 200, |frame| { - if frame % 3 == 0 { - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Line, - delta: egui::vec2(0.0, -1.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - } - h.step(); - }); - assert!(h.state().views[0].current > start, "wheel events must actually move through the document"); - assert!(average < budget, "wheel input: average frame {average:?}, budget {budget:?}"); -} - -#[test] -fn panels_with_hundreds_of_items_stay_within_the_frame_budget() { - if overloaded() { - return; - } - let _turn = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let bytes = big(500); - for panel in ["comments", "pages", "fields"] { - let b = bytes.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("big.pdf", None, b).expect("opens"); - app.set_option("panel", panel).unwrap(); - app - }); - h.run_steps(4); - let (avg, budget) = best_average(panel, 100, |f| { - h.state_mut().views[0].goto = Some(((f * 5) % 500, 0.3)); - h.step(); - }); - assert!(avg < budget, "{panel}: average frame {avg:?}, budget {budget:?}"); ->>>>>>> upstream/main } }