mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-22 18:31:26 +01:00
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)
This commit is contained in:
6 files changed
+1180
-2906
No files matched your search
@@ -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<f32> = 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<char> = stem.chars().collect();
|
||||
let with = |n: usize| format!("{}…{ext}", chars.iter().take(n).collect::<String>());
|
||||
// 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<Vec2> {
|
||||
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<u64, PageList>, f: &CombineFile) -> Option<PageList> {
|
||||
/// 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<PageList> {
|
||||
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<Cell> {
|
||||
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<CombineKey>,
|
||||
/// 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<CombineKey>,
|
||||
/// One group per expanded file, over its pages.
|
||||
groups: Vec<TileGroup<CombineKey>>,
|
||||
}
|
||||
|
||||
/// The rows of `draft`, the files in `lists` shown as their pages.
|
||||
fn rows_of(draft: &[CombineFile], lists: &HashMap<u64, PageList>) -> 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<usize, String>],
|
||||
selected: &[bool],
|
||||
twice: &[bool],
|
||||
) -> Option<RowAction> {
|
||||
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::<GridDrag>(&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<usize> = 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::<Vec2>(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<CombineKey>, 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<u64, usize>,
|
||||
/// The pages of the files shown as their pages.
|
||||
lists: &'a HashMap<u64, PageList>,
|
||||
/// What each entry's range takes, in list order.
|
||||
checks: &'a [Result<usize, String>],
|
||||
}
|
||||
|
||||
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<Act> {
|
||||
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<usize> {
|
||||
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<CombineKey>, keys: &[CombineKey]) -> Option<RowAction> {
|
||||
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<RowAction>`: 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<usize, String>], twice: &[bool]) -> Vec<RowAction> {
|
||||
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::<CombineKey>::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<u64> = 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<u64, PageList> {
|
||||
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<usize>,
|
||||
}
|
||||
let mut shown: HashMap<u64, Shown> = 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<Key> {
|
||||
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<usize>)> {
|
||||
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<usize> {
|
||||
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<ThumbState> {
|
||||
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<TextureState> {
|
||||
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<Arc<str>>) -> RenderConfig {
|
||||
RenderConfig { password, ..Default::default() }.on_screen()
|
||||
}
|
||||
|
||||
@@ -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<usize, String>,
|
||||
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<RowAction> {
|
||||
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<usize, String>) -> Vec<Act> {
|
||||
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<Act> {
|
||||
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<CombineKey>,
|
||||
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<usize, String>, 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<String> = 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<usize, String>,
|
||||
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<String> = 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<Vec<u8>>,
|
||||
auth: u64,
|
||||
password: Option<Arc<str>>,
|
||||
sizes: Arc<[(f32, f32)]>,
|
||||
count: usize,
|
||||
documents: Arc<Mutex<OpenDocuments>>,
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<CombineKey> {
|
||||
Thumbnails::<CombineKey>::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<OpenDocuments>) -> 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<Open>,
|
||||
/// 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<Mutex<OpenDocuments>>, bytes: Arc<Vec<u8>>, auth: u64, password: Option<Arc<str>>, 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<OpenDocuments>,
|
||||
bytes: &Arc<Vec<u8>>,
|
||||
auth: u64,
|
||||
password: Option<Arc<str>>,
|
||||
page: usize,
|
||||
scale: f32,
|
||||
cancel: &Cancel,
|
||||
) -> Result<LoadedPicture, LoadFailure> {
|
||||
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<Vec<u8>>,
|
||||
auth: u64,
|
||||
password: Option<Arc<str>>,
|
||||
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<u64, Entry>,
|
||||
documents: Arc<Mutex<OpenDocuments>>,
|
||||
}
|
||||
|
||||
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<u64, PageList>, documents: Arc<Mutex<OpenDocuments>>) -> 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<CombineKey> 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))
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
let mut objs: Vec<String> = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()];
|
||||
@@ -147,201 +83,26 @@ fn pdf(pages: usize, w: u32, h: u32) -> Arc<Vec<u8>> {
|
||||
Arc::new(out)
|
||||
}
|
||||
|
||||
fn key_of(bytes: &Arc<Vec<u8>>) -> Key {
|
||||
Key { source: Arc::as_ptr(bytes) as usize, auth: 1, page: 0, px: [32, 48] }
|
||||
}
|
||||
|
||||
fn want(file: u64, bytes: &Arc<Vec<u8>>) -> Want {
|
||||
Want { slot: (file, 0), key: key_of(bytes), bytes: bytes.clone(), password: None, scale: 0.15, visible: true }
|
||||
}
|
||||
|
||||
fn listing(files: &[(u64, &Arc<Vec<u8>>)]) -> HashMap<Slot, Key> {
|
||||
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<Slot, Key>) -> 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<Arc<Vec<u8>>> = (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<Slot, Key> = files.iter().enumerate().map(|(i, b)| ((i as u64, 0), key_of(b))).collect();
|
||||
frame(&ctx, &mut thumbs, ¤t);
|
||||
let mut kept: Vec<u64> = 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<Arc<Vec<u8>>> = (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<Vec<u8>>)> = (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<Arc<Vec<u8>>> = (0..6).map(|_| pdf(1, 200, 300)).collect();
|
||||
let shown: Vec<(u64, &Arc<Vec<u8>>)> = 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<Slot, Key> = [((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
|
||||
|
||||
@@ -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<TextureHandle>,
|
||||
pub(super) error: Option<String>,
|
||||
/// 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<Vec<u8>>,
|
||||
pub(super) password: Option<Arc<str>>,
|
||||
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<Slot, Entry>,
|
||||
pub(super) jobs: Vec<Job>,
|
||||
/// Pools done rendering, their documents still open (their threads count).
|
||||
pub(super) open: Vec<Open>,
|
||||
/// Threads of pools let go of, until they exit.
|
||||
pub(super) retiring: Vec<Retiring>,
|
||||
pub(super) frame: u64,
|
||||
pub(super) next_tag: u64,
|
||||
pub(super) wants: Vec<Want>,
|
||||
/// 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<egui::TextureId>),
|
||||
}
|
||||
|
||||
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<Key>) {
|
||||
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<Job>, Vec<Job>) = 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<Open>, Vec<Open>) = 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))
|
||||
}
|
||||
+301
-1313
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user