mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
pdf-canvas-w10: net change of 3 commits
- pdf-canvas-w10: written from its sheet - pdf-canvas-w10: repair 1 - pdf-canvas-w10: review fixes (review-1)
This commit is contained in:
@@ -1,83 +1,26 @@
|
||||
use super::find::Follow;
|
||||
use super::{
|
||||
Arc, Color32, DocInfo, DocView, HashSet, PRINT_TAG, PT, PageText, Range, RenderPool, RenderRequest, RequestKind, TextLink, TextureHandle,
|
||||
TextureOptions, device_pixels,
|
||||
};
|
||||
// PLAN: `craft::text::find::FindMatches` needs the facade's `text` feature and craft-text's `find` feature in the app's Cargo.toml (pdf-hub-w1 owns the manifest); every other error here is a `DocView` field (`view`, `placed`, `revisions`, `reports`, `text_queue`, `text`) that pdf-canvas-w8's `DocView` hunk adds
|
||||
use craft::host::queue::{Priority, QueueCounts};
|
||||
use craft::text::find::FindMatches;
|
||||
use craft::ui::primitives::textures::TextureState;
|
||||
|
||||
pub(super) const THUMB_TAG: u64 = 1 << 63;
|
||||
use super::{Arc, Color32, DocInfo, DocView, HashSet, PT, PageText, Range, RenderRequest, RequestKind, TextLink};
|
||||
|
||||
pub(super) const TEXT_TAG: u64 = 1 << 62;
|
||||
|
||||
/// A page rendered for the organize grid at the size it is drawn there.
|
||||
pub(super) const GRID_TAG: u64 = 1 << 61;
|
||||
|
||||
/// Preview rasters tagged with this bit are converted to luminance on receipt, matching the
|
||||
/// monochrome print requested by Print ▸ Print in grayscale. It is a bit of its own: the
|
||||
/// renderer's print bit ([`PRINT_TAG`]) is carried by every print preview, so sharing it would
|
||||
/// turn colour previews into monochrome ones too.
|
||||
pub(super) const GRAYSCALE_TAG: u64 = 1 << 59;
|
||||
|
||||
/// The tag of a raster that is out of date (shown until its replacement arrives).
|
||||
pub(super) const STALE_TAG: u64 = u64::MAX;
|
||||
/// At most this many text layers are cached beyond visible, selected and matched pages.
|
||||
/// Text layers are glyph structs, far smaller than rasters.
|
||||
pub(super) const MAX_CACHED_TEXT_PAGES: usize = 24;
|
||||
|
||||
/// Pages whose raster would exceed this many device pixels on a side are drawn in tiles.
|
||||
pub(crate) const TILE_THRESHOLD: f32 = 4096.0;
|
||||
|
||||
/// Base device-pixel side of a page tile. The actual side grows with the zoom
|
||||
/// ([`tile_side`]), so a zoomed viewport is covered by a few tiles instead of many.
|
||||
pub(super) const TILE: u32 = 1024;
|
||||
|
||||
/// Longest side of the backdrop drawn under tiles, and of a live page preview (signature drag).
|
||||
pub(crate) const BASE_SIDE: f32 = 2048.0;
|
||||
|
||||
/// Thumbnail slot before density scaling. The pages panel draws at most 150 logical points and
|
||||
/// the organize grid about 146; when the byte budget allows, density reaches the screen so those
|
||||
/// images are sampled down instead of stretched.
|
||||
pub(super) const THUMB_W: f32 = 240.0;
|
||||
|
||||
pub(super) const THUMB_H: f32 = 320.0;
|
||||
|
||||
pub(super) const THUMB_BYTES: usize = 24 * 1024 * 1024;
|
||||
|
||||
/// The smallest whole-page allowance ([`page_budget`]).
|
||||
pub(super) const PAGE_BYTES: usize = 128 * 1024 * 1024;
|
||||
|
||||
/// The largest whole-page allowance ([`page_budget`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_PAGE_BYTES: usize = 384 * 1024 * 1024;
|
||||
|
||||
/// The web build's largest whole-page allowance ([`page_budget`]).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const MAX_PAGE_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Rasters the size of the largest whole page on screen that the allowance holds between its
|
||||
/// limits: the pages on screen and the pages just behind and ahead of them.
|
||||
const BUDGET_PAGES: usize = 8;
|
||||
|
||||
pub(super) const TILE_BYTES: usize = 128 * 1024 * 1024;
|
||||
|
||||
const UPLOAD_BYTES_PER_FRAME: usize = 16 * 1024 * 1024;
|
||||
|
||||
const RESULTS_PER_FRAME: usize = 8;
|
||||
|
||||
/// A defensive ceiling for unusually large viewports / n-up previews.
|
||||
pub(super) const MAX_THUMB_DEMAND: usize = 256;
|
||||
|
||||
/// At most this many whole-page rasters are cached beyond the ones on screen.
|
||||
const MAX_CACHED_PAGES: usize = 24;
|
||||
|
||||
/// At most this many text layers are cached beyond visible, selected and matched pages.
|
||||
/// Text layers are glyph structs, far smaller than rasters; deliberately independent of
|
||||
/// `MAX_CACHED_PAGES` so raster tuning never silently retunes text memory.
|
||||
pub(super) const MAX_CACHED_TEXT_PAGES: usize = 24;
|
||||
|
||||
pub(super) fn rgba_bytes(width: usize, height: usize) -> usize {
|
||||
width.saturating_mul(height).saturating_mul(4)
|
||||
}
|
||||
|
||||
pub(super) fn texture_bytes(tex: &TextureHandle) -> usize {
|
||||
let [w, h] = tex.size();
|
||||
rgba_bytes(w, h)
|
||||
/// What a text-layer job found: the layer, or why there is none.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TextOutcome {
|
||||
text: Option<Arc<PageText>>,
|
||||
error: Option<String>,
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// Visible grid rows, plus one adjacent row in either direction. Work is independent of
|
||||
@@ -88,199 +31,67 @@ pub(crate) fn thumbnail_rows(top: f32, bottom: f32, row_height: f32, rows: usize
|
||||
first.saturating_sub(1).min(rows)..end.saturating_add(1).min(rows)
|
||||
}
|
||||
|
||||
pub(super) struct PageTex {
|
||||
pub(super) tag: u64,
|
||||
pub(super) tex: TextureHandle,
|
||||
}
|
||||
|
||||
/// Retained RGBA texture accounting for automation and performance regressions. These
|
||||
/// surface bytes exclude driver overhead and temporary upload buffers; they are not RSS.
|
||||
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
|
||||
pub struct RasterMemory {
|
||||
pub thumbnail_count: usize,
|
||||
pub thumbnail_bytes: usize,
|
||||
pub page_count: usize,
|
||||
pub page_bytes: usize,
|
||||
pub tile_count: usize,
|
||||
pub tile_bytes: usize,
|
||||
pub thumbnail_demand: usize,
|
||||
/// Last submitted missing results; workers may have completed some since submission.
|
||||
pub pending_requests: usize,
|
||||
}
|
||||
|
||||
/// Thumbnail device-pixel density when `demand` pages share the thumbnail allowance.
|
||||
pub(super) fn thumbnail_density(demand: usize, ppp: f32) -> f32 {
|
||||
let per_thumb = THUMB_BYTES / demand.max(1).next_power_of_two();
|
||||
ppp.clamp(0.25, 4.0).min((per_thumb as f32 / (4.0 * THUMB_W * THUMB_H)).sqrt() * 0.98)
|
||||
}
|
||||
|
||||
pub(super) fn thumbnail_scale(width: f32, height: f32, density: f32) -> f32 {
|
||||
(THUMB_W / width.max(1.0)).min(THUMB_H / height.max(1.0)) * density
|
||||
}
|
||||
|
||||
/// The whole-page byte allowance when the largest whole-page raster on screen takes `largest`
|
||||
/// bytes: [`BUDGET_PAGES`] such rasters, kept between [`PAGE_BYTES`] and [`MAX_PAGE_BYTES`].
|
||||
/// The raster's size follows the zoom, the display density and the page; a tiled page is on
|
||||
/// screen as a small backdrop, so it does not raise the allowance.
|
||||
pub(super) fn page_budget(largest: usize) -> usize {
|
||||
largest.saturating_mul(BUDGET_PAGES).clamp(PAGE_BYTES, MAX_PAGE_BYTES)
|
||||
}
|
||||
|
||||
impl DocView {
|
||||
pub fn raster_memory(&self) -> RasterMemory {
|
||||
RasterMemory {
|
||||
thumbnail_count: self.thumbs.len(),
|
||||
thumbnail_bytes: self.thumbs.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),
|
||||
page_count: self.pages.len(),
|
||||
page_bytes: self.pages.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex))),
|
||||
tile_count: self.tiles.len(),
|
||||
tile_bytes: self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex))),
|
||||
thumbnail_demand: self.thumb_demand.len(),
|
||||
pending_requests: self.last_queue.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pages whose content was cut at the renderer's limits, so part of each is not drawn and
|
||||
/// its text is incomplete (#623; for automation; 0-based, in order).
|
||||
pub fn cut_pages(&self) -> Vec<usize> {
|
||||
self.cut_pages.iter().copied().collect()
|
||||
self.reports.cut_pages()
|
||||
}
|
||||
|
||||
/// Pages that could not be rendered, with the reason (for automation; 0-based pages).
|
||||
pub fn page_errors(&self) -> Vec<(usize, &str)> {
|
||||
let mut v: Vec<(usize, &str)> = self.errors.iter().map(|(p, e)| (*p, e.as_str())).collect();
|
||||
v.sort_unstable_by_key(|(p, _)| *p);
|
||||
v
|
||||
/// Pages that could not be rendered, with the reason (for automation; 0-based pages, in order).
|
||||
pub fn page_errors(&self) -> Vec<(usize, String)> {
|
||||
self.reports.errors()
|
||||
}
|
||||
|
||||
/// Whether a text layer, a background or a page picture is still on its way.
|
||||
pub fn render_pending(&self) -> bool {
|
||||
!self.last_queue.is_empty() || self.text_background.pending() || self.move_background.pending()
|
||||
}
|
||||
|
||||
/// The cached tile keys of a page, as (scale tag, tile x, tile y) (diagnostics and tests).
|
||||
pub fn tiles_debug(&self, page: usize) -> Vec<(u64, u32, u32)> {
|
||||
let mut k: Vec<(u64, u32, u32)> = self.tiles.keys().filter(|key| key.0 == page).map(|key| (key.1, key.2, key.3)).collect();
|
||||
k.sort_unstable();
|
||||
k
|
||||
}
|
||||
|
||||
/// The pages with a cached whole-page raster, in page order (diagnostics and tests).
|
||||
pub fn cached_pages_debug(&self) -> Vec<usize> {
|
||||
let mut pages: Vec<usize> = self.pages.keys().copied().collect();
|
||||
pages.sort_unstable();
|
||||
pages
|
||||
self.text_queue.counts() != QueueCounts::default()
|
||||
|| self.text_background.pending()
|
||||
|| self.move_background.pending()
|
||||
|| self.placed.iter().any(|p| matches!(p.picture, TextureState::Loading { .. }))
|
||||
}
|
||||
|
||||
/// Re-render every page and text layer (the document's appearance changed, e.g. a layer
|
||||
/// was toggled). Out-of-date rasters stay on screen until their replacements arrive, so the
|
||||
/// was toggled). Out-of-date pictures stay on screen until their replacements arrive, so the
|
||||
/// view never flashes blank.
|
||||
pub fn invalidate_content(&mut self) {
|
||||
// Undo, redo and other document-wide changes: a released drawing's preview would be a ghost.
|
||||
self.comments.settling.clear();
|
||||
for p in self.pages.values_mut() {
|
||||
p.tag = STALE_TAG;
|
||||
}
|
||||
self.stale_thumbs.extend(self.thumbs.keys().copied());
|
||||
for slot in self.print_pages.values_mut() {
|
||||
slot.0 = STALE_TAG;
|
||||
}
|
||||
// Pages may have moved: a sharp render of another page would be worse than a soft one.
|
||||
self.grid_pages.clear();
|
||||
self.tiles.clear();
|
||||
self.stale_tiles.clear();
|
||||
self.revisions.bump_all();
|
||||
self.forms.unbaked.clear();
|
||||
self.texts.clear();
|
||||
self.text_failed.clear();
|
||||
self.errors.clear();
|
||||
self.cut_pages.clear();
|
||||
self.slow_pages.clear();
|
||||
self.waiting_since.clear();
|
||||
self.last_queue.clear();
|
||||
let _dropped = self.text_queue.reprioritize(|_, _| None);
|
||||
self.reports.clear();
|
||||
// Marks a tool waits to make go with the selection: its glyphs may name other text now.
|
||||
self.selection = None;
|
||||
self.text.selection = None;
|
||||
self.marks_waiting = None;
|
||||
self.all_text = false;
|
||||
// A content change is not reader navigation: keep the automatic anchor so the
|
||||
// re-extracted layers still follow it, and keep `follow_ended` so a reader who already
|
||||
// took over stays in control. `document_changed` clamps `current`; if the view no longer
|
||||
// sits where the automatic choice left it, `follow_page` ends it.
|
||||
let current = self.current;
|
||||
if let Some(f) = self.find.as_mut() {
|
||||
f.matches.clear();
|
||||
f.current = None;
|
||||
f.matches = FindMatches::new(current);
|
||||
}
|
||||
}
|
||||
|
||||
/// Only `page` changed (a comment was added, edited or removed): re-render that page and
|
||||
/// re-read its text, keep everything else. Out-of-date tiles stay on screen until replacements arrive.
|
||||
/// re-read its text, keep everything else.
|
||||
pub fn page_changed(&mut self, page: usize) {
|
||||
if let Some(p) = self.pages.get_mut(&page) {
|
||||
p.tag = STALE_TAG;
|
||||
}
|
||||
if self.thumbs.contains_key(&page) {
|
||||
self.stale_thumbs.insert(page);
|
||||
}
|
||||
if let Some(slot) = self.print_pages.get_mut(&page) {
|
||||
slot.0 = STALE_TAG;
|
||||
}
|
||||
let current_tag = if self.current_scale_tag != 0 {
|
||||
self.current_scale_tag
|
||||
} else {
|
||||
self.tiles.keys().filter(|k| k.0 == page).map(|k| k.1).max().unwrap_or(0)
|
||||
};
|
||||
self.tiles.retain(|key, _| key.0 != page || key.1 == current_tag);
|
||||
self.stale_tiles.retain(|key| key.0 != page || key.1 == current_tag);
|
||||
for &key in self.tiles.keys() {
|
||||
if key.0 == page && key.1 == current_tag {
|
||||
self.stale_tiles.insert(key);
|
||||
}
|
||||
}
|
||||
self.slow_pages.remove(&page);
|
||||
self.revisions.bump(page);
|
||||
self.texts.remove(&page);
|
||||
self.text_failed.remove(&page);
|
||||
self.errors.remove(&page);
|
||||
self.cut_pages.remove(&page);
|
||||
self.last_queue.clear();
|
||||
if self.selection.is_some_and(|s| s.pages().contains(&page)) {
|
||||
let _dropped = self.text_queue.reprioritize(|key, priority| (*key != page).then_some(priority));
|
||||
self.reports.forget(page);
|
||||
if self.text.selection.as_ref().is_some_and(|s| s.pages().contains(&page)) {
|
||||
// With the marks a tool waits to make on it (#5017 review).
|
||||
self.selection = None;
|
||||
self.text.selection = None;
|
||||
self.marks_waiting = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A page's thumbnail texture, when rendered.
|
||||
pub(crate) fn thumb_id(&self, page: usize) -> Option<egui::TextureId> {
|
||||
self.thumbs.get(&page).map(|t| t.tex.id())
|
||||
}
|
||||
|
||||
/// The whole-page raster on screen for `page` (the low-res backdrop of a tiled page), if any.
|
||||
pub(crate) fn page_raster(&self, page: usize) -> Option<egui::TextureId> {
|
||||
self.pages.get(&page).map(|p| p.tex.id())
|
||||
}
|
||||
|
||||
/// The size of `page`'s whole-page raster, when one is drawn and up to date (not waiting for
|
||||
/// its replacement after a change; tests and automation).
|
||||
pub fn drawn_page_size(&self, page: usize) -> Option<[usize; 2]> {
|
||||
self.pages.get(&page).filter(|p| p.tag != STALE_TAG).map(|p| p.tex.size())
|
||||
}
|
||||
|
||||
/// Whether `page`'s whole-page raster (a tiled page's backdrop too) is still the one from
|
||||
/// before its last change, whatever its tiles are.
|
||||
pub(crate) fn page_raster_out_of_date(&self, page: usize) -> bool {
|
||||
self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG)
|
||||
}
|
||||
|
||||
/// Whether `page` is still drawn, somewhere, as it was before its last change: its whole-page
|
||||
/// raster (a tiled page's backdrop too) or any of its tiles waits for a replacement.
|
||||
pub(crate) fn page_out_of_date(&self, page: usize) -> bool {
|
||||
self.pages.get(&page).is_some_and(|p| p.tag == STALE_TAG) || self.stale_tiles.iter().any(|k| k.0 == page)
|
||||
}
|
||||
|
||||
/// The print preview's picture of `page`: the sheet raster when it has arrived, otherwise the
|
||||
/// thumbnail.
|
||||
pub(crate) fn page_preview(&self, page: usize) -> Option<egui::TextureId> {
|
||||
self.print_pages.get(&page).map(|(_, tex)| tex.id()).or_else(|| self.thumb_id(page))
|
||||
}
|
||||
|
||||
pub(crate) fn page_text(&self, page: usize) -> Option<Arc<PageText>> {
|
||||
self.texts.get(&page).cloned()
|
||||
}
|
||||
@@ -322,251 +133,76 @@ impl DocView {
|
||||
self.texts.contains_key(&page)
|
||||
}
|
||||
|
||||
pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {
|
||||
self.thumbs.get(&page).map(|t| &t.tex)
|
||||
}
|
||||
|
||||
/// How many device pixels wide the grid's sharp render of `page` is, if it has one.
|
||||
pub fn grid_page_pixels(&self, page: usize) -> Option<u32> {
|
||||
self.grid_pages.get(&page).map(|(w, _)| *w)
|
||||
}
|
||||
|
||||
/// Start collecting demand from every consumer before scheduling or uploading results.
|
||||
pub(crate) fn begin_render_frame(&mut self) {
|
||||
self.frame_geometry_changed = false;
|
||||
self.pages_panel = None;
|
||||
self.panel_gap = None;
|
||||
self.thumb_demand.clear();
|
||||
self.frame_queue.clear();
|
||||
self.frame_visible.clear();
|
||||
}
|
||||
|
||||
pub(crate) fn need_thumbnail(&mut self, page: usize, visible: bool) {
|
||||
if page >= self.page_count {
|
||||
return;
|
||||
/// The text-layer step of a pass: takes the layers the jobs have finished (every result is for the current
|
||||
/// content: a change drops the jobs it outdates, so their results are never delivered), then asks for the ones the
|
||||
/// pass needs: the `visible` pages first, then `rest` in the order given (the selection's pages, and while a search
|
||||
/// runs every page from the current one on). Pages whose layer is held, failed or already on its way are not asked
|
||||
/// again, so calling it every pass submits nothing new. The queue's own wake asks for the pass a result needs.
|
||||
pub(crate) fn want_text(&mut self, session: &pdfcraft_engine::Session, visible: &[usize], rest: &[usize]) {
|
||||
while let Some(done) = self.text_queue.try_recv() {
|
||||
let page = done.key;
|
||||
let outcome = done.result;
|
||||
// Whether drawn or read for its text, a page cut at the limits is named (#623).
|
||||
if outcome.cut {
|
||||
self.reports.cut(page);
|
||||
}
|
||||
match outcome.text {
|
||||
Some(t) => {
|
||||
self.texts.insert(page, t);
|
||||
self.refresh_find_page(page);
|
||||
}
|
||||
None => {
|
||||
log::warn!("page {} text: {}", page + 1, outcome.error.unwrap_or_default());
|
||||
self.text_failed.insert(page);
|
||||
if let Some(f) = self.find.as_mut() {
|
||||
f.matches.set_page(page, Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(priority) = self.thumb_demand.get_mut(&page) {
|
||||
*priority |= visible;
|
||||
} else if self.thumb_demand.len() < MAX_THUMB_DEMAND {
|
||||
self.thumb_demand.insert(page, visible);
|
||||
} else if visible && let Some(prefetch) = self.thumb_demand.iter().find_map(|(&p, &v)| (!v).then_some(p)) {
|
||||
self.thumb_demand.remove(&prefetch);
|
||||
self.thumb_demand.insert(page, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the displayed document owns raster textures. Tabs keep their document and view
|
||||
/// state, but do not each retain a separate full application texture allowance.
|
||||
pub(crate) fn suspend_rendering(&mut self, pool: &RenderPool) {
|
||||
let queued = !self.last_queue.is_empty();
|
||||
self.release_rasters();
|
||||
if queued {
|
||||
pool.set_queue(Vec::new());
|
||||
}
|
||||
// Results already finished for this tab would otherwise sit in its pool, rasters and
|
||||
// all, until the tab is shown again. (An inline pool renders inside try_recv: skip it.)
|
||||
if !pool.is_inline() {
|
||||
while pool.try_recv().is_some() {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The view's half of [`DocView::suspend_rendering`]: its rasters and its demand go, and its
|
||||
/// document's pool is left alone. On its own for a view whose document another view on screen
|
||||
/// renders through the same pool (split view).
|
||||
pub(crate) fn release_rasters(&mut self) {
|
||||
self.begin_render_frame();
|
||||
self.pages.clear();
|
||||
self.tiles.clear();
|
||||
self.thumbs.clear();
|
||||
self.grid_pages.clear();
|
||||
self.print_pages.clear();
|
||||
self.stale_thumbs.clear();
|
||||
self.stale_tiles.clear();
|
||||
self.waiting_since.clear();
|
||||
// Signature previews own a separate renderer and image/background textures.
|
||||
self.signature_drag = Default::default();
|
||||
self.text_background = Default::default();
|
||||
self.move_background = Default::default();
|
||||
self.last_queue.clear();
|
||||
self.pane.shared = false;
|
||||
}
|
||||
|
||||
pub(super) fn thumbnail_requests(&self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {
|
||||
let mut pages: Vec<_> = self.thumb_demand.iter().map(|(&p, &visible)| (p, visible)).collect();
|
||||
pages.sort_unstable_by_key(|&(p, visible)| (!visible, p));
|
||||
// At high DPI or in a very large viewport every demanded cell still fits the same
|
||||
// byte allowance. Both dimensions are capped, including tall/wide page boxes.
|
||||
// The count is rounded up to a power of two: the scale is part of each request's tag,
|
||||
// so a density that followed every row scrolling in or out would re-render them all.
|
||||
let density = thumbnail_density(pages.len(), ppp);
|
||||
pages
|
||||
.into_iter()
|
||||
.filter_map(|(page, _)| {
|
||||
let p = info.pages.get(page)?;
|
||||
let scale = thumbnail_scale(p.width, p.height, density);
|
||||
Some(RenderRequest {
|
||||
page,
|
||||
kind: RequestKind::Pixels,
|
||||
tile: None,
|
||||
scale,
|
||||
tag: THUMB_TAG | u64::from(scale.to_bits()),
|
||||
// Thumbnails are previews: tiny images are skipped for them.
|
||||
preview: true,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Admit current demand within explicit byte limits. Cached and pending surfaces share
|
||||
/// the allowance, so an evicted page can be requested again without a permanent done set.
|
||||
pub(super) fn prepare_render_queue(&mut self, info: &DocInfo, ppp: f32) -> Vec<RenderRequest> {
|
||||
let requests = std::mem::take(&mut self.frame_queue);
|
||||
let mut queue = Vec::new();
|
||||
let mut pages = HashSet::new();
|
||||
let mut tiles = HashSet::new();
|
||||
let mut tile_tags = HashSet::new();
|
||||
let mut grid = Vec::new();
|
||||
let (mut page_bytes, mut tile_bytes) = (0usize, 0usize);
|
||||
let demand = requests
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
r.kind == RequestKind::Pixels && r.tile.is_none() && r.tag & (GRID_TAG | PRINT_TAG) == 0 && self.frame_visible.contains(&r.page)
|
||||
})
|
||||
.filter_map(|r| {
|
||||
let p = info.pages.get(r.page)?;
|
||||
Some(rgba_bytes(device_pixels(p.width, r.scale) as usize, device_pixels(p.height, r.scale) as usize))
|
||||
})
|
||||
.fold(0, usize::max);
|
||||
let page_limit = self.on_screen_page_budget(demand, None);
|
||||
for req in requests.iter().filter(|r| r.kind == RequestKind::Pixels) {
|
||||
let Some(p) = info.pages.get(req.page) else { continue };
|
||||
// Organize-grid renders: only the cells in view that need one (organize_grid).
|
||||
if req.tag & GRID_TAG != 0 {
|
||||
grid.push(*req);
|
||||
self.retain_text_layers(visible);
|
||||
let Some(doc) = session.get(self.id) else { return };
|
||||
let config = session.render_config(self.id).unwrap_or_default();
|
||||
let ranked = visible.iter().map(|p| (*p, Priority::VISIBLE)).chain(rest.iter().map(|p| (*p, Priority::BACKGROUND)));
|
||||
for (page, priority) in ranked {
|
||||
if page >= self.page_count || self.texts.contains_key(&page) || self.text_failed.contains(&page) || self.text_queue.contains(&page) {
|
||||
continue;
|
||||
}
|
||||
// Print-preview rasters: a few sheets at the pane's size (the dialog bounds them).
|
||||
if req.tag & PRINT_TAG != 0 {
|
||||
if !self.errors.contains_key(&req.page) {
|
||||
queue.push(*req);
|
||||
let (bytes, config) = (doc.display.clone(), config.clone());
|
||||
self.text_queue.submit(page, priority, move |cancel| {
|
||||
if cancel.is_cancelled() {
|
||||
return TextOutcome::default();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// On-screen work is always admitted (the viewport bounds it); the limits only
|
||||
// decide how much prefetch fits beside it.
|
||||
let visible = self.frame_visible.contains(&req.page);
|
||||
if let Some(tile) = req.tile {
|
||||
// Keyed by exact device-pixel origin: the tile side varies with the zoom
|
||||
// (`tile_side`), so grid indices would need the scale to decode.
|
||||
let key = (req.page, req.tag, tile.x, tile.y);
|
||||
let bytes = rgba_bytes(tile.w as usize, tile.h as usize);
|
||||
if (!visible && tile_bytes.saturating_add(bytes) > TILE_BYTES) || !tiles.insert(key) {
|
||||
continue;
|
||||
let mut renderer = pdfcraft_render::PageRenderer::new(bytes, config);
|
||||
let out = renderer.render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() });
|
||||
TextOutcome {
|
||||
cut: out.warnings.contains(&pdfcraft_render::RenderWarning::ContentTruncated),
|
||||
text: out.text,
|
||||
error: out.error,
|
||||
}
|
||||
tile_bytes = tile_bytes.saturating_add(bytes);
|
||||
tile_tags.insert(req.tag);
|
||||
if !self.tiles.contains_key(&key) || self.stale_tiles.contains(&key) {
|
||||
queue.push(*req);
|
||||
}
|
||||
} else {
|
||||
let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);
|
||||
if (!visible && (page_bytes.saturating_add(bytes) > page_limit || pages.len() >= MAX_CACHED_PAGES)) || !pages.insert(req.page) {
|
||||
continue;
|
||||
}
|
||||
page_bytes = page_bytes.saturating_add(bytes);
|
||||
if self.pages.get(&req.page).is_none_or(|p| p.tag != req.tag) {
|
||||
queue.push(*req);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Pages no longer demanded stay cached while the allowance has room, nearest to the
|
||||
// current page first, so turning back a page shows it at once instead of rendering.
|
||||
let mut undemanded: Vec<usize> = self.pages.keys().copied().filter(|p| !pages.contains(p)).collect();
|
||||
undemanded.sort_by_key(|p| p.abs_diff(self.current));
|
||||
self.frame_demanded = pages.clone();
|
||||
let mut kept = pages.len();
|
||||
for page in undemanded {
|
||||
let bytes = self.pages.get(&page).map_or(0, |p| texture_bytes(&p.tex));
|
||||
if kept < MAX_CACHED_PAGES && page_bytes.saturating_add(bytes) <= page_limit {
|
||||
page_bytes = page_bytes.saturating_add(bytes);
|
||||
kept += 1;
|
||||
pages.insert(page);
|
||||
}
|
||||
}
|
||||
self.pages.retain(|p, _| pages.contains(p));
|
||||
// Tiles of an earlier zoom (not a demanded scale) stay while the canvas keeps them, a
|
||||
// bounded few under a page whose current tiles are still missing (OLD_TILES). Tiles of a
|
||||
// page on screen stay too even when this frame does not demand them (#2196): the viewport
|
||||
// moves while zooming, so a tile that was sharp a moment ago falls outside the demanded
|
||||
// rectangle, and dropping it made every pan or zoom back a cold miss that re-blurred the
|
||||
// page and re-interpreted it once per tile. The per-frame cap below (OLD_TILES,
|
||||
// nearest scale first) is what bounds how much of that stays.
|
||||
self.tiles.retain(|key, _| tiles.contains(key) || !tile_tags.contains(&key.1) || self.frame_visible.contains(&key.0));
|
||||
self.stale_tiles.retain(|key| self.tiles.contains_key(key));
|
||||
queue.extend(grid);
|
||||
// Opening (or turning to) a page queues its pixels alongside thumbnails and
|
||||
// text extraction. The workers would otherwise spend the first seconds on
|
||||
// thumbnails and search text while the visible page stays blank: hold those
|
||||
// until no visible main-page raster is still missing. Errored pages never
|
||||
// block: they are never re-requested.
|
||||
let visible_mains_pending = queue.iter().any(|r| {
|
||||
r.kind == RequestKind::Pixels
|
||||
&& r.tag & (GRID_TAG | PRINT_TAG | THUMB_TAG | TEXT_TAG) == 0
|
||||
&& self.frame_visible.contains(&r.page)
|
||||
&& !self.errors.contains_key(&r.page)
|
||||
});
|
||||
if visible_mains_pending {
|
||||
// Caches are kept; demand is re-evaluated next frame once pixels arrive. Thumbnails
|
||||
// nothing shows any more (their panel closed) go now, though: no consumer is waiting.
|
||||
if self.thumb_demand.is_empty() {
|
||||
self.thumbs.clear();
|
||||
self.stale_thumbs.clear();
|
||||
}
|
||||
return queue;
|
||||
}
|
||||
let thumbs = self.thumbnail_requests(info, ppp);
|
||||
let mut thumb_bytes = 0usize;
|
||||
let mut admitted = HashSet::new();
|
||||
for req in thumbs {
|
||||
let Some(p) = info.pages.get(req.page) else { continue };
|
||||
let bytes = rgba_bytes(device_pixels(p.width, req.scale) as usize, device_pixels(p.height, req.scale) as usize);
|
||||
if thumb_bytes.saturating_add(bytes) > THUMB_BYTES || self.errors.contains_key(&req.page) {
|
||||
continue;
|
||||
}
|
||||
thumb_bytes += bytes;
|
||||
admitted.insert(req.page);
|
||||
if self.thumbs.get(&req.page).is_none_or(|t| t.tag != req.tag) || self.stale_thumbs.contains(&req.page) {
|
||||
queue.push(req);
|
||||
}
|
||||
}
|
||||
self.thumbs.retain(|p, _| admitted.contains(p));
|
||||
self.stale_thumbs.retain(|p| admitted.contains(p));
|
||||
self.retain_text_layers();
|
||||
// Visible main pages and thumbnails take precedence over background search work.
|
||||
queue.extend(requests.into_iter().filter(|r| r.kind == RequestKind::Text));
|
||||
queue
|
||||
}
|
||||
|
||||
/// Drop text layers nothing can still need. Every visited page's text used to stay
|
||||
/// cached for the session. Keep visible, selected and matched pages plus the nearest
|
||||
/// prefetch window; evicted pages re-extract on revisit. (Count window only: unlike
|
||||
/// rasters there is no byte budget here.) While a search is active keep everything:
|
||||
/// Drop text layers nothing can still need. Keep visible, selected and matched pages plus
|
||||
/// the nearest prefetch window; evicted pages re-extract on revisit. (Count window only: unlike
|
||||
/// pictures there is no byte budget here.) While a search is active keep everything:
|
||||
/// demand still wants every page, so evicting would re-request evicted pages each
|
||||
/// frame and churn the workers. Failures are never evicted either: they cost nothing
|
||||
/// to remember, and evicting one would re-request and re-fail it every frame.
|
||||
fn retain_text_layers(&mut self) {
|
||||
/// pass and churn the workers. Failures are never evicted either: they cost nothing
|
||||
/// to remember, and evicting one would re-request and re-fail it every pass.
|
||||
fn retain_text_layers(&mut self, visible: &[usize]) {
|
||||
if self.texts.len() <= MAX_CACHED_TEXT_PAGES {
|
||||
return;
|
||||
}
|
||||
if self.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {
|
||||
return;
|
||||
}
|
||||
let mut keep: HashSet<usize> = self.frame_visible.clone();
|
||||
if let Some(s) = self.selection {
|
||||
let mut keep: HashSet<usize> = visible.iter().copied().collect();
|
||||
if let Some(s) = self.text.selection.as_ref() {
|
||||
keep.extend(s.pages());
|
||||
}
|
||||
if let Some(f) = self.find.as_ref() {
|
||||
keep.extend(f.matches.iter().map(|(p, _)| *p));
|
||||
keep.extend(f.matches.matches().iter().map(|m| m.page));
|
||||
}
|
||||
let mut rest: Vec<usize> = self.texts.keys().filter(|p| !keep.contains(*p)).copied().collect();
|
||||
rest.sort_by_key(|p| p.abs_diff(self.current));
|
||||
@@ -574,354 +210,14 @@ impl DocView {
|
||||
self.texts.retain(|p, _| keep.contains(p));
|
||||
}
|
||||
|
||||
pub(crate) fn finish_render_frame(&mut self, ctx: &egui::Context, info: &DocInfo, pool: &RenderPool) {
|
||||
if self.frame_geometry_changed {
|
||||
// Dialogs and edits can replace pages after the canvas collected demand. Its
|
||||
// scales and indexes belong to the old pages, not to the new renderer (#3149).
|
||||
self.begin_render_frame();
|
||||
self.last_queue.clear();
|
||||
pool.set_queue(Vec::new());
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let queue = self.prepare_render_queue(info, ctx.pixels_per_point());
|
||||
// (Shared with another view of the document last frame, the pool's queue was both views'.)
|
||||
if queue != self.last_queue || std::mem::take(&mut self.pane.shared) {
|
||||
pool.set_queue(queue.clone());
|
||||
self.last_queue = queue;
|
||||
}
|
||||
if !self.hold_rasters {
|
||||
self.receive(ctx, pool);
|
||||
}
|
||||
if !self.last_queue.is_empty() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(30));
|
||||
}
|
||||
}
|
||||
|
||||
/// [`DocView::finish_render_frame`] for several views of one document on screen at once (split
|
||||
/// view), `group` in `views`: the document's one render pool works for
|
||||
/// all of them, and a request they share (the same page at the same scale) is rendered once
|
||||
/// and handed to each.
|
||||
pub(crate) fn finish_shared_render_frame(ctx: &egui::Context, info: &DocInfo, pool: &RenderPool, views: &mut [DocView], group: &[usize]) {
|
||||
// As for one view (#3149): an edit after the canvases collected demand leaves its scales
|
||||
// and indexes on the old pages, in every view of the document (the pool's queue is theirs).
|
||||
if group.iter().any(|&i| views.get(i).is_some_and(|v| v.frame_geometry_changed)) {
|
||||
for &i in group {
|
||||
if let Some(view) = views.get_mut(i) {
|
||||
view.begin_render_frame();
|
||||
view.last_queue.clear();
|
||||
}
|
||||
}
|
||||
pool.set_queue(Vec::new());
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let mut changed = false;
|
||||
let mut union: Vec<RenderRequest> = Vec::new();
|
||||
for &i in group {
|
||||
let Some(view) = views.get_mut(i) else { continue };
|
||||
let queue = view.prepare_render_queue(info, ppp);
|
||||
changed |= !view.pane.shared || queue != view.last_queue;
|
||||
for r in &queue {
|
||||
if !union.contains(r) {
|
||||
union.push(*r);
|
||||
}
|
||||
}
|
||||
view.last_queue = queue;
|
||||
view.pane.shared = true;
|
||||
}
|
||||
if changed {
|
||||
pool.set_queue(union);
|
||||
}
|
||||
// A result can go to both views, so one view holding its rasters holds them for both.
|
||||
if !group.iter().any(|&i| views.get(i).is_some_and(|v| v.hold_rasters)) {
|
||||
receive_batch(pool, |r| {
|
||||
let wanting: Vec<usize> =
|
||||
group.iter().copied().filter(|&i| views.get(i).is_some_and(|v| v.last_queue.contains(&r.request))).collect();
|
||||
let Some((&last, rest)) = wanting.split_last() else { return 0 };
|
||||
let mut uploaded = 0usize;
|
||||
for &i in rest {
|
||||
if let Some(view) = views.get_mut(i) {
|
||||
uploaded = uploaded.saturating_add(view.receive_result(ctx, copy_result(&r)));
|
||||
}
|
||||
}
|
||||
if let Some(view) = views.get_mut(last) {
|
||||
uploaded = uploaded.saturating_add(view.receive_result(ctx, r));
|
||||
}
|
||||
uploaded
|
||||
});
|
||||
}
|
||||
if group.iter().any(|&i| views.get(i).is_some_and(|v| !v.last_queue.is_empty())) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(30));
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull a bounded batch of current results into textures. Demand is committed first, so
|
||||
/// offscreen results and obsolete scale/configuration tags never allocate a ColorImage.
|
||||
pub fn receive(&mut self, ctx: &egui::Context, pool: &RenderPool) {
|
||||
receive_batch(pool, |r| self.receive_result(ctx, r));
|
||||
}
|
||||
|
||||
pub(super) fn receive_result(&mut self, ctx: &egui::Context, r: pdfcraft_render::RenderedPage) -> usize {
|
||||
if !self.last_queue.contains(&r.request) {
|
||||
return 0;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
// Whether drawn or read for its text, a page cut at the limits is named (#623).
|
||||
if r.warnings.contains(&pdfcraft_render::RenderWarning::ContentTruncated) {
|
||||
self.cut_pages.insert(r.request.page);
|
||||
}
|
||||
if r.request.kind == RequestKind::Text {
|
||||
match r.text {
|
||||
Some(t) => {
|
||||
self.texts.insert(r.request.page, t);
|
||||
self.refresh_find_page(r.request.page);
|
||||
}
|
||||
None => {
|
||||
log::warn!("page {} text: {}", r.request.page + 1, r.error.unwrap_or_default());
|
||||
self.text_failed.insert(r.request.page);
|
||||
if let Some(f) = self.find.as_mut() {
|
||||
let previous = f.current.and_then(|c| f.matches.get(c).cloned());
|
||||
let follow = f.follow_page(self.current);
|
||||
f.matches.retain(|(p, _)| *p != r.request.page);
|
||||
match follow {
|
||||
// An automatic choice keeps following its anchor; a failure never
|
||||
// flashes, so the view stays exactly where it was.
|
||||
Follow::Active(from) => f.current = f.first_at_or_after(from),
|
||||
Follow::Ended | Follow::Never => {
|
||||
let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));
|
||||
f.current = preserved.or_else(|| f.first_at_or_after(self.current));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if let Some(e) = r.error {
|
||||
log::warn!("page {}: {e}", r.request.page + 1);
|
||||
self.errors.insert(r.request.page, e);
|
||||
return 0;
|
||||
}
|
||||
// Even current demand may have been sized with obsolete geometry or a different
|
||||
// device limit. Check before cache eviction, conversion and every upload path.
|
||||
let max_side = ctx.input(|i| i.max_texture_side);
|
||||
if r.width == 0 || r.height == 0 || r.width as usize > max_side || r.height as usize > max_side {
|
||||
return 0;
|
||||
}
|
||||
// Remember heavy pages: only these get the zoom/pan settle holds, so fast pages
|
||||
// never pay added latency. Stale entries die with the tiles on edits.
|
||||
if r.millis >= SLOW_MILLIS {
|
||||
self.slow_pages.insert(r.request.page);
|
||||
}
|
||||
let page = r.request.page;
|
||||
let bytes = rgba_bytes(r.width as usize, r.height as usize);
|
||||
if bytes != r.rgba.len() || !self.admit_texture(r.request, bytes) {
|
||||
return 0;
|
||||
}
|
||||
// The length was checked above, so the renderer's buffer becomes the texture data as is.
|
||||
let img = texture_image([r.width as usize, r.height as usize], r.rgba);
|
||||
if let Some(t) = r.request.tile {
|
||||
let key = (page, r.request.tag, t.x, t.y);
|
||||
let tex = ctx.load_texture(format!("tile-{:?}-{page}-{}-{}", self.id, t.x, t.y), img, TextureOptions::LINEAR);
|
||||
self.tiles.insert(key, tex);
|
||||
self.stale_tiles.remove(&key);
|
||||
if !self.stale_tiles.iter().any(|k| k.0 == page) {
|
||||
self.forms.unbaked.retain(|(_, p)| *p != page);
|
||||
self.comments.page_rendered(page);
|
||||
}
|
||||
if !self.page_out_of_date(page) {
|
||||
self.text_background.page_received(page);
|
||||
}
|
||||
} else if r.request.tag & PRINT_TAG != 0 {
|
||||
let tex = ctx.load_texture(
|
||||
format!("print-{:?}-{page}", self.id),
|
||||
if r.request.tag & GRAYSCALE_TAG != 0 { grayscale(img) } else { img },
|
||||
TextureOptions::LINEAR,
|
||||
);
|
||||
self.print_pages.insert(page, (r.request.tag, tex));
|
||||
} else if r.request.tag & GRID_TAG != 0 {
|
||||
let tex = ctx.load_texture(format!("grid-{:?}-{page}", self.id), img, TextureOptions::LINEAR);
|
||||
self.grid_pages.insert(page, (r.width, tex));
|
||||
} else if r.request.tag & THUMB_TAG != 0 {
|
||||
let tex = ctx.load_texture(format!("thumb-{:?}-{page}", self.id), img, TextureOptions::LINEAR);
|
||||
self.thumbs.insert(page, PageTex { tag: r.request.tag, tex });
|
||||
self.stale_thumbs.remove(&page);
|
||||
} else {
|
||||
let tex = ctx.load_texture(format!("page-{:?}-{page}", self.id), img, TextureOptions::LINEAR);
|
||||
self.pages.insert(page, PageTex { tag: r.request.tag, tex });
|
||||
self.signature_drag.page_received(page);
|
||||
self.move_background.page_received(page);
|
||||
if !self.page_out_of_date(page) {
|
||||
self.text_background.page_received(page);
|
||||
}
|
||||
self.comments.page_rendered(page);
|
||||
self.waiting_since.remove(&page);
|
||||
if !self.stale_tiles.iter().any(|k| k.0 == page) {
|
||||
self.forms.unbaked.retain(|(_, p)| *p != page);
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Check real dimensions before conversion, including stale textures kept during edits.
|
||||
/// Dropping an old handle releases its backend allocation after the current frame.
|
||||
pub(super) fn admit_texture(&mut self, req: RenderRequest, bytes: usize) -> bool {
|
||||
// An on-screen page or tile is always taken (the viewport bounds it): it may evict
|
||||
// off-screen rasters but never another on-screen one, and is never refused.
|
||||
let visible = req.tag & THUMB_TAG == 0 && self.frame_visible.contains(&req.page);
|
||||
// Organize-grid renders are bounded by the cells in view (organize_grid). Print
|
||||
// previews are the sheets around the one on screen.
|
||||
if req.tag & (GRID_TAG | PRINT_TAG) != 0 {
|
||||
return true;
|
||||
}
|
||||
if let Some(t) = req.tile {
|
||||
let key = (req.page, req.tag, t.x, t.y);
|
||||
self.tiles.remove(&key);
|
||||
let retained = self.tiles.values().fold(0usize, |n, tex| n.saturating_add(texture_bytes(tex)));
|
||||
visible || bytes <= TILE_BYTES.saturating_sub(retained)
|
||||
} else {
|
||||
let thumb = req.tag & THUMB_TAG != 0;
|
||||
let page_limit = self.on_screen_page_budget(if visible { bytes } else { 0 }, Some(req.page));
|
||||
let (cache, limit) = if thumb { (&mut self.thumbs, THUMB_BYTES) } else { (&mut self.pages, page_limit) };
|
||||
cache.remove(&req.page);
|
||||
let mut retained = cache.values().fold(0usize, |n, p| n.saturating_add(texture_bytes(&p.tex)));
|
||||
// A zoom/DPI change can temporarily retain larger stale images than the new
|
||||
// demand estimates. Evict those first, then let the current demand refill them.
|
||||
let on_screen = |p: &usize| !thumb && self.frame_visible.contains(p);
|
||||
while retained.saturating_add(bytes) > limit {
|
||||
// Pages this frame does not ask for go first, then those behind the scroll, the
|
||||
// farthest from the current page first.
|
||||
let evict_order = |p: &usize| {
|
||||
let demanded = !thumb && self.frame_demanded.contains(p);
|
||||
(!demanded, !thumb && super::behind_scroll(self.continuous, self.scroll_dir, self.current, *p), p.abs_diff(self.current))
|
||||
};
|
||||
let Some(page) = cache.keys().copied().filter(|p| !on_screen(p)).max_by_key(evict_order) else { break };
|
||||
if let Some(old) = cache.remove(&page) {
|
||||
retained = retained.saturating_sub(texture_bytes(&old.tex));
|
||||
}
|
||||
}
|
||||
visible || bytes <= limit.saturating_sub(retained)
|
||||
}
|
||||
}
|
||||
|
||||
/// Device scale of a page raster: exactly the device scale, as a raster at any other scale is
|
||||
/// resampled on screen, which blurs every line and glyph (#260).
|
||||
pub(super) fn render_scale(&self, ppp: f32) -> f32 {
|
||||
// Exactly the device scale: a raster at any other scale is resampled on screen, which
|
||||
// blurs every line and glyph (#260).
|
||||
self.zoom * PT * ppp
|
||||
}
|
||||
|
||||
/// The whole-page allowance ([`page_budget`]) for the larger of `demand` and the rasters held
|
||||
/// for the pages on screen other than `except`. A held raster counts while a zoom hold keeps
|
||||
/// it on screen without a request.
|
||||
fn on_screen_page_budget(&self, demand: usize, except: Option<usize>) -> usize {
|
||||
page_budget(
|
||||
self.pages
|
||||
.iter()
|
||||
.filter(|(p, _)| Some(**p) != except && self.frame_visible.contains(p))
|
||||
.map(|(_, p)| texture_bytes(&p.tex))
|
||||
.fold(demand, usize::max),
|
||||
)
|
||||
}
|
||||
|
||||
/// Set whether the print preview rasters become luminance before upload. Toggling it drops
|
||||
/// the colour previews: new requests carry the grayscale tag, so stale ones are replaced.
|
||||
pub(crate) fn set_print_grayscale(&mut self, grayscale: bool) {
|
||||
if self.grayscale != grayscale {
|
||||
self.grayscale = grayscale;
|
||||
self.print_pages.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue sharp rasters for the print preview. Pages that leave the nearby sheets are dropped.
|
||||
/// Previews render with reading colours off (the request's tag tells the renderer): they must
|
||||
/// match the printout, which is imposed from the uncoloured document.
|
||||
pub(crate) fn queue_print_previews(&mut self, pages: &[(usize, f32)]) {
|
||||
self.print_pages.retain(|page, _| pages.iter().any(|(p, _)| p == page));
|
||||
for &(page, scale) in pages {
|
||||
if self.errors.contains_key(&page) || !scale.is_finite() || scale <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let tag = scale_tag(scale) | PRINT_TAG | if self.grayscale { GRAYSCALE_TAG } else { 0 };
|
||||
let fresh = self.print_pages.get(&page).is_some_and(|(have, _)| *have == tag);
|
||||
if !fresh {
|
||||
self.frame_queue.push(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale, tag, preview: false });
|
||||
}
|
||||
}
|
||||
self.view.zoom as f32 * PT * ppp
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a bounded batch of finished renders from `pool` and hand each to `receive`, which
|
||||
/// returns the bytes it uploaded: at most a few results, one frame's upload allowance, and 4 ms
|
||||
/// a frame.
|
||||
fn receive_batch(pool: &RenderPool, mut receive: impl FnMut(pdfcraft_render::RenderedPage) -> usize) {
|
||||
let budget = if pool.is_inline() { 1 } else { RESULTS_PER_FRAME };
|
||||
let mut uploaded = 0usize;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..budget {
|
||||
let Some(r) = pool.try_recv() else { break };
|
||||
uploaded = uploaded.saturating_add(receive(r));
|
||||
// One whole-page upload may exceed the frame allowance; it must still progress.
|
||||
if uploaded >= UPLOAD_BYTES_PER_FRAME {
|
||||
break;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if started.elapsed() >= std::time::Duration::from_millis(4) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of a render result, for a second view of the document that asked for the same request
|
||||
/// (split view). Not `Clone` on purpose: page rasters are large, and this is the one place they
|
||||
/// are copied.
|
||||
fn copy_result(r: &pdfcraft_render::RenderedPage) -> pdfcraft_render::RenderedPage {
|
||||
pdfcraft_render::RenderedPage {
|
||||
request: r.request,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
rgba: r.rgba.clone(),
|
||||
error: r.error.clone(),
|
||||
text: r.text.clone(),
|
||||
warnings: r.warnings.clone(),
|
||||
millis: r.millis,
|
||||
}
|
||||
}
|
||||
|
||||
/// The request tag for a raster at `scale`: equal tags mean the same scale (to 1/65536).
|
||||
pub(super) fn scale_tag(scale: f32) -> u64 {
|
||||
(f64::from(scale) * 65536.0).round() as u64
|
||||
}
|
||||
|
||||
/// The scale of a raster tagged by [`scale_tag`].
|
||||
pub(super) fn tag_scale(tag: u64) -> f32 {
|
||||
(tag as f64 / 65536.0) as f32
|
||||
}
|
||||
|
||||
/// Device-pixel side of a page tile at `scale` for a page `page_max_px` device pixels on
|
||||
/// its long side. Each tile costs a full page interpret, so tiles grow with the zoom and
|
||||
/// with the page: a zoomed viewport, or a giant sheet shown whole, is covered by a few
|
||||
/// large tiles instead of dozens of small ones. Bounded by the render backend (tile sides
|
||||
/// above 4096 are clamped there) and kept granular at ordinary zooms.
|
||||
pub(super) fn tile_side(scale: f32, page_max_px: u32) -> u32 {
|
||||
if !scale.is_finite() || scale <= 0.0 {
|
||||
return TILE;
|
||||
}
|
||||
let by_zoom = (TILE as f32 * (scale / 6.0)).clamp(TILE as f32, 4096.0) as u32;
|
||||
// At most four tiles along the long side, so a giant sheet needs a handful of
|
||||
// interprets instead of dozens.
|
||||
by_zoom.max(page_max_px.div_ceil(4).min(4096))
|
||||
}
|
||||
|
||||
/// Tiles of earlier zooms kept for a page while its current tiles are rendered.
|
||||
pub(super) const OLD_TILES: usize = 64;
|
||||
|
||||
/// A page whose raster took at least this long is heavy: zoom/pan holds apply to it,
|
||||
/// so gestures stay on stretched surfaces instead of queueing full-page interprets.
|
||||
const SLOW_MILLIS: u32 = 500;
|
||||
|
||||
/// A rendered raster as texture data. Its words are premultiplied RGBA bytes, exactly
|
||||
/// `Color32`s, so the renderer's buffer becomes the image without a copy on the UI thread.
|
||||
pub(crate) fn texture_image(size: [usize; 2], pixels: pdfcraft_render::Pixels) -> egui::ColorImage {
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The document's pages as pictures: what the page view, the Pages panel, Organize and the print preview ask the
|
||||
//! framework's texture contract for. Revisions say when a picture is out of date; render jobs own what they read.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use craft::behavior::kurbo::Size;
|
||||
use craft::pages::ui::PageSource;
|
||||
use craft::ui::primitives::textures::{LoadFailure, LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource};
|
||||
use egui::{Color32, ColorImage, Rect};
|
||||
use pdfcraft_engine::{DocId, DocInfo, Session};
|
||||
use pdfcraft_render::{PRINT_TAG, PageRenderer, RenderConfig, RenderRequest, RenderWarning, RequestKind, Tile};
|
||||
|
||||
use super::cache::{grayscale, texture_image};
|
||||
|
||||
/// A print preview picture: the page, in colour or as the monochrome print will be.
|
||||
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||
pub struct PrintPage {
|
||||
/// The page, 0-based.
|
||||
pub page: usize,
|
||||
/// Converted to luminance, as Print ▸ Print in grayscale prints it.
|
||||
pub grayscale: bool,
|
||||
}
|
||||
|
||||
/// Which generation of each page's picture is current: a base for the whole document and a bump per page. A picture's
|
||||
/// revision includes both, so a change makes the page's picture a new one and leaves the stale one as the stand-in.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PageRevisions {
|
||||
base: u64,
|
||||
bumps: HashMap<usize, u64>,
|
||||
}
|
||||
|
||||
impl PageRevisions {
|
||||
/// Every page's picture is out of date.
|
||||
pub fn bump_all(&mut self) {
|
||||
self.base = self.base.wrapping_add(1);
|
||||
}
|
||||
|
||||
/// Only `page`'s picture is out of date.
|
||||
pub fn bump(&mut self, page: usize) {
|
||||
let n = self.bumps.entry(page).or_insert(0);
|
||||
*n = n.wrapping_add(1);
|
||||
}
|
||||
|
||||
/// The generation of `page`'s picture: the document's and the page's own.
|
||||
pub fn of(&self, page: usize) -> (u64, u64) {
|
||||
(self.base, self.bumps.get(&page).copied().unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Reports {
|
||||
errors: HashMap<usize, String>,
|
||||
cut: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
/// What render jobs found out about pages: why a page could not be drawn, and which pages were cut at the
|
||||
/// renderer's limits. Shared with the jobs, which run on other threads.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct RenderReports(Arc<Mutex<Reports>>);
|
||||
|
||||
impl RenderReports {
|
||||
fn lock(&self) -> MutexGuard<'_, Reports> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Records that `page` could not be rendered.
|
||||
pub fn error(&self, page: usize, message: String) {
|
||||
self.lock().errors.insert(page, message);
|
||||
}
|
||||
|
||||
/// Records that `page`'s content was cut at the renderer's limits.
|
||||
pub fn cut(&self, page: usize) {
|
||||
self.lock().cut.insert(page);
|
||||
}
|
||||
|
||||
/// Forgets everything known about `page`: its content changed.
|
||||
pub fn forget(&self, page: usize) {
|
||||
let mut reports = self.lock();
|
||||
reports.errors.remove(&page);
|
||||
reports.cut.remove(&page);
|
||||
}
|
||||
|
||||
/// Forgets every page's reports.
|
||||
pub fn clear(&self) {
|
||||
let mut reports = self.lock();
|
||||
reports.errors.clear();
|
||||
reports.cut.clear();
|
||||
}
|
||||
|
||||
/// The pages that could not be rendered with the reason, in page order.
|
||||
pub fn errors(&self) -> Vec<(usize, String)> {
|
||||
let mut all: Vec<(usize, String)> = self.lock().errors.iter().map(|(p, e)| (*p, e.clone())).collect();
|
||||
all.sort_unstable_by_key(|(p, _)| *p);
|
||||
all
|
||||
}
|
||||
|
||||
/// The pages cut at the renderer's limits, in page order.
|
||||
pub fn cut_pages(&self) -> Vec<usize> {
|
||||
self.lock().cut.iter().copied().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// One document's pages as a [`PageSource`] and the source of print previews. It owns what a render job reads, so
|
||||
/// jobs outlive the pass that made them.
|
||||
pub struct DocPages<'a> {
|
||||
info: Option<&'a DocInfo>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
config: RenderConfig,
|
||||
rotation: u16,
|
||||
revisions: Option<&'a PageRevisions>,
|
||||
reports: Option<RenderReports>,
|
||||
}
|
||||
|
||||
impl<'a> DocPages<'a> {
|
||||
/// The pages of document `doc`; with no such document there are no pages.
|
||||
pub fn new(session: &'a Session, doc: DocId) -> Self {
|
||||
let document = session.get(doc);
|
||||
Self {
|
||||
info: document.map(|d| &d.info),
|
||||
bytes: document.map(|d| d.display.clone()).unwrap_or_default(),
|
||||
config: session.render_config(doc).unwrap_or_default(),
|
||||
rotation: 0,
|
||||
revisions: None,
|
||||
reports: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the pages turned by the view's rotation (degrees clockwise).
|
||||
#[must_use]
|
||||
pub fn rotated(mut self, degrees: u16) -> Self {
|
||||
self.rotation = degrees % 360;
|
||||
self
|
||||
}
|
||||
|
||||
/// Versions the pictures by `revisions`.
|
||||
#[must_use]
|
||||
pub fn revisions(mut self, revisions: &'a PageRevisions) -> Self {
|
||||
self.revisions = Some(revisions);
|
||||
self
|
||||
}
|
||||
|
||||
/// Has render jobs report failures and cut pages to `reports`.
|
||||
#[must_use]
|
||||
pub fn reports(mut self, reports: &RenderReports) -> Self {
|
||||
self.reports = Some(reports.clone());
|
||||
self
|
||||
}
|
||||
|
||||
fn revision_of(&self, page: usize, request: &ThumbRequest, print: Option<bool>) -> Revision {
|
||||
let generation = self.revisions.map_or((0, 0), |r| r.of(page));
|
||||
let region = request.region.map(|r| [r.min.x.to_bits(), r.min.y.to_bits(), r.max.x.to_bits(), r.max.y.to_bits()]);
|
||||
Revision::of(&(generation, request.side, region, self.rotation, print))
|
||||
}
|
||||
|
||||
/// The job making `page` at `request`; `print` is `Some(grayscale)` for a print preview.
|
||||
fn render_page(&self, page: usize, request: &ThumbRequest, print: Option<bool>) -> ThumbRender {
|
||||
let reports = self.reports.clone();
|
||||
let Some(info) = self.info.and_then(|i| i.pages.get(page)) else {
|
||||
return ThumbRender::Later(Box::new(|_| Err(LoadFailure::Missing)));
|
||||
};
|
||||
// The region is in the turned frame the view shows; the renderer draws the page unturned.
|
||||
let region = request.region.map(|r| unturned(r, self.rotation));
|
||||
let (pw, ph) = (f64::from(info.width), f64::from(info.height));
|
||||
let part = region.map_or((pw, ph), |r| (f64::from(r.width()) * pw, f64::from(r.height()) * ph));
|
||||
let scale = (f64::from(request.side) / part.0.max(part.1).max(1e-3)) as f32;
|
||||
if !scale.is_finite() || scale <= 0.0 {
|
||||
return ThumbRender::Later(Box::new(|_| Err(LoadFailure::Unreadable)));
|
||||
}
|
||||
let tile = region.map(|r| Tile {
|
||||
x: (f64::from(r.min.x) * pw * f64::from(scale)).floor().max(0.0) as u32,
|
||||
y: (f64::from(r.min.y) * ph * f64::from(scale)).floor().max(0.0) as u32,
|
||||
w: (part.0 * f64::from(scale)).ceil().max(1.0) as u32,
|
||||
h: (part.1 * f64::from(scale)).ceil().max(1.0) as u32,
|
||||
});
|
||||
let (bytes, rotation) = (self.bytes.clone(), self.rotation);
|
||||
// Installed faces draw on screen only: a print preview must match the printout.
|
||||
let config = if print.is_some() { self.config.clone() } else { self.config.clone().on_screen() };
|
||||
let tag = if print.is_some() { PRINT_TAG } else { 0 };
|
||||
ThumbRender::Later(Box::new(move |cancel| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(LoadFailure::Missing);
|
||||
}
|
||||
let mut renderer = PageRenderer::new(bytes, config);
|
||||
let out = renderer.render(RenderRequest { page, kind: RequestKind::Pixels, tile, scale, tag, preview: false });
|
||||
if cancel.is_cancelled() {
|
||||
return Err(LoadFailure::Missing);
|
||||
}
|
||||
if out.warnings.contains(&RenderWarning::ContentTruncated)
|
||||
&& let Some(reports) = &reports
|
||||
{
|
||||
reports.cut(page);
|
||||
}
|
||||
if let Some(error) = out.error {
|
||||
log::warn!("page {}: {error}", page + 1);
|
||||
if let Some(reports) = &reports {
|
||||
reports.error(page, error.clone());
|
||||
}
|
||||
return Err(LoadFailure::Message(error));
|
||||
}
|
||||
let size = [out.width as usize, out.height as usize];
|
||||
if size[0] == 0 || size[1] == 0 {
|
||||
return Err(LoadFailure::Unreadable);
|
||||
}
|
||||
let image = turned(texture_image(size, out.rgba), rotation);
|
||||
Ok(LoadedPicture::Image(if print == Some(true) { grayscale(image) } else { image }))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl PageSource for DocPages<'_> {
|
||||
fn page_count(&self) -> usize {
|
||||
self.info.map_or(0, |i| i.pages.len())
|
||||
}
|
||||
|
||||
fn page_size(&self, page: usize) -> Size {
|
||||
let Some(p) = self.info.and_then(|i| i.pages.get(page)) else { return Size::ZERO };
|
||||
let (w, h) = (f64::from(p.width), f64::from(p.height));
|
||||
if self.rotation % 180 == 90 { Size::new(h, w) } else { Size::new(w, h) }
|
||||
}
|
||||
|
||||
fn page_label(&self, page: usize) -> String {
|
||||
self.info.and_then(|i| i.pages.get(page)).map_or_else(|| (page + 1).to_string(), |p| p.label.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> for DocPages<'_> {
|
||||
fn revision(&self, key: &usize, request: &ThumbRequest) -> Revision {
|
||||
self.revision_of(*key, request, None)
|
||||
}
|
||||
|
||||
fn render(&self, key: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
self.render_page(*key, request, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<PrintPage> for DocPages<'_> {
|
||||
fn revision(&self, key: &PrintPage, request: &ThumbRequest) -> Revision {
|
||||
self.revision_of(key.page, request, Some(key.grayscale))
|
||||
}
|
||||
|
||||
fn render(&self, key: &PrintPage, request: &ThumbRequest) -> ThumbRender {
|
||||
self.render_page(key.page, request, Some(key.grayscale))
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of the unturned page that shows as `region` (fractions) once the page is turned `rotation` degrees
|
||||
/// clockwise.
|
||||
fn unturned(region: Rect, rotation: u16) -> Rect {
|
||||
let (u0, u1, v0, v1) = (region.min.x, region.max.x, region.min.y, region.max.y);
|
||||
match rotation % 360 {
|
||||
90 => Rect::from_min_max(egui::pos2(v0, 1.0 - u1), egui::pos2(v1, 1.0 - u0)),
|
||||
180 => Rect::from_min_max(egui::pos2(1.0 - u1, 1.0 - v1), egui::pos2(1.0 - u0, 1.0 - v0)),
|
||||
270 => Rect::from_min_max(egui::pos2(1.0 - v1, u0), egui::pos2(1.0 - v0, u1)),
|
||||
_ => region,
|
||||
}
|
||||
}
|
||||
|
||||
/// `image` turned `rotation` degrees clockwise (a multiple of 90; anything else leaves it).
|
||||
fn turned(image: ColorImage, rotation: u16) -> ColorImage {
|
||||
let [w, h] = image.size;
|
||||
let at = |x: usize, y: usize| image.pixels.get(y.saturating_mul(w).saturating_add(x)).copied().unwrap_or(Color32::TRANSPARENT);
|
||||
match rotation % 360 {
|
||||
90 => ColorImage::new([h, w], (0..w).flat_map(|y| (0..h).map(move |x| (x, y))).map(|(x, y)| at(y, h - 1 - x)).collect()),
|
||||
180 => ColorImage::new([w, h], image.pixels.iter().rev().copied().collect()),
|
||||
270 => ColorImage::new([h, w], (0..w).flat_map(|y| (0..h).map(move |x| (x, y))).map(|(x, y)| at(w - 1 - y, x)).collect()),
|
||||
_ => image,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::PdfCraftApp;
|
||||
use craft::host::{AppInfo, Host, ManualJobs, Wake};
|
||||
use egui_kittest::Harness;
|
||||
|
||||
/// Runs frames and the queued jobs until every picture has landed.
|
||||
fn settle(h: &mut Harness<'static, PdfCraftApp>, jobs: &ManualJobs) {
|
||||
for _ in 0..40 {
|
||||
h.run_steps(1);
|
||||
if jobs.run_all() == 0 && !h.state().render_pending() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("the pictures never settled");
|
||||
}
|
||||
|
||||
/// A page edit must queue a render for that page only and a document change one for every page: a wrong bump
|
||||
/// leaves a stale picture on screen with no error.
|
||||
#[test]
|
||||
fn a_page_edit_makes_its_picture_a_new_revision_and_leaves_the_others() {
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let queue = jobs.clone();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
// PLAN: assumed `AppInfo` built by literal and `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207, pdf-hub-w1)
|
||||
let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(queue.clone()).build();
|
||||
let mut app = PdfCraftApp::with_host(Arc::new(host), crate::AppServices::new(Wake::none(), None, None, None, None, None));
|
||||
let blank = app.session.create_blank(200.0, 300.0, 3).expect("a blank document");
|
||||
app.open_bytes("three.pdf", None, blank.as_ref().clone()).expect("opens");
|
||||
app
|
||||
});
|
||||
settle(&mut h, &jobs);
|
||||
// One frame queues what the change outdates; the jobs wait for the test to run them.
|
||||
h.state_mut().views[0].page_changed(1);
|
||||
h.run_steps(1);
|
||||
let edited = jobs.waiting();
|
||||
settle(&mut h, &jobs);
|
||||
let info = {
|
||||
let app = h.state();
|
||||
app.session.get(app.views[0].id).expect("the document").info.clone()
|
||||
};
|
||||
h.state_mut().views[0].document_changed(&info);
|
||||
h.run_steps(1);
|
||||
let all = jobs.waiting();
|
||||
assert!(edited >= 1, "the edited page is rendered again");
|
||||
assert!(edited < all, "the other pages keep their pictures: {edited} jobs for one page, {all} for the document");
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,13 @@
|
||||
use super::{DocInfo, DocView, Fit, GAP, MARGIN, PT, PageLayout, Pos2, Rect, SIDE, SavedDisplay, Vec2, device_pixels, pos2, vec2};
|
||||
use craft::pages::ui::THUMBNAIL_ZOOM;
|
||||
use craft::pages::{Fit, LayoutOptions, PageDisplay, shown_row};
|
||||
|
||||
/// The page grid's zoom range and the step of its buttons and keys.
|
||||
pub const GRID_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;
|
||||
|
||||
/// Thumbnail size in the Pages inspector, relative to its usual size.
|
||||
pub const THUMBNAIL_ZOOM_RANGE: std::ops::RangeInclusive<f32> = 0.5..=1.5;
|
||||
|
||||
pub(super) const GRID_ZOOM_STEP: f32 = 1.25;
|
||||
use super::{DocInfo, DocView, PT, SavedDisplay, vec2};
|
||||
|
||||
impl DocView {
|
||||
/// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).
|
||||
pub fn rotate_view(&mut self, clockwise: bool) {
|
||||
self.rotation = (self.rotation + if clockwise { 90 } else { 270 }) % 360;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.reset_coarse_state();
|
||||
}
|
||||
|
||||
/// Switch the zoom mode, keeping the current page in view.
|
||||
pub fn set_fit(&mut self, fit: Fit) {
|
||||
self.fit = fit;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.reset_coarse_state();
|
||||
/// Whether Select All of the document applies: it belongs to continuous scrolling, and the flag stays set
|
||||
/// while the view is paged.
|
||||
pub fn all_text_active(&self) -> bool {
|
||||
self.all_text && self.view.continuous
|
||||
}
|
||||
|
||||
/// Full screen, as Acrobat's Full Screen Mode (#379, #1459): one page at a time (or one
|
||||
@@ -30,35 +17,40 @@ impl DocView {
|
||||
if self.presentation.is_some() {
|
||||
return;
|
||||
}
|
||||
self.presentation =
|
||||
Some(SavedDisplay { layout: self.layout, continuous: self.continuous, cover: self.cover, fit: self.fit, zoom: self.zoom });
|
||||
self.continuous = false;
|
||||
self.fit = Fit::Page;
|
||||
self.selection = None;
|
||||
self.presentation = Some(SavedDisplay {
|
||||
display: self.view.display,
|
||||
continuous: self.view.continuous,
|
||||
cover: self.view.cover,
|
||||
fit: self.view.fit,
|
||||
zoom: self.view.zoom,
|
||||
});
|
||||
self.view.continuous = false;
|
||||
self.view.fit = Fit::Page;
|
||||
self.text.selection = None;
|
||||
self.presenter = Default::default();
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.view.go_to(self.view.current);
|
||||
}
|
||||
|
||||
/// Leave full screen: the display from before it comes back, at the page reached meanwhile.
|
||||
pub fn leave_presentation(&mut self) {
|
||||
let Some(saved) = self.presentation.take() else { return };
|
||||
self.presenter = Default::default();
|
||||
self.layout = saved.layout;
|
||||
self.continuous = saved.continuous;
|
||||
self.cover = saved.cover;
|
||||
self.fit = saved.fit;
|
||||
self.zoom = saved.zoom;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.view.display = saved.display;
|
||||
self.view.continuous = saved.continuous;
|
||||
self.view.cover = saved.cover;
|
||||
self.view.fit = saved.fit;
|
||||
self.view.zoom = saved.zoom;
|
||||
self.view.go_to(self.view.current);
|
||||
}
|
||||
|
||||
/// The display shown outside full screen: the one presenting replaced, or the current one.
|
||||
pub fn normal_display(&self) -> SavedDisplay {
|
||||
self.presentation.unwrap_or(SavedDisplay {
|
||||
layout: self.layout,
|
||||
continuous: self.continuous,
|
||||
cover: self.cover,
|
||||
fit: self.fit,
|
||||
zoom: self.zoom,
|
||||
display: self.view.display,
|
||||
continuous: self.view.continuous,
|
||||
cover: self.view.cover,
|
||||
fit: self.view.fit,
|
||||
zoom: self.view.zoom,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -78,323 +70,64 @@ impl DocView {
|
||||
self.presenter.turning()
|
||||
}
|
||||
|
||||
/// Switch the base page display (Single or Two-page), leaving continuous scrolling as it is.
|
||||
/// A no-op when the layout is already current, so re-selecting it never yanks a scrolled view
|
||||
/// back to the top.
|
||||
pub fn set_layout(&mut self, layout: PageLayout) {
|
||||
if self.layout == layout {
|
||||
return;
|
||||
}
|
||||
self.layout = layout;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.reset_coarse_state();
|
||||
}
|
||||
|
||||
/// Whether the view scrolls continuously (as opposed to one page or spread at a time).
|
||||
pub fn continuous(&self) -> bool {
|
||||
self.continuous
|
||||
}
|
||||
|
||||
/// Change page separation without editing the PDF or losing the reader's place.
|
||||
pub fn set_page_gaps(&mut self, show: bool) {
|
||||
if self.show_page_gaps == show {
|
||||
return;
|
||||
}
|
||||
if !self.organize && self.viewport_screen.is_positive() {
|
||||
let at = self.viewport_screen.center();
|
||||
if let Some((page, r)) = self
|
||||
.screen_rects
|
||||
.iter()
|
||||
.filter(|(_, r)| r.is_positive())
|
||||
.min_by(|(_, a), (_, b)| a.distance_sq_to_pos(at).total_cmp(&b.distance_sq_to_pos(at)))
|
||||
{
|
||||
let fraction = (at - r.min) / r.size();
|
||||
self.zoom_anchor = Some((*page, fraction.x, fraction.y, at - self.viewport_screen.min));
|
||||
}
|
||||
}
|
||||
self.show_page_gaps = show;
|
||||
}
|
||||
|
||||
/// Separation between adjacent page rectangles, in logical screen points.
|
||||
pub(super) fn page_gap(&self) -> f32 {
|
||||
if self.show_page_gaps { GAP } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Turn continuous scrolling on or off, keeping the current page in view. A no-op when it is
|
||||
/// already in that state.
|
||||
pub fn set_continuous(&mut self, continuous: bool) {
|
||||
if self.continuous != continuous {
|
||||
self.continuous = continuous;
|
||||
// Select All of the document belongs to continuous scrolling.
|
||||
self.all_text = false;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.reset_coarse_state();
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the whole page display at once (the base layout and continuous scrolling together),
|
||||
/// as the control channel and settings do through a single [`display_token`].
|
||||
pub fn set_display(&mut self, layout: PageLayout, continuous: bool) {
|
||||
self.set_layout(layout);
|
||||
self.set_continuous(continuous);
|
||||
}
|
||||
|
||||
/// Set the cover page in two-page view. A no-op unless something changed.
|
||||
pub fn set_cover(&mut self, cover: bool) {
|
||||
if self.cover != cover {
|
||||
self.cover = cover;
|
||||
self.goto = Some((self.current, 0.0));
|
||||
self.reset_coarse_state();
|
||||
}
|
||||
self.view.continuous
|
||||
}
|
||||
|
||||
/// Whether the cover page setting applies: only two-page view has a cover page.
|
||||
pub fn cover_applies(&self) -> bool {
|
||||
self.layout == PageLayout::TwoUp
|
||||
self.view.display == PageDisplay::TwoUp
|
||||
}
|
||||
|
||||
/// The page (or spread) the view shows first, as `FitWindow` sizes the window to it
|
||||
/// ([`crate::viewer_prefs::window_commands`]). `None` when there is no such page.
|
||||
///
|
||||
/// The row is the framework's own spread rule. The margins are the spacing the last layout used: the
|
||||
/// gutter at each side, the gap between a spread's pages, and the margin above and below.
|
||||
pub(crate) fn first_page_now(&self, info: &DocInfo) -> Option<crate::viewer_prefs::PageNow> {
|
||||
info.pages.get(self.current)?;
|
||||
// Two-page view shows the spread the page is in (a cover page on its own); the spread
|
||||
// is as wide as its pages side by side and as tall as the taller one, as `layout`
|
||||
// places it. The last spread of an odd page count has one page.
|
||||
let (first, last) = if self.layout == PageLayout::TwoUp {
|
||||
let first = self.spread_first(self.current);
|
||||
(first, if self.cover && first == 0 { 0 } else { first.saturating_add(1) })
|
||||
} else {
|
||||
(self.current, self.current)
|
||||
info.pages.get(self.view.current)?;
|
||||
let spacing = self.spacing?;
|
||||
let options = LayoutOptions {
|
||||
display: self.view.display,
|
||||
cover: self.view.cover,
|
||||
continuous: self.view.continuous,
|
||||
page_gaps: self.view.page_gaps,
|
||||
..LayoutOptions::ACROBAT
|
||||
};
|
||||
let row = shown_row(info.pages.len(), self.view.current, &options);
|
||||
let turned = self.view.rotation % 180 == 90;
|
||||
let sizes: Vec<(f32, f32)> =
|
||||
info.pages.iter().skip(first).take(last.saturating_sub(first).saturating_add(1)).map(|p| self.display_size(p)).collect();
|
||||
info.pages.get(row).unwrap_or_default().iter().map(|p| if turned { (p.height, p.width) } else { (p.width, p.height) }).collect();
|
||||
let w: f32 = sizes.iter().map(|s| s.0).sum();
|
||||
let h = sizes.iter().map(|s| s.1).fold(0.0, f32::max);
|
||||
let gap = self.page_gap() * sizes.len().saturating_sub(1) as f32;
|
||||
let gap = if self.view.page_gaps { spacing.gap as f32 } else { 0.0 };
|
||||
let across = gap * sizes.len().saturating_sub(1) as f32;
|
||||
Some(crate::viewer_prefs::PageNow {
|
||||
size: vec2(w * PT, h * PT),
|
||||
margins: vec2(2.0 * SIDE + gap, 2.0 * MARGIN),
|
||||
zoom: (self.fit == Fit::None).then_some(self.zoom),
|
||||
margins: vec2(2.0 * spacing.side as f32 + across, 2.0 * spacing.margin as f32),
|
||||
zoom: (self.view.fit == Fit::None).then_some(self.view.zoom as f32),
|
||||
})
|
||||
}
|
||||
|
||||
/// Displayed page size in points for this view rotation.
|
||||
pub(super) fn display_size(&self, p: &pdfcraft_render::PageInfo) -> (f32, f32) {
|
||||
if self.rotation % 180 == 90 { (p.height, p.width) } else { (p.width, p.height) }
|
||||
}
|
||||
|
||||
/// Marquee Zoom: zoom so `r` (on screen) fills the window, centred.
|
||||
pub fn zoom_to_rect(&mut self, r: Rect) {
|
||||
let Some((page, pr)) = self.screen_rects.iter().find(|(_, pr)| pr.contains(r.center())).copied() else { return };
|
||||
let k = (self.viewport_screen.width() / r.width().max(1.0)).min(self.viewport_screen.height() / r.height().max(1.0));
|
||||
let f = (r.center() - pr.min) / pr.size();
|
||||
self.zoom = (self.zoom * k).clamp(0.08, 64.0);
|
||||
self.fit = Fit::None;
|
||||
self.zoom_anchor = Some((page, f.x.clamp(0.0, 1.0), f.y.clamp(0.0, 1.0), self.viewport_screen.center() - self.viewport_screen.min));
|
||||
}
|
||||
|
||||
/// View ▸ Zoom ▸ Fit Visible: zoom so the visible content of `page` (display-normalised
|
||||
/// [x0, y0, x1, y1], i.e. after view rotation) spans the window's width, its left edge at
|
||||
/// the window's left and its top at the top.
|
||||
pub fn fit_content(&mut self, page: usize, content: [f32; 4]) -> bool {
|
||||
const PAD: f32 = 16.0;
|
||||
let Some((_, pr)) = self.screen_rects.iter().find(|(p, _)| *p == page).copied() else { return false };
|
||||
let w = (content[2] - content[0]).max(0.01) * pr.width();
|
||||
let k = (self.viewport_screen.width() - 2.0 * PAD).max(50.0) / w.max(1.0);
|
||||
self.zoom = (self.zoom * k).clamp(0.08, 64.0);
|
||||
self.fit = Fit::None;
|
||||
self.zoom_anchor = Some((page, content[0].clamp(0.0, 1.0), content[1].clamp(0.0, 1.0), vec2(PAD, MARGIN)));
|
||||
true
|
||||
}
|
||||
|
||||
/// How large the page grid draws its pages (1.0 = the usual thumbnails).
|
||||
pub fn grid_zoom(&self) -> f32 {
|
||||
self.grid_zoom
|
||||
}
|
||||
|
||||
/// Scale of the thumbnails in the Pages inspector (1.0 is the usual size).
|
||||
pub fn thumbnail_zoom(&self) -> f32 {
|
||||
self.thumbnail_zoom
|
||||
}
|
||||
|
||||
/// Resize the inspector thumbnails, keeping the current page in view after layout.
|
||||
/// Out-of-range values are clamped; non-finite values are ignored.
|
||||
/// Resize the inspector thumbnails.
|
||||
/// Out-of-range values are clamped to the framework's thumbnail zoom; non-finite values are ignored.
|
||||
pub fn set_thumbnail_zoom(&mut self, zoom: f32) {
|
||||
if zoom.is_finite() {
|
||||
let zoom = zoom.clamp(*THUMBNAIL_ZOOM_RANGE.start(), *THUMBNAIL_ZOOM_RANGE.end());
|
||||
if zoom != self.thumbnail_zoom {
|
||||
self.thumbnail_zoom = zoom;
|
||||
self.panel_followed = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zoom the page grid; out-of-range values are clamped and nonsense is ignored.
|
||||
pub fn set_grid_zoom(&mut self, zoom: f32) {
|
||||
if zoom.is_finite() {
|
||||
self.grid_zoom = zoom.clamp(*GRID_ZOOM_RANGE.start(), *GRID_ZOOM_RANGE.end());
|
||||
}
|
||||
}
|
||||
|
||||
/// Zoom keeping the centre of the view still.
|
||||
pub fn set_zoom(&mut self, zoom: f32) {
|
||||
// CLI/view options can set zoom before the first layout. Rect::NOTHING has no
|
||||
// finite centre yet, but an initial zoom still needs to leave the default fit mode.
|
||||
let centre = if self.viewport_screen.is_positive() { self.viewport_screen.center() } else { Pos2::ZERO };
|
||||
self.zoom_at(zoom, centre);
|
||||
}
|
||||
|
||||
/// Zoom keeping the document point under `screen_pos` still (pinch, ⌘-scroll).
|
||||
pub fn zoom_at(&mut self, zoom: f32, screen_pos: Pos2) {
|
||||
if !zoom.is_finite() || !screen_pos.is_finite() {
|
||||
return;
|
||||
}
|
||||
let zoom = zoom.clamp(0.08, 64.0);
|
||||
if zoom == self.zoom && self.fit == Fit::None {
|
||||
return;
|
||||
}
|
||||
// Just after a find step, around the match at the window's centre (#3530).
|
||||
let held = self.find_hold.map(|(p, fx, fy)| (p, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0));
|
||||
// In gutters/gaps, anchor relative to the nearest page rather than jumping to its top.
|
||||
// Fractions outside 0..1 preserve the pointer's position outside the page as well.
|
||||
let anchor = held.or_else(|| {
|
||||
self.screen_rects.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(screen_pos).total_cmp(&b.distance_sq_to_pos(screen_pos))).map(
|
||||
|(p, r)| {
|
||||
let f = (screen_pos - r.min) / r.size();
|
||||
(*p, f.x, f.y, screen_pos - self.viewport_screen.min)
|
||||
},
|
||||
)
|
||||
});
|
||||
self.zoom = zoom;
|
||||
self.fit = Fit::None;
|
||||
match anchor {
|
||||
Some(a) => self.zoom_anchor = Some(a),
|
||||
// Nothing on screen yet (e.g. a launch option): align the current page instead.
|
||||
None => self.goto = Some((self.current, 0.0)),
|
||||
let range = THUMBNAIL_ZOOM.range();
|
||||
self.thumbnail_zoom = zoom.clamp(*range.start() as f32, *range.end() as f32);
|
||||
}
|
||||
}
|
||||
|
||||
/// A zoom typed as a percentage ("150", "150%", " 62.5 % ") as a zoom factor; `None` unless it is a
|
||||
/// finite, positive number. `set_zoom` clamps it to the supported range.
|
||||
/// finite, positive number. The page view clamps it to the supported range.
|
||||
pub fn parse_zoom_percent(typed: &str) -> Option<f32> {
|
||||
let percent = typed.trim().trim_end_matches('%').trim_end().parse::<f32>().ok()?;
|
||||
(percent.is_finite() && percent > 0.0).then_some(percent / 100.0)
|
||||
}
|
||||
|
||||
/// Standard zoom steps (as in Acrobat's zoom menu).
|
||||
pub fn zoom_step(&mut self, up: bool) {
|
||||
const STEPS: [f32; 17] = [0.1, 0.25, 0.33, 0.5, 0.66, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 32.0];
|
||||
let z = self.zoom;
|
||||
let next = if up { STEPS.iter().copied().find(|s| *s > z * 1.01) } else { STEPS.iter().rev().copied().find(|s| *s < z * 0.99) };
|
||||
if let Some(n) = next {
|
||||
self.set_zoom(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// The first page of the two-page spread page `c` is in: spreads are [0, 1], [2, 3], … or,
|
||||
/// with a cover page, [0], [1, 2], [3, 4], ….
|
||||
pub(super) fn spread_first(&self, c: usize) -> usize {
|
||||
if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 }
|
||||
}
|
||||
|
||||
pub(super) fn fit_zoom(&mut self, info: &DocInfo) {
|
||||
let largest = |side: fn((f32, f32)) -> f32| info.pages.iter().map(|p| side(self.display_size(p))).fold(1.0, f32::max);
|
||||
let max_w = largest(|s| s.0);
|
||||
// A single page shown on its own fits that page, and full screen in two-page view fits
|
||||
// the spread it shows (review on #2070). Every other display (scrolling, or two-page
|
||||
// view in the window) fits its largest page, so the zoom holds still while pages of
|
||||
// other sizes scroll or page past.
|
||||
let (w, h) = if self.layout == PageLayout::Single && !self.continuous {
|
||||
info.pages.get(self.current).map_or_else(|| (max_w, largest(|s| s.1)), |p| self.display_size(p))
|
||||
} else if self.presentation.is_some() && self.layout == PageLayout::TwoUp && !self.continuous {
|
||||
let first = self.spread_first(self.current);
|
||||
let last = if self.cover && first == 0 { 0 } else { first.saturating_add(1) };
|
||||
let spread: Vec<(f32, f32)> = info.pages.iter().skip(first).take(last - first + 1).map(|p| self.display_size(p)).collect();
|
||||
if spread.is_empty() {
|
||||
(max_w, largest(|s| s.1))
|
||||
} else {
|
||||
(spread.iter().map(|s| s.0).fold(1.0, f32::max), spread.iter().map(|s| s.1).fold(1.0, f32::max))
|
||||
}
|
||||
} else {
|
||||
(max_w, largest(|s| s.1))
|
||||
};
|
||||
let avail_w = (self.viewport_w - 2.0 * SIDE).max(100.0);
|
||||
let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };
|
||||
match self.fit {
|
||||
Fit::Width => self.zoom = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row),
|
||||
Fit::Page => {
|
||||
let zw = (avail_w - self.page_gap() * (per_row - 1.0)) / (w * PT * per_row);
|
||||
let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);
|
||||
self.zoom = zw.min(zh);
|
||||
}
|
||||
Fit::Height => self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT),
|
||||
Fit::None => {}
|
||||
}
|
||||
self.zoom = self.zoom.clamp(0.08, 64.0);
|
||||
}
|
||||
|
||||
/// Width of the scroll content. Single-page view sizes it to the page it shows, so a
|
||||
/// wider page elsewhere in the document can't push the shown one off-centre.
|
||||
pub(super) fn content_width(&self, info: &DocInfo, avail_w: f32) -> f32 {
|
||||
let single = (self.layout == PageLayout::Single && !self.continuous).then(|| self.current.min(info.pages.len().saturating_sub(1)));
|
||||
let shown = info.pages.iter().enumerate().filter(|&(i, _)| single.is_none_or(|c| c == i));
|
||||
let max_w = shown.map(|(_, p)| self.display_size(p).0).fold(0.0, f32::max);
|
||||
let per_row = if self.layout == PageLayout::TwoUp { 2.0 } else { 1.0 };
|
||||
(max_w * self.zoom * PT * per_row + 2.0 * SIDE).max(avail_w)
|
||||
}
|
||||
|
||||
/// Page rects in content coordinates (origin at the scroll content's top-left).
|
||||
pub(super) fn layout(&self, info: &DocInfo, content_w: f32, ppp: f32) -> Vec<Rect> {
|
||||
let s = self.zoom * PT;
|
||||
let gap = self.page_gap();
|
||||
let page_size = |p: &pdfcraft_render::PageInfo| {
|
||||
let (w, h) = self.display_size(p);
|
||||
if self.show_page_gaps {
|
||||
vec2(w * s, h * s)
|
||||
} else {
|
||||
// Match the raster's whole physical pixels. Snapping each page's origin
|
||||
// independently with fractional sizes would leave hairline seams.
|
||||
vec2(device_pixels(w, s * ppp) as f32 / ppp, device_pixels(h, s * ppp) as f32 / ppp)
|
||||
}
|
||||
};
|
||||
let mut rects = Vec::with_capacity(info.pages.len());
|
||||
let mut y = MARGIN;
|
||||
match self.layout {
|
||||
PageLayout::Single => {
|
||||
for p in &info.pages {
|
||||
let size = page_size(p);
|
||||
rects.push(Rect::from_min_size(pos2(((content_w - size.x) / 2.0).max(SIDE), y), size));
|
||||
y += size.y + gap;
|
||||
}
|
||||
}
|
||||
PageLayout::TwoUp => {
|
||||
// With a cover page, the first page sits alone on the right.
|
||||
let rows: Vec<&[pdfcraft_render::PageInfo]> = if self.cover && !info.pages.is_empty() {
|
||||
std::iter::once(&info.pages[..1]).chain(info.pages[1..].chunks(2)).collect()
|
||||
} else {
|
||||
info.pages.chunks(2).collect()
|
||||
};
|
||||
for (ri, pair) in rows.into_iter().enumerate() {
|
||||
let sizes: Vec<Vec2> = pair.iter().map(page_size).collect();
|
||||
let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + gap * (sizes.len() as f32 - 1.0);
|
||||
let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);
|
||||
let mut x = if self.cover && ri == 0 { (content_w / 2.0 + gap / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) };
|
||||
for size in sizes {
|
||||
rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size));
|
||||
x += size.x + gap;
|
||||
}
|
||||
y += row_h + gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
rects
|
||||
}
|
||||
}
|
||||
|
||||
/// The scroll offset that puts `point` (content coordinates) at `rel` in the viewport, kept within
|
||||
/// the content as egui keeps it. egui clamps only after drawing, so an offset past the end showed
|
||||
/// the page misplaced for a frame and then jumped (zooming out beside a page that fits).
|
||||
pub(super) fn anchored_scroll(point: Pos2, rel: Vec2, content: Vec2, viewport: Vec2) -> Vec2 {
|
||||
let max = vec2((content.x - viewport.x).max(0.0), (content.y - viewport.y).max(0.0));
|
||||
vec2((point.x - rel.x).clamp(0.0, max.x), (point.y - rel.y).clamp(0.0, max.y))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user