From 4ffbdf3ac588f8822b01fd953ca061a04dec8e01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-workflows-w7: net change of 2 commits - pdf-workflows-w7: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) - pdf-workflows-w7: review fixes (review-1) --- crates/ui-egui/src/workflows/combine_grid.rs | 807 ++++----- .../src/workflows/combine_grid/card.rs | 668 +++---- .../src/workflows/combine_grid/source.rs | 265 +++ .../src/workflows/combine_grid/tests.rs | 341 +--- .../src/workflows/combine_grid/thumbs.rs | 391 ---- crates/ui-egui/tests/it/combine_grid.rs | 1614 +++-------------- 6 files changed, 1180 insertions(+), 2906 deletions(-) create mode 100644 crates/ui-egui/src/workflows/combine_grid/source.rs delete mode 100644 crates/ui-egui/src/workflows/combine_grid/thumbs.rs diff --git a/crates/ui-egui/src/workflows/combine_grid.rs b/crates/ui-egui/src/workflows/combine_grid.rs index 47851b443b..7379950c5e 100644 --- a/crates/ui-egui/src/workflows/combine_grid.rs +++ b/crates/ui-egui/src/workflows/combine_grid.rs @@ -1,521 +1,345 @@ -//! Combine files as a grid: a thumbnail of the first page each file contributes, drawn as a -//! stack when it contributes more than one, with its name below. Cards are selected and moved -//! with the same [`RowAction`]s as the table's rows, so both views share the selection, the -//! order and the undo history. +//! Combine files as a grid: a thumbnail of the first page each file contributes, drawn as a stack when +//! it contributes more than one, with its name below. The grid is the framework's [`TileGrid`] over +//! [`CombineKey`]s and binds the same selection as the table, so both views share the selection, the +//! order and the undo history; this module maps the grid's events onto the [`RowAction`]s of the list. //! -//! Thumbnails render off the UI thread through [`RenderPool`] (its panic guard, size caps and -//! watchdog), one small pool per thumbnail. Only missing ones are asked for, those in view first. -//! At most [`MAX_THREADS`] render threads exist at once, counted as threads, not pools: the pools -//! start no watchdog replacements ([`RenderPool::without_replacements`]), and a pool's threads -//! count until they have actually exited ([`RenderPool::retire`]), so a render the watchdog gave -//! up on, or one whose file left the list, holds its place until its thread is gone. A thread -//! stuck for good in one step that can't be interrupted keeps its place for good: threads can't -//! be killed safely. On the web the pool renders on the UI thread inside `try_recv`, with no -//! watchdog: there, at most one thumbnail per frame, only one waits at a time (its pool holds the -//! parsed document), and a very slow page still stalls that frame (as in the document view). +//! Pictures are [`Thumbnails`](craft::ui::primitives::textures::Thumbnails) over `source::CombineThumbs`: +//! the framework keeps the textures, the lanes and the budgets, and the source renders a page through +//! [`pdfcraft_render::RenderPool`]. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; -use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, TextureHandle, Vec2, pos2, vec2}; -use pdfcraft_render::{RenderConfig, RenderPool, RenderRequest, Retiring}; +use craft::behavior::{EditEvent, ReorderKeys, Selection, keyed}; +use craft::ui::contract::{Bind, CollectionEvent, ReorderMove, ReorderRule, ShowCollection as _, ShowContainer as _, SpaceAction}; +use craft::ui::primitives::textures::{TextureState, ThumbRequest}; +use craft::ui::tile_grid::{GridEvent, GridZoom, Tile, TileActionPlace, TileGrid, TileGroup, TilePartEvent, TileZoom}; +use pdfcraft_render::RenderConfig; use crate::PdfCraftApp; -use crate::combine_ui::{CombineFile, ERROR, Lock, RowAction, WARNING}; -use crate::icons; -use crate::theme::{self, Tokens}; +use crate::combine_ui::{CombineFile, CombineKey, CombineTab, RowAction}; mod card; -mod thumbs; +mod source; -use card::Card; +use card::{Act, Pictures}; pub(crate) use card::preview; -pub use thumbs::ThumbState; -pub(crate) use thumbs::Thumbs; -#[cfg(test)] -use thumbs::{Entry, Job, Look, MAX_SIDE, MAX_THREADS, Want}; -use thumbs::{Key, PREVIEW, Slot}; -/// The box a page is fitted in at 100%, and the room the card adds around it (for the hover bar -/// and the stack above it, the name and a note below), which doesn't scale. -const PAPER: Vec2 = vec2(132.0, 172.0); -const AROUND: Vec2 = vec2(52.0, 90.0); -/// From the top of a card to its page box: room for the hover bar, which sits mostly above the -/// page. -const ABOVE: f32 = 32.0; -/// The hover bar's height; a quarter of it overlaps the page. -const BAR_H: f32 = 34.0; -/// The grid's zoom range, and the sizes its buttons and keys step through (the slider, the wheel -/// and a pinch go anywhere between). -pub(crate) const ZOOM_RANGE: std::ops::RangeInclusive = 0.6..=5.0; -const ZOOM_STEPS: [f32; 11] = [0.6, 0.8, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0]; +use source::CombineThumbs; +pub(crate) use source::OpenDocuments; -/// The next size up (or down) from `zoom`; the end of the range stays put. -pub(crate) fn zoom_step(zoom: f32, larger: bool) -> f32 { - let next = - if larger { ZOOM_STEPS.iter().copied().find(|s| *s > zoom + 0.001) } else { ZOOM_STEPS.iter().rev().copied().find(|s| *s < zoom - 0.001) }; - next.unwrap_or(if larger { *ZOOM_RANGE.end() } else { *ZOOM_RANGE.start() }) -} -/// Space above the first row of cards. -const TOP: f32 = 12.0; -/// The most pages one file can be spread out into (each is a card, laid out every frame). +/// The most pages one file can be spread out into (each is a tile, laid out every frame). pub(crate) const MAX_EXPAND: usize = 2000; -/// The shape drawn for a page whose size is unknown (US Letter); nothing is rendered for it. -const FALLBACK_PAGE: (f32, f32) = (612.0, 792.0); -/// Icons drawn on the (always white) paper, in either theme: the light theme's muted text, which -/// keeps its contrast on white where the dark theme's doesn't. -const ON_PAPER: Color32 = Color32::from_rgb(0x5E, 0x5E, 0x66); -/// A card being dragged: which file, and the list as it was (see [`RowAction::DropAt`]). -#[derive(Clone, Copy)] -struct GridDrag { - file: u64, - revision: u64, - /// A page card's page (entry id, place among its pages): that page moves, not its file. - page: Option<(u64, usize)>, -} -/// `name` shortened in the middle to what `fits`, keeping its extension ("Pilot Boat Ad….pdf"). -pub(crate) fn fit_name(name: &str, fits: impl Fn(&str) -> bool) -> String { - if fits(name) { - return name.to_owned(); - } - // A short extension after the last dot (a dot is one byte, so these are char boundaries). - let split = name.rfind('.').filter(|p| *p > 0 && name.len() - p <= 6); - let (stem, ext) = match split { - Some(p) => (name.get(..p).unwrap_or(name), name.get(p..).unwrap_or("")), - None => (name, ""), - }; - let chars: Vec = stem.chars().collect(); - let with = |n: usize| format!("{}…{ext}", chars.iter().take(n).collect::()); - // The longest start of the stem that fits, found by halving. - let (mut lo, mut hi) = (0usize, chars.len()); - while lo < hi { - let mid = lo + (hi - lo).div_ceil(2); - if fits(&with(mid)) { lo = mid } else { hi = mid - 1 } - } - with(lo) -} - -/// The box a page is fitted in at `zoom` (clamped to [`ZOOM_RANGE`]). -fn paper_box(zoom: f32) -> Vec2 { - let zoom = if zoom.is_finite() { zoom.clamp(*ZOOM_RANGE.start(), *ZOOM_RANGE.end()) } else { 1.0 }; - PAPER * zoom -} - -/// The size to draw a page of `w` × `h` points in `fit`; `None` for a size that isn't one. -fn paper_size(w: f32, h: f32, fit: Vec2) -> Option { - if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { - return None; - } - let s = (fit.x / w).min(fit.y / h); - s.is_finite().then(|| vec2(w * s, h * s)) -} - -/// How many cards of `cell` fit across `width` (at least one). -fn columns_in(width: f32, cell: Vec2) -> usize { - ((width - 16.0) / cell.x).floor().max(1.0) as usize -} - -/// What one place in the grid shows: a file's card, or (the file expanded) one of the pages it -/// adds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Cell { - /// The file, by its place in the list. - pub(crate) file: usize, - /// For a page: its place among the pages the file adds, the page (0-based, in the file) and - /// how many it adds. - pub(crate) page: Option<(usize, usize, usize)>, -} - -/// The pages an expanded file shows: in its range's order, and sorted (to look one up), for the -/// range and page count they were worked out for. +/// The pages an expanded file shows, in its range's order. #[derive(Clone, Debug)] pub(crate) struct PageList { - of: (String, usize), pub(crate) order: Arc<[usize]>, - sorted: Arc<[usize]>, } -/// The pages an expanded file shows, worked out again only when its range or page count -/// changes; `None` when it can't be shown as its pages (locked, unreadable, a bad range, no page, -/// or more than [`MAX_EXPAND`]). -pub(crate) fn pages_shown(cache: &mut HashMap, f: &CombineFile) -> Option { +/// The pages an expanded file shows; `None` when it can't be shown as its pages (locked, unreadable, a +/// bad range, no page, or more than [`MAX_EXPAND`]). One page shows as a page tile too: a file split +/// into parts may leave one page in a part. +pub(crate) fn pages_shown(f: &CombineFile) -> Option { if f.lock.is_some() || f.problem.is_some() { return None; } - let list = match cache.get(&f.id) { - Some(list) if list.of.0 == f.range && list.of.1 == f.pages => list.clone(), - _ => { - let order = f.pages_taken().ok()?; - let mut sorted = order.clone(); - sorted.sort_unstable(); - let list = PageList { of: (f.range.clone(), f.pages), order: Arc::from(order), sorted: Arc::from(sorted) }; - cache.insert(f.id, list.clone()); - list - } - }; - // (One page shows as a page card too: a file split into parts may leave one page in a part.) - (!list.order.is_empty() && list.order.len() <= MAX_EXPAND).then_some(list) + // A whole file is listed only when it is short enough to be spread out. + if f.range.trim().is_empty() && f.pages > MAX_EXPAND { + return None; + } + let order = f.pages_taken().ok()?; + (!order.is_empty() && order.len() <= MAX_EXPAND).then(|| PageList { order: Arc::from(order) }) } -/// The grid's places, in order: each file's card, or its pages when it is expanded. -fn layout(app: &mut PdfCraftApp) -> Vec { - let tab = &mut app.combine_tab; - let mut cells = Vec::with_capacity(app.combine_draft.len()); - for (file, f) in app.combine_draft.iter().enumerate() { - match tab.expanded.contains(&f.id).then(|| pages_shown(&mut tab.page_lists, f)).flatten() { +/// What the grid shows, in display order. +struct Rows { + /// The tiles: a collapsed file's, or each page of an expanded file. + tiles: Vec, + /// Every row of the grid: the tiles, with a header row before each group. An expanded file shows no + /// tile of its own, so its header is keyed by the file. + rows: Vec, + /// One group per expanded file, over its pages. + groups: Vec>, +} + +/// The rows of `draft`, the files in `lists` shown as their pages. +fn rows_of(draft: &[CombineFile], lists: &HashMap) -> Rows { + let mut out = Rows { tiles: Vec::with_capacity(draft.len()), rows: Vec::with_capacity(draft.len()), groups: Vec::new() }; + for f in draft { + match lists.get(&f.id) { Some(list) => { - let of = list.order.len(); - cells.extend(list.order.iter().enumerate().map(|(nth, &page)| Cell { file, page: Some((nth, page, of)) })); + let detail = crate::i18n::fmt(tl!("Pages: {k} of {n}"), &[("k", &list.order.len().to_string()), ("n", &f.pages.to_string())]); + out.groups.push(TileGroup::new(CombineKey::File(f.id), out.tiles.len(), list.order.len(), f.name.clone()).detail(detail)); + out.rows.push(CombineKey::File(f.id)); + for nth in 0..list.order.len() { + out.tiles.push(CombineKey::Page(f.id, nth)); + out.rows.push(CombineKey::Page(f.id, nth)); + } } - None => cells.push(Cell { file, page: None }), - } - } - cells -} - -/// The file gap (0 = before the first file, n = after the last) a drop before place `at` means: a -/// drop inside an expanded file's pages goes to the nearer end of that file. -fn file_gap(cells: &[Cell], at: usize, files: usize) -> usize { - match cells.get(at) { - None => files, - Some(Cell { file, page: Some((nth, _, of)) }) if *nth > 0 => { - if nth.saturating_mul(2) < *of { - *file - } else { - file.saturating_add(1) + None => { + out.tiles.push(CombineKey::File(f.id)); + out.rows.push(CombineKey::File(f.id)); } } - Some(c) => c.file, } + out } -/// The grid of files, in the card that holds the list. Returns what the user did. -pub(crate) fn grid( - app: &mut PdfCraftApp, - ui: &mut egui::Ui, - t: &Tokens, - checks: &[Result], - selected: &[bool], - twice: &[bool], -) -> Option { - let ctx = ui.ctx().clone(); - let ppp = ctx.pixels_per_point(); - let mut action = None; - let revision = app.combine_tab.revision; - let drag = egui::DragAndDrop::payload::(&ctx).map(|d| *d); - // The card dragged may scroll out of the rows drawn, so its release is watched here. - let released = drag.is_some() && ctx.input(|i| i.pointer.any_released()); - let n = app.combine_draft.len(); - let places = layout(app); - // Each file's first place (for the keys and to scroll to it). - let mut first_place = vec![0usize; n]; - for (at, c) in places.iter().enumerate().rev() { - if let Some(slot) = first_place.get_mut(c.file) { - *slot = at; - } - } - app.combine_tab.grid_places = places.iter().map(|c| c.file).collect(); - // Pages counted over the list (an entry that can't be split counting as one, see - // `moved_pages`): where each place's pages start, for a page dropped before it. - let counts: Vec = app - .combine_draft - .iter_mut() - .map(|f| if f.lock.is_none() && f.problem.is_none() { f.selection().ok().filter(|k| *k > 0).unwrap_or(1) } else { 1 }) - .collect(); - let mut page_at = Vec::with_capacity(places.len()); - let mut total_pages = 0usize; - for c in &places { - page_at.push(total_pages); - total_pages = total_pages.saturating_add(if c.page.is_some() { 1 } else { counts.get(c.file).copied().unwrap_or(1) }); - } - let picked_pages = app.combine_tab.selected_pages.clone(); - let reveal = app.combine_tab.reveal.take(); - let fit = paper_box(app.combine_zoom); - let cell = fit + AROUND; - let mut cells: Vec<(usize, Rect)> = Vec::new(); - let viewport = ui.available_rect_before_wrap(); - let pointer = ctx.pointer_latest_pos(); - let files = &mut app.combine_draft; - let thumbs = &mut app.combine_thumbs; - let columns = &mut app.combine_tab.grid_columns; +/// Where a grid reorder lands, in the list's own indexes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Landing { + /// Files before entry `gap` of the list (0 = before the first, the list's length = after the last). + Files { gap: usize }, + /// Pages before item `gap` of every page of the list, collapsed files' pages included. + Pages { gap: usize }, +} - // Over the grid itself, not over a menu or dialog above it. - let over_grid = ui.rect_contains_pointer(viewport); - let mut width = viewport.width(); - let mut focused_card = None; - // A zoom in the previous frame asks for a new scroll position. 0.37 keeps `State`'s offset - // private, so the request is applied through the builder and consumed here. - let pending_offset = ctx.data_mut(|d| d.remove_temp::(pending_offset_id())); - let mut grid = egui::ScrollArea::vertical().id_salt("combine-grid").auto_shrink([false, false]); - if let Some(offset) = pending_offset { - grid = grid.vertical_scroll_offset(offset.y); - } - grid.show_viewport(ui, |ui, clip| { - // Dragging near the top or bottom edge scrolls. - if drag.is_some() - && let Some(p) = pointer - && viewport.contains(p) - { - let edge = 40.0; - let delta = if p.y < viewport.top() + edge { - 12.0 - } else if p.y > viewport.bottom() - edge { - -12.0 - } else { - 0.0 +/// Where `mv` lands. `ReorderMove::to` counts the grid's `rows` that remain once the moved keys are taken +/// out, header rows included, so the target is the row now at `to`. `ids` are the entries of the list and +/// `items` how many page items each contributes. +fn landing(rows: &[CombineKey], mv: &ReorderMove, ids: &[u64], items: &[usize]) -> Landing { + let target = rows.iter().filter(|k| !mv.keys.contains(k)).nth(mv.to); + let entry = |id: u64| ids.iter().position(|i| *i == id); + let total = || items.iter().fold(0usize, |sum, n| sum.saturating_add(*n)); + // The first item of entry `at`. + let start = |at: usize| items.iter().take(at).fold(0usize, |sum, n| sum.saturating_add(*n)); + match mv.key { + CombineKey::File(_) => { + let gap = match target { + Some(CombineKey::File(id) | CombineKey::Page(id, _)) => entry(*id), + None => None, }; - if delta != 0.0 { - ui.scroll_with_delta(vec2(0.0, delta)); - ctx.request_repaint(); - } + Landing::Files { gap: gap.unwrap_or(ids.len()) } } - ui.add_space(TOP); - width = ui.available_width(); - let cols = columns_in(width, cell); - *columns = cols; - let rows = places.len().div_ceil(cols); - let left = ((width - cols as f32 * cell.x) / 2.0).max(0.0); - let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * cell.y), Sense::hover()); - let cell_rect = |i: usize| { - let (row, col) = (i / cols, i % cols); - Rect::from_min_size(pos2(area.left() + left + col as f32 * cell.x, area.top() + row as f32 * cell.y), cell) - }; - if let Some(i) = reveal.and_then(|id| files.iter().position(|f| f.id == id)) { - ui.scroll_to_rect(cell_rect(first_place.get(i).copied().unwrap_or(0)), None); - } - for row in crate::canvas::thumbnail_rows(clip.top() - TOP, clip.bottom() - TOP, cell.y, rows) { - let first = row.saturating_mul(cols); - let in_row = places.get(first..first.saturating_add(cols).min(places.len())).unwrap_or_default(); - // An expanded file's pages on this row share a tinted band, so they read as one file. - let mut run = 0; - while run < in_row.len() { - let Some(start) = in_row.get(run).copied() else { break }; - let mut end = run; - while in_row.get(end.saturating_add(1)).is_some_and(|c| c.file == start.file && c.page.is_some()) { - end = end.saturating_add(1); - } - if start.page.is_some() { - let band = cell_rect(first.saturating_add(run)).union(cell_rect(first.saturating_add(end))).shrink2(vec2(2.0, 4.0)); - ui.painter().rect_filled(band, CornerRadius::same(10), t.accent_soft.gamma_multiply(0.45)); - } - run = end.saturating_add(1); - } - for (col, place) in in_row.iter().enumerate() { - let i = first.saturating_add(col); - let Some(f) = files.get_mut(place.file) else { break }; - let c = cell_rect(i); - cells.push((i, c)); - let card = Card { - i: place.file, - page: place.page, - rect: c, - check: checks.get(place.file).cloned().unwrap_or(Ok(f.pages)), - selected: selected.get(place.file).copied().unwrap_or(false) - || place.page.is_some_and(|(nth, ..)| picked_pages.contains(&(f.id, nth))), - twice: twice.get(place.file).copied().unwrap_or(false), - revision, - ppp, - fit, - }; - let card_id = card.id(ui, f); - if let Some(a) = card.show(ui, t, f, thumbs) { - action = Some(a); - } - if ui.memory(|m| m.has_focus(card_id)) { - focused_card = Some((card_id, f.id, place.page.map_or(0, |p| p.0))); - } - } - } - // While a page card is dragged: the page gap it would go to (any place, between any two - // pages), drawn at the nearest card's edge, and how many pages go. - if let Some(d) = drag - && let Some(page) = d.page - && let Some(p) = pointer - { - let at = crate::canvas::drop_gap(&cells, p); - let nearest = cells.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(p).total_cmp(&b.distance_sq_to_pos(p))); - if let Some((_, r)) = nearest { - let x = if p.x < r.center().x { r.left() + 2.0 } else { r.right() - 2.0 }; - ui.painter().line_segment([pos2(x, r.top() + 10.0), pos2(x, r.bottom() - 30.0)], Stroke::new(3.0, t.accent)); - } - let moving = if picked_pages.contains(&page) { picked_pages.len() } else { 1 }; - let label = if moving == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &moving.to_string())]) }; - ui.painter().text(p + vec2(14.0, 14.0), Align2::LEFT_TOP, label, theme::medium(12.0), t.accent_text); - if released - && viewport.contains(p) - && let Some(at) = at - { - let gap = page_at.get(at).copied().unwrap_or(total_pages); - action = Some(RowAction::MovePages { page, revision: d.revision, gap }); - } - } else if let Some(d) = drag - && let Some(p) = pointer - { - // A file's card: the file gap it would go to, drawn as a bar, and how many files go. - let gap = crate::canvas::drop_gap(&cells, p).map(|at| file_gap(&places, at, n)); - // Drawn at the end of the file before the gap or the start of the one after (an - // expanded file's pages are never split), whichever is nearer the pointer. - if let Some(gap) = gap { - let before = gap - .checked_sub(1) - .and_then(|f| first_place.get(f.saturating_add(1)).map(|next| next.saturating_sub(1)).or(places.len().checked_sub(1))); - let after = first_place.get(gap).copied(); - let ends = [before.map(|at| cell_rect(at).right() - 2.0).zip(before), after.map(|at| cell_rect(at).left() + 2.0).zip(after)]; - let nearest = ends.into_iter().flatten().min_by(|(xa, a), (xb, b)| { - let da = pos2(*xa, cell_rect(*a).center().y).distance_sq(p); - let db = pos2(*xb, cell_rect(*b).center().y).distance_sq(p); - da.total_cmp(&db) - }); - if let Some((x, at)) = nearest { - let r = cell_rect(at); - ui.painter().line_segment([pos2(x, r.top() + 10.0), pos2(x, r.bottom() - 30.0)], Stroke::new(3.0, t.accent)); - } - } - let moving = files - .iter() - .position(|f| f.id == d.file) - .map_or(1, |i| if selected.get(i).copied().unwrap_or(false) { selected.iter().filter(|s| **s).count() } else { 1 }); - let label = if moving == 1 { tl!("1 file").to_string() } else { crate::i18n::fmt(tl!("{n} files"), &[("n", &moving.to_string())]) }; - ui.painter().text(p + vec2(14.0, 14.0), Align2::LEFT_TOP, label, theme::medium(12.0), t.accent_text); - // Dropped in the grid: there. Anywhere else: nothing moves. - if released - && viewport.contains(p) - && let Some(gap) = gap - { - action = Some(RowAction::DropAt { file: d.file, revision: d.revision, gap }); - } - } - }); - - app.combine_tab.card_focus = focused_card.map(|(id, ..)| id); - app.combine_tab.card_focus_at = focused_card.map(|(_, file, nth)| (file, nth)); - - // Pinch, or Ctrl/⌘ with the wheel, over the grid zooms it. - let pinch = crate::motion::zoom_delta(&ctx); - if (pinch - 1.0).abs() > 0.001 && over_grid { - app.combine_tab.zoom_request = Some(app.combine_zoom * pinch); - } - // A zoom asked for this frame (toolbar, keys, pinch) applies now the grid has been laid out: - // the card under the pointer (or else the first in view) keeps its place on screen. Not while - // a card is dragged: the grid under it would change. - if let Some(zoom) = app.combine_tab.zoom_request.take() - && drag.is_none() - { - let before = app.combine_zoom; - app.set_combine_zoom(zoom); - if app.combine_zoom != before { - // The same card all through one gesture (a slider drag, a turn of the wheel): the - // first in view changes as the cards reflow, and following it would drift. A card is - // kept by its file and its place among the file's pages. - let now = ctx.input(|i| i.time); - let gesture = app.combine_tab.zoom_anchor.filter(|a| now - a.3 < 0.5).and_then(|(id, nth, above, _)| { - let file = app.combine_draft.iter().position(|f| f.id == id)?; - Some((first_place.get(file)?.saturating_add(nth).min(places.len().saturating_sub(1)), above)) - }); - // Cards just outside the view are drawn too (under the toolbar, say): the pointer - // counts only over the grid. - let under = pointer.filter(|_| over_grid).and_then(|p| cells.iter().find(|(_, r)| r.contains(p))); - let anchor = gesture - .or_else(|| under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top())).map(|(i, r)| (*i, r.top() - viewport.top()))); - app.combine_tab.zoom_anchor = anchor.and_then(|(i, above)| { - let place = places.get(i)?; - Some((app.combine_draft.get(place.file)?.id, place.page.map_or(0, |p| p.0), above, now)) - }); - if let Some((i, above)) = anchor { - // Where it will be: its row at the new size, as far below the top as it is now; - // within what can be scrolled to, so zooming out at the bottom shows no gap. - let cell = paper_box(app.combine_zoom) + AROUND; - let cols = columns_in(width, cell); - let content = TOP + places.len().div_ceil(cols) as f32 * cell.y; - let y = (TOP + (i / cols) as f32 * cell.y - above).min(content - viewport.height()).max(0.0); - // Applied by the next frame's scroll area, before anything is drawn there: no - // jump, and no scroll still animating (to a card revealed by the keys, say) can - // carry it elsewhere. The request is consumed once. - ctx.data_mut(|d| d.insert_temp(pending_offset_id(), vec2(0.0, y))); - } - ctx.request_repaint(); + CombineKey::Page(..) => { + let gap = match target { + Some(CombineKey::Page(id, nth)) => entry(*id).map(|at| start(at).saturating_add(*nth)), + // A tile or a header of a file: that entry's first item. + Some(CombineKey::File(id)) => entry(*id).map(start), + None => None, + }; + Landing::Pages { gap: gap.unwrap_or_else(total) } } } - - action } -/// The scroll position a zoom asked the next frame's grid to start at. -fn pending_offset_id() -> egui::Id { - egui::Id::unique("pdfcraft-combine-grid-offset") +/// What the grid reads of the list while its events are mapped. +struct View<'a> { + draft: &'a [CombineFile], + /// Each entry's place in the list, by id. + index: HashMap, + /// The pages of the files shown as their pages. + lists: &'a HashMap, + /// What each entry's range takes, in list order. + checks: &'a [Result], +} + +impl View<'_> { + fn file(&self, id: u64) -> Option<(usize, &CombineFile)> { + let at = *self.index.get(&id)?; + self.draft.get(at).map(|f| (at, f)) + } + + /// The actions the tile (or header) of `key` offers, in the order its band lists them. + fn acts(&self, key: &CombineKey) -> Vec { + match *key { + CombineKey::File(id) => { + let Some((at, f)) = self.file(id) else { return Vec::new() }; + if self.lists.contains_key(&id) { + return vec![Act::Collapse, Act::Remove]; + } + let check = self.checks.get(at).cloned().unwrap_or(Ok(f.pages)); + card::file_acts(f, &check) + } + CombineKey::Page(id, nth) => { + let Some((_, f)) = self.file(id) else { return Vec::new() }; + let Some(page) = self.lists.get(&id).and_then(|l| l.order.get(nth)) else { return Vec::new() }; + card::page_acts(f, *page) + } + } + } + + /// How many page items each entry of the list contributes: its pages, or one when it moves whole (a + /// locked file, a bad range). + fn items(&self) -> Vec { + self.draft + .iter() + .map(|f| { + let pages = (f.lock.is_none() && f.problem.is_none()).then(|| f.pages_taken().ok()).flatten().filter(|p| !p.is_empty()); + pages.map_or(1, |p| p.len()) + }) + .collect() + } +} + +/// The list action for `act` on the tile of `key`. +fn act_action(act: Act, key: CombineKey) -> RowAction { + match (act, key) { + (Act::Preview, CombineKey::File(id)) => RowAction::Preview(id), + (Act::Preview, CombineKey::Page(id, nth)) => RowAction::PreviewAt(id, nth), + (Act::Expand, CombineKey::File(id) | CombineKey::Page(id, _)) => RowAction::Expand(id, true), + (Act::Collapse, CombineKey::File(id) | CombineKey::Page(id, _)) => RowAction::Expand(id, false), + (Act::Remove, CombineKey::File(id)) => RowAction::RemoveFile(id), + (Act::Remove, CombineKey::Page(id, nth)) => RowAction::RemovePages(Some((id, nth))), + } +} + +/// What Delete removes: the selection when the keys are the selected tiles, else the one tile. +fn delete_action(selection: &Selection, keys: &[CombineKey]) -> Option { + let first = *keys.first()?; + let selected = keys.iter().all(|k| selection.items.contains(k)); + Some(match (first, selected) { + (CombineKey::File(_), true) => RowAction::Remove, + (CombineKey::Page(..), true) => RowAction::RemovePages(None), + (CombineKey::File(id), false) => RowAction::RemoveFile(id), + (CombineKey::Page(id, nth), false) => RowAction::RemovePages(Some((id, nth))), + }) +} + + +/// The grid of files, in the card that holds the list. `checks` is what each entry's range takes and +/// `twice` whether its file is in the list again, both in list order. Returns what the user did, in order. +// PLAN: the signature is `(app, ui, checks, twice) -> Vec`: the table's colours and selection +// flags are gone, and one pass can report several actions (owner of the caller: pdf-workflows-w6). +pub(crate) fn grid(app: &mut PdfCraftApp, ui: &mut egui::Ui, checks: &[Result], twice: &[bool]) -> Vec { + let ctx = ui.ctx().clone(); + let lists = app.combine_page_lists(); + let rows = rows_of(&app.combine_draft, &lists); + let source = CombineThumbs::new(&app.combine_draft, &lists, app.combine_tab.open_documents.clone()); + let thumbs = source::thumbnails(&ctx); + let pictures = Pictures { thumbs: &thumbs, source: &source }; + let view = View { draft: &app.combine_draft, index: app.combine_draft.iter().enumerate().map(|(at, f)| (f.id, at)).collect(), lists: &lists, checks }; + let tiles = keyed(&rows.tiles, |key: &CombineKey| *key); + + let shown = TileGrid::::new(tl!("Files").to_string()) + .card() + .detail_line() + .selection(Bind::bound(&mut app.combine_tab.selection)) + .zoom(GridZoom::Bound(Bind::bound(&mut app.combine_zoom), TileZoom::Ladder)) + .groups(&rows.groups) + .collapsible() + .reorder(ReorderRule::new().keys(ReorderKeys::AltArrows)) + .deletable(true) + .action_place(TileActionPlace::Band) + .space(SpaceAction::Preview) + .show_items(ui, &tiles, &mut |key, _| { + let tile = match *key { + CombineKey::File(id) => view.file(id).map(|(at, f)| { + let check = checks.get(at).cloned().unwrap_or(Ok(f.pages)); + card::file_tile(f, &check, twice.get(at).copied().unwrap_or(false), pictures) + }), + CombineKey::Page(id, nth) => view.file(id).and_then(|(_, f)| { + let page = *lists.get(&id)?.order.get(nth)?; + Some(card::page_tile(f, nth, page, pictures)) + }), + }; + tile.unwrap_or_else(|| Tile::new(String::new())) + }); + + let mut actions = Vec::new(); + let mut selection_changed = false; + for event in shown.response.events { + match event { + CollectionEvent::Selection(_) => selection_changed = true, + CollectionEvent::Reorder(EditEvent::Commit { after: mv, .. } | EditEvent::Set { after: mv, .. }) => { + let revision = app.combine_tab.revision; + let ids: Vec = app.combine_draft.iter().map(|f| f.id).collect(); + actions.extend(match (mv.key, landing(&rows.rows, &mv, &ids, &view.items())) { + (CombineKey::File(file), Landing::Files { gap }) => Some(RowAction::DropAt { file, revision, gap }), + (CombineKey::Page(id, nth), Landing::Pages { gap }) => Some(RowAction::MovePages { page: (id, nth), revision, gap }), + _ => None, + }); + } + CollectionEvent::Delete(keys) => actions.extend(delete_action(&app.combine_tab.selection, &keys)), + CollectionEvent::Preview(CombineKey::File(id)) => actions.push(RowAction::Preview(id)), + CollectionEvent::Preview(CombineKey::Page(id, nth)) => actions.push(RowAction::PreviewAt(id, nth)), + // PLAN: framework gap F-5: the tile's context menu (Preview, Expand/Collapse, Remove, Unlock…) needs a + // collection menu that carries the request's key; no key is kept between passes meanwhile. + CollectionEvent::Item(key, TilePartEvent::Action(at)) => { + actions.extend(view.acts(&key).get(at).map(|act| act_action(*act, key))); + } + _ => {} + } + } + for event in shown.events { + match event { + GridEvent::GroupOpen { group, open, .. } => { + if let Some(CombineKey::File(id)) = rows.groups.get(group).map(|g| g.key) { + actions.push(RowAction::Expand(id, open)); + } + } + _ => {} + } + } + // The pick that was just made decides which kind of tile stays selected. + if selection_changed { + app.combine_keep_one_kind(); + } + actions } impl PdfCraftApp { - /// The file shown large, the page on screen (0-based, in the file) and its render, while it - /// shows (tests and the control channel). - pub fn combine_preview(&self) -> Option<(String, usize, ThumbState)> { + /// The pages of each file shown as its pages in the grid, by entry id. + fn combine_page_lists(&self) -> HashMap { + let expanded = &self.combine_tab.expanded; + self.combine_draft.iter().filter(|f| expanded.contains(&f.id)).filter_map(|f| pages_shown(f).map(|list| (f.id, list))).collect() + } + + /// The thumbnail source for the list as it is now. + fn combine_thumb_source(&self) -> CombineThumbs { + CombineThumbs::new(&self.combine_draft, &self.combine_page_lists(), self.combine_tab.open_documents.clone()) + } + + /// What `key` shows now at the size `request` asks, read without starting a render. + fn combine_thumb_state(&self, ctx: &egui::Context, source: &CombineThumbs, key: CombineKey, request: &ThumbRequest) -> TextureState { + source.state_of(ctx, &key, request) + } + + /// The file shown large and the page on screen (0-based, in the file), while it shows (tests and the + /// control channel). + pub fn combine_preview(&self) -> Option<(String, usize)> { let p = self.combine_tab.preview.as_ref()?; let f = self.combine_draft.iter().find(|f| f.id == p.file)?; - Some((f.name.clone(), p.page?, self.combine_thumbs.state(PREVIEW))) + Some((f.name.clone(), p.page?)) } - /// Size the Combine grid's cards (1.0 = the usual); out-of-range values are clamped and - /// nonsense is ignored. - pub fn set_combine_zoom(&mut self, zoom: f32) { + /// Size the Combine grid's cards (1.0 = the usual); out-of-range values are clamped and nonsense is + /// ignored. + pub fn set_combine_zoom(&mut self, zoom: f64) { if zoom.is_finite() { - self.combine_zoom = zoom.clamp(*ZOOM_RANGE.start(), *ZOOM_RANGE.end()); + let range = TileZoom::Ladder.range(); + self.combine_zoom = zoom.clamp(*range.start(), *range.end()); } } - /// Every frame, whatever shows: take finished thumbnails, start those the grid asked for (only - /// while it is drawn), and let go of what no longer matches the list, so renders under way - /// finish and release their threads in the list view, on Home or in a document tab too. - pub(crate) fn combine_thumbs_frame(&mut self, ctx: &egui::Context) { - // What each thumbnail must match now (cards out of view included): each file's first page, - // and an expanded file's pages (looked up in its sorted list, never listed one by one). - // (By file: the parts a file is split into share its thumbnails.) - struct Shown { - source: usize, - auth: u64, - pages: Vec, - } - let mut shown: HashMap = HashMap::with_capacity(self.combine_draft.len()); - let tab = &mut self.combine_tab; - for f in self.combine_draft.iter_mut() { - let Ok(first) = f.first_page() else { continue }; - let sorted = tab.expanded.contains(&f.id).then(|| pages_shown(&mut tab.page_lists, f)).flatten().map(|l| l.sorted); - let entry = shown.entry(f.group).or_insert_with(|| Shown { source: Arc::as_ptr(&f.bytes) as usize, auth: f.auth, pages: Vec::new() }); - entry.pages.push(first); - entry.pages.extend(sorted.iter().flat_map(|s| s.iter().copied())); - } - for s in shown.values_mut() { - s.pages.sort_unstable(); - s.pages.dedup(); - } - // The page shown large, while it shows: leaving the tab closes it. - if !self.combine_showing() { - self.combine_tab.preview = None; - } - let preview = self.combine_tab.preview.as_ref().and_then(|p| { - let page = p.page?; - let f = self.combine_draft.iter().find(|f| f.id == p.file)?; - Some(Key { source: Arc::as_ptr(&f.bytes) as usize, auth: f.auth, page, px: [0, 0] }) - }); - let current = |slot: Slot| -> Option { - if slot == PREVIEW { - return preview; - } - let (id, page) = slot; - let s = shown.get(&id)?; - s.pages.binary_search(&page).is_ok().then_some(Key { source: s.source, auth: s.auth, page, px: [0, 0] }) - }; - self.combine_thumbs.finish(ctx, ¤t); + /// Closes the preview: leaving the tab ends it, and coming back does not reopen it. + // PLAN: called where the active tab changes away from Combine (owner: pdf-chrome-w12); closing the tab + // drops the preview with the tab's state. + pub(crate) fn close_combine_preview(&mut self) { + self.combine_tab.preview = None; } - /// The single pages selected: each one's entry (by place in the list) and page (0-based, in - /// the file), in list order (tests and the control channel). + /// The single pages selected: each one's entry (by place in the list) and page (0-based, in the + /// file), in list order (tests and the control channel). pub fn combine_selected_pages(&self) -> Vec<(usize, usize)> { + let picked: BTreeSet<(u64, usize)> = self + .combine_tab + .selection + .items + .iter() + .filter_map(|key| match key { + CombineKey::Page(id, nth) => Some((*id, *nth)), + CombineKey::File(_) => None, + }) + .collect(); let mut out = Vec::new(); for (i, f) in self.combine_draft.iter().enumerate() { - let pages = f.pages_taken().unwrap_or_default(); - for (nth, page) in pages.iter().enumerate() { - if self.combine_tab.selected_pages.contains(&(f.id, nth)) { + if !picked.iter().any(|(id, _)| *id == f.id) { + continue; + } + for (nth, page) in f.pages_taken().unwrap_or_default().iter().enumerate() { + if picked.contains(&(f.id, nth)) { out.push((i, *page)); } } @@ -523,57 +347,42 @@ impl PdfCraftApp { out } - /// Each entry's name and the pages it takes (0-based, in order): a file split into parts is - /// several entries (tests and the control channel). + /// Each entry's name and the pages it takes (0-based, in order): a file split into parts is several + /// entries (tests and the control channel). pub fn combine_parts_shown(&self) -> Vec<(String, Vec)> { self.combine_draft.iter().map(|f| (f.name.clone(), f.pages_taken().unwrap_or_default())).collect() } - /// The files shown as their pages in the grid, by place in the list (tests and the control - /// channel). + /// The files shown as their pages in the grid, by place in the list (tests and the control channel). pub fn combine_expanded(&self) -> Vec { self.combine_draft.iter().enumerate().filter(|(_, f)| self.combine_tab.expanded.contains(&f.id)).map(|(i, _)| i).collect() } - /// An expanded file's page cards: each page (0-based, in the file) and its thumbnail; empty - /// for a file shown as its card (tests and the control channel). - pub fn combine_page_thumbnails(&self, file: usize) -> Vec<(usize, ThumbState)> { + /// An expanded file's page tiles: each page (0-based, in the file) and its thumbnail; empty for a file + /// shown as its tile (tests and the control channel). + pub fn combine_page_thumbnails(&self, ctx: &egui::Context, file: usize, request: &ThumbRequest) -> Vec<(usize, TextureState)> { let Some(f) = self.combine_draft.get(file).filter(|f| self.combine_tab.expanded.contains(&f.id)) else { return Vec::new() }; + let source = self.combine_thumb_source(); let pages = f.pages_taken().unwrap_or_default(); - pages.into_iter().map(|p| (p, self.combine_thumbs.state((f.group, p)))).collect() + pages.into_iter().enumerate().map(|(nth, page)| (page, self.combine_thumb_state(ctx, &source, CombineKey::Page(f.id, nth), request))).collect() } /// Each listed file's grid thumbnail, in list order (tests and the control channel). - pub fn combine_thumbnails(&self) -> Vec { - self.combine_draft.iter().map(|f| f.first_taken().map_or(ThumbState::None, |p| self.combine_thumbs.state((f.group, p)))).collect() - } - - /// Thumbnail renders under way (tests: never more than a few). - pub fn combine_thumbnails_rendering(&self) -> usize { - self.combine_thumbs.jobs.len() - } - - /// Render threads for thumbnails that exist now (counted from the threads themselves), - /// including those of finished or abandoned renders that haven't exited yet (tests: never - /// more than three). - pub fn combine_thumbnail_threads(&mut self) -> usize { - self.combine_thumbs.threads() - } - - /// Whether no thumbnail render is under way and every render thread has exited (tests). - pub fn combine_thumbnail_threads_exited(&self) -> bool { - self.combine_thumbs.jobs.is_empty() && self.combine_thumbs.retiring.iter().all(Retiring::exited) - } - - /// Thumbnail textures held (tests: none once the tab is closed). - pub fn combine_thumbnail_textures(&self) -> usize { - self.combine_thumbs.entries.values().filter(|e| e.tex.is_some()).count() + pub fn combine_thumbnails(&self, ctx: &egui::Context, request: &ThumbRequest) -> Vec { + let source = self.combine_thumb_source(); + self.combine_draft.iter().map(|f| self.combine_thumb_state(ctx, &source, CombineKey::File(f.id), request)).collect() } } -/// The render configuration of a Combine thumbnail. Thumbnails are only shown on screen, so -/// installed CJK faces may draw fonts a PDF doesn't embed, as in the viewer; the combined file -/// itself is written from the original bytes and never from these rasters (AGENTS.md §1.4). +/// Lets go of every thumbnail and open document of a Combine tab that closed. +pub(crate) fn release_thumbnails(ctx: &egui::Context, tab: &CombineTab) { + source::thumbnails(ctx).retain(ctx, |_| false); + source::lock(&tab.open_documents).clear(); +} + +/// The render configuration of a Combine thumbnail. Thumbnails are only shown on screen, so installed CJK +/// faces may draw fonts a PDF doesn't embed, as in the viewer; the combined file itself is written from +/// the original bytes and never from these rasters (AGENTS.md §1.4). fn thumbnail_config(password: Option>) -> RenderConfig { RenderConfig { password, ..Default::default() }.on_screen() } diff --git a/crates/ui-egui/src/workflows/combine_grid/card.rs b/crates/ui-egui/src/workflows/combine_grid/card.rs index 3e98daa545..8fb65c74bc 100644 --- a/crates/ui-egui/src/workflows/combine_grid/card.rs +++ b/crates/ui-egui/src/workflows/combine_grid/card.rs @@ -1,333 +1,263 @@ -use super::thumbs::{Key, Look, MAX_SIDE, PREVIEW, PREVIEW_SIDE, SIZE_STEP, Thumbs, Want}; -use super::{ - ABOVE, Align2, Arc, BAR_H, Color32, CombineFile, CornerRadius, ERROR, FALLBACK_PAGE, GridDrag, Lock, MAX_EXPAND, ON_PAPER, PdfCraftApp, Rect, - RowAction, Sense, Stroke, TextureHandle, Tokens, Vec2, WARNING, fit_name, icons, paper_size, pos2, theme, vec2, -}; +//! The tiles of the Combine grid and the page shown large: a file's tile (a stack of sheets when it +//! takes more than one page), a page tile of an expanded file, and the preview over the window. -/// One card's place and what it shows. -pub(super) struct Card { - /// The file, by its place in the list. - pub(super) i: usize, - /// A page card (the file expanded): its place among the pages the file adds, the page and how - /// many it adds. `None` for the file's own card. - pub(super) page: Option<(usize, usize, usize)>, - pub(super) rect: Rect, - pub(super) check: Result, - pub(super) selected: bool, - pub(super) twice: bool, - pub(super) revision: u64, - pub(super) ppp: f32, - /// The box the page is fitted in (the zoom). - pub(super) fit: Vec2, +use std::sync::{Arc, Mutex}; + +use craft::behavior::IconId; +use craft::behavior::kurbo::Size; +use craft::pages::ui::{PagePreview, PageSource}; +use craft::theme::variant::Tone; +use craft::ui::contract::CommandSet; +use craft::ui::list::ThumbAspect; +use craft::ui::primitives::textures::{Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, Thumbnails}; +use craft::ui::style::DataColor; +use craft::ui::tile_grid::{BadgeKind, BadgeSlot, StackLook, Tile, TileBadge, TileStatus}; + +use super::source::{CombineThumbs, OpenDocuments, page_job, page_size}; +use super::{MAX_EXPAND, PdfCraftApp}; +use crate::combine_ui::{CombineFile, CombineKey, Lock}; + +/// The actions a tile offers in its band, and the rows of its menu. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "combineTile")] +pub(super) enum TileCommand { + #[command(label = "Preview")] + Preview, + #[command(label = "Expand")] + Expand, + #[command(label = "Collapse")] + Collapse, + #[command(label = "Remove")] + Remove, } -/// The paper box a card's page is drawn in. -struct Paper { - rect: Rect, - size: Vec2, - /// The page's size in points. - size_pt: (f32, f32), - /// Whether the page's own size is known (else a fallback is drawn and no preview is asked for). - known: bool, +/// One of a tile's own actions. A tile lists the ones that apply, in this order, and the grid reports a +/// click as the index into that list: [`file_acts`] and [`page_acts`] are the one place it is made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Act { + /// Show it large. + Preview, + /// A file as its pages. + Expand, + /// An expanded file's pages as the file's tile. + Collapse, + /// Take it out of the list: the file, or the page. + Remove, } -impl Card { - pub(super) fn id(&self, ui: &egui::Ui, f: &CombineFile) -> egui::Id { - match self.page { - None => ui.scope_id().with(("combine-card", f.id)), - Some((nth, ..)) => ui.scope_id().with(("combine-page", f.id, nth)), +impl Act { + fn command(self) -> TileCommand { + match self { + Act::Preview => TileCommand::Preview, + Act::Expand => TileCommand::Expand, + Act::Collapse => TileCommand::Collapse, + Act::Remove => TileCommand::Remove, } } - pub(super) fn show(&self, ui: &mut egui::Ui, t: &Tokens, f: &mut CombineFile, thumbs: &mut Thumbs) -> Option { - let mut action = None; - let c = self.rect; - let id = self.id(ui, f); - let resp = ui.interact(c.shrink(4.0), id, Sense::click_and_drag()); - let name = f.name.clone(); - // A page card: "Page 3", and the file it belongs to. - let page_label = self.page.map(|(_, p, _)| crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.saturating_add(1).to_string())])); - let label = match &page_label { - Some(page) => format!("{page} · {name}"), - None => name.clone(), - }; - // As the organize grid's pages: a check box that is on when selected; and, for screen - // readers, selected as items in a list are. - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.selected, &label)); - let pages = match self.page { - // For screen readers: which page of how many. - Some((_, p, _)) => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &p.saturating_add(1).to_string()), ("n", &f.pages.to_string())]), - None if f.pages == 1 => tl!("1 page").to_string(), - None => crate::i18n::fmt(tl!("{n} pages"), &[("n", &f.pages.to_string())]), - }; - let painter = ui.painter_at(c); - - // Selected and hovered cards. - if self.selected || resp.hovered() { - painter.rect_filled(c.shrink(6.0), CornerRadius::same(8), if self.selected { t.accent_soft } else { t.hover }); - } - if self.selected { - painter.rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); - } - - // The page, fitted in the paper box (top-aligned, room above for the stack). - let page = match self.page { - Some((_, p, _)) => Ok(p), - None => f.first_page(), - }; - // The page's own size, when it is known and is one. - let known = page.as_ref().ok().and_then(|p| f.sizes.get(*p).copied()).filter(|(w, h)| paper_size(*w, *h, self.fit).is_some()); - let size_pt = known.unwrap_or(FALLBACK_PAGE); - let size = paper_size(size_pt.0, size_pt.1, self.fit).unwrap_or(self.fit); - let top = c.top() + ABOVE; - let paper = Rect::from_min_size(pos2(c.center().x - size.x / 2.0 - 3.0, top + (self.fit.y - size.y)), size); - // A file's card that adds more than one page: sheets behind it. - let takes = self.check.as_ref().map_or(f.pages, |k| *k); - if self.page.is_none() && takes > 1 { - for d in [6.0, 3.0] { - let sheet = paper.translate(vec2(d, -d)); - painter.rect_filled(sheet, CornerRadius::ZERO, Color32::WHITE); - painter.rect_stroke(sheet, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); - } - } - painter.rect_filled(paper.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow); - painter.rect_filled(paper, CornerRadius::ZERO, Color32::WHITE); - - // What goes on the paper: the thumbnail, or why there isn't one. - let why = self.paper_content(ui, &painter, f, thumbs, page, Paper { rect: paper, size, size_pt, known: known.is_some() }); - if let Some((icon, colour, _)) = &why { - icons::paint(ui, Rect::from_center_size(paper.center(), Vec2::splat(28.0)), icon, 28.0, *colour); - } - // For screen readers: the pages, and why no page is shown (otherwise only in the tooltip). - let description = match &why { - Some((_, _, reason)) => format!("{pages}. {reason}"), - None => pages.clone(), - }; - ui.ctx().accesskit_node_builder(id, |node| { - node.set_selected(self.selected); - node.set_description(description); - }); - painter.rect_stroke(paper, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); - - // A warning that doesn't stop it being combined: a badge on the file's card. - let warned = self.page.is_none() && (!f.notes.is_empty() || self.twice); - if warned && why.as_ref().is_none_or(|(icon, ..)| *icon == "eye-off") { - let r = Rect::from_center_size(paper.right_top() + vec2(-2.0, 2.0), Vec2::splat(18.0)); - painter.circle_filled(r.center(), 10.0, t.card); - icons::paint(ui, r, "triangle-alert", 15.0, WARNING); - } - - // The name, shortened in the middle to fit, and the pages taken when a range is set; on a - // page card, the page first and the file's name below it, smaller. - let name_y = top + self.fit.y + 16.0; - let max_w = c.width() - 20.0; - let (font, colour, y) = match &page_label { - Some(page) => { - painter.text(pos2(c.center().x, name_y), Align2::CENTER_CENTER, page, theme::semibold(12.5), t.text); - (theme::regular(11.5), t.text_muted, name_y + 17.0) - } - None => (theme::medium(12.5), t.text, name_y), - }; - let fits = |s: &str| crate::bidi::layout_ltr(ui, s.to_owned(), font.clone(), colour).size().x <= max_w; - let shown = fit_name(&f.name, fits); - // A file name is file/path chrome: always left to right, so an Arabic name ends in `.pdf`. - let name_galley = crate::bidi::layout_ltr(ui, shown, font, colour); - painter.galley(pos2(c.center().x - name_galley.size().x / 2.0, y - name_galley.size().y / 2.0), name_galley, colour); - let note = if self.page.is_none() && !f.range.trim().is_empty() { - match &self.check { - Ok(k) => Some((crate::i18n::fmt(tl!("Pages: {k} of {n}"), &[("k", &k.to_string()), ("n", &f.pages.to_string())]), t.text_muted)), - Err(_) => Some((tl!("Check the pages").to_owned(), ERROR)), - } - } else { - None - }; - if let Some((text, colour)) = note { - painter.text(pos2(c.center().x, name_y + 17.0), Align2::CENTER_CENTER, text, theme::regular(11.5), colour); - } - - // On hover, the card's own actions along the top of the page (not while a card is - // dragged): remove this file only, and show it large when there is a page to show. Drawn - // over the card, so a click on one doesn't select or move it. - let previewable = why.is_none(); - // A file that adds more pages than one can be spread out into them. - let expandable = self.page.is_none() && takes > 1 && takes <= MAX_EXPAND && f.lock.is_none() && f.problem.is_none() && self.check.is_ok(); - let buttons = self.card_buttons(f, expandable, previewable); - // Nothing of the card shows over a dialog (the preview, the password box). - let covered = ui.ctx().memory(|m| m.top_modal_layer().is_some()); - let mut over_bar = false; - if !covered && ui.rect_contains_pointer(c.shrink(4.0)) && !egui::DragAndDrop::has_any_payload(ui.ctx()) { - let count = buttons.len() as f32; - // Mostly above the page (a quarter over its top edge), so it hides little of it, and - // never the name below. - let y = paper.top() + BAR_H / 4.0 - BAR_H / 2.0; - let bar = Rect::from_center_size(pos2(paper.center().x, y), vec2(count * 26.0 + (count - 1.0).max(0.0) * 2.0 + 8.0, BAR_H)); - over_bar = ui.rect_contains_pointer(bar); - painter.rect(bar, CornerRadius::same(8), t.card, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink(4.0)).layout(egui::Layout::left_to_right(egui::Align::Center))); - bar_ui.spacing_mut().item_spacing.x = 2.0; - for (icon, label, act) in &buttons { - if icons::button(&mut bar_ui, icon, 26.0, false, label).clicked() { - action = Some(act.clone()); - } - } - } - - let tip = self.tooltip(f, page_label.as_deref(), &pages, why.as_ref().map(|(_, _, reason)| reason.as_str())); - // (Over the bar, its buttons say what they do instead.) - let resp = if covered || over_bar { resp } else { resp.on_hover_text(tip) }; - - // The same actions on a right click, show large first (and Unlock… for a locked file). - let at = resp.rect.left_bottom(); - let locked = f.lock.is_some(); - resp.context_menu(|ui| { - let item = |ui: &mut egui::Ui, icon: &str, label: &str| { - ui.add(egui::Button::image_and_text(icons::image(icon, 15.0, ui.visuals().text_color()), label)).clicked() - }; - for (icon, label, act) in buttons.iter().rev() { - // (Remove names its file, as the trash button does.) - if item(ui, icon, label) { - action = Some(act.clone()); - ui.close(); - } - } - if locked && item(ui, "lock-open", tl!("Unlock…")) { - action = Some(RowAction::Unlock(Some(self.i), at)); - ui.close(); - } - }); - if resp.drag_started() { - egui::DragAndDrop::set_payload(ui.ctx(), GridDrag { file: f.id, revision: self.revision, page: self.page.map(|(nth, ..)| (f.id, nth)) }); - } - if resp.clicked() { - let mods = resp.ctx.input(|i| i.modifiers); - action = Some(match self.page { - Some((nth, ..)) => RowAction::ClickPage(f.id, nth, mods), - None => RowAction::Click(self.i, mods), - }); - } - action + fn icon(self) -> IconId { + IconId::new(match self { + Act::Preview => "search", + Act::Expand => "chevron_down", + Act::Collapse => "chevron_up", + Act::Remove => "trash", + }) } - /// The card's own actions, in this order: expand (or, on a page, collapse), remove (the file, or - /// the page), show large. - fn card_buttons(&self, f: &CombineFile, expandable: bool, previewable: bool) -> Vec<(&'static str, String, RowAction)> { - // Shown large: the file from its first page, or a page card's page. - let preview = match self.page { - Some((nth, ..)) => RowAction::PreviewAt(f.id, nth), - None => RowAction::Preview(f.id), - }; - // The card's own actions, in this order: expand (or, on a page, collapse), remove (the file, - // or the page), show large. - let mut buttons: Vec<(&'static str, String, RowAction)> = Vec::new(); - if expandable { - buttons.push(("maximize-2", tl!("Expand").to_owned(), RowAction::Expand(f.id, true))); - } - if let Some((nth, ..)) = self.page { - buttons.push(("minimize-2", tl!("Collapse").to_owned(), RowAction::Expand(f.id, false))); - buttons.push(("trash-2", tl!("Remove page").to_owned(), RowAction::RemovePages(Some((f.id, nth))))); - } else { - buttons.push(("trash-2", crate::i18n::fmt(tl!("Remove {name}"), &[("name", &f.name)]), RowAction::RemoveFile(f.id))); - } - if previewable { - buttons.push(("search", tl!("Preview").to_owned(), preview)); - } - buttons - } +} - /// The full name and everything known about the file, on hover (on a page card, which page). - fn tooltip(&self, f: &CombineFile, page_label: Option<&str>, pages: &str, why: Option<&str>) -> String { - let mut tip = match page_label { - Some(page) => format!("{}\n{page}", f.name), - None => format!("{}\n{pages} · {}", f.name, crate::panels::human_size(f.bytes.len())), +/// The page a file's tile shows, when one can be drawn: the first the range takes, in the file, with a size. +fn file_picture(f: &CombineFile) -> Option<(f32, f32)> { + let page = f.first_taken().filter(|p| *p < f.pages)?; + page_size(&f.sizes, page) +} + +/// The actions a file's tile (or the row for it) offers. `check` is what its range takes. +pub(super) fn file_acts(f: &CombineFile, check: &Result) -> Vec { + let readable = f.lock.is_none() && f.problem.is_none() && check.is_ok(); + let takes = check.as_ref().map_or(f.pages, |k| *k); + let mut acts = Vec::new(); + if readable && file_picture(f).is_some() { + acts.push(Act::Preview); + } + // A file that adds more pages than one can be spread out into them. + if readable && takes > 1 && takes <= MAX_EXPAND { + acts.push(Act::Expand); + } + acts.push(Act::Remove); + acts +} + +/// The actions the tile of page `page` (0-based, in the file) offers. +pub(super) fn page_acts(f: &CombineFile, page: usize) -> Vec { + let mut acts = Vec::new(); + if page < f.pages && page_size(&f.sizes, page).is_some() { + acts.push(Act::Preview); + } + acts.push(Act::Collapse); + acts.push(Act::Remove); + acts +} + +/// Where a tile's picture comes from. +#[derive(Clone, Copy)] +pub(super) struct Pictures<'a> { + pub(super) thumbs: &'a Thumbnails, + pub(super) source: &'a CombineThumbs, +} + +/// The shape a page of `size` points is drawn in. +fn aspect_of((w, h): (f32, f32)) -> ThumbAspect { + let side = |v: f32| v.round().clamp(1.0, f32::from(u16::MAX)) as u16; + ThumbAspect::new(side(w), side(h)) +} + +/// What a tile shows on its picture. +enum Face { + /// The page, drawn at this size in points. + Page((f32, f32)), + /// Why there is no page: an icon. + Icon(&'static str), +} + +impl<'a> Pictures<'a> { + /// `tile` showing `face`: the picture of `key`, or the icon. + fn put(self, tile: Tile<'a>, key: CombineKey, face: Face) -> Tile<'a> { + match face { + Face::Icon(icon) => tile.icon(IconId::new(icon)), + Face::Page(size) => tile.thumb(aspect_of(size), move |cx, rect| { + let ctx = cx.painter.ctx().clone(); + let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.painter.pixels_per_point()); + + let state = self.thumbs.state(&ctx, self.source, &key, &request, Priority::VISIBLE); + // A page is white paper in either theme. + self.thumbs.paint(cx, rect, &state, &ThumbPaint::default().paper(DataColor::new(egui::Color32::WHITE))); + }), + } + } +} + +/// The tile of a file shown as one: its first page (a stack of sheets when it takes several), its name, +/// the pages it takes, and what is wrong with it. `check` is what its range takes; `twice` that the same +/// file is in the list again. +pub(super) fn file_tile<'a>(f: &'a CombineFile, check: &Result, twice: bool, pictures: Pictures<'a>) -> Tile<'a> { + let takes = check.as_ref().map_or(f.pages, |k| *k); + let mut tile = Tile::new(f.name.clone()); + // What a screen reader hears after the name: everything the picture and the detail line only show. + let mut says: Vec = Vec::new(); + let (face, detail) = if let Some(lock) = f.lock { + let reason = match lock { + Lock::Open => tl!("Password-protected"), + Lock::Permissions => tl!("Its security settings don't allow copying pages"), }; - for line in why.into_iter().chain(f.notes.iter().map(String::as_str)) { - tip.push('\n'); - tip.push_str(line); - } - if self.twice { - tip.push('\n'); - tip.push_str(tl!("Added more than once")); - } + says.push(reason.to_string()); + (Face::Icon("lock"), Some(reason.to_string())) + } else if let Some(problem) = &f.problem { + tile = tile.status(TileStatus::Unreadable); + says.push(problem.clone()); + (Face::Icon("error"), Some(problem.clone())) + } else if let Err(why) = check { + tile = tile.status(TileStatus::Failed); + says.push(why.clone()); // Page ranges are typed in the list. - if self.page.is_none() && self.check.is_err() { - tip.push('\n'); - tip.push_str(tl!("Switch to List view to change the pages it takes.")); - } - tip - } - - /// What goes on the paper: the thumbnail, or why there isn't one (an icon, its colour and the reason). - fn paper_content( - &self, - ui: &egui::Ui, - painter: &egui::Painter, - f: &CombineFile, - thumbs: &mut Thumbs, - page: Result, - paper: Paper, - ) -> Option<(&'static str, Color32, String)> { - let mut why: Option<(&'static str, Color32, String)> = None; - if let Some(lock) = f.lock { - let text = match lock { - Lock::Open => tl!("Password-protected"), - Lock::Permissions => tl!("Its security settings don't allow copying pages"), - }; - why = Some(("lock", ON_PAPER, text.to_owned())); - } else if let Some(p) = &f.problem { - why = Some(("circle-x", ERROR, p.clone())); - } else { - match page { - Err(e) => why = Some(("circle-x", ERROR, e)), - // The pages couldn't be counted, or the page's size is unknown (some passwords - // open a file for combining but not for reading it here): nothing is drawn (the - // engine decides at Combine), and the card says so rather than look blank. - Ok(p) if p >= f.pages || !paper.known => why = Some(("eye-off", ON_PAPER, tl!("No preview").to_owned())), - Ok(p) => { - // Pixels per point: the size the paper is drawn at, on both sides, and never a - // side longer than a thumbnail's (a long, thin page fits by its long side). - let (w, h) = paper.size_pt; - let scale = (paper.size.x * self.ppp / w).min(paper.size.y * self.ppp / h).min(MAX_SIDE / w.max(h)); - let px = [w * scale, h * scale].map(|v| (v.max(1.0).ceil() as u32).div_ceil(SIZE_STEP).saturating_mul(SIZE_STEP)); - let key = Key { source: Arc::as_ptr(&f.bytes) as usize, auth: f.auth, page: p, px }; - let look = thumbs.look((f.group, p), key); - let mut want = false; - match look { - Look::Ready(tex) => { - painter.image(tex, paper.rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - Look::Failed(e) => why = Some(("triangle-alert", WARNING, crate::i18n::fmt(tl!("Preview unavailable: {e}"), &[("e", &e)]))), - Look::Pending(stand_in) => { - if let Some(tex) = stand_in { - painter.image(tex, paper.rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - want = true; - } - } - if want && scale.is_finite() && scale > 0.0 { - thumbs.wants.push(Want { - slot: (f.group, p), - key, - bytes: f.bytes.clone(), - password: f.password().map(Arc::from), - scale, - visible: ui.is_rect_visible(self.rect), - }); - } - } + says.push(tl!("Switch to List view to change the pages it takes").to_string()); + (Face::Icon("error"), Some(tl!("Check the pages").to_string())) + } else { + let detail = (!f.range.trim().is_empty()) + .then(|| crate::i18n::fmt(tl!("Pages: {k} of {n}"), &[("k", &takes.to_string()), ("n", &f.pages.to_string())])); + match file_picture(f) { + Some(size) => (Face::Page(size), detail), + // The pages couldn't be counted, or the page's size is unknown (some passwords open a file + // for combining but not for reading it here): nothing is drawn (the engine decides at + // Combine), and the tile says so rather than look blank. + None => { + says.push(tl!("No preview").to_string()); + (Face::Icon("eye_off"), detail.or_else(|| Some(tl!("No preview").to_string()))) } } - why + }; + let readable = f.lock.is_none() && f.problem.is_none() && check.is_ok(); + // A warning that doesn't stop it being combined. + if readable && (!f.notes.is_empty() || twice) { + let mut lines: Vec = f.notes.clone(); + if twice { + lines.push(tl!("Added more than once").to_string()); + } + says.extend(lines.iter().cloned()); + tile = tile.badge(TileBadge::new(BadgeSlot::EndTop, BadgeKind::Glyph(IconId::new("warning")), Tone::Warn, Some(lines.join("\n").into()))); + } + if takes > 1 { + tile = tile.stack(takes).stack_look(StackLook::Sheets); + } + if let Some(detail) = detail { + tile = tile.detail(detail); + } + // The whole name alone for a file with nothing to say: the tile is found and read by it. + let accessible = if says.is_empty() { f.name.clone() } else { format!("{}. {}", f.name, says.join(". ")) }; + tile = pictures.put(tile.accessible_name(accessible), CombineKey::File(f.id), face); + for act in file_acts(f, check) { + tile = tile.action(act.icon(), act.command()); + } + tile +} + +/// The tile of page `page` (0-based, in the file) of an expanded file, `nth` among the pages it adds: +/// "Page 3" and the file's name under it. +pub(super) fn page_tile<'a>(f: &'a CombineFile, nth: usize, page: usize, pictures: Pictures<'a>) -> Tile<'a> { + let label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &page.saturating_add(1).to_string())]); + let size = (page < f.pages).then(|| page_size(&f.sizes, page)).flatten(); + let face = size.map_or(Face::Icon("eye_off"), Face::Page); + // Named by its page and its file, so it is found and read as one of that file's pages. + let tile = Tile::new(label.clone()).detail(f.name.clone()).accessible_name(format!("{label} · {}", f.name)); + let mut tile = pictures.put(tile, CombineKey::Page(f.id, nth), face); + for act in page_acts(f, page) { + tile = tile.action(act.icon(), act.command()); + } + tile +} + +/// One Combine file's pages as the preview's page source: its pictures render through the same job path +/// as the grid's, on the tab's open documents. +struct FilePages { + bytes: Arc>, + auth: u64, + password: Option>, + sizes: Arc<[(f32, f32)]>, + count: usize, + documents: Arc>, +} + +impl ThumbSource for FilePages { + fn revision(&self, page: &usize, _: &ThumbRequest) -> Revision { + Revision::of(&(self.auth, *page)) + } + + fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender { + let Some((w, h)) = page_size(&self.sizes, *page) else { return ThumbRender::Blank }; + let scale = request.side as f32 / w.max(h); + if !(scale.is_finite() && scale > 0.0) { + return ThumbRender::Blank; + } + ThumbRender::Later(page_job(self.documents.clone(), self.bytes.clone(), self.auth, self.password.clone(), *page, scale)) } } -/// The file a card's magnifier opened, shown large over the page: one of the pages it adds at a -/// time, flipped with the buttons or the Left and Right keys; Esc, the close button or a click -/// outside closes it. It closes by itself when the file leaves the list or has nothing to show. -pub(crate) fn preview(app: &mut PdfCraftApp, ctx: &egui::Context, t: &Tokens) { - // The command palette goes over everything: the preview waits under it (drawn again after). - if app.palette_open { - return; +impl PageSource for FilePages { + fn page_count(&self) -> usize { + self.count } + + /// A page whose size is unknown is drawn as Letter paper, and nothing is rendered for it. + fn page_size(&self, page: usize) -> Size { + let (w, h) = page_size(&self.sizes, page).unwrap_or((612.0, 792.0)); + Size::new(f64::from(w), f64::from(h)) + } +} + +/// The file a tile's Preview opened, shown large over the window: one of the pages it adds at a time, +/// stepped with the buttons or the keys; Escape or Close closes it. It closes by itself when the file +/// leaves the list, is locked again or has nothing to show. +pub(crate) fn preview(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let Some(p) = app.combine_tab.preview.as_mut() else { return }; let Some(f) = app.combine_draft.iter().find(|f| f.id == p.file).filter(|f| f.lock.is_none() && f.problem.is_none()) else { app.combine_tab.preview = None; @@ -348,113 +278,25 @@ pub(crate) fn preview(app: &mut PdfCraftApp, ctx: &egui::Context, t: &Tokens) { } }, }; - let n = pages.len(); - p.at = p.at.min(n.saturating_sub(1)); + p.at = p.at.min(pages.len().saturating_sub(1)); let Some(&page) = pages.get(p.at) else { app.combine_tab.preview = None; return; }; p.page = Some(page); - let at = p.at; - // Flipped with the keys (the grid's arrows wait while this shows), unless a text field has - // them. - let typing = ctx.text_edit_focused(); - let (back, on) = ctx.input_mut(|i| { - for k in [egui::Key::Plus, egui::Key::Equals, egui::Key::Minus, egui::Key::Num0] { - i.consume_shortcut(&egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, k)); - } - if typing { - return (false, false); - } - ( - i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft) | i.consume_key(egui::Modifiers::NONE, egui::Key::PageUp), - i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight) | i.consume_key(egui::Modifiers::NONE, egui::Key::PageDown), - ) - }); - let (mut step, mut close) = (i64::from(on) - i64::from(back), false); - let screen = ctx.content_rect(); - let width = (screen.width() * 0.86).max(320.0); - let body_h = (screen.height() * 0.86 - 110.0).max(200.0); - let ppp = ctx.pixels_per_point(); - // No larger than the GPU takes, or the render would be refused. - let longest = ctx.input(|i| i.max_texture_side as f32).min(PREVIEW_SIDE); - let thumbs = &mut app.combine_thumbs; - let modal = egui::Modal::new(egui::Id::unique("combine-preview")).show(ctx, |ui| { - ui.set_width(width); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(f.name.clone()).font(theme::semibold(15.0))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icons::button(ui, "x", 30.0, false, tl!("Close")).clicked() { - close = true; - } - let of = crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &(at + 1).to_string()), ("n", &n.to_string())]); - ui.label(egui::RichText::new(of).color(t.text_muted)); - }); - }); - ui.add_space(8.0); - // The page, as large as fits. - let (area, _) = ui.allocate_exact_size(vec2(width, body_h), Sense::hover()); - let known = f.sizes.get(page).copied().filter(|(w, h)| paper_size(*w, *h, area.size()).is_some()); - let (w, h) = known.unwrap_or(FALLBACK_PAGE); - let size = paper_size(w, h, area.size() - vec2(8.0, 8.0)).unwrap_or(area.size()); - let paper = Rect::from_center_size(area.center(), size); - let painter = ui.painter_at(area); - painter.rect_filled(paper.translate(vec2(0.0, 2.0)), CornerRadius::same(1), t.page_shadow); - painter.rect_filled(paper, CornerRadius::ZERO, Color32::WHITE); - let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - if known.is_some() { - let scale = (size.x * ppp / w).min(size.y * ppp / h).min(longest / w.max(h)); - let px = [w * scale, h * scale].map(|v| (v.max(1.0).ceil() as u32).div_ceil(SIZE_STEP).saturating_mul(SIZE_STEP)); - let key = Key { source: Arc::as_ptr(&f.bytes) as usize, auth: f.auth, page, px }; - match thumbs.look(PREVIEW, key) { - Look::Ready(tex) => { - painter.image(tex, paper, uv, Color32::WHITE); - } - Look::Failed(e) => { - let text = crate::i18n::fmt(tl!("Preview unavailable: {e}"), &[("e", &e)]); - painter.text(paper.center(), Align2::CENTER_CENTER, text, theme::regular(13.0), ON_PAPER); - } - Look::Pending(stand_in) => { - // A smaller render of this page stands in: the last size shown, or its card's. - let card = thumbs.entries.get(&(f.group, page)).filter(|e| e.key.auth == f.auth).and_then(|e| e.tex.as_ref()); - if let Some(tex) = stand_in.or(card.map(TextureHandle::id)) { - painter.image(tex, paper, uv, Color32::WHITE); - } - if scale.is_finite() && scale > 0.0 { - thumbs.wants.push(Want { - slot: PREVIEW, - key, - bytes: f.bytes.clone(), - password: f.password().map(Arc::from), - scale, - visible: true, - }); - } - } - } - } else { - icons::paint(ui, Rect::from_center_size(paper.center(), Vec2::splat(36.0)), "eye-off", 36.0, ON_PAPER); - } - painter.rect_stroke(paper, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); - ui.add_space(8.0); - // Previous and next, centred below. - ui.horizontal(|ui| { - ui.add_space((width - 2.0 * 30.0 - 6.0) / 2.0); - if ui.add_enabled_ui(at > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, tl!("Previous page"))).inner.clicked() { - step = -1; - } - if ui.add_enabled_ui(at + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, tl!("Next page"))).inner.clicked() { - step = 1; - } - }); - }); - if close || modal.should_close() { + let source = FilePages { + bytes: f.bytes.clone(), + auth: f.auth, + password: f.password().map(Arc::from), + sizes: f.sizes.clone(), + count: f.pages, + documents: app.combine_tab.open_documents.clone(), + }; + let mut at = p.at; + let shown = PagePreview::new(&source, &pages, &mut at, DataColor::new(egui::Color32::WHITE)).show(ui); + p.at = at; + p.page = pages.get(at).copied(); + if shown.closed { app.combine_tab.preview = None; - } else if let Some(p) = app.combine_tab.preview.as_mut() { - p.at = match step { - s if s < 0 => p.at.saturating_sub(1), - s if s > 0 => (p.at + 1).min(n.saturating_sub(1)), - _ => p.at, - }; } } diff --git a/crates/ui-egui/src/workflows/combine_grid/source.rs b/crates/ui-egui/src/workflows/combine_grid/source.rs new file mode 100644 index 0000000000..17c4ca435e --- /dev/null +++ b/crates/ui-egui/src/workflows/combine_grid/source.rs @@ -0,0 +1,265 @@ +//! Where the Combine grid's pictures come from: the first page each file contributes (and every page +//! of an expanded file), rendered off the UI thread through [`RenderPool`], which keeps the renderer's +//! panic guard, size caps and watchdog. The thumbnail store, its budgets and its lanes are the +//! framework's ([`Thumbnails`]); this module only says what a key's picture is and how it is made. +//! +//! A file's render keeps its parsed document open for [`OpenDocuments::KEEP_OPEN`], so the next page +//! of the same file does not read the whole file again. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use craft::host::queue::Cancel; +use craft::ui::primitives::textures::{ + LoadFailure, LoadedPicture, Revision, TextureState, ThumbJob, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, +}; +use pdfcraft_render::{RenderPool, RenderRequest}; +use web_time::Instant; + +use super::{PageList, thumbnail_config}; +use crate::combine_ui::{CombineFile, CombineKey}; + +/// The longest side of a thumbnail, in pixels. A card at the top of the zoom ladder on a dense screen +/// asks for more than this and is drawn a little upscaled. +pub(super) const MAX_SIDE: u32 = 1536; + +/// The store's salt: the grid's thumbnails and nothing else live under it. +const SALT: &str = "pdfcraft-combine-thumbnails"; + +/// The thumbnails of the Combine grid in `ctx`. +pub(super) fn thumbnails(ctx: &egui::Context) -> Thumbnails { + Thumbnails::::in_context(ctx, SALT, ThumbnailOptions::new().max_side(MAX_SIDE)) +} + + +/// Page `page`'s size in points when it is one a picture can be drawn at. +pub(super) fn page_size(sizes: &[(f32, f32)], page: usize) -> Option<(f32, f32)> { + sizes.get(page).copied().filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0) +} + +/// The open documents, whether or not a render that panicked held the lock. +pub(super) fn lock(documents: &Mutex) -> MutexGuard<'_, OpenDocuments> { + documents.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A pool whose render is done, with its document still open for the file's next page. +struct Open { + /// The address of the file's shared bytes: the same file, even after undo brings it back. + source: usize, + /// How the file was read (with which password). + auth: u64, + pool: RenderPool, + since: Instant, +} + +impl std::fmt::Debug for Open { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Open").field("source", &self.source).field("auth", &self.auth).finish_non_exhaustive() + } +} + +/// The documents kept open between one page's render and the next, shared by the render jobs of one +/// Combine tab. +#[derive(Debug, Default)] +pub(crate) struct OpenDocuments { + open: Vec, + /// How many documents were opened (parsed) since the tab began. + opened: usize, +} + +impl OpenDocuments { + /// A file whose render is done keeps its document open this long, so the next page of the same + /// file renders without reading the whole file again. + pub(super) const KEEP_OPEN: Duration = Duration::from_secs(2); + /// Documents kept open at once (each holds a parsed file and an idle thread). + const MAX_OPEN: usize = 3; + + /// Closes the documents kept open past their time, as of `now`. + pub(super) fn sweep(&mut self, now: Instant) { + self.open.retain(|o| now.saturating_duration_since(o.since) < Self::KEEP_OPEN); + } + + /// Closes every document (the tab closed). + pub(crate) fn clear(&mut self) { + self.open.clear(); + } + + /// How many documents were opened (parsed) since the tab began. + #[cfg(test)] + pub(super) fn opened(&self) -> usize { + self.opened + } + + /// How many documents are kept open now. + #[cfg(test)] + pub(super) fn kept(&self) -> usize { + self.open.len() + } + + /// The pool that has `source` open as `auth` read it, or one from `make`; counts the ones made. + fn take_or_open(&mut self, source: usize, auth: u64, now: Instant, make: impl FnOnce() -> RenderPool) -> RenderPool { + self.sweep(now); + match self.open.iter().position(|o| o.source == source && o.auth == auth) { + Some(at) => self.open.swap_remove(at).pool, + None => { + self.opened = self.opened.saturating_add(1); + make() + } + } + } + + /// Keeps `pool` open for `source`'s next page; the longest-open document makes room. + fn keep(&mut self, source: usize, auth: u64, pool: RenderPool, now: Instant) { + self.sweep(now); + if self.open.len() >= Self::MAX_OPEN + && let Some(oldest) = self.open.iter().enumerate().min_by_key(|(_, o)| o.since).map(|(at, _)| at) + { + self.open.swap_remove(oldest); + } + self.open.push(Open { source, auth, pool, since: now }); + } +} + +/// The job that renders `page` of `bytes` at `scale` pixels per point. +pub(super) fn page_job(documents: Arc>, bytes: Arc>, auth: u64, password: Option>, page: usize, scale: f32) -> ThumbJob { + Box::new(move |cancel| render_page(&documents, &bytes, auth, password, page, scale, cancel)) +} + +/// Renders one page on the pool of its file, taking the document kept open if there is one. +fn render_page( + documents: &Mutex, + bytes: &Arc>, + auth: u64, + password: Option>, + page: usize, + scale: f32, + cancel: &Cancel, +) -> Result { + let source = Arc::as_ptr(bytes) as usize; + let pool = lock(documents).take_or_open(source, auth, Instant::now(), || { + RenderPool::new(bytes.clone(), 1, thumbnail_config(password)).without_replacements() + }); + pool.set_queue(vec![RenderRequest { page, scale, tag: 1, ..Default::default() }]); + // Poll the pool: its worker is the one that can be given up on (the watchdog answers an error), + // so a page that never finishes holds no queue lane for good. A pool without threads renders + // inside `try_recv`, so there no answer is one that never comes. + let answer = loop { + if cancel.is_cancelled() { + return Err(LoadFailure::Missing); + } + match pool.try_recv() { + Some(out) if out.request.page == page => break Some(out), + Some(_) => {} + None if pool.is_inline() => break None, + None => std::thread::sleep(Duration::from_millis(4)), + } + }; + let out = answer.ok_or_else(|| LoadFailure::Message("the page wasn't drawn".to_owned()))?; + if let Some(error) = out.error { + return Err(LoadFailure::Message(error)); + } + let (w, h) = (out.width as usize, out.height as usize); + let limit = 2 * MAX_SIDE as usize; + if w == 0 || h == 0 || w > limit || h > limit { + return Err(LoadFailure::Message(format!("the thumbnail came back {w}×{h} pixels"))); + } + if w.checked_mul(h).and_then(|p| p.checked_mul(4)) != Some(out.rgba.len()) { + return Err(LoadFailure::Message("the thumbnail came back incomplete".to_owned())); + } + // The renderer's words are premultiplied RGBA, as egui's colours are. + let image = egui::ColorImage::from_rgba_premultiplied([w, h], &out.rgba); + if pool.threads() <= 1 { + lock(documents).keep(source, auth, pool, Instant::now()); + } + Ok(LoadedPicture::Image(image)) +} + +/// What the grid needs of one file to say its pictures. +struct Entry { + bytes: Arc>, + auth: u64, + password: Option>, + sizes: Arc<[(f32, f32)]>, + /// The pages the file shows (0-based, in the file): its first taken page, or all of them when it is + /// expanded; none for a file that can't show a page (locked, unreadable, a bad range). + pages: Arc<[usize]>, +} + +/// The thumbnail source of the Combine grid, built each pass from the list: `File(id)` is the first page +/// the entry takes, `Page(id, nth)` the `nth` of the pages it adds. +pub(super) struct CombineThumbs { + files: HashMap, + documents: Arc>, +} + +impl CombineThumbs { + /// The source for `draft`; `expanded` holds the pages of each file shown as its pages. Documents kept + /// open past their time are closed. + pub(super) fn new(draft: &[CombineFile], expanded: &HashMap, documents: Arc>) -> Self { + lock(&documents).sweep(Instant::now()); + let files = draft + .iter() + .map(|f| { + let pages: Arc<[usize]> = if f.lock.is_some() || f.problem.is_some() { + Arc::from([]) + } else if let Some(list) = expanded.get(&f.id) { + list.order.clone() + } else { + f.first_taken().into_iter().collect() + }; + let entry = Entry { bytes: f.bytes.clone(), auth: f.auth, password: f.password().map(Arc::from), sizes: f.sizes.clone(), pages }; + (f.id, entry) + }) + .collect(); + CombineThumbs { files, documents } + } + + /// The entry of `key` and the page (0-based, in the file) it shows. + fn page_of(&self, key: &CombineKey) -> Option<(&Entry, usize)> { + let (id, nth) = match key { + CombineKey::File(id) => (id, 0), + CombineKey::Page(id, nth) => (id, *nth), + }; + let entry = self.files.get(id)?; + entry.pages.get(nth).map(|page| (entry, *page)) + } + + /// The version of `key`'s picture: how the file was read and the page it shows. The requested side is + /// the store's to add. + pub(super) fn revision_of(&self, key: &CombineKey) -> Revision { + Revision::of(&self.page_of(key).map(|(entry, page)| (entry.auth, page))) + } + + /// What `key` shows now, read without starting a render, at the side `request` asks. + pub(super) fn state_of(&self, ctx: &egui::Context, key: &CombineKey, request: &ThumbRequest) -> TextureState { + // A key with no page (a locked file, a range that takes none) shows nothing, whatever the store + // still holds of an earlier read. + if self.page_of(key).is_none() { + return TextureState::Missing; + } + let side = request.side.min(MAX_SIDE); + // The store keys a picture by the source's revision, the side and the region (none: the whole page). + // PLAN: `Thumbnails` keeps that combination private; it needs a read that starts no work, so this + // does not repeat its hash (owner: the framework's textures). + let revision = Revision::of(&(self.revision_of(key), side, None::<[u32; 4]>)); + thumbnails(ctx).cache().state(ctx, key, revision) + } +} + +impl ThumbSource for CombineThumbs { + fn revision(&self, key: &CombineKey, _: &ThumbRequest) -> Revision { + self.revision_of(key) + } + + fn render(&self, key: &CombineKey, request: &ThumbRequest) -> ThumbRender { + let Some((entry, page)) = self.page_of(key) else { return ThumbRender::Blank }; + let Some((w, h)) = page_size(&entry.sizes, page) else { return ThumbRender::Blank }; + // Pixels per point: the longest side of the page at `side` pixels. + let scale = request.side as f32 / w.max(h); + if !(scale.is_finite() && scale > 0.0) { + return ThumbRender::Blank; + } + ThumbRender::Later(page_job(self.documents.clone(), entry.bytes.clone(), entry.auth, entry.password.clone(), page, scale)) + } +} diff --git a/crates/ui-egui/src/workflows/combine_grid/tests.rs b/crates/ui-egui/src/workflows/combine_grid/tests.rs index 186cb5b3a4..18be17fe00 100644 --- a/crates/ui-egui/src/workflows/combine_grid/tests.rs +++ b/crates/ui-egui/src/workflows/combine_grid/tests.rs @@ -1,105 +1,14 @@ use std::collections::BTreeSet; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use craft::host::queue::Cancel; +use craft::ui::primitives::textures::LoadedPicture; +use web_time::Instant; + +use super::source::{self, OpenDocuments}; use super::*; -use crate::combine_ui::{moved_order, step_to}; - -#[test] -fn long_names_keep_their_extension_and_whole_characters() { - let fits = |n: usize| move |s: &str| s.chars().count() <= n; - assert_eq!(fit_name("short.pdf", fits(20)), "short.pdf"); - assert_eq!(fit_name("# 227 Pilot Boat Advance.pdf", fits(18)), "# 227 Pilot B….pdf"); - // Multi-byte characters are never cut in half. - assert_eq!(fit_name("Überweisungsbestätigung.pdf", fits(12)), "Überwei….pdf"); - assert_eq!(fit_name("日本語のファイル名です.pdf", fits(8)), "日本語….pdf"); - // No extension, or a dot that isn't one. - assert_eq!(fit_name("README-without-extension", fits(10)), "README-wi…"); - assert_eq!(fit_name(".hidden-file-name", fits(8)), ".hidden…"); - // Nothing fits: the ellipsis and the extension. - assert_eq!(fit_name("abcdef.pdf", fits(0)), "….pdf"); -} - -#[test] -fn paper_sizes_fit_the_box_and_bad_sizes_are_refused() { - // The box follows the zoom, within its range; nonsense is 100%. - assert_eq!(paper_box(1.0), PAPER); - assert_eq!(paper_box(2.0), PAPER * 2.0); - assert_eq!(paper_box(99.0), PAPER * 5.0); - assert_eq!(paper_box(-1.0), PAPER * 0.6); - assert_eq!(paper_box(f32::NAN), PAPER); - for zoom in [0.6, 1.0, 2.0, 5.0] { - let fit = paper_box(zoom); - // Letter is a little wider than the box: it fills the width. A tall page fills the height. - let letter = paper_size(612.0, 792.0, fit).unwrap(); - assert!((letter.x - fit.x).abs() < 0.01 && letter.y <= fit.y + 0.01, "{letter:?}"); - let tall = paper_size(612.0, 1008.0, fit).unwrap(); - assert!((tall.y - fit.y).abs() < 0.01 && tall.x <= fit.x + 0.01, "{tall:?}"); - let landscape = paper_size(792.0, 612.0, fit).unwrap(); - assert!((landscape.x - fit.x).abs() < 0.01 && landscape.y < fit.y, "{landscape:?}"); - for (w, h) in [(0.0, 792.0), (612.0, -1.0), (f32::NAN, 1.0), (f32::INFINITY, 1.0), (1e-30, 1e30)] { - let s = paper_size(w, h, fit); - assert!(s.is_none_or(|s| s.x.is_finite() && s.y.is_finite() && s.x <= fit.x + 0.01 && s.y <= fit.y + 0.01), "{w}×{h}: {s:?}"); - } - } -} - -#[test] -fn zoom_buttons_step_through_round_sizes() { - let mut z = 0.6; - let mut up = vec![z]; - while z < 5.0 { - z = zoom_step(z, true); - up.push(z); - } - assert_eq!(up, ZOOM_STEPS); - assert_eq!(zoom_step(5.0, true), 5.0, "the largest stays put"); - assert_eq!(zoom_step(0.6, false), 0.6, "the smallest stays put"); - // From anywhere the slider left it, to the next round size. - assert_eq!(zoom_step(1.1, true), 1.25); - assert_eq!(zoom_step(1.1, false), 1.0); - assert_eq!(zoom_step(1.953, true), 2.0); - assert_eq!(zoom_step(1.0000001, true), 1.25, "a hair over a size counts as that size"); -} - -#[test] -fn the_cards_zoom_far_enough_to_read_a_value() { - // #2531: the grid stopped at 200%, which was not enough to read invoice values while - // reordering the pages of a statement. It has to reach 500%. - assert_eq!(*ZOOM_RANGE.end(), 5.0, "the grid stops at {}%, not 500%", ZOOM_RANGE.end() * 100.0); - assert_eq!(paper_box(5.0), PAPER * 5.0, "500% is kept, not clamped to the old ceiling"); - // Every round size above the old 200% ceiling is a step the toolbar can reach. - let mut z = *ZOOM_RANGE.start(); - let mut up = vec![z]; - while z < *ZOOM_RANGE.end() { - z = zoom_step(z, true); - up.push(z); - } - for want in [2.5, 3.0, 4.0, 5.0] { - assert!(up.contains(&want), "no step reaches {want}%: {up:?}"); - } - // A card stays sharp at the ceiling instead of upscaled from the old 768px cap. A Letter - // page fills the height of the box, so at 500% it needs PAPER.y * 5.0 points of it, which - // on a 1.5 pixels-per-point screen is this many pixels. - let wanted = PAPER.y * 5.0 * 1.5; - assert!(MAX_SIDE >= wanted, "MAX_SIDE {MAX_SIDE} is under the {wanted}px a card needs at 500%"); -} - -#[test] -fn arrow_keys_step_by_file_and_by_row() { - // The list: one at a time, staying put at both ends. - assert_eq!(step_to(0, 5, 1, false), 0); - assert_eq!(step_to(4, 5, 1, true), 4); - assert_eq!(step_to(2, 5, 1, true), 3); - // A grid of 3 per row and 8 files: rows [0 1 2] [3 4 5] [6 7]. - assert_eq!(step_to(1, 8, 3, true), 4, "down one row, same column"); - assert_eq!(step_to(5, 8, 3, true), 7, "a short last row is reached at its last file"); - assert_eq!(step_to(6, 8, 3, true), 6, "the last row goes no further down"); - assert_eq!(step_to(2, 8, 3, false), 2, "the first row goes no further up"); - assert_eq!(step_to(7, 8, 3, false), 4); - // Out-of-range starts and empty lists don't panic. - assert_eq!(step_to(99, 8, 3, false), 4); - assert_eq!(step_to(0, 0, 3, true), 0); - assert_eq!(step_to(0, 1, 0, true), 0); -} +use crate::combine_ui::moved_order; #[test] fn moves_to_a_gap_keep_order_and_report_no_ops() { @@ -122,6 +31,33 @@ fn moves_to_a_gap_keep_order_and_report_no_ops() { assert_eq!(moved_order(&ids, &set(&[10]), 99), Some(vec![11, 12, 13, 14, 10])); } +/// The grid counts its rows (a header is one); the list counts entries and every page of every entry, +/// collapsed files' pages included. A page dropped by its grid position would land among another file's +/// pages and split that file. +#[test] +fn a_reorder_lands_in_the_lists_own_indexes_not_the_grids() { + use CombineKey::{File, Page}; + // A has 3 pages and is collapsed; B has 2 and is expanded: rows [A, B header, B0, B1] over items + // [A0 A1 A2 B0 B1]. + let rows = [File(1), File(2), Page(2, 0), Page(2, 1)]; + let (ids, items) = ([1, 2], [3, 2]); + let moved = |key: CombineKey, to: usize| ReorderMove::new(key, vec![key], to, false); + + // B1 between the header and B0: before B0, which is item 3 (a grid position 2 would be among A's). + assert_eq!(landing(&rows, &moved(Page(2, 1), 2), &ids, &items), Landing::Pages { gap: 3 }); + // B1 before A: item 0. + assert_eq!(landing(&rows, &moved(Page(2, 1), 0), &ids, &items), Landing::Pages { gap: 0 }); + // B1 after the last row that remains: the end of every page. + assert_eq!(landing(&rows, &moved(Page(2, 1), 3), &ids, &items), Landing::Pages { gap: 5 }); + // B0 onto B's header: that entry's first item. + assert_eq!(landing(&rows, &moved(Page(2, 0), 1), &ids, &items), Landing::Pages { gap: 3 }); + + // A file lands before the entry of the row now at `to`: B's header, then a page of B, then the end. + assert_eq!(landing(&rows, &moved(File(1), 0), &ids, &items), Landing::Files { gap: 1 }); + assert_eq!(landing(&rows, &moved(File(1), 2), &ids, &items), Landing::Files { gap: 1 }); + assert_eq!(landing(&rows, &moved(File(1), 3), &ids, &items), Landing::Files { gap: 2 }); +} + /// A PDF of `pages` pages of `w` × `h` points. fn pdf(pages: usize, w: u32, h: u32) -> Arc> { let mut objs: Vec = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()]; @@ -147,201 +83,26 @@ fn pdf(pages: usize, w: u32, h: u32) -> Arc> { Arc::new(out) } -fn key_of(bytes: &Arc>) -> Key { - Key { source: Arc::as_ptr(bytes) as usize, auth: 1, page: 0, px: [32, 48] } -} - -fn want(file: u64, bytes: &Arc>) -> Want { - Want { slot: (file, 0), key: key_of(bytes), bytes: bytes.clone(), password: None, scale: 0.15, visible: true } -} - -fn listing(files: &[(u64, &Arc>)]) -> HashMap { - files.iter().map(|(f, b)| ((*f, 0), key_of(b))).collect() -} - -/// One frame of `finish`, as the app runs it; how soon it asks to be drawn again. -fn frame(ctx: &egui::Context, thumbs: &mut Thumbs, current: &HashMap) -> std::time::Duration { - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| thumbs.finish(ui.ctx(), &|slot| current.get(&slot).copied())); - // No GPU here: the texture uploads are taken as done. - out.textures_delta.clear(); - out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) -} - -#[test] -fn a_thumbnail_that_arrives_is_drawn_without_waiting_for_input() { - // Regression: the cards are drawn before results are taken; the last result used to - // leave its card blank until the next mouse move. - let ctx = egui::Context::default(); - let mut thumbs = Thumbs::default(); - let bytes = pdf(1, 200, 300); - let current = listing(&[(1, &bytes)]); - thumbs.wants.push(want(1, &bytes)); - frame(&ctx, &mut thumbs, ¤t); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - loop { - let delay = frame(&ctx, &mut thumbs, ¤t); - if thumbs.entries.get(&(1, 0)).is_some_and(|e| e.tex.is_some()) { - assert_eq!(delay, std::time::Duration::ZERO, "the frame that took the result asks for another"); - break; - } - assert!(std::time::Instant::now() < deadline, "the thumbnail arrives"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } -} - -#[test] -fn a_result_for_a_file_that_changed_is_never_shown() { - let ctx = egui::Context::default(); - let mut thumbs = Thumbs::default(); - let bytes = pdf(1, 200, 300); - thumbs.wants.push(want(1, &bytes)); - frame(&ctx, &mut thumbs, &listing(&[(1, &bytes)])); - assert_eq!(thumbs.jobs.len(), 1, "the render started"); - // The file leaves the list (or is unlocked differently) while it renders. - let other = pdf(1, 200, 300); - let changed = listing(&[(1, &other)]); - frame(&ctx, &mut thumbs, &changed); - assert!(thumbs.jobs.is_empty(), "let go of at once"); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while thumbs.threads() > 0 { - assert!(std::time::Instant::now() < deadline, "its thread exits"); - frame(&ctx, &mut thumbs, &changed); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(thumbs.entries.is_empty(), "its result is never kept"); -} - -#[test] -fn textures_over_budget_go_longest_unseen_first_and_those_in_view_stay() { - let ctx = egui::Context::default(); - let mut thumbs = Thumbs::default(); - let tex = |n: &str| ctx.load_texture(n, egui::ColorImage::new([1, 1], vec![Color32::WHITE]), egui::TextureOptions::LINEAR); - let files: Vec>> = (0..4).map(|_| pdf(1, 200, 300)).collect(); - thumbs.frame = 10; - // Seen at frames 1, 5 and 9 (out of view now), and 10 (in view), 20 MB each as counted. - for (i, seen) in [1u64, 5, 9, 10].into_iter().enumerate() { - let key = key_of(&files[i]); - thumbs.entries.insert((i as u64, 0), Entry { key, tex: Some(tex(&format!("t{i}"))), error: None, seen, bytes: 20 << 20 }); - } - let current: HashMap = files.iter().enumerate().map(|(i, b)| ((i as u64, 0), key_of(b))).collect(); - frame(&ctx, &mut thumbs, ¤t); - let mut kept: Vec = thumbs.entries.keys().map(|k| k.0).collect(); - kept.sort_unstable(); - assert_eq!(kept, [3], "80 MB: the three out of view go, oldest first; the one in view stays even over budget"); -} - -#[test] -fn render_threads_never_exceed_three_while_files_come_and_go() { - let ctx = egui::Context::default(); - let mut thumbs = Thumbs::default(); - let files: Vec>> = (0..12).map(|i| pdf(1 + i % 3, 200, 300)).collect(); - let mut most = 0; - for round in 0..120u64 { - // A different handful of files every few frames: renders are abandoned all the time. - let start = (round / 3 % 4 * 3) as usize; - let shown: Vec<(u64, &Arc>)> = (start..start + 4).map(|i| (i as u64, &files[i % files.len()])).collect(); - for (file, bytes) in &shown { - thumbs.wants.push(want(*file, bytes)); - } - frame(&ctx, &mut thumbs, &listing(&shown)); - let threads = thumbs.threads(); - most = most.max(threads); - assert!(threads <= MAX_THREADS, "round {round}: {threads} render threads"); - std::thread::sleep(std::time::Duration::from_millis(2)); - } - assert!(most > 0, "renders did run"); -} - -#[test] -fn on_the_web_one_thumbnail_waits_at_a_time() { - // Regression: pools that render on the UI thread have no threads to count, so three - // started every frame while one finished, each holding its parsed document. - let ctx = egui::Context::default(); - let mut thumbs = Thumbs { inline: true, ..Default::default() }; - let files: Vec>> = (0..6).map(|_| pdf(1, 200, 300)).collect(); - let shown: Vec<(u64, &Arc>)> = files.iter().enumerate().map(|(i, b)| (i as u64, b)).collect(); - // One heavy step a frame on the UI thread: a parse, then the next frame its render. - for round in 0..14 { - for (file, bytes) in &shown { - thumbs.wants.push(want(*file, bytes)); - } - frame(&ctx, &mut thumbs, &listing(&shown)); - assert!(thumbs.jobs.len() <= 1, "round {round}: {} renders waiting", thumbs.jobs.len()); - assert!(thumbs.jobs.iter().all(|j| j.pool.is_inline())); - } - assert!(thumbs.entries.values().filter(|e| e.tex.is_some()).count() == 6, "all six drawn, one heavy step per frame"); -} - +/// Regression: each page of an expanded file read (parsed) the whole file again. The job is what +/// `CombineThumbs::render` hands the queue. #[test] fn the_next_page_of_a_file_reuses_its_open_document_until_it_closes() { - // Regression: each page of an expanded file read (parsed) the whole file again. - let ctx = egui::Context::default(); - let mut thumbs = Thumbs::default(); + let documents = Arc::new(Mutex::new(OpenDocuments::default())); let bytes = pdf(3, 200, 300); - let first = key_of(&bytes); - let second = Key { page: 1, ..first }; - let current: HashMap = [((1, 0), first), ((1, 1), second)].into_iter().collect(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - let drawn = |thumbs: &Thumbs, slot: Slot| thumbs.entries.get(&slot).is_some_and(|e| e.tex.is_some()); - while !drawn(&thumbs, (1, 0)) { - assert!(std::time::Instant::now() < deadline, "page 1 is drawn"); - thumbs.wants.push(want(1, &bytes)); - frame(&ctx, &mut thumbs, ¤t); - std::thread::sleep(std::time::Duration::from_millis(5)); + let cancel = Cancel::new(); + for page in 0..2 { + let picture = source::page_job(documents.clone(), bytes.clone(), 1, None, page, 0.15)(&cancel); + assert!(matches!(picture, Ok(LoadedPicture::Image(_))), "page {page} is drawn"); } - assert_eq!(thumbs.open.len(), 1, "its document stays open a moment"); - // Page 2 of the same file, read the same way: that open document renders it. - thumbs.wants.push(Want { slot: (1, 1), key: second, ..want(1, &bytes) }); - frame(&ctx, &mut thumbs, ¤t); - assert!(thumbs.open.is_empty() && thumbs.jobs.len() == 1, "reused, not a new pool: {} open, {} jobs", thumbs.open.len(), thumbs.jobs.len()); - while !drawn(&thumbs, (1, 1)) { - assert!(std::time::Instant::now() < deadline, "page 2 is drawn"); - frame(&ctx, &mut thumbs, ¤t); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(thumbs.threads() <= MAX_THREADS); - // Unused, it closes after a while, and its thread goes. - while thumbs.threads() > 0 || !thumbs.open.is_empty() { - assert!(std::time::Instant::now() < deadline, "the open document closes and its thread exits"); - frame(&ctx, &mut thumbs, ¤t); - } -} - -#[test] -fn a_page_that_failed_is_not_tried_again_at_another_size() { - // Regression: each zoom step asked for a new render of a page that had failed (or hung - // for the watchdog's 20 s), filling the render threads. - // (A card asks for a render only when it looks Pending.) - let mut thumbs = Thumbs::default(); - let bytes = pdf(1, 200, 300); - let key = key_of(&bytes); - thumbs.entries.insert((1, 0), Entry { key, tex: None, error: Some("broken".into()), seen: 0, bytes: 0 }); - let larger = Key { px: [key.px[0] + 64, key.px[1] + 64], ..key }; - assert!(matches!(thumbs.look((1, 0), larger), Look::Failed(e) if e == "broken"), "the failure stands at another size"); - // Another read of the file (a new password) is a new page: tried again. - let reread = Key { auth: 2, ..key }; - assert!(matches!(thumbs.look((1, 0), reread), Look::Pending(None))); -} - -#[test] -fn on_the_web_a_render_that_never_answers_fails_and_lets_the_rest_through() { - // A pool without threads answers on the call that renders: no answer then never comes. - // It used to wait for good, so nothing else started and every frame asked for another. - let ctx = egui::Context::default(); - let mut thumbs = Thumbs { inline: true, ..Default::default() }; - let (silent, next) = (pdf(1, 200, 300), pdf(1, 200, 300)); - let pool = RenderPool::new_inline(silent.clone(), RenderConfig::default()); - // Nothing queued: this pool has nothing to answer with. - thumbs.jobs.push(Job { slot: (1, 0), key: key_of(&silent), pool, tag: 7 }); - let current = listing(&[(1, &silent), (2, &next)]); - for _ in 0..4 { - thumbs.wants.push(want(2, &next)); - frame(&ctx, &mut thumbs, ¤t); - } - assert!(thumbs.entries.get(&(1, 0)).is_some_and(|e| e.tex.is_none() && e.error.is_some()), "the silent one failed"); - assert!(thumbs.entries.get(&(2, 0)).is_some_and(|e| e.tex.is_some()), "the next one was drawn"); - assert!(thumbs.jobs.is_empty()); - assert!(frame(&ctx, &mut thumbs, ¤t) > std::time::Duration::ZERO, "no more frames asked for at once"); + assert_eq!(source::lock(&documents).opened(), 1, "the file was read once for both pages"); + assert_eq!(source::lock(&documents).kept(), 1, "its document stays open a moment"); + // Read the other way (a new password) it is another document. + let other = source::page_job(documents.clone(), bytes.clone(), 2, None, 2, 0.15)(&cancel); + assert!(matches!(other, Ok(LoadedPicture::Image(_)))); + assert_eq!(source::lock(&documents).opened(), 2, "a file read another way is read again"); + // Unused, they close after a while. + source::lock(&documents).sweep(Instant::now() + OpenDocuments::KEEP_OPEN + Duration::from_millis(1)); + assert_eq!(source::lock(&documents).kept(), 0, "the open documents close after the keep-open time"); } /// Combine thumbnails are on-screen rasters: like the viewer, they may draw a non-embedded diff --git a/crates/ui-egui/src/workflows/combine_grid/thumbs.rs b/crates/ui-egui/src/workflows/combine_grid/thumbs.rs deleted file mode 100644 index 1de9ad05b6..0000000000 --- a/crates/ui-egui/src/workflows/combine_grid/thumbs.rs +++ /dev/null @@ -1,391 +0,0 @@ -use super::{Arc, HashMap, RenderPool, RenderRequest, Retiring, TextureHandle, thumbnail_config}; - -/// Render threads for thumbnails at once, counting those of retired pools until they exit. -pub(super) const MAX_THREADS: usize = 3; - -/// Results taken per frame, and the bytes they may upload. -const UPLOADS_PER_FRAME: usize = 4; - -const UPLOAD_BYTES_PER_FRAME: usize = 8 << 20; - -/// Thumbnail textures kept, in bytes. Those out of view go first, longest unseen first; those in -/// view are kept even over budget (at most a screenful of thumbnails of at most [`MAX_SIDE`]). -const TEXTURE_BUDGET: usize = 32 << 20; - -/// The longest side of a thumbnail, in pixels. -/// (Room for a Letter page at 500% on a screen of 1.5 pixels per point; sharper screens upscale a -/// little at the largest sizes.) This only binds near the top of the zoom range: a card below it -/// asks for less than this and costs no more than it did. Near the top one thumbnail is a few -/// megabytes, so [`TEXTURE_BUDGET`] and [`UPLOAD_BYTES_PER_FRAME`] keep the cache at a screenful -/// plus one frame's uploads — and at the top of the range a screenful is a card or two, because a -/// card is wider than most windows. -pub(super) const MAX_SIDE: f32 = 1536.0; - -/// Thumbnail sizes round up to this many pixels, so a slightly different layout reuses them. -pub(super) const SIZE_STEP: u32 = 16; - -/// A thumbnail's place: the file (by id) and the page (0-based, in the file). A file's card and -/// the card of its first page when expanded show the same thumbnail. -pub(super) type Slot = (u64, usize); - -/// The page shown large (a card's magnifier) is kept beside the thumbnails under this slot, so it -/// shares their threads, their limits and their checks. -pub(super) const PREVIEW: Slot = (u64::MAX, 0); - -/// The longest side of the page shown large, in pixels. -pub(super) const PREVIEW_SIDE: f32 = 2048.0; - -/// A file whose render is done keeps its document open this long (seconds), so the next page of -/// the same file renders without reading the whole file again. -const KEEP_OPEN: f64 = 2.0; - -/// What the grid has for a file (tests and the control channel). -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum ThumbState { - /// Nothing yet: not in view, or nothing to draw (locked, unreadable, a bad page range, a page - /// whose size is unknown). - None, - /// Being rendered. - Pending, - /// A thumbnail of page `page` (0-based), `width` × `height` pixels. - Ready { page: usize, width: u32, height: u32 }, - /// The page couldn't be drawn. - Failed(String), -} - -/// Everything a thumbnail depends on: the file's bytes, how it was read (its password), the page -/// and the size. A cached thumbnail is used only while all of them still match. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Key { - /// The address of the file's shared bytes: the same file, even after undo brings it back. - pub(super) source: usize, - pub(super) auth: u64, - pub(super) page: usize, - pub(super) px: [u32; 2], -} - -impl Key { - fn same_page(&self, other: &Key) -> bool { - (self.source, self.auth, self.page) == (other.source, other.auth, other.page) - } -} - -pub(super) struct Entry { - pub(super) key: Key, - pub(super) tex: Option, - pub(super) error: Option, - /// The frame the card last showed it. - pub(super) seen: u64, - pub(super) bytes: usize, -} - -pub(super) struct Job { - pub(super) slot: Slot, - pub(super) key: Key, - pub(super) pool: RenderPool, - pub(super) tag: u64, -} - -/// A pool whose render is done, with its document still open: kept a moment for the next page of -/// the same file, read the same way. -pub(super) struct Open { - source: usize, - auth: u64, - pool: RenderPool, - /// When its render finished (seconds). - since: f64, -} - -/// A thumbnail a card needs this frame. -pub(super) struct Want { - pub(super) slot: Slot, - pub(super) key: Key, - pub(super) bytes: Arc>, - pub(super) password: Option>, - pub(super) scale: f32, - pub(super) visible: bool, -} - -/// The grid's thumbnails and the renders under way. -#[derive(Default)] -pub(crate) struct Thumbs { - pub(super) entries: HashMap, - pub(super) jobs: Vec, - /// Pools done rendering, their documents still open (their threads count). - pub(super) open: Vec, - /// Threads of pools let go of, until they exit. - pub(super) retiring: Vec, - pub(super) frame: u64, - pub(super) next_tag: u64, - pub(super) wants: Vec, - /// Render on the UI thread, as the web build does (tests). - #[cfg(test)] - pub(super) inline: bool, -} - -/// What a card can draw now. -pub(super) enum Look { - Ready(egui::TextureId), - Failed(String), - /// Not ready; an older thumbnail of the same page may stand in. - Pending(Option), -} - -impl Thumbs { - /// Forget every thumbnail (the tab closed). Renders under way are let go of: told to stop at - /// their next drawing operator, and counted until their threads exit. - pub(crate) fn clear(&mut self) { - self.entries.clear(); - self.wants.clear(); - for job in self.jobs.drain(..) { - self.retiring.push(job.pool.retire()); - } - for open in self.open.drain(..) { - self.retiring.push(open.pool.retire()); - } - } - - /// Render threads that exist now (real threads, not pools): those of pools at work, of pools - /// keeping a document open, and of pools let go of. - pub(super) fn threads(&mut self) -> usize { - self.retiring.retain_mut(|r| r.running() > 0); - let retiring: usize = self.retiring.iter_mut().map(Retiring::running).sum(); - let working: usize = self.jobs.iter().map(|j| j.pool.threads()).sum(); - let open: usize = self.open.iter().map(|o| o.pool.threads()).sum(); - working.saturating_add(open).saturating_add(retiring) - } - - pub(super) fn look(&mut self, slot: Slot, key: Key) -> Look { - let frame = self.frame; - match self.entries.get_mut(&slot) { - Some(e) if e.key == key => { - e.seen = frame; - match (&e.tex, &e.error) { - (Some(tex), _) => Look::Ready(tex.id()), - (None, Some(err)) => Look::Failed(err.clone()), - (None, None) => Look::Pending(None), - } - } - // Another size of the same page stands in until this one arrives. A page that failed - // isn't tried again at another size: it would fail (or hang) the same way, each zoom. - Some(e) if e.key.same_page(&key) => { - e.seen = frame; - match &e.error { - Some(err) if e.tex.is_none() => Look::Failed(err.clone()), - _ => Look::Pending(e.tex.as_ref().map(TextureHandle::id)), - } - } - _ => Look::Pending(None), - } - } - - pub(super) fn state(&self, slot: Slot) -> ThumbState { - if let Some(e) = self.entries.get(&slot) { - if let Some(tex) = &e.tex { - let [w, h] = tex.size(); - return ThumbState::Ready { - page: e.key.page, - width: u32::try_from(w).unwrap_or(u32::MAX), - height: u32::try_from(h).unwrap_or(u32::MAX), - }; - } - if let Some(err) = &e.error { - return ThumbState::Failed(err.clone()); - } - } - if self.jobs.iter().any(|j| j.slot == slot) { ThumbState::Pending } else { ThumbState::None } - } - - /// Once per frame, whatever shows: drop what no longer matches the list, take finished - /// renders, start those the grid asked for and keep the textures within budget. `current` - /// says what a thumbnail must match now (looked up, so the cost follows the files and the - /// thumbnails kept, not the pages of an expanded file). - pub(super) fn finish(&mut self, ctx: &egui::Context, current: &dyn Fn(Slot) -> Option) { - let now = ctx.input(|i| i.time); - // Reconcile with the list as it is now (undo, redo, unlock, a new range, removal): a - // thumbnail of another page, password or file is never shown again. - self.entries.retain(|slot, e| current(*slot).is_some_and(|k| k.same_page(&e.key))); - // Renders nobody wants any more are let go of now (on the web, before they would render). - let (keep, gone): (Vec, Vec) = self.jobs.drain(..).partition(|job| current(job.slot).is_some_and(|k| k.same_page(&job.key))); - self.jobs = keep; - self.retiring.extend(gone.into_iter().map(|job| job.pool.retire())); - // Documents kept open past their time are closed. - let (keep, gone): (Vec, Vec) = self.open.drain(..).partition(|o| now - o.since < KEEP_OPEN); - self.open = keep; - self.retiring.extend(gone.into_iter().map(|o| o.pool.retire())); - - // Finished renders, a few per frame. A pool without threads (the web) renders inside - // `try_recv`: at most one of those per frame. - let gpu_side = ctx.input(|i| i.max_texture_side); - let max_side = gpu_side.min(2 * MAX_SIDE as usize); - let (mut taken, mut uploaded, mut inline_used) = (0usize, 0usize, false); - let mut i = 0; - while i < self.jobs.len() { - if taken >= UPLOADS_PER_FRAME || uploaded >= UPLOAD_BYTES_PER_FRAME { - break; - } - let Some(job) = self.jobs.get(i) else { break }; - if job.pool.is_inline() { - if inline_used { - i += 1; - continue; - } - inline_used = true; - } - // Not done yet, or not this job's answer (cannot happen with one request per pool): - // keep waiting. A pool without threads answers on the call that renders, so there no - // answer is one that never comes: the thumbnail fails rather than hold up the rest. - let answer = job.pool.try_recv().filter(|out| out.request.tag == job.tag); - if answer.is_none() && !job.pool.is_inline() { - i += 1; - continue; - } - let job = self.jobs.swap_remove(i); - taken += 1; - // A pool that rendered (rather than failed or hung) can keep its document open. - let healthy = answer.as_ref().is_some_and(|out| out.error.is_none()); - let failed = |e: String| Entry { key: job.key, tex: None, error: Some(e), seen: self.frame, bytes: 0 }; - let entry = match answer { - None => failed("the page wasn't drawn".to_owned()), - Some(out) => match out.error { - Some(e) => failed(e), - None => match texture( - ctx, - job.slot, - [out.width, out.height], - out.rgba, - if job.slot == PREVIEW { gpu_side.min(PREVIEW_SIDE as usize) } else { max_side }, - ) { - Ok((tex, bytes)) => { - uploaded = uploaded.saturating_add(bytes); - Entry { key: job.key, tex: Some(tex), error: None, seen: self.frame, bytes } - } - Err(e) => failed(e), - }, - }, - }; - self.entries.insert(job.slot, entry); - // Its document stays open a moment for the file's next page (its thread, idle, still - // counts); otherwise its thread (idle, or finishing a render the watchdog gave up on) - // counts until it exits. - if healthy && job.pool.threads() <= 1 && self.open.len() < MAX_THREADS { - self.open.push(Open { source: job.key.source, auth: job.key.auth, pool: job.pool, since: now }); - } else { - self.retiring.push(job.pool.retire()); - } - } - - // New renders: the cards in view first, in grid order; one per thumbnail at a time. - let mut wants = std::mem::take(&mut self.wants); - wants.sort_by_key(|w| (w.slot != PREVIEW, !w.visible)); - // A pool without threads (the web) parses its document when it is made and keeps it until - // it renders, one per frame: while one waits, nothing else starts. - // (Nor in the frame that rendered one: one heavy step per frame on the UI thread.) - let mut threads = if inline_used || self.jobs.iter().any(|j| j.pool.is_inline()) { MAX_THREADS } else { self.threads() }; - let mut waiting = false; - for w in wants { - // Wanted for the list as it is now (not changed by this frame's action); one render - // per thumbnail at a time; and a want made earlier this frame may have just been - // answered. - if current(w.slot).is_none_or(|k| !k.same_page(&w.key)) - || self.jobs.iter().any(|j| j.slot == w.slot) - || self.entries.get(&w.slot).is_some_and(|e| e.key == w.key) - { - continue; - } - // The same file, read the same way, still open from a render just done: no new read of - // the file (and its thread is already counted). On the web, not while another waits. - let inline_waiting = self.jobs.iter().any(|j| j.pool.is_inline()); - if let Some(k) = - self.open.iter().position(|o| o.source == w.key.source && o.auth == w.key.auth && !(o.pool.is_inline() && inline_waiting)) - { - let pool = self.open.swap_remove(k).pool; - self.next_tag = self.next_tag.wrapping_add(1); - let tag = self.next_tag; - pool.set_queue(vec![RenderRequest { page: w.key.page, scale: w.scale, tag, ..Default::default() }]); - if pool.is_inline() { - threads = MAX_THREADS; - } - self.jobs.push(Job { slot: w.slot, key: w.key, pool, tag }); - continue; - } - if threads >= MAX_THREADS { - // A document kept open for another file gives its thread up: it exits, and this - // starts then. - if let Some(k) = self.open.iter().enumerate().min_by(|(_, a), (_, b)| a.since.total_cmp(&b.since)).map(|(k, _)| k) { - let open = self.open.swap_remove(k); - self.retiring.push(open.pool.retire()); - } - waiting = true; - break; - } - let config = thumbnail_config(w.password); - #[cfg(test)] - let pool = if self.inline { RenderPool::new_inline(w.bytes, config) } else { RenderPool::new(w.bytes, 1, config).without_replacements() }; - #[cfg(not(test))] - let pool = RenderPool::new(w.bytes, 1, config).without_replacements(); - self.next_tag = self.next_tag.wrapping_add(1); - let tag = self.next_tag; - // The request stays in the pool's queue (it is never replaced) until its answer. - pool.set_queue(vec![RenderRequest { page: w.key.page, scale: w.scale, tag, ..Default::default() }]); - threads = if pool.is_inline() { MAX_THREADS } else { threads.saturating_add(1) }; - self.jobs.push(Job { slot: w.slot, key: w.key, pool, tag }); - } - - // Within budget: drop the thumbnails out of view longest unseen first. - // (The page shown large has its own: one texture, gone when it closes.) - let mut total: usize = self.entries.iter().filter(|(f, _)| **f != PREVIEW).map(|(_, e)| e.bytes).sum(); - if total > TEXTURE_BUDGET { - let mut old: Vec<(u64, Slot, usize)> = self - .entries - .iter() - .filter(|(f, e)| **f != PREVIEW && e.seen != self.frame && e.bytes > 0) - .map(|(f, e)| (e.seen, *f, e.bytes)) - .collect(); - old.sort_unstable(); - for (_, slot, bytes) in old { - if total <= TEXTURE_BUDGET { - break; - } - self.entries.remove(&slot); - total = total.saturating_sub(bytes); - } - } - - // The cards were drawn before these results arrived: draw them again. Keep polling while - // renders are under way, and while a thumbnail waits for a thread to exit (not when - // nothing waits: a thread exiting changes nothing on screen). - if taken > 0 || self.jobs.iter().any(|j| j.pool.is_inline()) { - ctx.request_repaint(); - } else if !self.jobs.is_empty() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } else if waiting { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } else if !self.open.is_empty() { - // To close the documents kept open when their time is up. - ctx.request_repaint_after(std::time::Duration::from_secs_f64(KEEP_OPEN)); - } - self.frame = self.frame.wrapping_add(1); - } -} - -/// A rendered thumbnail as a texture, and its size in bytes. A raster that doesn't add up, or is -/// larger than a thumbnail can be (or than the GPU accepts), is refused, never uploaded. -fn texture( - ctx: &egui::Context, - slot: Slot, - size: [u32; 2], - pixels: pdfcraft_render::Pixels, - max_side: usize, -) -> Result<(TextureHandle, usize), String> { - let [w, h] = size.map(|v| v as usize); - if w == 0 || h == 0 || w > max_side || h > max_side { - return Err(format!("the thumbnail came back {w}×{h} pixels")); - } - let bytes = w.checked_mul(h).and_then(|p| p.checked_mul(4)).ok_or("the thumbnail is too large")?; - if pixels.len() != bytes { - return Err("the thumbnail came back incomplete".to_owned()); - } - let image = crate::canvas::texture_image([w, h], pixels); - Ok((ctx.load_texture(format!("combine-thumb-{}-{}", slot.0, slot.1), image, egui::TextureOptions::LINEAR), bytes)) -} diff --git a/crates/ui-egui/tests/it/combine_grid.rs b/crates/ui-egui/tests/it/combine_grid.rs index 577bbed123..f8143ea5e3 100644 --- a/crates/ui-egui/tests/it/combine_grid.rs +++ b/crates/ui-egui/tests/it/combine_grid.rs @@ -1,13 +1,15 @@ -//! Headless UI tests for the Combine files grid: a thumbnail card per file, selected, moved and -//! undone like the list's rows; thumbnails rendered lazily, a few at a time, and never stale. +//! Headless UI tests for the Combine files grid: a tile per file, selected, moved and undone like the +//! list's rows; thumbnails never stale; a file shown as its pages; the preview. use std::time::Duration; +use craft::ui::primitives::textures::TextureState; +use craft::ui::tile_grid::TileZoom; use egui::{Key, Modifiers, Pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind}; -use pdfcraft_ui_egui::{CombineThumb, CombineView, FilePurpose, PdfCraftApp}; +use pdfcraft_ui_egui::{CombineView, FilePurpose, PdfCraftApp}; /// An `n`-page document with a proper xref table; page `i` shows "Page i+1". fn fixture(n: usize) -> Vec { @@ -16,12 +18,21 @@ fn fixture(n: usize) -> Vec { /// The same, with pages of `w` × `h` points. fn fixture_sized(n: usize, w: f32, h: f32) -> Vec { + fixture_pages(&vec![(w, h); n]) +} + +/// A document with one page of each of `sizes` (width, height in points); page `i` shows "Page i+1". +fn fixture_pages(sizes: &[(f32, f32)]) -> Vec { + let n = sizes.len(); let mut objs: Vec = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()]; let kids: Vec = (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect(); - objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 {w} {h}] >>", kids.join(" "))); + objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))); objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into()); - for i in 0..n { - objs.push(format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >>", 5 + 2 * i)); + for (i, (w, h)) in sizes.iter().enumerate() { + objs.push(format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >>", + 5 + 2 * i + )); let body = format!("BT /F1 24 Tf 20 150 Td (Page {}) Tj ET", i + 1); objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len())); } @@ -40,34 +51,6 @@ fn fixture_sized(n: usize, w: f32, h: f32) -> Vec { out } -/// A one-page document whose page takes a while to draw (tens of thousands of shapes), so a -/// thumbnail render is still under way when a test acts. -fn heavy() -> Vec { - let mut body = String::from("0.2 0.4 0.8 rg\n"); - for i in 0..60_000 { - body.push_str(&format!("{} {} 1 1 re f\n", i % 200, (i / 200) % 300)); - } - let objs = [ - "<< /Type /Catalog /Pages 2 0 R >>".to_string(), - "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_string(), - "<< /Type /Page /Parent 2 0 R /Contents 4 0 R >>".to_string(), - format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()), - ]; - let mut out = b"%PDF-1.7\n".to_vec(); - let mut offsets = Vec::new(); - for (i, o) in objs.iter().enumerate() { - offsets.push(out.len()); - out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); - } - let xref = out.len(); - out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); - for o in offsets { - out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); - } - out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); - out -} - /// A two-page fixture that opens with `user` and allows everything with `owner`. fn protected(user: &str, owner: &str) -> Vec { protected_with(pdfcraft_cos::Algorithm::Aes256, user, owner) @@ -92,7 +75,7 @@ fn grid_of(files: Vec<(&str, Vec)>, size: egui::Vec2) -> Harness<'static, Pd grid_after(files, size, 4) } -/// The same, after only `steps` frames (1: the first thumbnails have only just been asked for). +/// The same, after only `steps` frames. fn grid_after(files: Vec<(&str, Vec)>, size: egui::Vec2, steps: usize) -> Harness<'static, PdfCraftApp> { let files: Vec<(String, Vec)> = files.into_iter().map(|(n, b)| (n.to_string(), b)).collect(); let mut h = Harness::builder().with_size(size).build_eframe(move |_cc| { @@ -105,19 +88,6 @@ fn grid_after(files: Vec<(&str, Vec)>, size: egui::Vec2, steps: usize) -> Ha h } -/// The grid on the frame its first thumbnails start rendering (a render started in one frame -/// is collected in a later one, so there always is such a frame). -fn grid_after_one(files: Vec<(&str, Vec)>, size: egui::Vec2) -> Harness<'static, PdfCraftApp> { - let mut h = grid_after(files, size, 0); - for _ in 0..20 { - h.run_steps(1); - if h.state().combine_thumbnails_rendering() > 0 { - break; - } - } - h -} - fn grid_of_pages(names: &[(&str, usize)]) -> Harness<'static, PdfCraftApp> { grid_of(names.iter().map(|(n, p)| (*n, fixture(*p))).collect(), vec2(1400.0, 900.0)) } @@ -126,6 +96,7 @@ fn names(h: &Harness<'static, PdfCraftApp>) -> Vec { h.state().combine_draft.iter().map(|f| f.name.clone()).collect() } +/// The rule in `view`: only files with the same bytes are warned, and undo and redo follow it. fn check_duplicate_warnings(view: &str) { let first = fixture_sized(1, 200.0, 300.0); let other = fixture_sized(1, 300.0, 200.0); @@ -134,33 +105,22 @@ fn check_duplicate_warnings(view: &str) { let mut h = grid_of(vec![("report.pdf", first.clone()), ("report.pdf", other)], vec2(1400.0, 900.0)); h.state_mut().set_option("combine-view", view).unwrap(); h.run_steps(2); - let warning_count = |h: &mut Harness<'static, PdfCraftApp>| { - if view == "grid" { - let at = h.get_all_by_label("report.pdf").next().unwrap().rect().center(); - h.hover_at(at); - h.run_steps(60); - } - h.query_all_by_label_contains("Added more than once").count() - }; - assert_eq!(warning_count(&mut h), 0, "different equal-sized PDFs are not duplicates in {view}"); + let warnings = |h: &Harness<'static, PdfCraftApp>| h.query_all_by_label_contains("Added more than once").count(); + assert_eq!(warnings(&h), 0, "different equal-sized PDFs are not duplicates in {view}"); h.state_mut().use_files(FilePurpose::Combine, vec![("report.pdf".into(), first)]); h.run_steps(3); - assert_eq!(warning_count(&mut h), if view == "grid" { 1 } else { 2 }, "only the two identical files are warned"); + assert_eq!(warnings(&h), 2, "only the two identical files are warned in {view}"); h.key_press_modifiers(Modifiers::COMMAND, Key::Z); h.run_steps(3); - assert_eq!(warning_count(&mut h), 0, "undo removes the duplicate warning"); + assert_eq!(warnings(&h), 0, "undo removes the duplicate warning in {view}"); h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z); h.run_steps(3); - assert_eq!(warning_count(&mut h), if view == "grid" { 1 } else { 2 }, "redo restores the duplicate warning"); + assert_eq!(warnings(&h), 2, "redo restores the duplicate warning in {view}"); } #[test] fn list_duplicate_warnings_compare_contents_and_follow_undo() { check_duplicate_warnings("list"); -} - -#[test] -fn grid_duplicate_warnings_compare_contents_and_follow_undo() { check_duplicate_warnings("grid"); } @@ -176,8 +136,29 @@ fn settle(h: &mut Harness<'static, PdfCraftApp>, done: impl Fn(&PdfCraftApp) -> false } -fn ready(t: &CombineThumb) -> bool { - matches!(t, CombineThumb::Ready { .. }) +fn ready(t: &TextureState) -> bool { + matches!(t, TextureState::Ready(_)) +} + +/// The picture's size in pixels, when it is drawn. +fn shape(t: &TextureState) -> Option<(f32, f32)> { + match t { + TextureState::Ready(texture) => { + let size = texture.size_vec2(); + Some((size.x, size.y)) + } + _ => None, + } +} + +/// A picture wider than it is high. +fn landscape(t: &TextureState) -> bool { + shape(t).is_some_and(|(w, h)| w > h) +} + +/// A picture higher than it is wide. +fn portrait(t: &TextureState) -> bool { + shape(t).is_some_and(|(w, h)| h > w) } /// Wait for a modal opened by an action to be laid out and present in the accessibility tree. @@ -205,11 +186,15 @@ fn drag(h: &mut Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2) { h.run_steps(4); } -/// Where a file's card is. +/// Where a file's tile is. fn card(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Rect { h.get_by_label(name).rect() } +fn disabled(h: &Harness<'static, PdfCraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().is_disabled() +} + fn texts_of(app: &PdfCraftApp, tab: usize) -> Vec { let doc = app.session.get(app.views[tab].id).unwrap(); let mut r = PageRenderer::new(doc.bytes.clone(), Default::default()); @@ -251,31 +236,6 @@ fn combine_shows_a_grid_by_default_and_the_view_is_kept_in_the_settings() { assert_eq!(app.set_option("combine-view", "tiles"), Err("combine-view must be grid or list".into())); } -#[test] -fn cards_select_like_the_list_and_the_selection_survives_switching_views() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1), ("e.pdf", 1)]); - h.get_by_label("b.pdf").click(); - h.run_steps(1); - h.get_by_label("d.pdf").click_modifiers(Modifiers::SHIFT); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1, 2, 3]); - h.get_by_label("c.pdf").click_modifiers(Modifiers::COMMAND); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1, 3], "Ctrl/⌘ toggles one card"); - h.get_by_label("2 selected"); - assert!(h.get_by_label("b.pdf").accesskit_node().is_selected() == Some(true), "cards say they are selected"); - h.get_by_label("List view").click(); - h.run_steps(2); - assert_eq!(h.state().combine_selection(), [1, 3]); - h.get_by_label("Grid view").click(); - h.run_steps(2); - assert_eq!(h.state().combine_selection(), [1, 3]); - // The toolbar acts on it in the grid too. - h.get_by_label("Remove 2 files").click(); - h.run_steps(2); - assert_eq!(names(&h), ["a.pdf", "c.pdf", "e.pdf"]); -} - #[test] fn dragging_a_card_moves_it_and_undo_puts_it_back() { let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1)]); @@ -301,218 +261,45 @@ fn dragging_a_card_moves_it_and_undo_puts_it_back() { assert_eq!(names(&h), ["b.pdf", "c.pdf", "a.pdf", "d.pdf"]); } -#[test] -fn a_dragged_selection_moves_together_to_the_first_and_last_gaps() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1), ("e.pdf", 1)]); - // A selection with a gap in it. - h.state_mut().select_combine_rows(&[1, 3]); - h.run_steps(1); - let (b, e) = (card(&h, "b.pdf"), card(&h, "e.pdf")); - drag(&mut h, b.center(), e.center() + vec2(e.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["a.pdf", "c.pdf", "e.pdf", "b.pdf", "d.pdf"], "to the end, in their order"); - assert_eq!(h.state().combine_selection(), [3, 4]); - // And back to the very start. - let (d, a) = (card(&h, "d.pdf"), card(&h, "a.pdf")); - drag(&mut h, d.center(), a.center() - vec2(a.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["b.pdf", "d.pdf", "a.pdf", "c.pdf", "e.pdf"]); - // A file that isn't selected moves alone, and becomes the selection. - let (c, b) = (card(&h, "c.pdf"), card(&h, "b.pdf")); - drag(&mut h, c.center(), b.center() - vec2(b.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["c.pdf", "b.pdf", "d.pdf", "a.pdf", "e.pdf"]); - assert_eq!(h.state().combine_selection(), [0]); -} - -#[test] -fn a_drop_that_changes_nothing_or_lands_outside_the_grid_leaves_no_undo_step() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1)]); - // The same drag gesture, to a real gap, does move (and is undone). - let (b, c) = (card(&h, "b.pdf"), card(&h, "c.pdf")); - drag(&mut h, b.center(), c.center() + vec2(c.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["a.pdf", "c.pdf", "b.pdf"]); - h.key_press_modifiers(Modifiers::COMMAND, Key::Z); - h.run_steps(2); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf"]); - h.state_mut().combine_tab.sort = Some((pdfcraft_ui_egui::SortKey::Name, true)); - let b = card(&h, "b.pdf"); - // Onto its own place. - drag(&mut h, b.center(), b.center() + vec2(b.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf"]); - // Onto the toolbar, outside the grid. - let toolbar = h.get_by_label("Grid view").rect().center(); - drag(&mut h, b.center(), toolbar); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf"]); - assert!(h.state().combine_tab.sort.is_some(), "a move that didn't happen keeps the sort"); - // The only step is still the adding of the files: one undo empties the list. - h.key_press_modifiers(Modifiers::COMMAND, Key::Z); - h.run_steps(2); - assert!(names(&h).is_empty()); - assert!(h.get_by_label("Undo").accesskit_node().is_disabled()); -} - -#[test] -fn arrow_keys_move_by_card_and_by_row_and_shift_extends() { - let files: Vec<(String, usize)> = (0..9).map(|i| (format!("f{i}.pdf"), 1)).collect(); - let named: Vec<(&str, usize)> = files.iter().map(|(n, p)| (n.as_str(), *p)).collect(); - // Narrow enough for several rows. - let mut h = grid_of(named.iter().map(|(n, p)| (*n, fixture(*p))).collect(), vec2(760.0, 1200.0)); - let top = card(&h, "f0.pdf").top(); - let cols = (0..9).filter(|i| (card(&h, &format!("f{i}.pdf")).top() - top).abs() < 1.0).count(); - assert!((2..9).contains(&cols), "several cards per row and several rows ({cols} per row)"); - h.get_by_label("f0.pdf").click(); - h.run_steps(1); - h.key_press(Key::ArrowRight); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1]); - h.key_press(Key::ArrowDown); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1 + cols], "down one row, same column"); - h.key_press(Key::ArrowUp); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1]); - h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowDown); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), (1..=1 + cols).collect::>(), "Shift extends from the anchor"); - // On the first row, Up stays. - h.get_by_label("f0.pdf").click(); - h.run_steps(1); - h.key_press(Key::ArrowUp); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [0]); - // Alt+arrows still move the selection. - h.key_press_modifiers(Modifiers::ALT, Key::ArrowDown); - h.run_steps(1); - assert_eq!(names(&h).first().map(String::as_str), Some("f1.pdf")); -} - -#[test] -fn shift_arrows_extend_the_selection_in_the_list_too() { - // Regression: a plain arrow matched with Shift held, so Shift+Up/Down only stepped. - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1)]); - h.state_mut().set_option("combine-view", "list").unwrap(); - h.run_steps(2); - h.get_by_label("b.pdf").click(); - h.run_steps(1); - h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowDown); - h.run_steps(1); - h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowDown); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1, 2, 3]); - h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowUp); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1, 2]); - h.key_press(Key::ArrowUp); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1], "a plain arrow still steps"); -} - #[test] fn thumbnails_show_the_first_page_each_file_takes() { - let mut h = grid_of_pages(&[("three.pdf", 3), ("one.pdf", 1)]); + // Page 3 is the only landscape page, so the shape of a thumbnail says which page it shows. + let pages = fixture_pages(&[(200.0, 300.0), (200.0, 300.0), (300.0, 200.0)]); + let mut h = grid_of(vec![("three.pdf", pages), ("one.pdf", fixture(1))], vec2(1400.0, 900.0)); h.state_mut().combine_draft[0].range = "3, 1".into(); - assert!(settle(&mut h, |app| app.combine_thumbnails().iter().all(ready)), "{:?}", h.state().combine_thumbnails()); + assert!(settle(&mut h, |app| app.combine_thumbnails().iter().all(ready) && landscape(&app.combine_thumbnails()[0])), "{:?}", h.state().combine_thumbnails()); let thumbs = h.state().combine_thumbnails(); - assert!(matches!(thumbs[0], CombineThumb::Ready { page: 2, .. }), "\"3, 1\" starts with page 3: {:?}", thumbs[0]); - assert!(matches!(thumbs[1], CombineThumb::Ready { page: 0, .. })); - let CombineThumb::Ready { width, height, .. } = thumbs[1] else { unreachable!() }; - // Within MAX_SIDE (combine_grid), which is not visible from here. - assert!(width > 0 && height > 0 && width <= 1536 && height <= 1536, "{width}×{height}"); + assert!(landscape(&thumbs[0]), "\"3, 1\" starts with page 3: {:?}", thumbs[0]); + assert!(portrait(&thumbs[1]), "{:?}", thumbs[1]); + let (width, height) = shape(&thumbs[1]).unwrap(); + // Within the thumbnails' longest side, which is not visible from here. + assert!(width > 0.0 && height > 0.0 && width <= 1536.0 && height <= 1536.0, "{width}×{height}"); // A new range is a new thumbnail, never the old page. h.state_mut().combine_draft[0].range = "2".into(); - assert!(settle(&mut h, |app| matches!(app.combine_thumbnails()[0], CombineThumb::Ready { page: 1, .. }))); + assert!(settle(&mut h, |app| portrait(&app.combine_thumbnails()[0])), "{:?}", h.state().combine_thumbnails()); // A range that can't be used shows no page at all. h.state_mut().combine_draft[0].range = "9".into(); h.run_steps(2); - assert_eq!(h.state().combine_thumbnails()[0], CombineThumb::None); + assert_eq!(h.state().combine_thumbnails()[0], TextureState::Missing); } #[test] fn a_locked_file_shows_no_page_until_unlocked_and_undo_locks_it_again() { let mut h = grid_of(vec![("one.pdf", fixture(1)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0)); assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[0]))); - assert_eq!(h.state().combine_thumbnails()[1], CombineThumb::None, "nothing is drawn of a locked file"); + assert_eq!(h.state().combine_thumbnails()[1], TextureState::Missing, "nothing is drawn of a locked file"); assert!(h.state_mut().combine_unlock_rows(&[1], "pw")); assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[1])), "{:?}", h.state().combine_thumbnails()); // Undo brings back the locked file: its unlocked thumbnail goes with the password. h.key_press_modifiers(Modifiers::COMMAND, Key::Z); h.run_steps(3); assert!(h.state().combine_draft[1].lock.is_some()); - assert_eq!(h.state().combine_thumbnails()[1], CombineThumb::None); + assert_eq!(h.state().combine_thumbnails()[1], TextureState::Missing); // Unlocked again (a new branch of the history): drawn again, from this unlock. assert!(h.state_mut().combine_unlock_rows(&[1], "pw")); assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[1])), "{:?}", h.state().combine_thumbnails()); } -#[test] -fn many_files_render_only_what_is_in_view_a_few_at_a_time() { - // The first few are slow to draw, so renders are still under way while the frames are watched - // (small pages can all be drawn before the first look). - let files: Vec<(String, Vec)> = (0..200).map(|i| (format!("scan{i:03}.pdf"), if i < 6 { heavy() } else { fixture(1) })).collect(); - let mut h = grid_after(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1200.0, 800.0), 0); - let mut most = 0; - let mut done = false; - for _ in 0..800 { - h.run_steps(1); - // Every render thread counts, including those of finished renders not yet exited. - most = most.max(h.state_mut().combine_thumbnail_threads()); - let app = h.state(); - if app.combine_thumbnails().first().is_some_and(ready) && app.combine_thumbnails_rendering() == 0 { - done = true; - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - assert!(done, "the first cards render"); - assert!(most > 0, "renders were seen under way"); - assert!(most <= 3, "never more than three render threads at once ({most})"); - let thumbs = h.state().combine_thumbnails(); - let drawn = thumbs.iter().filter(|t| ready(t)).count(); - assert!(drawn > 0 && drawn < 60, "only the cards in view (and a row either side) are rendered: {drawn} of 200"); - assert_eq!(thumbs.last(), Some(&CombineThumb::None), "the last card, far out of view, isn't rendered"); -} - -#[test] -fn removing_a_file_while_it_renders_and_closing_the_tab_leave_nothing_behind() { - let files: Vec<(String, Vec)> = (0..12).map(|i| (format!("f{i}.pdf"), fixture(2))).collect(); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - // Remove files straight away, while their thumbnails may still be rendering. - h.state_mut().select_combine_rows(&[0, 1, 2]); - h.key_press(Key::Delete); - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0 && app.combine_thumbnails().iter().take(4).all(ready))); - assert_eq!(h.state().combine_thumbnails().len(), 9); - // Undo brings them back, and their thumbnails follow. - h.key_press_modifiers(Modifiers::COMMAND, Key::Z); - assert!(settle(&mut h, |app| app.combine_draft.len() == 12 && app.combine_thumbnails().iter().take(3).all(ready))); - // Closing the tab forgets everything. - h.state_mut().select_combine_rows(&[0]); - h.key_press(Key::Delete); - h.run_steps(1); - h.state_mut().close_combine_tab(); - h.run_steps(2); - assert!(h.state().combine_thumbnails().is_empty()); - assert_eq!(h.state().combine_thumbnails_rendering(), 0); - assert_eq!(h.state().combine_thumbnail_textures(), 0, "no thumbnail texture is kept"); - assert!(settle(&mut h, |app| app.combine_thumbnail_threads_exited()), "every render thread exits"); -} - -#[test] -fn switching_to_the_list_lets_renders_under_way_finish() { - let files: Vec<(String, Vec)> = (0..6).map(|i| (format!("f{i}.pdf"), heavy())).collect(); - let mut h = grid_after_one(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - assert!(h.state().combine_thumbnails_rendering() > 0, "renders are under way"); - // Straight to the list, while the grid's first thumbnails are still rendering. - h.state_mut().set_option("combine-view", "list").unwrap(); - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0), "renders finish and let go of their threads"); - for _ in 0..20 { - h.run_steps(1); - assert_eq!(h.state().combine_thumbnails_rendering(), 0, "nothing new starts in the list"); - } - assert!(h.state().combine_thumbnails().contains(&CombineThumb::None), "the rest wait for the grid"); - assert!(settle(&mut h, |app| app.combine_thumbnail_threads_exited()), "and their threads exit"); - // Back in the grid, the rest follow. - h.get_by_label("Grid view").click(); - assert!(settle(&mut h, |app| app.combine_thumbnails().iter().all(ready))); -} - #[test] fn combine_follows_the_order_shown_in_the_grid() { let mut h = grid_of_pages(&[("one.pdf", 2), ("two.pdf", 1), ("three.pdf", 1)]); @@ -528,645 +315,54 @@ fn combine_follows_the_order_shown_in_the_grid() { assert_eq!(doc.info.outline.iter().map(|o| o.title.as_str()).collect::>(), ["three", "one", "two"]); } -#[test] -fn long_and_unusual_names_are_shortened_on_the_card_but_kept_whole() { - if crate::support::skip_without_glyphs("long_and_unusual_names_are_shortened_on_the_card_but_kept_whole", "en", "日本語のファイル名.pdf") - { - return; - } - let long = "Überweisungsbestätigung für das dritte Quartal 2026 – Endfassung (unterschrieben).pdf"; - let mut h = grid_of(vec![(long, fixture(1)), ("日本語のファイル名.pdf", fixture(1)), ("a&b 'd'.pdf", fixture(1))], vec2(1400.0, 900.0)); - // The card's label is the whole name; only the drawing is shortened. - h.get_by_label(long); - h.get_by_label("日本語のファイル名.pdf"); - h.get_by_label("a&b 'd'.pdf"); - assert!(settle(&mut h, |app| app.combine_thumbnails().iter().all(ready))); -} - -#[test] -fn long_thin_pages_get_thumbnails_within_the_size_limits() { - // Regression: the scale came from the rounded width alone, so a strip 1 pt wide and 999 pt - // long asked for a 9×8192 raster, over the GPU texture limit (a panic in load_texture). - let files = vec![ - ("strip.pdf", fixture_sized(1, 1.0, 999.0)), - ("tall.pdf", fixture_sized(1, 10.0, 3000.0)), - ("wide.pdf", fixture_sized(1, 3000.0, 10.0)), - ("big.pdf", fixture_sized(1, 14400.0, 14400.0)), - ]; - let mut h = grid_of(files, vec2(1400.0, 900.0)); - assert!(settle(&mut h, |app| app.combine_thumbnails().iter().all(|t| *t != CombineThumb::None && *t != CombineThumb::Pending))); - for t in h.state().combine_thumbnails() { - match t { - // Within MAX_SIDE (combine_grid), which is not visible from here. - CombineThumb::Ready { width, height, .. } => assert!(width <= 1536 && height <= 1536, "{width}×{height}"), - other => panic!("each strip gets a thumbnail: {other:?}"), - } - } -} - #[test] fn a_bad_page_range_on_a_card_says_where_to_fix_it() { let mut h = grid_of_pages(&[("a.pdf", 3), ("b.pdf", 1)]); h.state_mut().combine_draft[0].range = "9".into(); h.run_steps(2); - let a = card(&h, "a.pdf"); - h.hover_at(a.center()); - for _ in 0..60 { - h.run_steps(1); - if h.query_by_label_contains("Switch to List view to change the pages it takes").is_some() { - break; - } - } h.get_by_label_contains("Switch to List view to change the pages it takes"); } -#[test] -fn a_file_whose_pages_cant_be_measured_says_there_is_no_preview() { - // An RC4 owner password opens the file for combining but not for reading it here, so the - // page's size is unknown and nothing is drawn. Regression: the card was a blank white page. - // The fixture must keep the size unknown: if the inspector learns RC4 owner passwords, this - // needs another file it can't measure (the check below says so rather than pass vacuously). - let mut h = - grid_of(vec![("one.pdf", fixture(1)), ("old.pdf", protected_with(pdfcraft_cos::Algorithm::Rc4_128, "pw", "owner"))], vec2(1400.0, 900.0)); - assert!(h.state_mut().combine_unlock_rows(&[1], "owner")); - assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[0]))); - assert!(h.state().combine_draft[1].lock.is_none(), "unlocked for combining"); - assert_eq!(h.state().combine_thumbnails()[1], CombineThumb::None, "nothing rendered (is the page size still unknown?)"); - assert_eq!(h.state().combine_thumbnails_rendering(), 0); - // Screen readers hear it too, not only in the tooltip. - let description = |h: &Harness<'static, PdfCraftApp>, name: &str| h.get_by_label(name).accesskit_node().description().unwrap_or_default(); - assert!(description(&h, "old.pdf").contains("No preview"), "{}", description(&h, "old.pdf")); - assert_eq!(description(&h, "one.pdf"), "1 page"); - let tip_of = |h: &mut Harness<'static, PdfCraftApp>, name: &str, text: &str| { - let at = card(h, name).center(); - h.hover_at(at); - (0..60).any(|_| { - h.run_steps(1); - h.query_by_label_contains(text).is_some() - }) - }; - assert!(tip_of(&mut h, "old.pdf", "No preview"), "the card says why it shows no page"); - h.hover_at(egui::pos2(5.0, 890.0)); - h.run_steps(3); - assert!(!tip_of(&mut h, "one.pdf", "No preview"), "a card with its page doesn't"); -} - -#[test] -fn thumbnails_under_way_finish_on_home_and_in_a_document_tab() { - // Regression: they were only collected while the Combine page was drawn. - let files: Vec<(String, Vec)> = (0..6).map(|i| (format!("f{i}.pdf"), heavy())).collect(); - let mut h = grid_after_one(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - assert!(h.state().combine_thumbnails_rendering() > 0, "renders are under way"); - // Home. - h.state_mut().combine_tab.focused = false; - h.run_steps(1); - assert!(!h.state().combine_showing()); - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0 && app.combine_thumbnail_threads_exited())); - // A document tab: the same. - h.state_mut().open_combine_tab(); - h.run_steps(1); - h.state_mut().open_bytes("doc.pdf", None, fixture(1)).unwrap(); - h.run_steps(1); - assert!(h.state().active.is_some()); - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0 && app.combine_thumbnail_threads_exited())); -} - -#[test] -fn a_focused_card_still_takes_the_arrow_keys() { - // Regression: the keys were ignored whenever any widget, a card included, had focus. - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1)]); - h.get_by_label("a.pdf").click(); - h.run_steps(1); - h.get_by_label("a.pdf").focus(); - h.run_steps(1); - h.key_press(Key::ArrowRight); - h.run_steps(1); - assert_eq!(h.state().combine_selection(), [1]); -} - -#[test] -fn a_drag_is_dropped_when_the_list_changes_under_it() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1)]); - h.state_mut().select_combine_rows(&[3]); - h.key_press(Key::Delete); - h.run_steps(2); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf"]); - // A drag begins; undo brings d.pdf back while it is under way; then the card is dropped. - let (a, c) = (card(&h, "a.pdf"), card(&h, "c.pdf")); - let to = c.center() + vec2(c.width() * 0.3, 0.0); - h.hover_at(a.center()); - h.run_steps(1); - h.drag_at(a.center()); - h.run_steps(1); - for k in 1..=3 { - h.hover_at(a.center() + (to - a.center()) * (k as f32 / 6.0)); - h.run_steps(1); - } - h.key_press_modifiers(Modifiers::COMMAND, Key::Z); - h.run_steps(1); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf", "d.pdf"]); - h.hover_at(to); - h.run_steps(1); - h.drop_at(to); - h.run_steps(3); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf", "d.pdf"], "the gap it was aimed at no longer means the same: nothing moves"); -} - -#[test] -fn a_card_dragged_to_the_bottom_edge_scrolls_the_grid_and_still_drops() { - let files: Vec<(String, Vec)> = (0..30).map(|i| (format!("f{i:02}.pdf"), fixture(1))).collect(); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(820.0, 860.0)); - let from = card(&h, "f00.pdf").center(); - let totals = h.get_by_label_contains("30 files").rect(); - let edge = egui::pos2(from.x, totals.top() - 30.0); - h.hover_at(from); - h.run_steps(1); - h.drag_at(from); - h.run_steps(1); - h.hover_at(edge); - // Held at the edge, the grid scrolls; the card dragged leaves the rows drawn. - for _ in 0..80 { - h.run_steps(1); - } - assert!(h.query_by_label("f00.pdf").is_none(), "scrolled away from the first row"); - // A card wholly in view (rows just outside it are drawn too, to scroll smoothly). - let top = h.get_by_label("Grid view").rect().bottom() + 40.0; - let (target_name, target) = (1..30) - .map(|i| format!("f{i:02}.pdf")) - .find_map(|n| h.query_by_label(&n).map(|c| c.rect()).filter(|r| r.top() > top && r.bottom() < totals.top() - 20.0).map(|r| (n, r))) - .expect("a card in view"); - let to = target.center() - vec2(target.width() * 0.3, 0.0); - h.hover_at(to); - h.run_steps(1); - h.drop_at(to); - h.run_steps(3); - let order = names(&h); - let at = order.iter().position(|n| n == "f00.pdf").unwrap(); - assert!(at > 0, "moved from the start: {order:?}"); - assert_eq!(order.get(at + 1), Some(&target_name), "dropped before {target_name}: {order:?}"); -} - -/// Check that right-clicking a locked card selects that card and offers Unlock for it. -#[test] -fn a_locked_card_offers_unlock_on_a_right_click() { - let mut h = grid_of(vec![("one.pdf", fixture(1)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0)); - h.get_by_label("secret.pdf").click_secondary(); - h.run_steps(2); - // The menu's item comes after the toolbar's button of the same name. - h.get_all_by_label("Unlock…").last().unwrap().click(); - h.run_steps(2); - wait_for_label(&mut h, "Unlock secret.pdf"); - h.get_by_label("Unlock secret.pdf"); - assert_eq!(h.state().combine_selection(), [1], "the card right-clicked is the one unlocked"); -} - -fn disabled(h: &Harness<'static, PdfCraftApp>, label: &str) -> bool { - h.get_by_label(label).accesskit_node().is_disabled() -} - -/// Ctrl/⌘ with the wheel at `at` (a positive `dy` zooms in). -fn ctrl_wheel(h: &mut Harness<'static, PdfCraftApp>, at: Pos2, dy: f32) { - h.hover_at(at); - h.run_steps(1); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, dy), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::COMMAND, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(3); -} - -#[test] -fn the_toolbar_sizes_the_cards_within_limits_and_the_size_is_kept_in_the_settings() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 2)]); - assert_eq!(h.state().combine_zoom, 1.0); - let before = card(&h, "a.pdf"); - h.get_by_label("Larger pages").click(); - h.run_steps(3); - assert_eq!(h.state().combine_zoom, 1.25); - let after = card(&h, "a.pdf"); - assert!(after.width() > before.width() && after.height() > before.height(), "{before:?} → {after:?}"); - // Larger until it can't go further: 500% (#2531), and the button says so. - for _ in 0..12 { - if disabled(&h, "Larger pages") { - break; - } - h.get_by_label("Larger pages").click(); - h.run_steps(2); - } - assert_eq!(h.state().combine_zoom, 5.0); - assert!(disabled(&h, "Larger pages")); - // The percentage resets it. - h.get_by_label("Reset page size").click(); - h.run_steps(2); - assert_eq!(h.state().combine_zoom, 1.0); - for _ in 0..10 { - if disabled(&h, "Smaller pages") { - break; - } - h.get_by_label("Smaller pages").click(); - h.run_steps(2); - } - assert_eq!(h.state().combine_zoom, 0.6); - let smallest = card(&h, "a.pdf"); - assert!(smallest.width() < before.width() && smallest.height() < before.height(), "{smallest:?}"); - // Kept in the settings, and read back; a damaged setting is clamped or ignored. - let saved = h.state().persist(); - let mut fresh = PdfCraftApp::new(); - fresh.restore(&saved); - assert_eq!(fresh.combine_zoom, 0.6); - fresh.restore(r#"{"combine_zoom": 99}"#); - assert_eq!(fresh.combine_zoom, 5.0); - fresh.restore(r#"{"combine_zoom": "big"}"#); - assert_eq!(fresh.combine_zoom, 5.0); - // Scriptable in percent, with a clear refusal outside the range. - let app = h.state_mut(); - app.set_option("combine-zoom", "150%").unwrap(); - assert_eq!(app.combine_zoom, 1.5); - // #2531: 200% was not enough to read a value off a card; 500% has to be reachable. - for pct in ["200", "300", "400", "500"] { - app.set_option("combine-zoom", pct).unwrap(); - assert_eq!(app.combine_zoom, pct.parse::().unwrap() / 100.0); - } - for bad in ["59", "501", "big", "NaN", "inf", ""] { - assert!(app.set_option("combine-zoom", bad).is_err(), "{bad:?}"); - } - assert_eq!(app.combine_zoom, 5.0, "a refused value leaves the size alone"); - // The list has no card size. - h.get_by_label("List view").click(); - h.run_steps(2); - assert!(h.query_by_label("Larger pages").is_none() && h.query_by_label("Page size").is_none()); -} - -#[test] -fn the_slider_sizes_the_cards_from_smallest_to_largest() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1)]); - let slider = h.get_by_label("Page size").rect(); - drag(&mut h, slider.center(), slider.right_center() + vec2(40.0, 0.0)); - assert_eq!(h.state().combine_zoom, 5.0); - let slider = h.get_by_label("Page size").rect(); - drag(&mut h, slider.center(), slider.left_center() - vec2(40.0, 0.0)); - assert_eq!(h.state().combine_zoom, 0.6); - // The cards are still there and in order. - assert_eq!(names(&h), ["a.pdf", "b.pdf"]); - assert!(card(&h, "a.pdf").left() < card(&h, "b.pdf").left()); -} - -#[test] -fn ctrl_keys_and_ctrl_wheel_size_the_cards_and_leave_the_window_alone() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1)]); - h.key_press_modifiers(Modifiers::COMMAND, Key::Equals); - h.run_steps(3); - assert_eq!(h.state().combine_zoom, 1.25); - h.key_press_modifiers(Modifiers::COMMAND, Key::Plus); - h.run_steps(3); - assert_eq!(h.state().combine_zoom, 1.5); - h.key_press_modifiers(Modifiers::COMMAND, Key::Minus); - h.run_steps(3); - assert_eq!(h.state().combine_zoom, 1.25); - h.key_press_modifiers(Modifiers::COMMAND, Key::Num0); - h.run_steps(3); - assert_eq!(h.state().combine_zoom, 1.0); - assert_eq!(h.ctx.zoom_factor(), 1.0, "the window's text keeps its size"); - // Ctrl/⌘ with the wheel over the grid: in, then out. - let at = card(&h, "b.pdf").center(); - ctrl_wheel(&mut h, at, 120.0); - let zoomed = h.state().combine_zoom; - assert!(zoomed > 1.0, "{zoomed}"); - let at = card(&h, "b.pdf").center(); - ctrl_wheel(&mut h, at, -240.0); - assert!(h.state().combine_zoom < zoomed, "{}", h.state().combine_zoom); - // Not over the grid (the toolbar): nothing. - let now = h.state().combine_zoom; - let toolbar = h.get_by_label("Grid view").rect().center(); - ctrl_wheel(&mut h, toolbar, 120.0); - assert_eq!(h.state().combine_zoom, now); - // Nor in the list. - h.get_by_label("List view").click(); - h.run_steps(2); - h.key_press_modifiers(Modifiers::COMMAND, Key::Equals); - h.run_steps(2); - assert_eq!(h.state().combine_zoom, now); -} - -/// Check that wheel zoom keeps the card under the pointer fixed and never blanks its thumbnail while a -/// sharper render arrives. -#[test] -fn zooming_keeps_the_card_under_the_pointer_in_place_and_thumbnails_never_go_blank() { - let files: Vec<(String, Vec)> = (0..40).map(|i| (format!("f{i:02}.pdf"), fixture(1))).collect(); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - // Scroll down a little, so the grid isn't simply at its top. - let first = card(&h, "f00.pdf"); - h.hover_at(first.center()); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -300.0), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(6); - // A card fully in view, below the toolbar, with its thumbnail drawn. - let toolbar = h.get_by_label("Grid view").rect().bottom(); - let pick = files - .iter() - .map(|(n, _)| n.as_str()) - .find(|n| h.query_by_label(n).is_some_and(|c| c.rect().top() > toolbar + 80.0 && c.rect().bottom() < 820.0)) - .expect("a card in view") - .to_string(); - let i = names(&h).iter().position(|n| *n == pick).unwrap(); - assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[i]))); - let CombineThumb::Ready { height: small, .. } = h.state().combine_thumbnails()[i] else { unreachable!() }; - let before = card(&h, &pick); - h.hover_at(before.center()); - h.run_steps(1); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, 120.0), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::COMMAND, - source: egui::MouseWheelSource::Unknown, - }); - // The wheel zooms smoothly over several frames; in every one the card stays put. - let mut zooms = Vec::new(); - for frame in 0..12 { - h.run_steps(1); - zooms.push(h.state().combine_zoom); - let now = card(&h, &pick); - assert!((now.top() - before.top()).abs() < 2.0, "frame {frame}: the card under the pointer moved: {before:?} → {now:?}"); - } - assert!(h.state().combine_zoom > 1.0, "{zooms:?}"); - // Its thumbnail never went blank: the smaller one stands in until the sharper one arrives. - for _ in 0..400 { - h.run_steps(1); - match h.state().combine_thumbnails()[i] { - CombineThumb::Ready { height, .. } if height > small => break, - CombineThumb::Ready { .. } => {} - ref other => panic!("went blank: {other:?}"), - } - std::thread::sleep(Duration::from_millis(10)); - } - assert!(matches!(h.state().combine_thumbnails()[i], CombineThumb::Ready { height, .. } if height > small), "re-rendered larger"); -} - -#[test] -fn cards_at_the_top_zoom_render_a_sharper_thumbnail_within_the_texture_limit() { - // #2531: raising the ceiling is only worth something if the thumbnail gets sharper with it. - // The texture cap was 768px, which upscaled any card past 200%. - let mut h = grid_of_pages(&[("a.pdf", 1)]); - h.state_mut().set_option("combine-zoom", "100").unwrap(); - assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[0]))); - let CombineThumb::Ready { width: w0, height: h0, .. } = h.state().combine_thumbnails()[0] else { unreachable!() }; - let at_100 = w0.max(h0); - - h.state_mut().set_option("combine-zoom", "500").unwrap(); - // The old thumbnail stands in until the sharper one arrives, so "ready" is not enough: wait - // for the size to actually change. - let mut redrawn = false; - for _ in 0..400 { - h.run_steps(1); - if matches!(h.state().combine_thumbnails()[0], CombineThumb::Ready { width, height, .. } if width.max(height) != at_100) { - redrawn = true; - break; - } - std::thread::sleep(Duration::from_millis(10)); - } - let CombineThumb::Ready { width, height, .. } = h.state().combine_thumbnails()[0] else { unreachable!() }; - let at_500 = width.max(height); - assert!(redrawn, "500% never re-rendered the thumbnail: {width}×{height}"); - assert!(at_500 <= 1536, "past the texture limit: {width}×{height}"); - assert!(at_500 >= at_100 * 4, "500% is not sharper than 100%: {at_100}px → {at_500}px"); -} - -// 60% against a large size, rather than the largest: at 500% a card is wider than this viewport, -// so only one fits across and "down moves a row" would have nothing to check. -#[test] -fn dragging_and_arrow_keys_work_at_the_smallest_and_a_large_size() { - let mut columns = Vec::new(); - for zoom in ["60", "200"] { - let files: Vec<(String, Vec)> = (0..24).map(|i| (format!("f{i:02}.pdf"), fixture(1))).collect(); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - h.state_mut().set_option("combine-zoom", zoom).unwrap(); - h.run_steps(3); - let (a, c) = (card(&h, "f00.pdf"), card(&h, "f02.pdf")); - drag(&mut h, a.center(), c.center() + vec2(c.width() * 0.3, 0.0)); - assert_eq!(&names(&h)[..4], ["f01.pdf", "f02.pdf", "f00.pdf", "f03.pdf"], "at {zoom}%"); - // Down moves one row: as many files as fit across. - h.get_by_label("f01.pdf").click(); - h.run_steps(1); - h.key_press(Key::ArrowDown); - h.run_steps(2); - let row = h.state().combine_selection(); - assert_eq!(row.len(), 1); - assert!(row[0] > 1, "at {zoom}%: {row:?}"); - columns.push(row[0]); - } - assert!(columns[0] > columns[1], "more cards fit across when they are smaller: {columns:?}"); -} - -#[test] -fn zooming_quickly_never_runs_more_than_three_render_threads() { - let files: Vec<(String, Vec)> = (0..60).map(|i| (format!("f{i:02}.pdf"), if i < 6 { heavy() } else { fixture(1) })).collect(); - let mut h = grid_after(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0), 0); - let mut most = 0; - for k in 0..80 { - let key = if (k / 5) % 2 == 0 { Key::Equals } else { Key::Minus }; - h.key_press_modifiers(Modifiers::COMMAND, key); - h.run_steps(1); - let threads = h.state_mut().combine_thumbnail_threads(); - most = most.max(threads); - assert!(threads <= 3, "frame {k}: {threads} render threads"); - std::thread::sleep(Duration::from_millis(3)); - } - assert!(most > 0, "renders were seen under way"); - // And it settles: the cards in view all get their thumbnails. - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0 && app.combine_thumbnails().first().is_some_and(ready))); -} - -/// The grid with 40 one-page files, scrolled down by `dy`; and where the top of the grid is. -fn scrolled_grid(dy: f32) -> (Harness<'static, PdfCraftApp>, f32) { - let files: Vec<(String, Vec)> = (0..40).map(|i| (format!("f{i:02}.pdf"), fixture(1))).collect(); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - // Unscrolled, the first card sits a fixed space (12 points) below the top of the grid. - let top = card(&h, "f00.pdf").top() - 12.0; - let at = card(&h, "f00.pdf").center(); - h.hover_at(at); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -dy), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(8); - (h, top) -} - -/// The first card (in list order) still showing below `top`. -fn first_in_view(h: &Harness<'static, PdfCraftApp>, top: f32) -> String { - names(h).into_iter().find(|n| h.query_by_label(n).is_some_and(|c| c.rect().bottom() > top)).expect("a card in view") -} - -#[test] -fn zooming_from_the_toolbar_while_scrolled_keeps_the_top_cards_in_place() { - // Regression: with the pointer over the toolbar, a card drawn just above the view (under the - // toolbar) was taken as the one to keep in place, and the cards in view jumped. - for how in ["keys", "button", "slider"] { - let (mut h, top) = scrolled_grid(700.0); - let anchor = first_in_view(&h, top); - let before = card(&h, &anchor).top(); - let over_toolbar = egui::pos2(card(&h, &anchor).center().x, h.get_by_label("Grid view").rect().center().y); - h.hover_at(over_toolbar); - h.run_steps(1); - match how { - "keys" => h.key_press_modifiers(Modifiers::COMMAND, Key::Equals), - "button" => h.get_by_label("Larger pages").click(), - _ => { - let s = h.get_by_label("Page size").rect(); - drag(&mut h, s.center(), s.right_center() + vec2(40.0, 0.0)); - } - } - h.run_steps(3); - assert!(h.state().combine_zoom > 1.0, "{how}"); - let after = card(&h, &anchor).top(); - assert!((after - before).abs() < 2.0, "{how}: {anchor} moved from {before} to {after}"); - } -} - -/// Check that zooming out at the bottom keeps the last card in place without leaving a gap below it. -#[test] -fn zooming_out_at_the_bottom_leaves_no_gap_below_the_last_card() { - let (mut h, _) = scrolled_grid(20_000.0); - h.state_mut().set_option("combine-zoom", "200").unwrap(); - h.run_steps(2); - // Over the middle of the grid. - h.hover_at(egui::pos2(900.0, 600.0)); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -20_000.0), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(8); - let bottom = card(&h, "f39.pdf").bottom(); - h.get_by_label("Smaller pages").click(); - for frame in 0..6 { - h.run_steps(1); - let now = card(&h, "f39.pdf").bottom(); - assert!((now - bottom).abs() < 2.0, "frame {frame}: the last card left a gap below it ({bottom} → {now})"); - } - assert_eq!(h.state().combine_zoom, 1.75); -} - -#[test] -fn the_size_slider_takes_the_arrow_keys_when_it_has_the_keyboard() { - // Regression: the grid's arrow keys moved the selection instead. - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1)]); - h.get_by_label("a.pdf").click(); - h.run_steps(1); - h.get_by_label("Page size").focus(); - h.run_steps(1); - h.key_press(Key::ArrowRight); - h.run_steps(2); - assert!(h.state().combine_zoom > 1.0, "{}", h.state().combine_zoom); - assert_eq!(h.state().combine_selection(), [0], "the selection stays"); - let node = h.get_by_label("Page size"); - assert!(node.accesskit_node().numeric_value().is_some_and(|v| v > 100.0), "read out as a percentage"); -} - -#[test] -fn the_toolbar_fits_the_smallest_window() { - // 820 points is the narrowest the window goes. - let mut h = grid_after(vec![("a.pdf", fixture(1)), ("b.pdf", fixture(1))], vec2(820.0, 700.0), 4); - h.get_by_label("a.pdf").click(); - h.run_steps(1); - h.get_by_label("b.pdf").click_modifiers(Modifiers::COMMAND); - h.run_steps(2); - let controls: Vec = [ - "Add open documents", - "Undo", - "Redo", - "Grid view", - "List view", - "2 selected", - "Smaller pages", - "Page size", - "Reset page size", - "Larger pages", - ] - .iter() - .map(|l| h.get_by_label(l).rect()) - .collect(); - for (i, a) in controls.iter().enumerate() { - assert!(a.right() <= 820.0, "{i}: {a:?} is off the window"); - for b in controls.iter().skip(i + 1) { - assert!(!a.intersects(*b), "{a:?} overlaps {b:?}"); - } - } -} - -/// The pointer over a card (its centre, below the bar of actions at the top of its page). +/// The pointer over a tile (its centre), which shows the tile's own actions. fn hover_card(h: &mut Harness<'static, PdfCraftApp>, name: &str) { let at = card(h, name).center(); h.hover_at(at); h.run_steps(2); } -/// A primary click at a point, as a user makes one. -fn click_at(h: &mut Harness<'static, PdfCraftApp>, at: Pos2) { - h.hover_at(at); - h.run_steps(1); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(1); +/// Click the Remove action of the tile the pointer is over (the toolbar's own Remove comes before it). +fn remove_hovered(h: &mut Harness<'static, PdfCraftApp>) { + h.get_all_by_label("Remove").last().expect("the hovered tile offers Remove").click(); + h.run_steps(2); } -#[test] -fn hovering_a_card_shows_its_trash_and_magnifier_and_only_then() { - let mut h = grid_of(vec![("a.pdf", fixture(1)), ("b.pdf", fixture(3)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0)); - h.hover_at(egui::pos2(5.0, 890.0)); - h.run_steps(2); - assert!(h.query_by_label("Preview").is_none() && h.query_by_label("Remove a.pdf").is_none(), "nothing until a card is hovered"); - hover_card(&mut h, "a.pdf"); - h.get_by_label("Preview"); - h.get_by_label("Remove a.pdf"); - // Over the bar itself it stays (the pointer is still on the card). - let bar = h.get_by_label("Preview").rect().center(); - h.hover_at(bar); - h.run_steps(2); - h.get_by_label("Remove a.pdf"); - // Another card: its own. - hover_card(&mut h, "b.pdf"); - h.get_by_label("Remove b.pdf"); - assert!(h.query_by_label("Remove a.pdf").is_none()); - // A locked file has nothing to show large, but can still be removed. - hover_card(&mut h, "secret.pdf"); - h.get_by_label("Remove secret.pdf"); - assert!(h.query_by_label("Preview").is_none(), "no magnifier on a locked file"); +/// A page tile's label: "Page 3 · b.pdf". +fn page_card(page: usize, name: &str) -> String { + format!("Page {page} · {name}") } -#[test] -fn the_card_trash_removes_only_that_file_and_undo_brings_it_back() { +/// Expand a file from its tile's own action. +fn expand(h: &mut Harness<'static, PdfCraftApp>, name: &str) { + hover_card(h, name); + h.get_by_label("Expand").click(); + h.run_steps(2); +} + +/// Trash removes only its own file, whatever else is selected, in one undo step. +fn row_remove_acts_on_its_own_file() { let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1), ("d.pdf", 1)]); h.get_by_label("b.pdf").click(); h.run_steps(1); h.get_by_label("c.pdf").click_modifiers(Modifiers::COMMAND); h.run_steps(1); - // The trash of a card that isn't selected: that file only, the selection stays. + // The trash of a tile that isn't selected: that file only, the selection stays. hover_card(&mut h, "a.pdf"); - h.get_by_label("Remove a.pdf").click(); - h.run_steps(2); + remove_hovered(&mut h); assert_eq!(names(&h), ["b.pdf", "c.pdf", "d.pdf"]); assert_eq!(h.state().combine_selection(), [0, 1], "b and c stay selected"); - // The trash of a selected card: still that file only. + // The trash of a selected tile: still that file only. hover_card(&mut h, "b.pdf"); - h.get_all_by_label("Remove b.pdf").last().unwrap().click(); - h.run_steps(2); + remove_hovered(&mut h); assert_eq!(names(&h), ["c.pdf", "d.pdf"]); assert_eq!(h.state().combine_selection(), [0], "c stays selected"); // One undo step each. @@ -1178,261 +374,53 @@ fn the_card_trash_removes_only_that_file_and_undo_brings_it_back() { assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf", "d.pdf"]); } -#[test] -fn the_magnifier_shows_the_file_large_and_flips_through_the_pages_it_adds() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 4)]); - h.state_mut().combine_draft[1].range = "3, 1".into(); +/// Preview opens the tile's own file, from its first page; the grid's selection stays. +fn row_preview_opens_that_file() { + let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 3)]); h.get_by_label("a.pdf").click(); h.run_steps(1); - assert!(settle(&mut h, |app| ready(&app.combine_thumbnails()[1]))); - let CombineThumb::Ready { width: card_width, .. } = h.state().combine_thumbnails()[1] else { unreachable!() }; hover_card(&mut h, "b.pdf"); h.get_by_label("Preview").click(); h.run_steps(2); - // The card under it says nothing over it (its tooltip, its actions). - for _ in 0..150 { - h.run_steps(1); - } - assert!(h.query_by_label_contains("4 pages ·").is_none(), "no card tooltip over the preview"); - assert!(h.query_by_label("Remove b.pdf").is_none(), "no card actions over the preview"); - // The first page it adds: page 3. - let (name, page, _) = h.state().combine_preview().expect("shown large"); - assert_eq!((name.as_str(), page), ("b.pdf", 2)); - h.get_by_label("Page 1 of 2"); - assert!(disabled(&h, "Previous page")); - // Rendered larger than its card. - assert!( - settle(&mut h, |app| matches!(app.combine_preview(), Some((_, _, CombineThumb::Ready { width, .. })) if width > card_width)), - "{:?}", - h.state().combine_preview() - ); - // The arrow keys flip, and stop at the ends; the grid's selection doesn't move. - h.key_press(Key::ArrowRight); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0), "then page 1"); - h.get_by_label("Page 2 of 2"); - assert!(disabled(&h, "Next page")); - h.key_press(Key::ArrowRight); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0)); - h.get_by_label("Previous page").click(); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(2)); + assert_eq!(h.state().combine_preview(), Some(("b.pdf".to_string(), 0))); assert_eq!(h.state().combine_selection(), [0]); - // Esc closes it; so do the close button and a click outside. - h.key_press(Key::Escape); - h.run_steps(2); - assert!(h.state().combine_preview().is_none()); - for how in ["close", "outside"] { - hover_card(&mut h, "b.pdf"); - h.get_by_label("Preview").click(); - h.run_steps(2); - assert!(h.state().combine_preview().is_some(), "{how}"); - match how { - "close" => h.get_by_label("Close").click(), - _ => click_at(&mut h, egui::pos2(6.0, 6.0)), - } - h.run_steps(2); - assert!(h.state().combine_preview().is_none(), "{how}"); - } - assert_eq!(names(&h), ["a.pdf", "b.pdf"], "nothing else changed"); } -#[test] -fn a_right_click_on_a_card_offers_preview_and_remove() { - let mut h = grid_of_pages(&[("a.pdf", 2), ("b.pdf", 1)]); - h.get_by_label("a.pdf").click_secondary(); - h.run_steps(2); - // The menu's items come after the card's own buttons of the same name. - h.get_all_by_label("Preview").last().unwrap().click(); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| (p.0, p.1)), Some(("a.pdf".to_string(), 0))); - h.key_press(Key::Escape); - h.run_steps(2); - h.get_by_label("b.pdf").click_secondary(); - h.run_steps(2); - h.get_all_by_label("Remove b.pdf").last().unwrap().click(); - h.run_steps(2); - assert_eq!(names(&h), ["a.pdf"]); -} - -#[test] -fn the_preview_closes_when_its_file_leaves_and_keeps_to_three_render_threads() { - let files: Vec<(String, Vec)> = (0..12).map(|i| (format!("f{i:02}.pdf"), heavy())).collect(); - let mut h = grid_after_one(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - hover_card(&mut h, "f03.pdf"); - h.get_by_label("Preview").click(); - let (mut most, mut rendered) = (0, false); - for frame in 0..60 { - h.run_steps(1); - let threads = h.state_mut().combine_thumbnail_threads(); - most = most.max(threads); - assert!(threads <= 3, "frame {frame}: {threads} render threads"); - // The large page itself is rendered (under way, or done) among them. - rendered |= matches!(h.state().combine_preview(), Some((_, _, CombineThumb::Pending | CombineThumb::Ready { .. }))); - std::thread::sleep(Duration::from_millis(5)); - } - assert!(most > 0); - assert!(rendered, "the preview's own render ran: {:?}", h.state().combine_preview()); - // The file leaves the list (as undo of its adding would): the preview closes, nothing stays. - h.state_mut().combine_draft.retain(|f| f.name != "f03.pdf"); - h.run_steps(2); - assert!(h.state().combine_preview().is_none()); - assert!(settle(&mut h, |app| app.combine_thumbnails_rendering() == 0 && app.combine_thumbnail_threads_exited())); -} - -#[test] -fn space_shows_the_selected_file_large_in_the_grid_and_the_list() { - // The way to the preview without a pointer (screen readers, the keyboard). - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 2), ("c.pdf", 1)]); - h.key_press(Key::Space); - h.run_steps(2); - assert!(h.state().combine_preview().is_none(), "nothing selected, nothing shown"); - h.get_by_label("a.pdf").click(); - h.run_steps(1); - h.key_press(Key::ArrowRight); - h.run_steps(1); - h.key_press(Key::Space); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.0), Some("b.pdf".to_string()), "the file the keyboard is on"); - // While it shows, the grid's keys wait: an arrow flips its pages, Delete removes nothing. - h.key_press(Key::ArrowRight); - h.key_press(Key::Delete); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(1)); - assert_eq!(names(&h).len(), 3); - assert_eq!(h.state().combine_selection(), [1]); - h.key_press(Key::Escape); - h.run_steps(2); - assert!(h.state().combine_preview().is_none()); - // The list too. - h.get_by_label("List view").click(); - h.run_steps(2); - h.key_press(Key::Space); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.0), Some("b.pdf".to_string())); -} - -#[test] -fn flipping_quickly_ends_on_the_page_shown_and_leaving_the_tab_closes_the_preview() { - let mut h = grid_of_pages(&[("a.pdf", 6)]); - hover_card(&mut h, "a.pdf"); - h.get_by_label("Preview").click(); - h.run_steps(1); - // A page a frame, faster than they render. - for _ in 0..4 { - h.key_press(Key::ArrowRight); - h.run_steps(1); - } - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(4)); - assert!( - settle(&mut h, |app| matches!(app.combine_preview(), Some((_, 4, CombineThumb::Ready { page: 4, .. })))), - "the render shown is of the page shown: {:?}", - h.state().combine_preview() - ); - // Home, then back: the preview is gone, not waiting there. - h.state_mut().combine_tab.focused = false; - h.run_steps(2); - assert!(h.state().combine_preview().is_none()); - h.state_mut().open_combine_tab(); - h.run_steps(2); - assert!(h.state().combine_preview().is_none()); - assert!(h.query_by_label("Page 5 of 6").is_none()); -} - -#[test] -fn space_on_a_focused_button_presses_it_and_previews_only_what_can_be_shown() { - // Regression: with a file selected, Space opened the preview whatever had the keyboard. - let mut h = - grid_of(vec![("a.pdf", fixture(2)), ("old.pdf", protected_with(pdfcraft_cos::Algorithm::Rc4_128, "pw", "owner"))], vec2(1400.0, 900.0)); - h.get_by_label("a.pdf").click(); - h.run_steps(1); - h.get_by_label("List view").focus(); - h.run_steps(1); - h.key_press(Key::Space); - h.run_steps(2); - assert_eq!(h.state().combine_view, CombineView::List, "the focused button was pressed"); - assert!(h.state().combine_preview().is_none()); - // A file whose pages can't be measured has nothing to show large (its card has no magnifier). - h.get_by_label("Grid view").click(); - h.run_steps(1); - assert!(h.state_mut().combine_unlock_rows(&[1], "owner")); - h.run_steps(2); - h.get_by_label("old.pdf").click(); - h.run_steps(1); - h.key_press(Key::Space); - h.run_steps(2); - assert!(h.state().combine_preview().is_none(), "nothing to show"); -} - -#[test] -fn a_drag_held_while_the_tab_closes_and_reopens_moves_nothing() { - // Regression: closing the tab started the list's revisions over, so a drag begun before could - // match a new list and move one of its files. - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 1), ("c.pdf", 1)]); - let (a, c) = (card(&h, "a.pdf"), card(&h, "c.pdf")); - h.hover_at(a.center()); - h.run_steps(1); - h.drag_at(a.center()); - h.run_steps(1); - h.hover_at(a.center() + vec2(30.0, 0.0)); - h.run_steps(1); - // While held: the tab closes, and the same files come back. - h.state_mut().close_combine_tab(); - h.state_mut().use_files(FilePurpose::Combine, ["a.pdf", "b.pdf", "c.pdf"].iter().map(|n| (n.to_string(), fixture(1))).collect()); - h.run_steps(2); - let to = c.center() + vec2(c.width() * 0.3, 0.0); - h.hover_at(to); - h.run_steps(1); - h.drop_at(to); - h.run_steps(3); - assert_eq!(names(&h), ["a.pdf", "b.pdf", "c.pdf"], "the old drag moves nothing in the new list"); -} - -// ---- Stage 3: a file shown as its pages ---- - -/// The label of a page card: "Page 3 · b.pdf". -fn page_card(page: usize, name: &str) -> String { - format!("Page {page} · {name}") -} - -/// Expand a file from its card's hover bar. -fn expand(h: &mut Harness<'static, PdfCraftApp>, name: &str) { - hover_card(h, name); - h.get_by_label("Expand").click(); - h.run_steps(2); -} - -#[test] -fn expanding_a_file_shows_the_pages_it_adds_in_order_with_their_numbers() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 4)]); +/// A page tile's Preview opens that page of its file. +fn row_page_preview_opens_that_page() { + let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 5)]); + // Pages 3, 1, 4: page 4 is the third the file adds. h.state_mut().combine_draft[1].range = "3, 1, 4".into(); h.run_steps(2); - // A single page has nothing to expand. - hover_card(&mut h, "a.pdf"); - assert!(h.query_by_label("Expand").is_none()); expand(&mut h, "b.pdf"); - assert_eq!(h.state().combine_expanded(), [1]); - assert!(h.query_by_label("b.pdf").is_none(), "the file's card gives way to its pages"); - // The pages it adds, in the range's order, each saying which page of which file. - let xs: Vec = [3, 1, 4].iter().map(|p| card(&h, &page_card(*p, "b.pdf")).left()).collect(); - assert!(xs.windows(2).all(|w| w[0] < w[1]), "pages 3, 1, 4 in that order: {xs:?}"); - assert!(h.query_by_label(&page_card(2, "b.pdf")).is_none(), "page 2 isn't added, so isn't shown"); - // Each renders its own page. - assert!(settle(&mut h, |app| { - let pages = app.combine_page_thumbnails(1); - pages.len() == 3 && pages.iter().all(|(p, t)| matches!(t, CombineThumb::Ready { page, .. } if page == p)) - })); - // A page card collapses the file again. - hover_card(&mut h, &page_card(1, "b.pdf")); - h.get_by_label("Collapse").click(); + hover_card(&mut h, &page_card(4, "b.pdf")); + h.get_by_label("Preview").click(); h.run_steps(2); - assert!(h.state().combine_expanded().is_empty()); - h.get_by_label("b.pdf"); + assert_eq!(h.state().combine_preview(), Some(("b.pdf".to_string(), 3))); } -#[test] -fn expand_all_and_collapse_all_from_the_toolbar_and_a_right_click() { +/// Unlock… is on a locked file's menu only. +fn row_unlock_is_on_a_locked_files_menu_only() { + let mut h = grid_of(vec![("one.pdf", fixture(1)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0)); + // (The toolbar may have an Unlock… of its own: the menu's item is one more.) + let toolbar = h.query_all_by_label("Unlock…").count(); + h.get_by_label("one.pdf").click_secondary(); + h.run_steps(2); + assert_eq!(h.query_all_by_label("Unlock…").count(), toolbar, "an open file's menu adds no Unlock…"); + h.key_press(Key::Escape); + h.run_steps(2); + h.get_by_label("secret.pdf. Password-protected").click_secondary(); + h.run_steps(2); + assert_eq!(h.query_all_by_label("Unlock…").count(), toolbar + 1, "a locked file's menu offers it"); + // The menu's item comes after the toolbar's button of the same name. + h.get_all_by_label("Unlock…").last().unwrap().click(); + h.run_steps(2); + wait_for_label(&mut h, "Unlock secret.pdf"); + h.get_by_label("Unlock secret.pdf"); +} + +/// Expand and Collapse on a tile, and from the toolbar for every file. +fn row_expand_and_collapse() { let mut h = grid_of( vec![("a.pdf", fixture(1)), ("b.pdf", fixture(3)), ("c.pdf", fixture(2)), ("secret.pdf", protected("pw", "owner"))], vec2(1400.0, 900.0), @@ -1445,24 +433,178 @@ fn expand_all_and_collapse_all_from_the_toolbar_and_a_right_click() { h.get_by_label("Collapse all").click(); h.run_steps(2); assert!(h.state().combine_expanded().is_empty()); - // On a right click too (the pointer then off the card, so its hover bar is gone and the - // label is the menu's alone). - h.get_by_label("c.pdf").click_secondary(); - h.run_steps(2); - h.hover_at(egui::pos2(5.0, 890.0)); - h.run_steps(2); - h.get_by_label("Expand").click(); - h.run_steps(2); + expand(&mut h, "c.pdf"); assert_eq!(h.state().combine_expanded(), [2]); - h.get_by_label(&page_card(2, "c.pdf")).click_secondary(); - h.run_steps(2); - h.hover_at(egui::pos2(5.0, 890.0)); - h.run_steps(2); + hover_card(&mut h, &page_card(2, "c.pdf")); h.get_by_label("Collapse").click(); h.run_steps(2); assert!(h.state().combine_expanded().is_empty()); } +/// What each tile action does to its own tile, one row each. +const TILE_ACTIONS: [(&str, fn()); 5] = [ + ("Remove acts on its own file", row_remove_acts_on_its_own_file), + ("Preview opens that file", row_preview_opens_that_file), + ("a page's Preview opens that page", row_page_preview_opens_that_page), + ("Unlock is on a locked file's menu only", row_unlock_is_on_a_locked_files_menu_only), + ("Expand and Collapse", row_expand_and_collapse), +]; + +#[test] +fn tile_actions_act_on_their_own_tile() { + for (name, row) in TILE_ACTIONS { + println!("tile action: {name}"); + row(); + } +} + +#[test] +fn the_preview_shows_the_files_range_in_order_and_the_grid_selection_stays() { + let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 4)]); + h.state_mut().combine_draft[1].range = "3, 1".into(); + h.get_by_label("a.pdf").click(); + h.run_steps(1); + hover_card(&mut h, "b.pdf"); + h.get_by_label("Preview").click(); + h.run_steps(2); + // The first page it adds: page 3. + assert_eq!(h.state().combine_preview(), Some(("b.pdf".to_string(), 2))); + // The page keys flip in the range's order, and stop at the ends; the grid's selection doesn't move. + h.key_press(Key::PageDown); + h.run_steps(2); + assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0), "then page 1"); + h.key_press(Key::PageDown); + h.run_steps(2); + assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0), "the last stays"); + h.key_press(Key::PageUp); + h.run_steps(2); + assert_eq!(h.state().combine_preview().map(|p| p.1), Some(2)); + assert_eq!(h.state().combine_selection(), [0]); + // Escape closes it, and nothing else changed. + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().combine_preview().is_none()); + assert_eq!(names(&h), ["a.pdf", "b.pdf"]); +} + +#[test] +fn the_preview_closes_when_its_file_leaves() { + let mut h = grid_of_pages(&[("f00.pdf", 2), ("f01.pdf", 2), ("f02.pdf", 2)]); + hover_card(&mut h, "f01.pdf"); + h.get_by_label("Preview").click(); + h.run_steps(2); + assert!(h.state().combine_preview().is_some()); + // The file leaves the list (as undo of its adding would): the preview closes. + h.state_mut().combine_draft.retain(|f| f.name != "f01.pdf"); + h.run_steps(2); + assert!(h.state().combine_preview().is_none()); +} + +#[test] +fn leaving_the_tab_closes_the_preview_and_coming_back_does_not_reopen_it() { + let mut h = grid_of_pages(&[("a.pdf", 6)]); + hover_card(&mut h, "a.pdf"); + h.get_by_label("Preview").click(); + h.run_steps(2); + assert!(h.state().combine_preview().is_some()); + // Home, then back: the preview is gone, not waiting there. + h.state_mut().combine_tab.focused = false; + h.run_steps(2); + assert!(h.state().combine_preview().is_none()); + h.state_mut().open_combine_tab(); + h.run_steps(2); + assert!(h.state().combine_preview().is_none()); + assert!(h.query_by_label("Page 1 of 6").is_none()); +} + +#[test] +fn the_toolbar_sizes_the_cards_within_limits_and_the_size_is_kept_in_the_settings() { + let ladder = TileZoom::Ladder.range(); + let (smallest, largest) = (*ladder.start(), *ladder.end()); + let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 2)]); + assert_eq!(h.state().combine_zoom, 1.0); + let before = card(&h, "a.pdf"); + h.get_by_label("Larger Thumbnails").click(); + h.run_steps(3); + assert!(h.state().combine_zoom > 1.0, "{}", h.state().combine_zoom); + let after = card(&h, "a.pdf"); + assert!(after.width() > before.width() && after.height() > before.height(), "{before:?} → {after:?}"); + // Larger until it can't go further, which is the end of the ladder (#2531). + for _ in 0..12 { + h.get_by_label("Larger Thumbnails").click(); + h.run_steps(2); + } + assert_eq!(h.state().combine_zoom, largest); + for _ in 0..14 { + h.get_by_label("Smaller Thumbnails").click(); + h.run_steps(2); + } + assert_eq!(h.state().combine_zoom, smallest); + let smallest_card = card(&h, "a.pdf"); + assert!(smallest_card.width() < before.width() && smallest_card.height() < before.height(), "{smallest_card:?}"); + // Kept in the settings, and read back; a damaged setting is clamped or ignored. + let saved = h.state().persist(); + let mut fresh = PdfCraftApp::new(); + fresh.restore(&saved); + assert_eq!(fresh.combine_zoom, smallest); + fresh.restore(r#"{"combine_zoom": 99}"#); + assert_eq!(fresh.combine_zoom, largest); + fresh.restore(r#"{"combine_zoom": "big"}"#); + assert_eq!(fresh.combine_zoom, largest); + // Scriptable in percent, with a clear refusal outside the range. + let app = h.state_mut(); + app.set_option("combine-zoom", "150%").unwrap(); + assert_eq!(app.combine_zoom, 1.5); + // #2531: 200% was not enough to read a value off a card; 500% has to be reachable. + for pct in ["200", "300", "400", "500"] { + app.set_option("combine-zoom", pct).unwrap(); + assert_eq!(app.combine_zoom, pct.parse::().unwrap() / 100.0); + } + for bad in ["59", "501", "big", "NaN", "inf", ""] { + assert!(app.set_option("combine-zoom", bad).is_err(), "{bad:?}"); + } + assert_eq!(app.combine_zoom, largest, "a refused value leaves the size alone"); + // The list has no card size. + h.get_by_label("List view").click(); + h.run_steps(2); + assert!(h.query_by_label("Larger Thumbnails").is_none()); +} + +#[test] +fn expanding_a_file_shows_the_pages_it_adds_in_order_with_their_numbers() { + // Page 3 is landscape, page 4 square, the others portrait: the shape of a thumbnail says its page. + let pages = fixture_pages(&[(200.0, 300.0), (200.0, 300.0), (300.0, 200.0), (250.0, 250.0)]); + let mut h = grid_of(vec![("a.pdf", fixture(1)), ("b.pdf", pages)], vec2(1400.0, 900.0)); + h.state_mut().combine_draft[1].range = "3, 1, 4".into(); + h.run_steps(2); + // A single page has nothing to expand. + hover_card(&mut h, "a.pdf"); + assert!(h.query_by_label("Expand").is_none()); + expand(&mut h, "b.pdf"); + assert_eq!(h.state().combine_expanded(), [1]); + assert!(h.query_by_label("b.pdf").is_none(), "the file's tile gives way to its pages"); + // The pages it adds, in the range's order, each saying which page of which file. + let xs: Vec = [3, 1, 4].iter().map(|p| card(&h, &page_card(*p, "b.pdf")).left()).collect(); + assert!(xs.windows(2).all(|w| w[0] < w[1]), "pages 3, 1, 4 in that order: {xs:?}"); + assert!(h.query_by_label(&page_card(2, "b.pdf")).is_none(), "page 2 isn't added, so isn't shown"); + // Each renders its own page. + assert!(settle(&mut h, |app| { + let pages = app.combine_page_thumbnails(1); + pages.len() == 3 && pages.iter().all(|(_, t)| ready(t)) + })); + let shapes: Vec<(usize, TextureState)> = h.state().combine_page_thumbnails(1); + assert_eq!(shapes.iter().map(|(p, _)| *p).collect::>(), [2, 0, 3]); + assert!(landscape(&shapes[0].1) && portrait(&shapes[1].1), "{shapes:?}"); + let (w, h4) = shape(&shapes[2].1).unwrap(); + assert!((w - h4).abs() < 2.0, "page 4 is square: {w}×{h4}"); + // A page tile collapses the file again. + hover_card(&mut h, &page_card(1, "b.pdf")); + h.get_by_label("Collapse").click(); + h.run_steps(2); + assert!(h.state().combine_expanded().is_empty()); + h.get_by_label("b.pdf"); +} + #[test] fn expanding_is_a_view_kept_across_views_and_zoom_and_never_an_undo_step() { let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 3)]); @@ -1474,19 +616,18 @@ fn expanding_is_a_view_kept_across_views_and_zoom_and_never_an_undo_step() { h.run_steps(2); h.get_by_label("Grid view").click(); h.run_steps(2); - h.get_by_label("Larger pages").click(); + h.get_by_label("Larger Thumbnails").click(); h.run_steps(2); assert_eq!(h.state().combine_expanded(), [1], "still shown as its pages"); h.get_by_label(&page_card(3, "b.pdf")); - // Its range edited down to one page: that page's card (a part of a file can be one page). + // Its range edited down to one page: that page's tile (a part of a file can be one page). h.state_mut().combine_draft[1].range = "2".into(); h.run_steps(2); h.get_by_label(&page_card(2, "b.pdf")); - // A bad range: its card again, no longer expanded, and it doesn't come back expanded by - // itself when the range is fixed. + // A bad range: its tile again, no longer expanded, and it doesn't come back expanded by itself + // when the range is fixed. h.state_mut().combine_draft[1].range = "9".into(); h.run_steps(2); - h.get_by_label("b.pdf"); assert!(h.state().combine_expanded().is_empty(), "no longer expanded"); assert!(disabled(&h, "Collapse all")); h.state_mut().combine_draft[1].range = String::new(); @@ -1495,8 +636,8 @@ fn expanding_is_a_view_kept_across_views_and_zoom_and_never_an_undo_step() { assert!(h.state().combine_expanded().is_empty()); expand(&mut h, "b.pdf"); h.get_by_label(&page_card(2, "b.pdf")); - // The file removed (its file selected with the keys, then Delete): forgotten; undo brings - // the file back as its card. + // The file removed (its file selected with the keys, then Delete): forgotten; undo brings the file + // back as its tile. h.get_by_label("a.pdf").click(); h.run_steps(1); h.key_press(Key::ArrowRight); @@ -1512,52 +653,6 @@ fn expanding_is_a_view_kept_across_views_and_zoom_and_never_an_undo_step() { h.get_by_label("b.pdf"); } -#[test] -fn a_page_click_selects_that_page_and_the_arrows_step_rows_of_cards() { - // a, then b's 6 pages, then eight more files: rows of cards below b's last page whatever - // the window's width. - let mut files = vec![("a.pdf".to_string(), fixture(1)), ("b.pdf".to_string(), fixture(6))]; - files.extend((0..8).map(|i| (format!("f{i}.pdf"), fixture(1)))); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1000.0, 1100.0)); - expand(&mut h, "b.pdf"); - let top = card(&h, "a.pdf").top(); - let cols = ["a.pdf".to_string(), page_card(1, "b.pdf"), page_card(2, "b.pdf"), page_card(3, "b.pdf"), page_card(4, "b.pdf")] - .iter() - .filter(|n| (card(&h, n).top() - top).abs() < 1.0) - .count(); - assert!((2..5).contains(&cols), "a row of cards is shorter than a + b's pages ({cols})"); - h.get_by_label(&page_card(2, "b.pdf")).click(); - h.run_steps(2); - assert_eq!(h.state().combine_selected_pages(), [(1, 1)], "that page"); - assert!(h.state().combine_selection().is_empty(), "no file"); - assert!(h.get_by_label(&page_card(2, "b.pdf")).accesskit_node().is_selected() == Some(true)); - assert!(h.get_by_label(&page_card(5, "b.pdf")).accesskit_node().is_selected() == Some(false), "only that page"); - // Ctrl adds, Shift takes a run. - h.get_by_label(&page_card(4, "b.pdf")).click_modifiers(Modifiers::COMMAND); - h.run_steps(2); - assert_eq!(h.state().combine_selected_pages(), [(1, 1), (1, 3)]); - h.get_by_label(&page_card(6, "b.pdf")).click_modifiers(Modifiers::SHIFT); - h.run_steps(2); - assert_eq!(h.state().combine_selected_pages(), [(1, 3), (1, 4), (1, 5)], "from the last page clicked"); - // Down goes a row of cards from b's last page, to the file below it; Up comes back to b. - let last = card(&h, &page_card(6, "b.pdf")); - h.key_press(Key::ArrowDown); - h.run_steps(2); - let below = h.state().combine_selection(); - assert_eq!(below.len(), 1); - assert!(h.state().combine_selected_pages().is_empty(), "the keys select files again"); - let name = names(&h)[below[0]].clone(); - assert!(below[0] > 1, "a file after b: {name}"); - let r = card(&h, &name); - assert!((r.left() - last.left()).abs() < 1.0 && r.top() > last.top(), "the card right below b's last page: {r:?} vs {last:?}"); - h.key_press(Key::ArrowUp); - h.run_steps(2); - assert_eq!(h.state().combine_selection(), [1]); - h.key_press(Key::ArrowLeft); - h.run_steps(2); - assert_eq!(h.state().combine_selection(), [0], "left and right step by file"); -} - #[test] fn dragging_a_page_moves_that_page_even_between_another_files_pages() { let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 4), ("c.pdf", 1)]); @@ -1584,67 +679,10 @@ fn dragging_a_page_moves_that_page_even_between_another_files_pages() { let (p3, a) = (card(&h, &page_card(3, "b.pdf")), card(&h, "a.pdf")); drag(&mut h, p3.center(), a.center() - vec2(a.width() * 0.3, 0.0)); assert_eq!(parts(&h), ["b.pdf:[0, 2]", "a.pdf:[0]", "b.pdf:[3, 1]", "c.pdf:[0]"]); - // A file's card still moves its whole file, and a drop among a file's pages goes to its nearer end. + // A file's tile still moves its whole file, and a drop among a file's pages goes before that file. let (cc, early) = (card(&h, "c.pdf"), card(&h, &page_card(3, "b.pdf"))); drag(&mut h, cc.center(), early.center() - vec2(early.width() * 0.3, 0.0)); - assert_eq!(names(&h), ["b.pdf", "c.pdf", "a.pdf", "b.pdf"], "the second of that part's two pages: its end"); -} - -#[test] -fn a_long_file_expanded_renders_only_its_pages_in_view_within_three_threads() { - let mut h = grid_of(vec![("long.pdf", fixture(300)), ("b.pdf", fixture(1))], vec2(1400.0, 900.0)); - h.get_by_label("Expand all").click(); - let mut most = 0; - for _ in 0..200 { - h.run_steps(1); - let threads = h.state_mut().combine_thumbnail_threads(); - most = most.max(threads); - assert!(threads <= 3, "{threads} render threads"); - if h.state().combine_thumbnails_rendering() == 0 && h.state().combine_page_thumbnails(0).first().is_some_and(|(_, t)| ready(t)) { - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - let pages = h.state().combine_page_thumbnails(0); - assert_eq!(pages.len(), 300); - let drawn = pages.iter().filter(|(_, t)| ready(t)).count(); - assert!(drawn > 0 && drawn < 60, "only the pages in view (and a row either side): {drawn} of 300"); - assert!(h.query_by_label(&page_card(300, "long.pdf")).is_none(), "the last page, far out of view, isn't even laid out as a widget"); -} - -#[test] -fn a_page_cards_magnifier_opens_the_preview_on_that_page() { - let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 5)]); - // Pages 3, 1, 4: page 4 is the third the file adds. - h.state_mut().combine_draft[1].range = "3, 1, 4".into(); - h.run_steps(2); - expand(&mut h, "b.pdf"); - hover_card(&mut h, &page_card(4, "b.pdf")); - h.get_by_label("Preview").click(); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| (p.0, p.1)), Some(("b.pdf".to_string(), 3))); - wait_for_label(&mut h, "Page 3 of 3"); - h.get_by_label("Page 3 of 3"); - // The preview is modal: the card's actions are not drawn behind it. - assert!(h.query_by_label("Remove page").is_none(), "the preview covers the page card's actions"); - h.key_press(Key::Escape); - h.run_steps(2); - // A page card's own actions: Collapse, Remove page, Preview (its file can't be removed from - // it); nothing is selected yet, so no "Remove b.pdf" anywhere. - hover_card(&mut h, &page_card(4, "b.pdf")); - h.get_by_label("Remove page"); - h.get_by_label("Collapse"); - assert!(h.query_by_label("Remove b.pdf").is_none()); - // Space on a page card that has the keyboard: that page too. - h.get_by_label(&page_card(1, "b.pdf")).click(); - h.run_steps(2); - h.get_by_label(&page_card(1, "b.pdf")).focus(); - h.run_steps(2); - h.key_press(Key::Space); - h.run_steps(2); - assert_eq!(h.state().combine_preview().map(|p| p.1), Some(0), "page 1, the second the file adds"); - wait_for_label(&mut h, "Page 2 of 3"); - h.get_by_label("Page 2 of 3"); + assert_eq!(names(&h), ["c.pdf", "b.pdf", "a.pdf", "b.pdf"], "before the file whose page it was dropped on"); } #[test] @@ -1662,60 +700,15 @@ fn combining_with_files_expanded_gives_the_same_document() { } #[test] -fn collapsing_brings_the_files_card_into_view() { - // Many files after it, so the grid stays long once it collapses (it would otherwise scroll - // back by itself). - let mut files = vec![("long.pdf".to_string(), fixture(60))]; - files.extend((0..40).map(|i| (format!("f{i:02}.pdf"), fixture(1)))); - let mut h = grid_of(files.iter().map(|(n, b)| (n.as_str(), b.clone())).collect(), vec2(1400.0, 900.0)); - expand(&mut h, "long.pdf"); - // Down to its last pages. - h.hover_at(egui::pos2(900.0, 600.0)); - for _ in 0..80 { - if h.query_by_label(&page_card(60, "long.pdf")).is_some_and(|c| c.rect().top() > 300.0 && c.rect().bottom() < 880.0) { - break; - } - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -120.0), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(3); - } - hover_card(&mut h, &page_card(60, "long.pdf")); - h.get_by_label("Collapse").click(); - for _ in 0..20 { - h.run_steps(1); - } - let r = card(&h, "long.pdf"); - let toolbar = h.get_by_label("Grid view").rect().bottom(); - assert!(r.bottom() > toolbar && r.top() < 900.0, "the file's card is in view: {r:?}"); -} - -#[test] -fn a_file_too_long_to_spread_out_offers_no_expand() { - // 2001 pages: more cards than are laid out comfortably every frame. - let mut h = grid_of(vec![("huge.pdf", fixture(2001)), ("b.pdf", fixture(3))], vec2(1400.0, 900.0)); - hover_card(&mut h, "huge.pdf"); - assert!(h.query_by_label("Expand").is_none()); - h.get_by_label("Expand all").click(); - h.run_steps(2); - assert_eq!(h.state().combine_expanded(), [1], "only the file that can be"); -} - -#[test] -fn removing_pages_from_the_hover_bar_the_toolbar_and_delete_never_touches_the_file() { +fn removing_pages_from_the_tile_the_toolbar_and_delete_never_touches_the_file() { let mut h = grid_of_pages(&[("a.pdf", 1), ("b.pdf", 4)]); let original = h.state().combine_draft[1].bytes.clone(); expand(&mut h, "b.pdf"); let parts = |h: &Harness<'static, PdfCraftApp>| h.state().combine_parts_shown().into_iter().map(|(n, p)| format!("{n}:{p:?}")).collect::>(); - // A page card's trash: that page. + // A page tile's trash: that page. hover_card(&mut h, &page_card(2, "b.pdf")); - h.get_by_label("Remove page").click(); - h.run_steps(2); + remove_hovered(&mut h); assert_eq!(parts(&h), ["a.pdf:[0]", "b.pdf:[0, 2, 3]"]); // Two selected: the toolbar's trash says so, and takes both. h.get_by_label(&page_card(1, "b.pdf")).click(); @@ -1758,13 +751,9 @@ fn a_split_file_counts_once_and_combines_with_one_bookmark() { let (p2, t2) = (card(&h, &page_card(2, "one.pdf")), card(&h, &page_card(2, "two.pdf"))); drag(&mut h, p2.center(), t2.center() - vec2(t2.width() * 0.3, 0.0)); assert_eq!(names(&h), ["one.pdf", "two.pdf", "one.pdf", "two.pdf"]); - // Still two files, of the same size (each counted once), and the parts aren't "added more - // than once". + // Still two files, of the same size (each counted once), and the parts aren't "added more than + // once". assert_eq!(totals(&h), before); - hover_card(&mut h, &page_card(2, "one.pdf")); - for _ in 0..60 { - h.run_steps(1); - } assert!(h.query_by_label_contains("Added more than once").is_none()); h.hover_at(egui::pos2(5.0, 890.0)); h.run_steps(2); @@ -1785,7 +774,7 @@ fn pages_picked_out_of_sight_or_before_an_undo_are_let_go_of() { let parts = |h: &Harness<'static, PdfCraftApp>| h.state().combine_parts_shown().into_iter().map(|(n, p)| format!("{n}:{p:?}")).collect::>(); expand(&mut h, "b.pdf"); - // Collapsed from its hover bar: nothing picked, Delete takes nothing. + // Collapsed from a page tile's action: nothing picked, Delete takes nothing. h.get_by_label(&page_card(2, "b.pdf")).click(); h.run_steps(2); hover_card(&mut h, &page_card(3, "b.pdf")); @@ -1819,7 +808,7 @@ fn pages_picked_out_of_sight_or_before_an_undo_are_let_go_of() { h.run_steps(2); assert_eq!(parts(&h), ["a.pdf:[0]", "b.pdf:[0, 1, 2, 3]", "c.pdf:[0]"]); assert!(!disabled(&h, "Redo"), "a Delete with nothing picked makes no undo step"); - // A file picked (by dragging its card) lets go of the pages: Delete takes the file. + // A file picked (by dragging its tile) lets go of the pages: Delete takes the file. h.get_by_label(&page_card(2, "b.pdf")).click(); h.run_steps(2); let (cc, a) = (card(&h, "c.pdf"), card(&h, "a.pdf")); @@ -1843,8 +832,7 @@ fn a_files_parts_join_when_what_was_between_them_goes_and_one_file_cannot_be_com assert_eq!(parts(&h), ["one.pdf:[0]", "two.pdf:[0]", "one.pdf:[1]"]); // two goes: one's parts meet and are one entry again, in the same undo step. hover_card(&mut h, "two.pdf"); - h.get_by_label("Remove two.pdf").click(); - h.run_steps(2); + remove_hovered(&mut h); assert_eq!(parts(&h), ["one.pdf:[0, 1]"]); // One file is nothing to combine, however it is split. assert!(h.get_by_label("Combine").accesskit_node().is_disabled());