PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge branch 'upstream/main' into main with layout adaptation
Combiler012650cbc90698
diff --cc crates/engine/src/doc_state.rsindex 000000000,d25cc6503..db7e3b950mode 000000,100644..100644--- a/crates/engine/src/doc_state.rs+++ b/crates/engine/src/doc_state.rs@@@ -1,0 -1,118 +1,124 @@@+ use super::*;++ /// A change to an existing page image.+ #[derive(Clone, Debug, PartialEq)]+ pub enum ImageEdit {+ /// Move and resize it to this box (user space).+ Move([f64; 4]),+ /// Quarter turns clockwise about its centre.+ Rotate(i32),+ /// Any angle in degrees clockwise about its centre (the unit is degrees, not quarter turns).+ RotateBy(f64),+ Flip {+ horizontal: bool,+ },+ /// Show only this box of it (user space), the pixels staying where they are.+ Crop([f64; 4]),+ /// Draw this image file (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000) in its place.+ Replace {+ name: String,+ bytes: Arc<Vec<u8>>,+ },+ Delete,++ /// Affine transform [a, b, c, d, e, f] applied to the image's matrix.++ Transform([f64; 6]),++ /// Change the stacking order.++ Arrange(ArrangeOrder),++ /// Remove any private crop on the image.++ RemoveCrop,+ }++ /// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a+ /// filled-in PDF form), as CSV with one row per file.+ pub fn merge_data_files(files: &[(String, Vec<u8>)]) -> Result<String, String> {+ let rows =+ files.iter().map(|(name, bytes)| pdfcraft_xfdf::data_values(bytes).map_err(|e| format!("{name}: {e}"))).collect::<Result<Vec<_>, _>>()?;+ Ok(pdfcraft_xfdf::merge_csv(&rows))+ }++ /// One file produced by a split: (1-based first page, last page, PDF bytes).+ pub type SplitPart = (usize, usize, Arc<Vec<u8>>);++ /// Stable identifier of an open document within a session.+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+ pub struct DocId(pub u64);++ /// The highest resolution a document that allows only low-resolution printing (Table 22, bit 12+ /// clear) is printed at.+ pub(crate) const LOW_RESOLUTION_PRINT_DPI: f64 = 150.0;++ pub(crate) fn render_threads() -> usize {+ std::thread::available_parallelism().map(std::num::NonZeroUsize::get).unwrap_or(4).clamp(2, 8) - 1+ }++ /// A document's working file captured for crash recovery.+ #[derive(Clone, Debug)]+ pub struct RecoverySnapshot {+ pub doc: DocId,+ pub name: String,+ pub path: Option<String>,+ pub bytes: Arc<Vec<u8>>,+ /// The snapshot is encrypted (recovering it asks for the password again).+ pub encrypted: bool,+ }++ /// The recovered user password of an R2–R4 file as text for the renderer, which tries a password+ /// as its UTF-8 bytes and then in PDFDocEncoding: UTF-8 bytes (as some writers store passwords+ /// PDFDocEncoding can't hold, such as "şifre") stay UTF-8, and other bytes are read as+ /// PDFDocEncoding, so either way the renderer gets back exactly these bytes.+ pub(crate) fn renderer_password(bytes: &[u8]) -> String {+ match std::str::from_utf8(bytes) {+ Ok(text) => text.to_owned(),+ Err(_) => bytes.iter().map(|b| pdfcraft_cos::pdfdoc_char(*b)).collect(),+ }+ }++ /// The document as it may be written to a file (#3926, #3944): a copy without the values of text+ /// fields with the Password flag (or XFA `<passwordEdit/>` fields in the datasets), or `cos`+ /// itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231 (a note to the Password flag):+ /// "it is imperative that PDF processors never store the value of the text field in the PDF file+ /// if this flag is set". The open document keeps them in memory.+ pub(crate) fn writable(cos: &pdfcraft_cos::Document) -> Result<std::borrow::Cow<'_, pdfcraft_cos::Document>, EditError> {+ let has_form_pw = pdfcraft_forms::has_password_values(cos);+ let has_xfa_pw = pdfcraft_xfa::has_password_values(cos);+ if !has_form_pw && !has_xfa_pw {+ return Ok(std::borrow::Cow::Borrowed(cos));+ }+ let mut copy = cos.clone();+ if has_form_pw {+ pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;+ }+ if has_xfa_pw {+ pdfcraft_xfa::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;+ }+ Ok(std::borrow::Cow::Owned(copy))+ }++ /// The last-resort guard (AGENTS.md §4): run `f`, turning a panic that escapes it into an error+ /// message, so one bad file or edit can't take the app and its other documents down. It is a+ /// safety net for bugs, not a substitute for returning errors.+ pub fn guard<T>(f: impl FnOnce() -> T) -> Result<T, String> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|p| {+ p.downcast_ref::<&str>().map(|s| (*s).to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown error".into())+ })+ }++ /// Validate the signature fields of `cos` (written as `bytes`).+ pub(crate) fn signatures_of(+ cos: &pdfcraft_cos::Document,+ bytes: &[u8],+ trust: &TrustStore,+ cache: &pdfcraft_sign::DigestCache,+ ) -> Vec<SignatureInfo> {+ pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache)+ }++ /// What Optimize PDF did.+ #[derive(Clone, Debug, Default, PartialEq, Eq)]+ pub struct OptimizeReport {+ pub optimize: optimize::Report,+ /// Identical objects merged.+ pub merged: usize,+ /// Remove Hidden Information categories discarded, with counts.+ pub discarded: Vec<(Hidden, usize)>,+ }diff --cc crates/engine/src/edit/labels.rsindex 000000000,5e25ae465..9b3a3677bmode 000000,100644..100644--- a/crates/engine/src/edit/labels.rs+++ b/crates/engine/src/edit/labels.rs@@@ -1,0 -1,336 +1,351 @@@+ use super::*;++ /// Every wording [`Edit::label`] can produce, for an interface to translate. `Edit::Batch` is not+ /// here: its wording is only the hole, because a batch carries its name as text (see+ /// [`BATCH_LABELS`]).+ pub const EDIT_LABELS: &[&str] = &[+ "Rotate page",+ "Change tag properties",+ "Rotate pages",+ "Delete page",+ "Delete pages",+ "Move page",+ "Move pages",+ "Reverse pages",+ "Insert blank page",+ "Duplicate page",+ "Duplicate pages",+ "Replace page",+ "Replace pages",+ "Crop page",+ "Crop pages",+ "Set page boxes",+ "Set page transitions",+ "Change Title",+ "Change Author",+ "Change Subject",+ "Change Keywords",+ "Change {key}",+ "Insert pages from {name}",+ "Insert pages from {name} — 1 field renamed",+ "Insert pages from {name} — fields renamed",+ "Attach {name}",+ "Delete attachment {key}",+ "Add bookmark",+ "Rename bookmark",+ "Delete bookmark",+ "Move bookmark",+ "Set bookmark destination",+ "Colour",+ "Style",+ "New bookmarks from structure",+ "Number pages",+ "Measure distance",+ "Measure perimeter",+ "Measure area",+ "Set measurement scale",+ "Add sticky note",+ "Add highlight",+ "Add underline",+ "Add strikethrough",+ "Add squiggly underline",+ "Add rectangle",+ "Add oval",+ "Add arrow",+ "Add line",+ "Add drawing",+ "Add text box",+ "Add checkmark",+ "Add cross",+ "Add dot",+ "Add signature",+ "Add redaction mark",+ "Add cloud",+ "Add polygon",+ "Add connected lines",+ "Add callout",+ "Add inserted text",+ "Add file attachment",+ "Add stamp",+ "Delete comment",+ "Edit comment",+ "Reply",+ "Set status None",+ "Set status Accepted",+ "Set status Rejected",+ "Set status Cancelled",+ "Set status Completed",+ "Replace text",+ "Erase",+ "Mark with checkmark",+ "Remove checkmark",+ "Lock comment",+ "Unlock comment",+ "Move comment",+ "Reshape comment",+ "Resize comment",+ "Change comment properties",+ "Fill in {name}",+ "Set the image of {name}",+ "Clear form",+ "Add field",+ "Change field properties",+ "Delete field",+ "Duplicate field",+ "Set tab order",+ "Set calculation order",+ "Change initial view",+ "Set alternate text",+ "Mark figure as decorative",+ "Recognize text",+ "Run JavaScript",+ "Run form script",+ "Save as {level}",+ "Remove {standard} identification",+ "Edit script of {name}",+ "Delete document JavaScript",+ "Edit document JavaScript",+ "Edit text",+ "Load document font",+ "Move object",+ "Move objects",+ "Move image",++ "Transform image",+ "Rotate image",++ "Crop image",+ "Flip image",+ "Replace image",+ "Delete image",++ "Bring to front",++ "Bring forward",++ "Send backward",++ "Send to back",++ "Remove crop",+ "Add header & footer",+ "Update header & footer",+ "Add watermark",+ "Update watermark",+ "Add background",+ "Update background",+ "Remove header & footer",+ "Remove watermark",+ "Remove background",+ "Add text",+ "Add image",+ "Edit content",+ "Delete content",+ "Paste",+ "Apply redactions",+ "Remove redaction marks",+ "Remove hidden information",+ "Import {name}",+ "Add link",+ "Change link properties",+ "Delete link",+ "Remove all links",+ "Create link",+ "Create links",+ "Sanitize document",+ "Flatten comments",+ "Flatten form fields",+ "Flatten",+ "Flatten Fill & Sign",+ "Protect with password",+ "Remove security",+ ];++ /// The names of the batches built below L7, which an interface shows in the same places as+ /// [`EDIT_LABELS`] and so translates the same way. A batch built in the interface itself arrives+ /// already worded in the interface's language.+ pub const BATCH_LABELS: &[&str] =+ &["Set document title", "Mark differences", "Detect form fields", "Run JavaScript", "Recognize text", field_table::LABEL, "Style"];++ impl Edit {+ /// Label for the Edit menu and history ("Undo Rotate pages").+ pub fn label(&self) -> Label {+ match self {+ Edit::RotatePages { pages, .. } => plural("Rotate page", "Rotate pages", pages.len()),+ Edit::DeletePages { pages } => plural("Delete page", "Delete pages", pages.len()),+ Edit::MovePages { pages, .. } => plural("Move page", "Move pages", pages.len()),+ Edit::ReversePages { .. } => Label::of("Reverse pages"),+ Edit::InsertBlankPage { .. } => Label::of("Insert blank page"),+ Edit::DuplicatePages { pages, .. } => plural("Duplicate page", "Duplicate pages", pages.len()),+ Edit::ReplacePages { pages, .. } => plural("Replace page", "Replace pages", pages.len()),+ Edit::SetPageBox { pages, which: PageBox::Crop, .. } => plural("Crop page", "Crop pages", pages.len()),+ Edit::SetPageBox { .. } => Label::of("Set page boxes"),+ Edit::SetTransition { .. } => Label::of("Set page transitions"),+ // The four `/Info` keys PdfCraft itself offers get a wording of their own, so each can+ // be said in another language; any other key is the document's and goes in as it stands.+ Edit::SetInfo { key, .. } => match key.as_str() {+ "Title" => Label::of("Change Title"),+ "Author" => Label::of("Change Author"),+ "Subject" => Label::of("Change Subject"),+ "Keywords" => Label::of("Change Keywords"),+ _ => Label::with("Change {key}", key.as_str()),+ },+ Edit::InsertPagesFrom { name, .. } => Label::with("Insert pages from {name}", name.as_str()),+ Edit::AddBookmark { .. } => Label::of("Add bookmark"),+ Edit::RenameBookmark { .. } => Label::of("Rename bookmark"),+ Edit::DeleteBookmark { .. } => Label::of("Delete bookmark"),+ Edit::MoveBookmark { .. } => Label::of("Move bookmark"),+ Edit::SetBookmarkPage { .. } => Label::of("Set bookmark destination"),+ // The bookmark Style and Colour menus' own names, already said in every language.+ Edit::SetBookmarkColor { .. } => Label::of("Colour"),+ Edit::SetBookmarkStyle { .. } => Label::of("Style"),+ Edit::BookmarksFromStructure => Label::of("New bookmarks from structure"),+ Edit::NumberPages { .. } => Label::of("Number pages"),+ // What was measured is part of the wording too, for the same reason.+ Edit::AddMeasurement(m) => Label::of(match m.kind {+ pdfcraft_measure::Kind::Distance => "Measure distance",+ pdfcraft_measure::Kind::Perimeter => "Measure perimeter",+ pdfcraft_measure::Kind::Area => "Measure area",+ }),+ Edit::SetMeasurementScale { .. } => Label::of("Set measurement scale"),+ Edit::AddAnnotation(a) => Label::of(add_annotation(&a.shape)),+ Edit::AddCustomStamp { .. } => Label::of("Add stamp"),+ Edit::DeleteAnnotation { .. } => Label::of("Delete comment"),+ Edit::SetAnnotationContents { .. } => Label::of("Edit comment"),+ Edit::ReplyToAnnotation { .. } => Label::of("Reply"),+ // The state's name is part of the wording: a language may need to agree it with the rest.+ Edit::SetAnnotationStatus { state, .. } => Label::of(match state {+ ReviewState::None => "Set status None",+ ReviewState::Accepted => "Set status Accepted",+ ReviewState::Rejected => "Set status Rejected",+ ReviewState::Cancelled => "Set status Cancelled",+ ReviewState::Completed => "Set status Completed",+ }),+ Edit::ReplaceText { .. } => Label::of("Replace text"),+ Edit::EraseInk { .. } => Label::of("Erase"),+ Edit::MarkAnnotation { marked: true, .. } => Label::of("Mark with checkmark"),+ Edit::MarkAnnotation { .. } => Label::of("Remove checkmark"),+ Edit::LockAnnotation { locked: true, .. } => Label::of("Lock comment"),+ Edit::LockAnnotation { .. } => Label::of("Unlock comment"),+ Edit::MoveAnnotation { .. } => Label::of("Move comment"),+ Edit::ReshapeAnnotation { .. } => Label::of("Reshape comment"),+ Edit::ResizeAnnotation { .. } => Label::of("Resize comment"),+ Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } | Edit::FontSizeAnnotation { .. } | Edit::SetAnnotationInfo { .. } => {+ Label::of("Change comment properties")+ }+ Edit::SetFieldValue { name, .. } => Label::with("Fill in {name}", name.as_str()),+ Edit::SetFieldImage { name, .. } => Label::with("Set the image of {name}", name.as_str()),+ Edit::ResetForm { .. } => Label::of("Clear form"),+ Edit::AddField { .. } => Label::of("Add field"),+ Edit::SetFieldProps { .. } => Label::of("Change field properties"),+ Edit::DeleteField { .. } => Label::of("Delete field"),+ Edit::DuplicateField { .. } => Label::of("Duplicate field"),+ Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),+ Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),+ Edit::SetInitialView(_) => Label::of("Change initial view"),+ Edit::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),+ Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),+ Edit::AutoTagText => Label::of("Automatically tag text"),+ Edit::SetAltText { .. } => Label::of("Set alternate text"),+ Edit::AutoTagFormFields => Label::of("Tag form fields"),+ Edit::SetTagProperty { .. } => Label::of("Change tag properties"),+ Edit::MoveTag { .. } => Label::of("Move object"),+ Edit::MarkDecorative { .. } => Label::of("Mark figure as decorative"),+ Edit::MarkTagArtifact { .. } => Label::of("Mark content as artifact"),+ Edit::AddOcrText { .. } => Label::of("Recognize text"),+ Edit::ApplyScriptChanges { .. } => Label::of("Run JavaScript"),+ Edit::XfaEvent { .. } => Label::of("Run form script"),+ // The level is the standard's own name ("PDF/A-2b"), so it goes in as it stands.+ Edit::ConvertPdfA { level } => Label::with("Save as {level}", level.label()),+ Edit::RemoveStandardId { standard } => Label::with("Remove {standard} identification", standard.label()),+ Edit::SetFieldScript { name, .. } => Label::with("Edit script of {name}", name.as_str()),+ Edit::SetDocumentScript { script: None, .. } => Label::of("Delete document JavaScript"),+ Edit::SetDocumentScript { .. } => Label::of("Edit document JavaScript"),+ Edit::EditTextLine { .. } | Edit::EditTextBlock { .. } => Label::of("Edit text"),+ Edit::RegisterTextFont { .. } => Label::of("Load document font"),+ Edit::MoveObjects { objects, .. } => plural("Move object", "Move objects", objects.len()),+ Edit::EditPageImage { change, .. } => Label::of(match change {+ ImageEdit::Move(_) => "Move image",++ ImageEdit::Transform(_) => "Transform image",+ ImageEdit::Rotate(_) | ImageEdit::RotateBy(_) => "Rotate image",+ ImageEdit::Crop(_) => "Crop image",+ ImageEdit::Flip { .. } => "Flip image",+ ImageEdit::Replace { .. } => "Replace image",+ ImageEdit::Delete => "Delete image",++ ImageEdit::Arrange(ord) => match ord {++ pdfcraft_edit::ArrangeOrder::BringToFront => "Bring to front",++ pdfcraft_edit::ArrangeOrder::BringForward => "Bring forward",++ pdfcraft_edit::ArrangeOrder::SendBackward => "Send backward",++ pdfcraft_edit::ArrangeOrder::SendToBack => "Send to back",++ },++ ImageEdit::RemoveCrop => "Remove crop",+ }),+ Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),+ Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),+ Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"),+ Edit::AddWatermark { .. } => Label::of("Update watermark"),+ Edit::AddBackground { replace: false, .. } => Label::of("Add background"),+ Edit::AddBackground { .. } => Label::of("Update background"),+ Edit::RemoveMarks { kind: MarkKind::HeaderFooter } => Label::of("Remove header & footer"),+ Edit::RemoveMarks { kind: MarkKind::Watermark } => Label::of("Remove watermark"),+ Edit::RemoveMarks { kind: MarkKind::Background } => Label::of("Remove background"),+ Edit::AddText { .. } => Label::of("Add text"),+ Edit::AddImage { .. } => Label::of("Add image"),+ Edit::UpdateContent { .. } => Label::of("Edit content"),+ Edit::DeleteContent { .. } => Label::of("Delete content"),+ Edit::ReplaceImage { .. } => Label::of("Replace image"),+ Edit::PasteContent { .. } => Label::of("Paste"),+ Edit::ApplyRedactions { .. } => Label::of("Apply redactions"),+ Edit::ClearRedactions => Label::of("Remove redaction marks"),+ Edit::RemoveHidden { .. } => Label::of("Remove hidden information"),+ Edit::ImportData { name, .. } => Label::with("Import {name}", name.as_str()),+ Edit::AddLink { .. } => Label::of("Add link"),+ Edit::SetLink { .. } => Label::of("Change link properties"),+ Edit::DeleteLink { .. } => Label::of("Delete link"),+ Edit::RemoveLinks { .. } => Label::of("Remove all links"),+ Edit::AddLinks { links, .. } => plural("Create link", "Create links", links.len()),+ Edit::Sanitize => Label::of("Sanitize document"),+ Edit::XfaToStatic => Label::of("Convert to a static form"),+ Edit::Flatten { comments: true, fields: false } => Label::of("Flatten comments"),+ Edit::Flatten { comments: false, fields: true } => Label::of("Flatten form fields"),+ Edit::Flatten { .. } => Label::of("Flatten"),+ Edit::FlattenFillSign => Label::of("Flatten Fill & Sign"),+ Edit::Protect(_) => Label::of("Protect with password"),+ Edit::RemoveProtection => Label::of("Remove security"),+ // A batch carries its own name, already worded by whoever built it.+ // A batch carries its name as text, so the wording is only the hole (see `BATCH_LABELS`).+ Edit::Batch { label, .. } => Label::with("{batch}", label.as_str()),+ }+ }+ }++ /// What the Edit menu calls a new comment ("Undo Add highlight"). A whole wording for each kind,+ /// so a language can give the noun the article and the gender its own grammar asks for.+ fn add_annotation(s: &Shape) -> &'static str {+ match s {+ Shape::Note { .. } => "Add sticky note",+ Shape::TextMarkup { kind: Markup::Highlight, .. } => "Add highlight",+ Shape::TextMarkup { kind: Markup::Underline, .. } => "Add underline",+ Shape::TextMarkup { kind: Markup::StrikeOut, .. } => "Add strikethrough",+ Shape::TextMarkup { kind: Markup::Squiggly, .. } => "Add squiggly underline",+ Shape::Rectangle { .. } => "Add rectangle",+ Shape::Oval { .. } => "Add oval",+ Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. } => "Add arrow",+ Shape::Line { .. } => "Add line",+ Shape::Ink { .. } => "Add drawing",+ Shape::TextBox { .. } => "Add text box",+ Shape::Typewriter { .. } => "Add text",+ Shape::Mark { mark: FillMark::Check, .. } => "Add checkmark",+ Shape::Mark { mark: FillMark::Cross, .. } => "Add cross",+ Shape::Mark { mark: FillMark::Dot, .. } => "Add dot",+ Shape::Mark { mark: FillMark::Line, .. } => "Add line",+ Shape::Signature { .. } | Shape::TypedSignature { .. } => "Add signature",+ Shape::Redact { .. } => "Add redaction mark",+ Shape::Stamp { .. } | Shape::CustomStamp { .. } => "Add stamp",+ Shape::Polygon { cloud: true, .. } => "Add cloud",+ Shape::Polygon { .. } => "Add polygon",+ Shape::PolyLine { .. } => "Add connected lines",+ Shape::Callout { .. } => "Add callout",+ Shape::Caret { .. } => "Add inserted text",+ Shape::Attachment { .. } => "Add file attachment",+ }+ }++ /// The singular or the plural wording, by count. Both are written out: a language forms its plural+ /// its own way, and `one` and `many` may differ in more than an "s".+ fn plural(one: &'static str, many: &'static str, n: usize) -> Label {+ Label::of(if n == 1 { one } else { many })+ }diff --cc crates/engine/src/edit/run.rsindex 000000000,7901a3b7d..b357c1e47mode 000000,100644..100644--- a/crates/engine/src/edit/run.rs+++ b/crates/engine/src/edit/run.rs@@@ -1,0 -1,696 +1,842 @@@+ use super::*;++ /// Whether the opening password allows an edit (§7.6.4.2, Table 22).+ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), EditError> {+ match edit {+ Edit::RotatePages { .. }+ | Edit::DeletePages { .. }+ | Edit::MovePages { .. }+ | Edit::ReversePages { .. }+ | Edit::InsertBlankPage { .. }+ | Edit::DuplicatePages { .. }+ | Edit::ReplacePages { .. }+ | Edit::SetPageBox { .. }+ | Edit::SetTransition { .. }+ | Edit::InsertPagesFrom { .. }+ // "Assemble the document: insert, rotate or delete pages and create bookmarks" (Table 22).+ | Edit::AddBookmark { .. }+ | Edit::RenameBookmark { .. }+ | Edit::DeleteBookmark { .. }+ | Edit::MoveBookmark { .. }+ | Edit::SetBookmarkPage { .. }+ | Edit::SetBookmarkColor { .. }+ | Edit::SetBookmarkStyle { .. }+ | Edit::BookmarksFromStructure+ | Edit::NumberPages { .. } => {+ if p.assemble() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("page changes"))+ }+ }+ Edit::AddMeasurement(_)+ | Edit::AddAnnotation(_)+ | Edit::AddCustomStamp { .. }+ | Edit::DeleteAnnotation { .. }+ | Edit::SetAnnotationContents { .. }+ | Edit::ReplyToAnnotation { .. }+ | Edit::SetAnnotationStatus { .. }+ | Edit::MarkAnnotation { .. }+ | Edit::ReplaceText { .. }+ | Edit::EraseInk { .. }+ | Edit::LockAnnotation { .. }+ | Edit::MoveAnnotation { .. }+ | Edit::ReshapeAnnotation { .. }+ | Edit::ResizeAnnotation { .. }+ | Edit::StyleAnnotation { .. }+ | Edit::FillAnnotation { .. }+ | Edit::FontSizeAnnotation { .. }+ | Edit::SetAnnotationInfo { .. }+ | Edit::SetMeasurementScale { .. } => {+ if p.annotate() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("comments"))+ }+ }+ Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } | Edit::XfaEvent { .. } => {+ if p.fill_forms() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("filling in form fields"))+ }+ }+ Edit::Protect(_) | Edit::RemoveProtection => {+ if unrestricted(p) {+ Ok(())+ } else {+ Err(EditError::NotPermitted("changing security"))+ }+ }+ // Converting to PDF/A takes the encryption off (PDF/A forbids it), so on an encrypted+ // document it is a change of security (#3921).+ Edit::ConvertPdfA { .. } => {+ if unrestricted(p) {+ Ok(())+ } else {+ Err(EditError::NotPermitted("removing the encryption, which PDF/A forbids"))+ }+ }+ Edit::SetInfo { .. }+ | Edit::AddHeaderFooter { .. }+ | Edit::AddWatermark { .. }+ | Edit::AddBackground { .. }+ | Edit::RemoveMarks { .. }+ | Edit::AddField { .. }+ | Edit::ApplyRedactions { .. }+ | Edit::AddText { .. }+ | Edit::AddImage { .. }+ | Edit::UpdateContent { .. }+ | Edit::MoveObjects { .. }+ | Edit::DeleteContent { .. }+ | Edit::ReplaceImage { .. }+ | Edit::PasteContent { .. }+ | Edit::ClearRedactions+ | Edit::RemoveHidden { .. }+ | Edit::ImportData { .. }+ | Edit::AddLink { .. }+ | Edit::SetLink { .. }+ | Edit::DeleteLink { .. }+ | Edit::RemoveLinks { .. }+ | Edit::AddLinks { .. }+ | Edit::Sanitize+ | Edit::XfaToStatic+ | Edit::SetFieldProps { .. }+ | Edit::DeleteField { .. }+ | Edit::DuplicateField { .. }+ | Edit::SetTabOrder { .. }+ | Edit::MoveInTabOrder { .. }+ | Edit::SetCalculationOrder { .. }+ | Edit::SetInitialView(_)+ | Edit::AddAttachment { .. }+ | Edit::DeleteAttachment { .. }+ | Edit::AutoTagText+ | Edit::SetAltText { .. }+ | Edit::AutoTagFormFields+ | Edit::SetTagProperty { .. }+ | Edit::MoveTag { .. }+ | Edit::MarkDecorative { .. }+ | Edit::MarkTagArtifact { .. }+ | Edit::AddOcrText { .. }+ | Edit::SetDocumentScript { .. }+ | Edit::SetFieldScript { .. }+ | Edit::RemoveStandardId { .. }+ | Edit::EditTextLine { .. }+ | Edit::EditTextBlock { .. }+ | Edit::RegisterTextFont { .. }+ | Edit::EditPageImage { .. }+ | Edit::Flatten { .. }+ | Edit::FlattenFillSign => {+ if p.modify() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("changes to the document"))+ }+ }+ Edit::Batch { edits, .. } => edits.iter().try_for_each(|e| check_permission(e, p)),+ }+ }++ /// Dates and unique ids stamped onto what an edit creates.+ pub(crate) struct EditCtx {+ /// Field scripts run (`None`: JavaScript is off) and what they produced.+ pub(crate) js: Option<js::JsRunner>,+ /// A laid-out XFA form's template (`None`: not an XFA form, or JavaScript is off) and what+ /// its scripts produced.+ pub(crate) xfa: Option<Arc<pdfcraft_xfa::model::Template>>,+ pub(crate) xfa_out: js::JsOutput,+ /// The datasets stream this edit wrote (later writes in the edit replace it in place).+ pub(crate) xfa_datasets: Option<pdfcraft_cos::ObjRef>,+ /// A form script ran too long and was abandoned: the document's scripts go off.+ pub(crate) xfa_ran_away: bool,+ /// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).+ pub(crate) xfa_time_scale: u32,+ /// The edit took the XFA out of the form: what went with it, for the document's warnings.+ pub(crate) xfa_removed: Vec<String>,+ /// Pages in the document, for `xfa.layout.pageCount()`.+ pub(crate) pages: usize,+ pub(crate) date: Option<String>,+ /// Today in local time, for date tokens.+ pub(crate) today: (i64, u32, u32),+ pub(crate) seed: u64,+ pub(crate) count: u64,+ /// Fields the edit renamed to keep imported names separate (old → new), for the repair+ /// log and the undo label.+ pub(crate) renamed_fields: Vec<(String, String)>,+ /// The overlay streams the edit's applied redactions added, which alone the renderer's check+ /// leaves out.+ pub(crate) redaction_overlays: Vec<pdfcraft_cos::ObjRef>,+ }++ impl EditCtx {+ pub(crate) fn new(now: Option<i64>, salt: u64) -> Self {+ let mut seed = 0x9E37_79B9_7F4A_7C15u64 ^ salt;+ if let Some(t) = now {+ seed ^= (t as u64).rotate_left(17);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if now.is_some() {+ // Real clock: mix in sub-second time so ids from two sessions don't collide.+ seed ^= std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos() as u64).unwrap_or(0) << 32;+ }+ Self {+ js: None,+ xfa: None,+ xfa_out: Default::default(),+ xfa_datasets: None,+ xfa_ran_away: false,+ xfa_time_scale: 1,+ xfa_removed: Vec::new(),+ pages: 0,+ date: now.map(pdfcraft_cos::pdf_date),+ today: (1970, 1, 1),+ seed,+ count: 0,+ renamed_fields: Vec::new(),+ redaction_overlays: Vec::new(),+ }+ }++ /// 32 bytes of entropy for new encryption keys and salts. `RandomState` is seeded by the+ /// operating system, so no extra dependency is needed.+ fn entropy(&mut self) -> [u8; 32] {+ use std::hash::{BuildHasher, Hasher};+ let mut out = [0u8; 32];+ for (i, chunk) in out.chunks_mut(8).enumerate() {+ let mut h = std::collections::hash_map::RandomState::new().build_hasher();+ h.write_u64(self.seed ^ i as u64);+ h.write_u64(self.count);+ self.count += 1;+ chunk.copy_from_slice(&h.finish().to_le_bytes());+ }+ out+ }++ /// A fresh `/NM`: a random-looking UUID (version 4 layout) from a splitmix64 stream.+ fn meta(&mut self) -> pdfcraft_annot::Meta {+ let mut next = || {+ self.count += 1;+ let mut z = self.seed.wrapping_add(self.count.wrapping_mul(0x9E37_79B9_7F4A_7C15));+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ };+ let (a, b) = (next(), next());+ let id = format!(+ "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",+ a >> 32,+ (a >> 16) & 0xffff,+ a & 0xfff,+ 0x8000 | (b >> 48) & 0x3fff,+ b & 0xffff_ffff_ffff+ );+ pdfcraft_annot::Meta { date: self.date.clone(), id }+ }+ }++ /// Perform an edit on a working copy (the caller discards it on error).+ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {+ match edit {+ Edit::RotatePages { pages, degrees } => pdfcraft_organize::rotate_pages(doc, pages, *degrees)?,+ Edit::DeletePages { pages } => pdfcraft_organize::delete_pages(doc, pages)?,+ Edit::MovePages { pages, to } => pdfcraft_organize::move_pages(doc, pages, *to)?,+ Edit::ReversePages { pages } => pdfcraft_organize::reverse_pages(doc, pages)?,+ Edit::InsertBlankPage { at, width, height } => {+ pdfcraft_organize::insert_blank_page(doc, *at, *width, *height)?;+ }+ Edit::SetInfo { key, value } => pdfcraft_organize::set_info(doc, key, value)?,+ Edit::DuplicatePages { pages, at } => pdfcraft_organize::duplicate_pages(doc, pages, *at)?,+ Edit::ReplacePages { pages, name, bytes, src_pages } => {+ let src = open_source(name, bytes)?;+ pdfcraft_organize::replace_pages(doc, pages, &src, src_pages)?;+ }+ Edit::SetPageBox { pages, which, spec } => pdfcraft_organize::set_page_box(doc, pages, *which, *spec)?,+ Edit::SetTransition { pages, spec } => pdfcraft_organize::set_transition(doc, pages, spec)?,+ Edit::InsertPagesFrom { name, bytes, pages, at, field_conflicts } => {+ let src = open_source(name, bytes)?;+ let pages = match pages {+ Some(p) => p.clone(),+ None => (0..pdfcraft_organize::page_count(&src)?).collect(),+ };+ // The file's bookmarks come along under one named after it, as in Combine Files.+ let title = std::path::Path::new(name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());+ let outcome = pdfcraft_organize::insert_file_pages(doc, &src, &title, &pages, *at, *field_conflicts)?;+ cx.renamed_fields = outcome.renamed_fields;+ }+ Edit::AddBookmark { parent, index, title, page, left, top } => {+ pdfcraft_organize::add_bookmark_at(doc, parent, *index, title, *page, *left, *top)?;+ }+ Edit::RenameBookmark { path, title } => pdfcraft_organize::rename_bookmark(doc, path, title)?,+ Edit::DeleteBookmark { path } => pdfcraft_organize::delete_bookmark(doc, path)?,+ Edit::MoveBookmark { from, to_parent, index } => {+ pdfcraft_organize::move_bookmark(doc, from, to_parent, *index)?;+ }+ Edit::SetBookmarkPage { path, page } => pdfcraft_organize::set_bookmark_page(doc, path, *page)?,+ Edit::SetBookmarkColor { path, color } => pdfcraft_organize::set_bookmark_color(doc, path, *color)?,+ Edit::SetBookmarkStyle { path, bold, italic } => pdfcraft_organize::set_bookmark_style(doc, path, *bold, *italic)?,+ Edit::BookmarksFromStructure => {+ let entries: Vec<_> = pdfcraft_a11y::headings(doc)+ .into_iter()+ .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj })+ .collect();+ pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;+ }+ Edit::NumberPages { from, to, style, prefix, first } => pdfcraft_organize::number_pages(doc, *from, *to, *style, prefix, *first)?,+ Edit::AddMeasurement(m) => {+ measure::add(doc, m, &cx.meta())?;+ }+ Edit::SetMeasurementScale { page, bbox, name, scale } => measure::set_scale(doc, *page, *bbox, name, scale)?,+ Edit::AddAnnotation(a) => {+ pdfcraft_annot::add_annotation(doc, a, &cx.meta())?;+ }+ Edit::AddCustomStamp { page, rect, name, file, author } => {+ let src = mark_source(doc, file)?;+ let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));+ let natural = rect[2] == rect[0] && rect[3] == rect[1];+ let rotation = pdfcraft_organize::page_rotation(doc, *page)?;+ // The picture as displayed: a quarter turn swaps its sides in user space.+ let (dw, dh) = if matches!(rotation, 90 | 270) { (sh, sw) } else { (sw, sh) };+ let rect = if natural {+ let k = (200.0 / sw.max(sh)).min(1.0);+ let (w, h) = (dw * k, dh * k);+ [rect[0] - w / 2.0, rect[1] - h / 2.0, rect[0] + w / 2.0, rect[1] + h / 2.0]+ } else {+ fit_picture(*rect, dw, dh)+ };+ let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };+ let style = pdfcraft_annot::Style::default_for(&shape);+ let new = NewAnnotation { page: *page, shape, style, contents: name.clone(), author: author.clone() };+ let index = pdfcraft_annot::add_annotation(doc, &new, &cx.meta())?;+ pdfcraft_annot::orient_image_stamp(doc, *page, index, rotation)?;+ }+ Edit::DeleteAnnotation { page, index } => pdfcraft_annot::delete_annotation(doc, *page, *index)?,+ Edit::SetAnnotationContents { page, index, text } => pdfcraft_annot::set_contents(doc, *page, *index, text, &cx.meta())?,+ Edit::ReplyToAnnotation { page, index, text, author } => {+ pdfcraft_annot::add_reply(doc, *page, *index, text, author, &cx.meta())?;+ }+ Edit::SetAnnotationStatus { page, index, state, author } => {+ pdfcraft_annot::set_review_state(doc, *page, *index, *state, author, &cx.meta())?;+ }+ Edit::EraseInk { page, index, path, radius } => {+ pdfcraft_annot::erase_ink(doc, *page, *index, path, *radius, &cx.meta())?;+ }+ Edit::AddAttachment { name, bytes, description, mime } => {+ pdfcraft_organize::add_attachment(doc, name, bytes, description.as_deref(), mime.as_deref(), cx.date.as_deref())?;+ }+ Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,+ Edit::ReplaceText { page, quads, text, author, strike, caret } => {+ // One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by+ // the strikeout's `/NM` (#2666).+ let (strike_meta, caret_meta) = (cx.meta(), cx.meta());+ pdfcraft_annot::add_text_replacement(doc, *page, quads, text, author, strike, caret, &strike_meta, &caret_meta)?;+ }+ Edit::MarkAnnotation { page, index, marked, author } => {+ pdfcraft_annot::set_marked(doc, *page, *index, *marked, author, &cx.meta())?;+ }+ Edit::LockAnnotation { page, index, locked } => pdfcraft_annot::set_locked(doc, *page, *index, *locked)?,+ Edit::MoveAnnotation { page, index, dx, dy } => pdfcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,+ Edit::ReshapeAnnotation { page, index, points } => pdfcraft_annot::set_points(doc, *page, *index, points, &cx.meta())?,+ Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,+ Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {+ pdfcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, endings.as_deref(), &cx.meta())?;+ }+ Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?,+ Edit::FontSizeAnnotation { page, index, size } => pdfcraft_annot::set_font_size(doc, *page, *index, *size, &cx.meta())?,+ Edit::SetAnnotationInfo { page, index, author, subject, icon } => {+ pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;+ }+ Edit::SetFieldValue { name, value } => {+ let mut set = |doc: &mut pdfcraft_cos::Document, value: &FieldValue| match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js),+ None => pdfcraft_forms::set_value(doc, name, value),+ };+ match set(doc, value) {+ Ok(()) => {}+ // A date the field's format doesn't read may be typed by another of an XFA date+ // field's patterns: it is kept in the first. Only a format refusal is tried+ // again: it comes before any of the field's scripts run, so they run once.+ Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) {+ Some(typed) => set(doc, &typed)?,+ None => return Err(refused.into()),+ },+ Err(refused) => return Err(refused.into()),+ }+ }+ Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?,+ None => pdfcraft_forms::apply_script_changes(doc, changes, &mut pdfcraft_forms::NoScripts)?,+ },+ Edit::XfaEvent { som, activity } => {+ let tpl = cx.xfa.clone().ok_or_else(|| EditError::Invalid("this is not a laid-out XFA form, or JavaScript is off".into()))?;+ let mut run =+ xfa::XfaRun { page_count: cx.pages, out: &mut cx.xfa_out, datasets: cx.xfa_datasets, ran_away: false, time_scale: cx.xfa_time_scale };+ let ran = xfa::on_event(doc, &tpl, som, activity, &mut run);+ cx.xfa_datasets = run.datasets;+ cx.xfa_ran_away |= run.ran_away;+ ran.map_err(EditError::Invalid)?;+ }+ Edit::SetFieldImage { name, image } => {+ let (img, _) = embed_image(doc, name, image)?;+ let px = match &*doc.get(img) {+ pdfcraft_cos::Object::Stream(s) => (s.dict.int(b"Width").unwrap_or(1) as u32, s.dict.int(b"Height").unwrap_or(1) as u32),+ _ => (1, 1),+ };+ // An XFA image field keeps the picture in the data too (as Designer saves it), and a+ // laid-out form shows it from there: so only pictures the layout can show, and only+ // for image fields (a laid-out one carries its SOM path; a static form's field name+ // is its path).+ let is_xfa = pdfcraft_xfa::read_packets(doc).ok().flatten().is_some();+ let image_field = is_xfa+ && pdfcraft_forms::fields(doc).iter().any(|f| f.name == *name && f.button == Some(pdfcraft_forms::af::ButtonAction::ImportIcon));+ if image_field {+ let Some(content_type) = image_content_type(image) else {+ return Err(EditError::Invalid(format!("{name}: an XFA form keeps a PNG, JPEG, GIF, BMP or TIFF picture; choose one of those")));+ };+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;+ let som = pdfcraft_xfa::fields_by_som(doc).into_iter().find(|(_, n)| n == name).map(|(s, _)| s).unwrap_or_else(|| name.clone());+ let path = match cx.xfa.as_deref() {+ Some(tpl) => pdfcraft_xfa::data_path(tpl, &som),+ None => pdfcraft_xfa::som_to_path(&som),+ };+ let r =+ pdfcraft_xfa::write_data_image(doc, &path, content_type, image, cx.xfa_datasets).map_err(|e| EditError::Write(e.to_string()))?;+ if !r.written && r.warnings.is_empty() {+ return Err(EditError::Write(format!("{name}: the picture could not be written into the form's data")));+ }+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);+ cx.xfa_out.errors.extend(r.warnings);+ xfa_after_data_change(doc, cx, false)?;+ } else {+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;+ }+ }+ Edit::ResetForm { names } => {+ pdfcraft_forms::reset(doc, names.as_deref())?;+ }+ Edit::AddField { page, rect, kind, name } => {+ pdfcraft_forms::add_field(doc, *page, *rect, kind, name.as_deref())?;+ }+ Edit::SetFieldProps { name, props } => {+ pdfcraft_forms::set_props(doc, name, props)?;+ }+ Edit::DuplicateField { name, pages } => {+ if pdfcraft_forms::duplicate_field(doc, name, pages)? == 0 {+ return Err(EditError::Form(pdfcraft_forms::FormError::Invalid(format!("{name} is already on those pages"))));+ }+ }+ Edit::DeleteField { name } => pdfcraft_forms::delete_field(doc, name)?,+ Edit::SetTabOrder { pages, order } => pdfcraft_forms::set_tab_order(doc, pages, *order)?,+ Edit::MoveInTabOrder { name, earlier } => pdfcraft_forms::move_in_tab_order(doc, name, *earlier)?,+ // As after a script edit: the values the new order gives show at once.+ Edit::SetCalculationOrder { names } => {+ pdfcraft_forms::set_calculation_order(doc, names)?;+ match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,+ None => pdfcraft_forms::recalculate(doc)?,+ };+ }+ Edit::SetInitialView(v) => pdfcraft_organize::set_initial_view(doc, v)?,+ Edit::AutoTagText => {+ a11y::autotag_text(doc).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::SetAltText { figure, alt } => {+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));+ a11y::set_alt(doc, r, alt.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::AutoTagFormFields => {+ a11y::tag_form_fields(doc).map_err(EditError::Accessibility)?;+ }+ Edit::SetTagProperty { object, property, value } => {+ a11y::set_tag_property(doc, *object, *property, value.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::MoveTag { object, anchor, placement } => {+ a11y::move_tag(doc, *object, *anchor, *placement).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::EditTextLine { page, line, text } => {+ pdfcraft_edit::replace_line(doc, *page, *line, text)?;+ }+ Edit::SetFieldScript { name, event, script } => {+ pdfcraft_forms::set_field_script(doc, name, event, script.as_deref())?;+ match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,+ None => pdfcraft_forms::recalculate(doc)?,+ };+ }+ Edit::ConvertPdfA { level } => {+ pdfcraft_preflight::convert(doc, *level).map_err(|e| EditError::Invalid(e.to_string()))?;+ }+ Edit::RemoveStandardId { standard } => pdfcraft_organize::remove_standard_id(doc, *standard)?,+ Edit::SetDocumentScript { name, script } => pdfcraft_forms::set_document_script(doc, name, script.as_deref())?,+ Edit::AddOcrText { page, words } => {+ pdfcraft_edit::stamp(doc, *page, "OCR", pdfcraft_ocr::text_layer(words))?;+ }+ Edit::EditPageImage { page, index, change } => {++ match change {++ ImageEdit::Move(to) if !to.iter().all(|v| v.is_finite()) => {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("invalid position".into())));++ }++ ImageEdit::Transform(t) if !t.iter().all(|v| v.is_finite()) => {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("the image transform must be finite".into())));++ }++ ImageEdit::Crop(keep) if !keep.iter().all(|v| v.is_finite()) => {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("invalid crop".into())));++ }++ _ => {}++ }+ let img = pdfcraft_edit::page_images(doc, *page)?+ .into_iter()+ .nth(*index)+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1))))?;+ let c = match change {+ ImageEdit::Move(to) => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::rect_to_rect(img.rect, *to)),++ ImageEdit::Transform(t) => pdfcraft_edit::ImageChange::Transform(*t),+ ImageEdit::Rotate(q) => {+ pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(img.visible_rect.unwrap_or(img.rect), *q, false, false))+ }+ ImageEdit::RotateBy(degrees) => {+ let t = pdfcraft_edit::turn_by_degrees(img.visible_rect.unwrap_or(img.rect), *degrees)+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid("the rotation angle must be a finite number".into())))?;+ pdfcraft_edit::ImageChange::Transform(t)+ }+ ImageEdit::Flip { horizontal } => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(+ img.visible_rect.unwrap_or(img.rect),+ 0,+ *horizontal,+ !*horizontal,+ )),+ ImageEdit::Replace { name, bytes } => {+ if img.is_form {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(+ "grouped Form artwork cannot be replaced with a bitmap".into(),+ )));+ }+ pdfcraft_edit::ImageChange::Replace(embed_image(doc, name, bytes)?.0)+ }+ ImageEdit::Crop(keep) => pdfcraft_edit::ImageChange::Crop(*keep),+ ImageEdit::Delete => pdfcraft_edit::ImageChange::Delete,++ ImageEdit::Arrange(order) => pdfcraft_edit::ImageChange::Arrange(*order),++ ImageEdit::RemoveCrop => pdfcraft_edit::ImageChange::RemoveCrop,+ };- pdfcraft_edit::change_image(doc, *page, *index, &c)?;++ let page_model = pdfcraft_model::pages(doc)++ .into_iter()++ .nth(*page)++ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid(format!("page {} not found", page + 1))))?;++ let target_stream_obj = match page_model.dict.get(b"Contents") {++ None => None,++ Some(c) => match &*doc.resolve(c) {++ pdfcraft_cos::Object::Array(a) => a.get(img.stream).and_then(|o| o.as_ref()),++ _ if img.stream == 0 => c.as_ref(),++ _ => None,++ },++ };++++ let added_items: Vec<(usize, pdfcraft_edit::Added)> = pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).enumerate().collect();++ let matched_added = if let Some(st_ref) = target_stream_obj {++ added_items.iter().find(|(_, a)| a.obj == st_ref)++ } else if let Some(target_ref) = img.object {++ added_items.iter().find(|(_, a)| matches!(&a.content, AddedContent::Image(ai) if ai.image == target_ref))++ } else {++ None++ };++++ let mut ai_to_update = None;++ if let Some((added_idx, added_item)) = matched_added++ && let AddedContent::Image(ai) = added_item.content.clone()++ {++ let has_active_crop = ai.crop.iter().any(|v| v.abs() > 1e-6)++ || img.visible_rect.is_some_and(|v| {++ (v[0] - img.rect[0]).abs() > 1e-4++ || (v[1] - img.rect[1]).abs() > 1e-4++ || (v[2] - img.rect[2]).abs() > 1e-4++ || (v[3] - img.rect[3]).abs() > 1e-4++ });++ let rotated_transform = matches!(change, ImageEdit::Transform(t) if t[1].abs() >= 1e-6 || t[2].abs() >= 1e-6);++ let should_promote = has_active_crop++ || rotated_transform++ || matches!(++ change,++ ImageEdit::Crop(_) | ImageEdit::RemoveCrop | ImageEdit::RotateBy(_) | ImageEdit::Arrange(_) | ImageEdit::Delete++ );++++ if should_promote {++ doc.update_dict(added_item.obj, |d| {++ d.remove(b"PCAdded");++ d.remove(b"PCMark");++ })++ .map_err(|e| EditError::Edit(pdfcraft_edit::EditError::Invalid(e.to_string())))?;++ } else {++ ai_to_update = Some((*added_idx, ai));++ }++ }++++ if let Some((added_idx, mut ai)) = ai_to_update {++ let view = page_model.view_matrix(doc);++ let det = view[0] * view[3] - view[1] * view[2];++ if det.abs() < 1e-12 || !det.is_finite() {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("invalid page transform".into())));++ }++ let (ia, ib, ic, id) = (view[3] / det, -view[1] / det, -view[2] / det, view[0] / det);++ let to_display = [ia, ib, ic, id, -(view[4] * ia + view[5] * ic), -(view[4] * ib + view[5] * id)];++ let apply = |m: [f64; 6], x: f64, y: f64| (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]);++ let bbox = |m: [f64; 6], r: [f64; 4]| {++ let pts = [apply(m, r[0], r[1]), apply(m, r[2], r[1]), apply(m, r[0], r[3]), apply(m, r[2], r[3])];++ let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];++ for (x, y) in pts {++ b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];++ }++ b++ };++++ match change {++ ImageEdit::Move(to) => {++ if !to.iter().all(|v| v.is_finite()) {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("invalid position".into())));++ }++ ai.rect = bbox(to_display, *to);++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Transform(t) => {++ let mul = |m1: [f64; 6], m2: [f64; 6]| {++ [++ m1[0] * m2[0] + m1[1] * m2[2],++ m1[0] * m2[1] + m1[1] * m2[3],++ m1[2] * m2[0] + m1[3] * m2[2],++ m1[2] * m2[1] + m1[3] * m2[3],++ m1[4] * m2[0] + m1[5] * m2[2] + m2[4],++ m1[4] * m2[1] + m1[5] * m2[3] + m2[5],++ ]++ };++ let t_display = mul(mul(view, *t), to_display);++ if t_display[0] < 0.0 {++ ai.flip_h = !ai.flip_h;++ }++ if t_display[3] < 0.0 {++ ai.flip_v = !ai.flip_v;++ }++ ai.rect = bbox(t_display, ai.rect);++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Rotate(q) => {++ let k = ((4 - q.rem_euclid(4)) % 4) as u8;++ ai.rotation = (ai.rotation + k) % 4;++ let r = ai.rect;++ let (cx, cy) = ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0);++ if k % 2 == 1 {++ let (w, h) = (r[2] - r[0], r[3] - r[1]);++ ai.rect = [cx - h / 2.0, cy - w / 2.0, cx + h / 2.0, cy + w / 2.0];++ }++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Flip { horizontal: true } => {++ ai.flip_h = !ai.flip_h;++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Flip { horizontal: false } => {++ ai.flip_v = !ai.flip_v;++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Replace { .. } => {++ let pdfcraft_edit::ImageChange::Replace(new_image) = c else {++ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("expected replace".into())));++ };++ ai.image = new_image;++ pdfcraft_edit::update_content(doc, *page, added_idx, &AddedContent::Image(ai))?;++ }++ ImageEdit::Crop(_) | ImageEdit::RemoveCrop | ImageEdit::RotateBy(_) | ImageEdit::Arrange(_) | ImageEdit::Delete => {++ pdfcraft_edit::change_image(doc, *page, *index, &c)?;++ }++ }++ } else {++ pdfcraft_edit::change_image(doc, *page, *index, &c)?;++ }+ }+ Edit::MoveObjects { page, objects, offset } => pdfcraft_edit::move_objects(doc, *page, objects, *offset)?,+ Edit::EditTextBlock { page, block, text, style } => {+ pdfcraft_edit::rewrite_block(doc, *page, *block, Some(text), style)?;+ }+ Edit::RegisterTextFont { page, bytes } => {+ pdfcraft_edit::text::register_text_font(doc, *page, bytes)?;+ }+ Edit::MarkDecorative { figure } => {+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));+ a11y::mark_decorative(doc, r).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::MarkTagArtifact { object } => {+ a11y::mark_tag_artifact(doc, *object).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::AddHeaderFooter { pages, settings, replace } => {+ let date = cx.today;+ pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?;+ }+ Edit::AddWatermark { pages, settings, replace, file } => {+ let mut s = settings.clone();+ if let Some(f) = file {+ s.source = Some(mark_source(doc, f)?);+ }+ pdfcraft_edit::add_watermark(doc, pages, &s, *replace)?+ }+ Edit::AddBackground { pages, settings, replace, file } => {+ let mut s = settings.clone();+ if let Some(f) = file {+ s.source = Some(mark_source(doc, f)?);+ }+ pdfcraft_edit::add_background(doc, pages, &s, *replace)?+ }+ Edit::RemoveMarks { kind } => {+ let n = pdfcraft_model::pages(doc).len();+ if pdfcraft_edit::remove_marks(doc, &(0..n).collect::<Vec<_>>(), *kind)? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there is nothing to remove".into())));+ }+ }+ Edit::AddText { page, text } => {+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Text(text.clone()))?;+ }+ Edit::AddImage { page, rect, name, bytes } => {+ let (image, natural) = embed_image(doc, name, bytes)?;+ let rect = match rect {+ Some(r) => *r,+ None => {+ let p = pdfcraft_model::pages(doc).swap_remove(*page);+ let (pw, ph) = p.display_size(doc);+ let k = ((pw * 0.8) / natural.0).min((ph * 0.8) / natural.1).min(1.0);+ let (w, h) = (natural.0 * k, natural.1 * k);+ [(pw - w) / 2.0, (ph - h) / 2.0, (pw + w) / 2.0, (ph + h) / 2.0]+ }+ };+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Image(pdfcraft_edit::AddedImage::new(rect, image)))?;+ }+ Edit::UpdateContent { page, index, content } => pdfcraft_edit::update_content(doc, *page, *index, content)?,+ Edit::DeleteContent { page, index } => pdfcraft_edit::delete_content(doc, *page, *index)?,+ Edit::ReplaceImage { page, index, name, bytes } => {+ let item = pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).nth(*index);+ let Some(AddedContent::Image(old)) = item.map(|a| a.content) else {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("that item is not an image".into())));+ };+ let (image, _) = embed_image(doc, name, bytes)?;+ pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;+ }+ Edit::PasteContent { page, content, file } => {+ let content = match content {+ AddedContent::Text(_) => content.clone(),+ AddedContent::Image(img) => {+ let Some((name, bytes)) = file else {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("a pasted image needs its picture".into())));+ };+ // The same picture in this document (copied here, pasted here before, or an+ // identical file): drawn again from the one image object rather than stored twice.+ let image = if copy_image::is_picture(doc, img.image, bytes) {+ img.image+ } else {+ match copy_image::added_picture(doc, bytes) {+ Some(image) => image,+ None => embed_image(doc, name, bytes)?.0,+ }+ };+ AddedContent::Image(pdfcraft_edit::AddedImage { image, ..img.clone() })+ }+ };+ pdfcraft_edit::add_content(doc, *page, &content)?;+ }+ Edit::ApplyRedactions { pages } => {+ cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;+ }+ Edit::ClearRedactions => {+ pdfcraft_redact::clear_marks(doc, None)?;+ }+ Edit::AddLink { page, rect, action, style } => {+ pdfcraft_annot::links::add(doc, *page, *rect, action, style)?;+ }+ Edit::SetLink { page, index, rect, action, style } => pdfcraft_annot::links::set(doc, *page, *index, *rect, action.as_ref(), style.as_ref())?,+ Edit::DeleteLink { page, index } => pdfcraft_annot::links::delete(doc, *page, *index)?,+ Edit::RemoveLinks { pages } => {+ if pdfcraft_annot::links::remove_all(doc, pages.as_deref())? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there are no links to remove".into())));+ }+ }+ Edit::AddLinks { links, style } => {+ if pdfcraft_annot::links::add_many(doc, links, style)? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("no web addresses were found".into())));+ }+ }+ Edit::ImportData { bytes, .. } => {+ // An XFA form takes XFA data files (XDP, datasets, or a data document) as its data;+ // XFDF, FDF, Acrobat's XML and tables go the usual way.+ let text = (pdfcraft_xfa::read_packets(doc).ok().flatten().is_some()).then(|| decode_data_file(bytes)).flatten();+ match text {+ Some(Ok(text)) if is_xfa_data_file(&text) => {+ let expect_root = cx.xfa.as_ref().and_then(|t| t.root.common.name.clone());+ let r = pdfcraft_xfa::import_data(doc, &text, expect_root.as_deref(), cx.xfa_datasets)+ .map_err(|e| EditError::Write(e.to_string()))?;+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);+ cx.xfa_out.errors.extend(r.warnings);+ cx.xfa_out.console.push(format!("Imported XFA data: {} node(s)", r.nodes));+ xfa_after_data_change(doc, cx, true)?;+ }+ Some(Err(why)) => return Err(EditError::Invalid(why)),+ _ => {+ pdfcraft_xfdf::import(doc, bytes)?;+ }+ }+ }+ Edit::RemoveHidden { which } => {+ pdfcraft_redact::sanitize::remove_hidden(doc, which)?;+ }+ Edit::Sanitize => {+ pdfcraft_redact::sanitize::sanitize(doc)?;+ }+ Edit::Flatten { comments, fields } => {+ // An XFA form's fields baked into the pages: the XFA goes too, or Adobe's viewers+ // would lay the form out again from its template over the baked pages. A dynamic+ // form that was never laid out keeps its XFA: without it only placeholders remain.+ let shape = (*fields).then(|| pdfcraft_xfa::xfa_shape(doc)).flatten();+ let n = pdfcraft_model::pages(doc).len();+ pdfcraft_edit::flatten(doc, &(0..n).collect::<Vec<_>>(), *comments, *fields)?;+ match shape {+ Some(shape) if shape.strippable() => strip_xfa(doc, cx)?,+ Some(_) => cx.xfa_removed.push("The XFA was kept: this dynamic form was not laid out, so its fields were not baked in".into()),+ None => {}+ }+ }+ Edit::XfaToStatic => {+ let Some(shape) = pdfcraft_xfa::xfa_shape(doc) else {+ return Err(EditError::Invalid("this document is not an XFA form".into()));+ };+ if !shape.strippable() {+ return Err(EditError::Invalid("this dynamic XFA form was not laid out, so there is no static form to keep".into()));+ }+ strip_xfa(doc, cx)?;+ }+ Edit::FlattenFillSign => {+ let n = pdfcraft_model::pages(doc).len();+ pdfcraft_edit::flatten_fill_sign(doc, &(0..n).collect::<Vec<_>>())?;+ }+ Edit::Protect(p) => {+ p.validate()?;+ let seed = cx.entropy();+ // Without a permissions password nothing is restricted, so the owner password is a+ // random one nobody needs.+ let random_owner: String = cx.entropy().iter().map(|b| format!("{b:02x}")).collect();+ let params = pdfcraft_cos::NewEncryption {+ algorithm: p.algorithm,+ user_password: p.open_password.as_deref().unwrap_or(""),+ owner_password: p.permissions_password.as_deref().unwrap_or(&random_owner),+ permissions: p.permission_bits(),+ encrypt_metadata: p.encrypt_metadata,+ seed,+ };+ doc.set_encryption(¶ms).map_err(|e| EditError::Protection(e.to_string()))?;+ }+ Edit::RemoveProtection => {+ if doc.output_handler().is_none() {+ return Err(EditError::Protection("the document isn't protected".into()));+ }+ doc.remove_encryption();+ }+ Edit::Batch { edits, .. } => {+ for e in edits {+ run_edit(doc, e, cx)?;+ }+ }+ }+ Ok(())+ }diff --cc crates/engine/src/lib.rsindex cbb339ba1,889b83936..bd0b9af81--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -98,137 -147,12 +147,14 @@@ use xfa_form::undrawn_field_warnings, xfa_after_data_change, xfa_layout, xfa_redraw, xfa_sync_datasets, xfa_values_from_datasets,};- /// A change to an existing page image.- #[derive(Clone, Debug, PartialEq)]- pub enum ImageEdit {- /// Move and resize it to this box (user space).- Move([f64; 4]),- /// Quarter turns clockwise about its centre.- Rotate(i32),- /// Any angle in degrees clockwise about its centre (the unit is degrees, not quarter turns).- RotateBy(f64),- Flip {- horizontal: bool,- },- /// Show only this box of it (user space), the pixels staying where they are.- Crop([f64; 4]),- /// Draw this image file (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000) in its place.- Replace {- name: String,- bytes: Arc<Vec<u8>>,- },- /// Apply an arbitrary 2D affine transform matrix in user space.- Transform([f64; 6]),- Delete,- /// Change the stacking order.- Arrange(ArrangeOrder),- /// Remove any private crop on the image.- RemoveCrop,- }-- /// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a- /// filled-in PDF form), as CSV with one row per file.- pub fn merge_data_files(files: &[(String, Vec<u8>)]) -> Result<String, String> {- let rows =- files.iter().map(|(name, bytes)| pdfcraft_xfdf::data_values(bytes).map_err(|e| format!("{name}: {e}"))).collect::<Result<Vec<_>, _>>()?;- Ok(pdfcraft_xfdf::merge_csv(&rows))- }-- /// One file produced by a split: (1-based first page, last page, PDF bytes).- pub type SplitPart = (usize, usize, Arc<Vec<u8>>);-- /// Stable identifier of an open document within a session.- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]- pub struct DocId(pub u64);-- /// The highest resolution a document that allows only low-resolution printing (Table 22, bit 12- /// clear) is printed at.- const LOW_RESOLUTION_PRINT_DPI: f64 = 150.0;-- fn render_threads() -> usize {- std::thread::available_parallelism().map(std::num::NonZeroUsize::get).unwrap_or(4).clamp(2, 8) - 1- }-- /// A document's working file captured for crash recovery.- #[derive(Clone, Debug)]- pub struct RecoverySnapshot {- pub doc: DocId,- pub name: String,- pub path: Option<String>,- pub bytes: Arc<Vec<u8>>,- /// The snapshot is encrypted (recovering it asks for the password again).- pub encrypted: bool,- }-- /// Seconds to add to UTC for local time (0 where unknown).- fn local_utc_offset() -> i64 {- #[cfg(not(target_arch = "wasm32"))]- return i64::from(chrono::Local::now().offset().local_minus_utc());- #[cfg(target_arch = "wasm32")]- return 0;- }-- /// (year, month, day) from a PDF date `D:YYYYMMDD…`.- fn parse_ymd(d: &str) -> Option<(i64, u32, u32)> {- let d = d.strip_prefix("D:").unwrap_or(d);- Some((d.get(0..4)?.parse().ok()?, d.get(4..6)?.parse().ok()?, d.get(6..8)?.parse().ok()?))- }-- /// The recovered user password of an R2–R4 file as text for the renderer, which tries a password- /// as its UTF-8 bytes and then in PDFDocEncoding: UTF-8 bytes (as some writers store passwords- /// PDFDocEncoding can't hold, such as "şifre") stay UTF-8, and other bytes are read as- /// PDFDocEncoding, so either way the renderer gets back exactly these bytes.- fn renderer_password(bytes: &[u8]) -> String {- match std::str::from_utf8(bytes) {- Ok(text) => text.to_owned(),- Err(_) => bytes.iter().map(|b| pdfcraft_cos::pdfdoc_char(*b)).collect(),- }- }-- /// The document as it may be written to a file (#3926, #3944): a copy without the values of text- /// fields with the Password flag (or XFA `<passwordEdit/>` fields in the datasets), or `cos`- /// itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231 (a note to the Password flag):- /// "it is imperative that PDF processors never store the value of the text field in the PDF file- /// if this flag is set". The open document keeps them in memory.- fn writable(cos: &pdfcraft_cos::Document) -> Result<std::borrow::Cow<'_, pdfcraft_cos::Document>, EditError> {- let has_form_pw = pdfcraft_forms::has_password_values(cos);- let has_xfa_pw = pdfcraft_xfa::has_password_values(cos);- if !has_form_pw && !has_xfa_pw {- return Ok(std::borrow::Cow::Borrowed(cos));- }- let mut copy = cos.clone();- if has_form_pw {- pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;- }- if has_xfa_pw {- pdfcraft_xfa::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;- }- Ok(std::borrow::Cow::Owned(copy))- }-- /// The last-resort guard (AGENTS.md §4): run `f`, turning a panic that escapes it into an error- /// message, so one bad file or edit can't take the app and its other documents down. It is a- /// safety net for bugs, not a substitute for returning errors.- pub fn guard<T>(f: impl FnOnce() -> T) -> Result<T, String> {- std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|p| {- p.downcast_ref::<&str>().map(|s| (*s).to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown error".into())- })- }-- /// Validate the signature fields of `cos` (written as `bytes`).- fn signatures_of(cos: &pdfcraft_cos::Document, bytes: &[u8], trust: &TrustStore, cache: &pdfcraft_sign::DigestCache) -> Vec<SignatureInfo> {- pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache)- }-- /// What Optimize PDF did.- #[derive(Clone, Debug, Default, PartialEq, Eq)]- pub struct OptimizeReport {- pub optimize: optimize::Report,- /// Identical objects merged.- pub merged: usize,- /// Remove Hidden Information categories discarded, with counts.- pub discarded: Vec<(Hidden, usize)>,- }+ mod clock;+ mod doc_state;+++pub use pdfcraft_edit::ArrangeOrder;+++ use clock::{local_utc_offset, parse_ymd};+ pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files};+ use doc_state::{LOW_RESOLUTION_PRINT_DPI, render_threads, renderer_password, signatures_of, writable};#[cfg(test)]mod tests;diff --cc crates/engine/src/session/editing.rsindex 000000000,9b1a8340a..77fb7e5f3mode 000000,100644..100644--- a/crates/engine/src/session/editing.rs+++ b/crates/engine/src/session/editing.rs@@@ -1,0 -1,521 +1,522 @@@+ use super::*;++ impl Session {+ /// Apply an edit. On success the previous state is undoable and the view data is refreshed.+ pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {+ let now = self.now();+ let today = self.today();+ let js_off = self.js_off;+ let xfa_time_scale = self.xfa_time_scale.unwrap_or(1);+ let doc = self.doc_mut(id)?;+ doc.edit_notices.clear();+ let name = doc.name.clone();+ let is_xfa = doc.info.xfa.is_some();+ let mut scope = scope_of(&edit);+ let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48));+ if !js_off {+ cx.xfa = doc.xfa_template.clone();+ }+ cx.xfa_time_scale = xfa_time_scale;+ cx.pages = doc.info.pages.len();+ cx.today = today;+ let reason = doc.read_only_reason.clone().unwrap_or_default();+ let signed = doc.is_signed();+ let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;+ if let Some(p) = editor.cos.permissions() {+ check_permission(&edit, &p)?;+ }+ // Rewriting an OCR word (invisible text over a scan) also hides the scanned word: cover it+ // in the paper's colour and draw the new text in the ink's.+ let edit = match edit {+ Edit::EditTextBlock { page, block, text, mut style } => {+ // Only invisible text is sampled; the blocks are usually cached from opening it.+ if style.cover.is_none()+ && let Some(info) = doc.info.pages.get(page)+ && let Some(b) = editor.text_blocks(page).ok().and_then(|b| b.get(block).filter(|b| b.invisible).cloned())+ && let Some((paper, ink)) = guard(|| scan_colours::sample(&editor.cos, info, page, &b)).ok().flatten()+ {+ style.cover = Some(paper);+ style.color = style.color.or(Some(ink));+ }+ Edit::EditTextBlock { page, block, text, style }+ }+ other => other,+ };+ // Nothing to bake: leave undo history and the dirty flag alone.+ if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) {+ return Ok(());+ }+ let mut next = editor.cos.clone();+ if !js_off && uses_scripts(&edit) {+ cx.js = Some(js::JsRunner::new(&next, &name));+ }+ cx.renamed_fields.clear();+ cx.redaction_overlays.clear();+ // `next` is a copy: if the edit fails or crashes, the document is unchanged.+ guard(|| run_edit(&mut next, &edit, &mut cx))+ .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;+ // Redaction removed what its own interpreter places under the marks. The marks were drawn+ // over the page as the renderer shows it, so the renderer has the last word.+ if let Edit::ApplyRedactions { pages } = &edit {+ let marks: Vec<pdfcraft_redact::Mark> =+ pdfcraft_redact::marks(&editor.cos).into_iter().filter(|m| pages.as_ref().is_none_or(|p| p.contains(&m.page))).collect();+ guard(|| shown_under_redactions(&next, &marks, &cx.redaction_overlays, &doc.info.pages, doc.password.as_deref()))+ .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;+ }+ // Renamed fields are said, not slipped in: a repair-log note (with the caveat that+ // scripts were left alone) and a count in the undo step's label.+ let renamed_note = |renamed: &[(String, String)]| {+ (!renamed.is_empty()).then(|| {+ let shown: Vec<String> = renamed.iter().take(5).map(|(old, new)| format!("{old} → {new}")).collect();+ let more = renamed.len().saturating_sub(shown.len());+ let more = if more > 0 { format!(", and {more} more") } else { String::new() };+ format!(+ "inserted pages renamed {} form field{} to keep their names separate ({}{more}); scripts that refer to the old names were not rewritten",+ renamed.len(),+ if renamed.len() == 1 { "" } else { "s" },+ shown.join(", ")+ )+ })+ };+ if let Some(note) = renamed_note(&cx.renamed_fields) {+ next.note_repair(note);+ }+ // Only Insert from File renames fields; its label says so in a wording the interface+ // translates (the count lives in the repair note).+ let label = match (&edit, cx.renamed_fields.len()) {+ (_, 0) => edit.label(),+ (Edit::InsertPagesFrom { name, .. }, n) => Label::with(+ if n == 1 { "Insert pages from {name} — 1 field renamed" } else { "Insert pages from {name} — fields renamed" },+ name.as_str(),+ ),+ _ => edit.label(),+ };+ // An XFA form's scripts answer the change: exit and validate scripts of the field, then+ // every calculation (and a reset recalculates). They read the data, so it is brought up+ // to date first.+ if let Some(tpl) = cx.xfa.clone() {+ if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {+ let datasets = &mut cx.xfa_datasets;+ let notes = guard(|| xfa_sync_datasets(&mut next, Some(&tpl), datasets))+ .unwrap_or_else(|m| Err(format!("writing the XFA data failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ cx.xfa_out.errors.extend(notes);+ }+ fn collect(e: &Edit, changed: &mut Vec<String>, reset: &mut bool) {+ match e {+ Edit::SetFieldValue { name, .. } => changed.push(name.clone()),+ Edit::ResetForm { .. } => *reset = true,+ Edit::Batch { edits, .. } => edits.iter().for_each(|e| collect(e, changed, reset)),+ _ => {}+ }+ }+ let mut changed: Vec<String> = Vec::new();+ let mut reset = false;+ collect(&edit, &mut changed, &mut reset);+ if !changed.is_empty() || reset {+ let mut run = xfa::XfaRun {+ page_count: cx.pages,+ out: &mut cx.xfa_out,+ datasets: cx.xfa_datasets,+ ran_away: false,+ time_scale: cx.xfa_time_scale,+ };+ // Every changed field's scripts, then the calculations once (after a reset,+ // only those).+ let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run))+ .unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));+ cx.xfa_datasets = run.datasets;+ cx.xfa_ran_away |= run.ran_away;+ if let Err(e) = ran {+ cx.xfa_out.errors.push(e);+ }+ }+ }+ // XFA forms keep their values in the datasets packet too, for Adobe's viewers.+ let mut xfa_notes = Vec::new();+ if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {+ let (tpl, datasets) = (cx.xfa.as_deref(), &mut cx.xfa_datasets);+ xfa_notes = guard(|| xfa_sync_datasets(&mut next, tpl, datasets))+ .unwrap_or_else(|m| Err(format!("writing the XFA data failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ // Rebuilding from stale data would discard accepted widget values.+ if xfa_notes.is_empty() {+ let reflow = guard(|| xfa::relayout_changed_text(&mut next, tpl, &doc.form))+ .unwrap_or_else(|m| Err(format!("laying out the XFA text failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ if let Some(warnings) = reflow {+ xfa_notes.extend(warnings);+ // Layout replaces pages and widgets, even if the page count is unchanged.+ // Undo/redo must rebuild these too instead of refreshing only field values.+ scope = Scope::Full;+ }+ }+ }+ // Signed documents are only ever saved incrementally: an edit that needs a full rewrite+ // (applying redactions, changing security, sanitizing) would invalidate the signatures.+ // So does any edit to a file rebuilt from object headers: it has no chain to append to.+ let rewrites = |c: &pdfcraft_cos::Document| c.full_save_required() || c.encryption_changed();+ if signed && ((rewrites(&next) && !rewrites(&editor.cos)) || (next.is_modified() && next.revisions().is_empty())) {+ return Err(EditError::SignedRewrite(edit.label().to_string()));+ }+ // What this edit drew with `?` (a value or comment text its font can't draw, stored as+ // typed): reported, never silent (AGENTS.md §4).+ let notices = if matches!(scope_of(&edit), Scope::Form | Scope::Comments | Scope::Full) {+ guard(|| undrawn_notices(&editor.cos, &next)).unwrap_or_default()+ } else {+ Vec::new()+ };+ let previous = std::mem::replace(&mut editor.cos, next);+ let keys = keys_after(&edit).unwrap_or_else(|| editor.keys.clone());+ let previous_keys = std::mem::replace(&mut editor.keys, keys);+ editor.undo.push((label, previous, previous_keys, scope));+ if editor.undo.len() > MAX_UNDO {+ editor.undo.remove(0);+ }+ editor.redo.clear();+ Self::adopt_keys(doc);+ let refreshed = guard(|| if scope == Scope::Content { Self::refresh_content(doc, Some(&edit)) } else { Self::refresh_scoped(doc, scope) })+ .unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ // Roll back: the edit produced something we cannot display.+ if let Some(ed) = doc.editor.as_mut()+ && let Some((_, prev, keys, _)) = ed.undo.pop()+ {+ ed.cos = prev;+ ed.keys = keys;+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.dirty = true;+ doc.generation += 1;+ doc.edit_notices = notices;+ if !cx.xfa_removed.is_empty() {+ let removed: Vec<String> = cx.xfa_removed.iter().map(|n| format!("{XFA_REMOVED_PREFIX}{n}")).collect();+ doc.xfa_warnings.retain(|w| w.starts_with(XFA_REMOVED_PREFIX));+ note_warnings(&mut doc.xfa_warnings, &removed);+ note_warnings(&mut doc.info.warnings, &removed);+ }+ note_warnings(&mut doc.xfa_warnings, &xfa_notes);+ let notes = doc.xfa_warnings.clone();+ note_warnings(&mut doc.info.warnings, ¬es);+ if let Some(js) = cx.js {+ doc.js_output.append(js.output);+ }+ doc.js_output.append(cx.xfa_out);+ if cx.xfa_ran_away {+ doc.xfa_template = None;+ doc.xfa_scripts_off = true;+ doc.js_output.errors.push(XFA_SCRIPTS_OFF.into());+ }+ Ok(())+ }++ pub fn undo(&mut self, id: DocId) -> Result<Label, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToUndo)?;+ let (label, prev, keys, scope) = editor.undo.pop().ok_or(EditError::NothingToUndo)?;+ let current = std::mem::replace(&mut editor.cos, prev);+ let current_keys = std::mem::replace(&mut editor.keys, keys);+ editor.redo.push((label.clone(), current, current_keys, scope));+ Self::adopt_keys(doc);+ let refreshed = guard(|| Self::refresh_scoped(doc, scope)).unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ if let Some(ed) = doc.editor.as_mut()+ && let Some((label, current, current_keys, scope)) = ed.redo.pop()+ {+ let prev = std::mem::replace(&mut ed.cos, current);+ let keys = std::mem::replace(&mut ed.keys, current_keys);+ ed.undo.push((label, prev, keys, scope));+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.edit_notices.clear();+ Self::sync_dirty(doc);+ doc.generation += 1;+ Ok(label)+ }++ pub fn redo(&mut self, id: DocId) -> Result<Label, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToRedo)?;+ let (label, next, keys, scope) = editor.redo.pop().ok_or(EditError::NothingToRedo)?;+ let current = std::mem::replace(&mut editor.cos, next);+ let current_keys = std::mem::replace(&mut editor.keys, keys);+ editor.undo.push((label.clone(), current, current_keys, scope));+ Self::adopt_keys(doc);+ let refreshed = guard(|| Self::refresh_scoped(doc, scope)).unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ if let Some(ed) = doc.editor.as_mut()+ && let Some((label, current, current_keys, scope)) = ed.undo.pop()+ {+ let next = std::mem::replace(&mut ed.cos, current);+ let keys = std::mem::replace(&mut ed.keys, current_keys);+ ed.redo.push((label, next, keys, scope));+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.edit_notices.clear();+ Self::sync_dirty(doc);+ doc.generation += 1;+ Ok(label)+ }++ /// Unsaved when the working graph is not the last opened or saved file. Undo back to that+ /// file is clean; undo past a later save is not, because the restored snapshot's own base+ /// is an earlier revision.+ pub(super) fn sync_dirty(doc: &mut Document) {+ doc.dirty = doc.editor.as_ref().is_some_and(|e| e.unsaved_file || e.cos.is_modified() || !Arc::ptr_eq(e.cos.bytes(), &e.saved));+ }++ /// Use the current state's password for viewing (protection edits change it).+ pub(super) fn adopt_keys(doc: &mut Document) {+ if let Some(e) = doc.editor.as_ref() {+ doc.password = e.keys.render.clone();+ doc.config.password = e.keys.render.as_deref().map(Arc::from);+ }+ }++ /// Rebuild the working bytes and the view data that `scope` may have changed. Metadata edits+ /// keep the renderer; other scopes also replace it.+ /// Comment and form edits skip the full re-inspection (seconds on very large files): the+ /// comment list and field values are re-read from the object graph instead.+ fn refresh_scoped(doc: &mut Document, scope: Scope) -> Result<(), EditError> {+ if scope == Scope::Full || doc.info.encrypted != doc.editor.as_ref().is_some_and(|e| e.cos.output_handler().is_some()) {+ return Self::refresh(doc);+ }+ if scope == Scope::Content {+ return Self::refresh_content(doc, None);+ }+ if scope == Scope::Links {+ return Self::refresh_links(doc);+ }+ // Metadata edits keep the renderer, which holds the working file anyway.+ if scope != Scope::Metadata {+ Self::release_working(doc);+ }+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ // Comment edits, and form edits (a script may change annotation properties), may change+ // annotation dictionaries, invalidating cached appearances.+ if matches!(scope, Scope::Comments | Scope::Form) {+ editor.appearances.clear();+ }+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ if scope == Scope::Metadata {+ for (field, value) in info_fields(&mut doc.info, &editor.cos) {+ *field = value;+ }+ doc.info.custom = pdfcraft_organize::custom_info(&editor.cos);+ doc.info.file_size = bytes.len();+ #[cfg(test)]+ check_refresh_panic();+ if !doc.signatures.is_empty() {+ let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);+ doc.signatures = Arc::new(signatures);+ }+ doc.bytes = bytes;+ return Ok(());+ }+ let mut form = pdfcraft_forms::fields(&editor.cos);+ xfa::mark_script_buttons(&editor.cos, &mut form);+ let form = Arc::new(form);+ match scope {+ Scope::Metadata => return Ok(()),+ Scope::Comments => {+ doc.info.annotations = comment_list(&editor.cos);+ // Link indexes are positions in /Annots, so comment insertion/deletion can move them.+ doc.links = OnceLock::new();+ }+ Scope::Form => {+ // PERF: keystroke path, index once. A linear find per field is O(F^2);+ // forms reach 10k fields.+ let mut by_name = std::collections::HashMap::with_capacity(form.len());+ for x in form.iter() {+ // First match wins (do not simplify to collect: it keeps the last).+ by_name.entry(x.name.as_str()).or_insert(x);+ }+ for f in &mut doc.info.fields {+ if let Some(ff) = by_name.get(f.name.as_str()) {+ f.value = match ff.kind {+ pdfcraft_forms::FieldKind::CheckBox | pdfcraft_forms::FieldKind::Radio => {+ Some(ff.value.first().cloned().unwrap_or_else(|| "Off".into()))+ }+ _ if ff.value.is_empty() => None,+ _ => Some(ff.value.join(", ")),+ };+ }+ }+ }+ Scope::Links => return Self::refresh_links(doc),+ // Handled above; kept as a full refresh so the match stays total.+ Scope::Full => return Self::refresh(doc),+ // Handled above (content-only refresh); the arm keeps the match total.+ Scope::Content => return Self::refresh_content(doc, None),+ }+ doc.info.file_size = bytes.len();+ doc.form = form;+ let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone());+ doc.bytes = bytes;+ Ok(())+ }++ /// Which derived lists a content-only edit can change: added content (`None`, from+ /// undo/redo, re-reads both: always correct, rarely paid).+ pub(crate) fn content_refresh_lists(edit: Option<&Edit>) -> (bool, bool) {+ if let Some(Edit::Batch { edits, .. }) = edit {+ // A batch of content edits (from a script, say) changes what its parts change.+ return edits.iter().fold((false, false), |(added, marks), part| {+ let (a, m) = Self::content_refresh_lists(Some(part));+ (added || a, marks || m)+ });+ }+ let touches_added = edit.is_none_or(|e| {+ matches!(+ e,+ Edit::AddText { .. }+ | Edit::AddImage { .. }+ | Edit::UpdateContent { .. }+ | Edit::DeleteContent { .. }+ | Edit::ReplaceImage { .. }+ | Edit::PasteContent { .. }++ | Edit::EditPageImage { .. }+ ) || matches!(e, Edit::MoveObjects { objects, .. } if objects.iter().any(|o| o.kind == ObjectKind::Added))+ });+ let touches_marks = edit.is_none_or(|e| {+ matches!(e, Edit::AddHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. })+ });+ (touches_added, touches_marks)+ }++ /// Rebuild working bytes, display bytes and renderer after a content-only edit: page+ /// content streams, resources and added content/marks. The page tree, annotations, form+ /// fields, links, outline and fonts are unchanged, so the full re-inspection (seconds on+ /// very large files) is skipped. `edit` selects which derived lists are re-read (`None`,+ /// from undo/redo, re-reads both: always correct, rarely paid). The cached display+ /// appearances are kept: content edits leave every annotation dictionary alone.+ fn refresh_content(doc: &mut Document, edit: Option<&Edit>) -> Result<(), EditError> {+ Self::release_working(doc);+ sync_xfa_state(doc);+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ // The edit must still leave a file the viewer can open; anything else rolls back above.+ pdfcraft_render::check_pages(bytes.clone(), doc.password.as_deref(), doc.info.pages.len()).map_err(|e| EditError::Reopen(e.to_string()))?;+ let (touches_added, touches_marks) = Self::content_refresh_lists(edit);+ if touches_added || touches_marks {+ doc.marker_scan = OnceLock::new();+ }+ doc.info.file_size = bytes.len();+ let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone());+ doc.bytes = bytes;+ doc.fonts_stale = true;+ Ok(())+ }++ /// Let go of the working file before the next one is written (gap 13). The working file is+ /// the original plus one appended revision, so on a 1 GiB file keeping the old one (in the+ /// working bytes, the display bytes and the renderer) while writing the new one held three+ /// copies at once; this keeps two. Until the refresh finishes, the working and display bytes+ /// are the original's (already held by the editor, so free) and the renderer draws nothing.+ /// A failed edit rolls back and refreshes again, which replaces all three; where a refresh+ /// still fails, [`Self::show_released`] draws the original rather than nothing. Save writes+ /// from the editor, never from these.+ pub(crate) fn release_working(doc: &mut Document) {+ let Some(original) = doc.editor.as_ref().map(|e| e.cos.bytes().clone()) else { return };+ // Dropping the pool stops its workers; each lets go of the file when it exits.+ doc.renderer = RenderPool::new_inline(Arc::new(Vec::new()), doc.config.clone());+ doc.display = original.clone();+ doc.bytes = original;+ #[cfg(test)]+ check_refresh_panic();+ }++ /// After a refresh failed: draw the display bytes it left (the original, once released),+ /// so the page still shows a document.+ pub(super) fn show_released(doc: &mut Document) {+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone());+ }++ /// Rebuild working bytes, inspection and renderer from the current edit state.+ pub(crate) fn refresh(doc: &mut Document) -> Result<(), EditError> {+ Self::refresh_with_indexes(doc, true, true)+ }++ /// Reinspect a link edit while preserving the page-content marker scan cache.+ fn refresh_links(doc: &mut Document) -> Result<(), EditError> {+ Self::refresh_with_indexes(doc, false, true)+ }++ fn refresh_with_indexes(doc: &mut Document, invalidate_markers: bool, invalidate_links: bool) -> Result<(), EditError> {+ // A full refresh may follow structural or annotation changes: cached appearances+ // may be stale, so they are rebuilt below.+ if let Some(editor) = doc.editor.as_mut() {+ editor.appearances.clear();+ }+ Self::release_working(doc);+ sync_xfa_state(doc);+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ let info = inspect(bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;+ // Keep the user's layer choices where the layers still exist.+ let mut info = info;+ for l in &mut info.layers {+ if let Some(old) = doc.info.layers.iter().find(|o| o.id == l.id) {+ l.visible = old.visible;+ }+ }+ note_warnings(&mut info.warnings, &doc.xfa_warnings);+ // As in `build_document`: the inspection reads only `/Info`, so fields stated only in XMP+ // are filled in again after every full refresh.+ for (field, value) in info_fields(&mut info, &editor.cos) {+ if field.is_none() {+ *field = value;+ }+ }+ doc.info = info;+ doc.fonts_stale = false;+ let mut form = pdfcraft_forms::fields(&editor.cos);+ xfa::mark_script_buttons(&editor.cos, &mut form);+ doc.form = Arc::new(form);+ if invalidate_markers {+ doc.marker_scan = OnceLock::new();+ }+ if invalidate_links {+ doc.links = OnceLock::new();+ }+ let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), doc.config.clone());+ doc.bytes = bytes;+ Ok(())+ }+ }diff --cc crates/ui-egui/src/app.rsindex 000000000,8925a0dca..5c1f007dfmode 000000,100644..100644--- a/crates/ui-egui/src/app.rs+++ b/crates/ui-egui/src/app.rs@@@ -1,0 -1,610 +1,654 @@@+ use super::hooks::OsEvent;+ use super::state::{+ Dialog, DocumentCopyJob, GridFile, LeftPanel, LinkOrigin, Mode, NumberDraft, PasswordPrompt, PendingLink, PropsTab, QuickTool, RecentFile,+ RightPanel, UnlockPrompt,+ };+ #[cfg(not(target_arch = "wasm32"))]+ use super::state::{OpenOutcome, OpenRequest, PendingRemoteLink};+ use super::*;++ mod clipboard;+ mod commands;+ mod control;+ mod files;+ mod frame;+ mod input;+ mod keys;+ mod links;+ mod prefs;+ mod window;++ pub(crate) use clipboard::{copy_refused, print_refused};+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use files::same_file;+ use frame::migrate_panel_state;+ pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf};++ impl Default for PdfCraftApp {+ fn default() -> Self {+ Self::new()+ }+ }++ impl PdfCraftApp {+ /// Construct an application with the default session, panels, theme and control state.+ pub fn new() -> Self {+ Self {+ session: Session::new(),+ views: Vec::new(),+ closed_tabs: Vec::new(),+ active: None,+ mode: Mode::AllTools,+ default_mode: Mode::AllTools,+ view_defaults: Default::default(),+ units: Default::default(),+ date_format_draft: None,+ mode_override: None,+ left: LeftPanel::AllTools,+ side_panels: Default::default(),+ left_open: true,+ right: None,+ last_right: RightPanel::Comments,+ right_before_read: None,+ comments_panel_closed: false,+ right_panel_closed: false,+ quick_tool: QuickTool::Select,+ space_hand: None,+ full_screen_tool: None,+ comment_prefs: Default::default(),+ theme: ThemeKind::Light,+ // A fresh install follows the desktop's appearance (#1248); saved settings override.+ theme_preference: ThemePreference::System,+ reading_colors: Default::default(),+ #[cfg(target_os = "linux")]+ desktop_theme: None,+ #[cfg(target_os = "linux")]+ desktop_theme_enabled: false,+ scroll_speed: scroll_speed::ScrollSpeed::default(),+ animation_effects: motion::AnimationEffects::default(),+ motion: motion::Motion::default(),+ language: i18n::AUTO.to_string(),+ ui_scale: None,+ system_text_scale: 1.0,+ ui_scale_applied: None,+ flatten_fill_sign_on_save: false,+ fill_text_size: fill_sign::TEXT_SIZE,+ dialog: None,+ updates: updates::Updates::default(),+ printer_source: None,+ options_source: None,+ print_tasks: print_ui::PrintTasks::default(),+ palette_open: false,+ palette_query: String::new(),+ all_tools_expanded: false,+ all_tools_full: false,+ all_tools_query: String::new(),+ all_tools_tab: (None, false),+ recent: Vec::new(),+ reopen_last_session: false,+ restore_last_view: true,+ last_views: Vec::new(),+ last_session: Default::default(),+ quit_session: None,+ reload_changed_files: true,+ show_secured_notice: true,+ always_default_view: false,+ #[cfg(not(target_arch = "wasm32"))]+ watch: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ open_worker: None,+ #[cfg(not(target_arch = "wasm32"))]+ pending_opens: Vec::new(),+ #[cfg(not(target_arch = "wasm32"))]+ next_open_token: 0,+ #[cfg(all(test, not(target_arch = "wasm32")))]+ open_prepare_gate: None,+ pinned: Default::default(),++ pinned_tools: Vec::new(),++ pin_tool_search: String::new(),+ toast: None,+ integrated_titlebar: false,+ window_controls: None,+ system_title_bar: false,+ app_frame_shown: None,+ password_prompt: None,+ document_copy: None,+ unlock_prompt: None,+ full_screen: false,+ inbox: Default::default(),+ startup_inbox: Default::default(),+ startup_superseded: false,+ failed_inbox: Default::default(),+ unsaved_flag: Default::default(),+ os_events: None,+ host_save: None,+ host_dirty: None,+ close_request: None,+ save_prompt_button: Default::default(),+ save_prompt_seen: false,+ save_prompt_attention: false,+ #[cfg(not(target_arch = "wasm32"))]+ pending_overwrite: None,+ save_override: None,+ props_draft: None,+ view_draft: None,+ custom_draft: None,+ requests: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pickers: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pick_override: None,+ export_dir_override: None,+ split_draft: SplitDraft::default(),+ extract_draft: ExtractDraft::default(),+ rotate_draft: RotateDraft::default(),+ summary_sort: Default::default(),+ sign_draft: None,+ digital_ids: Vec::new(),+ sig_expanded: Vec::new(),+ a11y_options: a11y_ui::A11yOptions::default(),+ ocr_draft: ocr_ui::OcrDraft::default(),+ ocr_run: None,+ ocr_batch: None,+ run_inline: false,+ custom_actions: Vec::new(),+ wizard: Default::default(),+ action_run: None,+ action_files_override: None,+ pdfa: Default::default(),+ compare_old: None,+ compare: None,+ js_console: Default::default(),+ doc_js: Default::default(),+ a11y: a11y_ui::A11yState::default(),+ tags_state: Default::default(),+ a11y_skipped: Default::default(),+ alt_draft: Default::default(),+ os_key_store_ids: false,+ cert_viewer: None,+ space_audit: Vec::new(),+ space_audit_of: None,+ combine_draft: Vec::new(),+ combine_conflicts: Default::default(),+ combine_tab: Default::default(),+ combine_columns: Default::default(),+ combine_view: Default::default(),+ combine_zoom: 1.0,+ organize_zoom: 1.0,+ combine_thumbs: Default::default(),+ image_import: None,+ custom_stamps: Vec::new(),+ stamp_draft: Default::default(),+ optimize_draft: OptimizeDraft::default(),+ optimize_run: None,+ progress_notice: None,+ page_clipboard: None,+ grid_drop: None,+ last_snapshot: None,+ last_copied_image: None,+ last_copied_file: None,++ last_copied_image_rect: None,+ system_clipboard: true,+ clipboard_override: None,+ v_pressed: false,++ last_command_time: None,+ attach_override: None,+ duplicate_draft: None,+ field_table_draft: None,+ form_preview: false,+ window_title: String::new(),+ recovery: None,+ recoverable: Vec::new(),+ recovery_keys: Default::default(),+ last_autosave: None,+ allow_quit: false,+ deferred_commands: Vec::new(),+ native_menu: None,+ menu_input: Vec::new(),+ dialog_seen: None,+ dialog_epoch: 0,+ ctx: None,+ #[cfg(not(target_arch = "wasm32"))]+ window_state: Default::default(),+ styled: false,+ fonts_ready: false,+ fonts_cjk: theme::CjkPreference::Default,+ control: None,+ bookmark_rename: None,+ last_opened_url: None,+ community_card_closed: false,+ pending_link: None,+ pending_full_screen: None,+ pending_remote_link: None,+ protect_draft: Default::default(),+ boxes_draft: Default::default(),+ marks_draft: Default::default(),+ export_draft: Default::default(),+ export_status: None,+ signature: None,+ initials: None,+ signature_draft: Default::default(),+ signature_preview: None,+ signature_photo: None,+ saved_signature_previews: [None, None],+ sign_graphic: sign_ui::SignGraphic::Name,+ sign_graphic_preview: None,+ #[cfg(target_arch = "wasm32")]+ signature_images: Default::default(),+ comment_props: None,+ field_props: None,+ bulk_field_props: None,+ redact_prefs: RedactPrefs::default(),+ redact_defaults: RedactPrefs::default(),+ redact_before: None,+ redact_pages_draft: RedactPagesDraft::default(),+ redact_search: RedactSearchDraft::default(),+ hidden_draft: HiddenDraft::default(),+ print_draft: PrintDraft::default(),+ link_draft: None,+ text_style: content_ui::default_style(),+ replace_draft: None,+ number_draft: NumberDraft { from: 1, to: 1, style: pdfcraft_engine::LabelStyle::Decimal, prefix: String::new(), start: 1 },+ word_count_draft: word_count_ui::Draft::default(),+ }+ }++ /// Fields are being edited (Prepare a form or its Calculation order is open, or a field tool+ /// is picked), unless the form is being previewed.+ pub fn is_preparing(&self) -> bool {+ ((self.left_open && matches!(self.left, LeftPanel::Tool("form") | LeftPanel::CalculationOrder))+ || matches!(self.quick_tool, QuickTool::Field(_)))+ && !self.form_preview+ }++ /// A number that changes whenever the open dialog changes (opened, closed or replaced by+ /// another), checked every frame. A picker started from a dialog's Browse… button answers+ /// only into the same showing of that dialog.+ pub(crate) fn dialog_epoch(&mut self) -> u64 {+ if self.dialog != self.dialog_seen {+ self.dialog_seen = self.dialog;+ self.dialog_epoch = self.dialog_epoch.wrapping_add(1);+ }+ self.dialog_epoch+ }++ pub fn active_ids(&self) -> Option<(usize, DocId)> {+ self.active.and_then(|i| self.views.get(i).map(|v| (i, v.id)))+ }++ /// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act+ /// on the document underneath it.+ pub(crate) fn modal_open(&self) -> bool {+ self.dialog.is_some()+ || self.close_request.is_some()+ || self.password_prompt.is_some()+ || self.unlock_prompt.is_some()+ || self.pending_link.is_some()+ || self.pending_remote_link.is_some()+ || self.updates.open+ }++ pub fn notify(&mut self, msg: impl Into<String>) {+ self.toast = Some((msg.into(), 0.0));+ }++ /// Notify with a static message in the UI language.+ pub fn notify_tr(&mut self, text: &str) {+ self.notify(tl!(text).to_string());+ }++ /// Notify with an error's own text. Engine and OS messages are not translated: matching their+ /// English wording would break silently whenever it changes.+ pub fn notify_error(&mut self, error: impl std::fmt::Display) {+ self.notify(error.to_string());+ }++ /// Notify with a `{name}`-style template in the UI language (placeholders filled once).+ pub fn notify_fmt(&mut self, template: &str, args: &[(&str, &str)]) {+ self.notify(i18n::fmt(tl!(template), args));+ }++ /// `true` while any open document still waits for page renders (used by headless capture).+ pub fn render_pending(&self) -> bool {+ self.views.iter().any(|v| v.render_pending())+ }++++ /// Check whether a tool group is pinned to Home.++ pub fn is_tool_pinned(&self, id: &str) -> bool {++ self.pinned_tools.iter().any(|t| t == id)++ }++++ /// Pin a tool group to Home. Returns true if newly pinned.++ pub fn pin_tool(&mut self, id: &str) -> bool {++ if pdfcraft_engine::catalog::group(id).is_none() {++ return false;++ }++ if !self.is_tool_pinned(id) {++ self.pinned_tools.push(id.to_string());++ if let Some(g) = pdfcraft_engine::catalog::group(id) {++ self.notify_fmt("Pinned {tool} to Home", &[("tool", &g.label)]);++ }++ return true;++ }++ false++ }++++ /// Unpin a tool group from Home.++ pub fn unpin_tool(&mut self, id: &str) {++ if let Some(pos) = self.pinned_tools.iter().position(|t| t == id) {++ self.pinned_tools.remove(pos);++ if let Some(g) = pdfcraft_engine::catalog::group(id) {++ self.notify_fmt("Unpinned {tool} from Home", &[("tool", &g.label)]);++ }++ }++ }++++ /// Toggle a tool group's pinned state on Home. Returns whether it is now pinned.++ pub fn toggle_pin_tool(&mut self, id: &str) -> bool {++ if self.is_tool_pinned(id) {++ self.unpin_tool(id);++ false++ } else {++ self.pin_tool(id)++ }++ }+ }++ impl eframe::App for PdfCraftApp {+ /// While files are dragged over the window the system sends no pointer moves, so egui+ /// would keep the place the pointer entered at: tell it where the pointer really is, so the+ /// page grid can show (and use) the gap under it.+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {+ // The button's release a window move or resize kept from egui.+ window_controls::release_after_desktop_grab(ctx, raw);+ self.prepare_raw_input(ctx, raw);+ if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() {+ return;+ }+ if let Some(pos) = drag_pointer::in_window(ctx) {+ raw.events.push(egui::Event::PointerMoved(pos));+ }+ ctx.request_repaint();+ }++ fn save(&mut self, storage: &mut dyn eframe::Storage) {+ // eframe has just stored the window as it is now: not while it is minimized.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let minimized = self.ctx.as_ref().is_some_and(|c| c.input(|i| i.viewport().minimized == Some(true)));+ self.window_state.keep(storage, minimized);+ }+ storage.set_string("pdfcraft", self.persist());+ }++ /// Each frame's work before drawing: opens, operating-system and control-channel requests,+ /// the quit guard, shortcuts, and the background jobs' results.+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {+ self.ctx = Some(ctx.clone());+ #[cfg(not(target_arch = "wasm32"))]+ self.window_state.repair(ctx);+ self.dialog_epoch();+ // Notices raised outside `ui` (opened files, OS events, the control channel) translate too.+ let lang = i18n::Lang::from_pref(&self.language);+ i18n::set_current(lang);+ #[cfg(not(target_arch = "wasm32"))]+ {+ if let Some(worker) = &self.open_worker {+ worker.set_context(ctx);+ }+ self.poll_pending_opens();+ }+ // Chinese wants its own faces before the Japanese ones (one baseline per line).+ let cjk = theme::CjkPreference::for_language(lang.code());+ if !self.styled {+ egui_extras::install_image_loaders(ctx);+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ theme::apply(ctx, self.theme);+ self.styled = true;+ } else {+ self.fonts_ready = true;+ if cjk != self.fonts_cjk {+ // Same family names as before, so named fonts stay valid while the new set loads.+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ }+ }+ self.sync_theme(ctx);+ let native = ctx.native_pixels_per_point().unwrap_or(1.0);+ ui_scale::sync(ctx, ui_scale::zoom(self.ui_scale, self.system_text_scale, native), &mut self.ui_scale_applied);+ // Remember user work even if its tab is subsequently closed or Home is selected.+ self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some();+ // Also done in `raw_input_hook`, before input; here for hosts that don't call the hook.+ self.scroll_speed.set_line_speed(ctx);+ // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase:+ // `logic` also runs alone while hidden, where the input events and time are stale.+ // Before taking this frame's drop: the grid must be drawn once with the pointer where+ // the files were let go before the gap is read.+ self.finish_grid_drop(ctx);+ // Showing a document hides the Combine files tab.+ if self.active.is_some() {+ self.combine_tab.focused = false;+ }+ #[cfg(target_arch = "wasm32")]+ self.process_signature_images();+ let dropped = ctx.input(|i| i.raw.dropped_files.clone());+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_signature_pad(dropped);+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_grid(dropped, ctx);+ for f in dropped {+ // Files dropped on the Combine files tab join its list instead of opening.+ if self.combine_showing() {+ self.drop_into_combine(f, ctx);+ } else {+ self.open_dropped(f, ctx);+ }+ }+ let arrived: Vec<(String, Vec<u8>)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in arrived {+ if let Err(e) = self.open_bytes(&name, None, bytes) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]);+ }+ }+ // Don't replace a pending prompt or import. A startup file may need its own password+ // prompt, so its bytes stay queued until the current interaction finishes.+ #[cfg(not(target_arch = "wasm32"))]+ let opening = !self.pending_opens.is_empty();+ #[cfg(target_arch = "wasm32")]+ let opening = false;+ if !opening+ && self.password_prompt.is_none()+ && self.image_import.is_none()+ && self.dialog.is_none()+ && self.close_request.is_none()+ && self.pending_link.is_none()+ && self.pending_remote_link.is_none()+ {+ let startup = self.startup_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in startup {+ let activate = !self.startup_superseded;+ if let Err(e) = self.open_bytes_with_focus(&name, None, bytes, activate) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ }+ }+ let failed: Vec<(String, String)> = self.failed_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, e) in failed {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ let os_events = self.os_events.as_mut().map(|poll| poll()).unwrap_or_default();+ for e in os_events {+ match e {+ #[cfg(not(target_arch = "wasm32"))]+ OsEvent::Open(paths) => {+ paths.iter().for_each(|p| {+ self.open_path(p);+ });+ // Files handed to the running app (Finder, or another launch): bring its+ // window to the front, also when minimized or full screen on another Space.+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);+ }+ #[cfg(target_arch = "wasm32")]+ OsEvent::Open(_) => {}+ // Like closing the window: `guard_quit` asks about unsaved changes.+ OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),+ }+ }+ if let Some((_, id)) = self.active_ids() {+ let out = self.session.take_js_output(id);+ self.handle_js(id, out);+ }+ if let Some(mut control) = self.control.take() {+ control.tick(ctx, self);+ self.control = Some(control);+ }+ self.guard_quit(ctx);+ // macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136).+ #[cfg(target_os = "macos")]+ craft_quit::on_close_request(ctx);+ self.autosave_tick(ctx, web_time::Instant::now());+ // Reload documents whose files a build rewrote (#431).+ #[cfg(not(target_arch = "wasm32"))]+ self.watch_files();+ if self.host_dirty.is_some() {+ let dirty = self.first_dirty().is_some();+ if let Some(report) = self.host_dirty.as_mut() {+ report(dirty);+ }+ }+ self.poll_updates();+ self.poll_print();+ // Shortcuts deferred last frame: the text field has taken that frame's typing since.+ let deferred = std::mem::take(&mut self.deferred_commands);+ self.native_menu_clicks(ctx);+ // The keys a menu click stands for (⌘C, Delete…), before anything reads this frame's keys.+ if !self.menu_input.is_empty() {+ let events = std::mem::take(&mut self.menu_input);+ ctx.input_mut(|i| i.events.extend(events));+ }+ self.shortcuts(ctx);+ // Scrolling and group-drag previews are transient: never resume after changing tabs,+ // opening a modal/palette, or returning to a window that lost focus.+ let blocked = self.modal_open() || self.palette_open || !ctx.input(|i| i.focused);+ for (index, view) in self.views.iter_mut().enumerate() {+ view.objects.set_input_blocked(blocked || self.active != Some(index));+ if blocked || self.active != Some(index) {+ view.auto_scroll.cancel();+ }+ }+ // A field that refused its value this frame keeps the shortcut from saving or printing+ // behind the user's back; so does a save prompt opened since.+ if self.process_pending_edits() && self.close_request.is_none() {+ for (id, doc) in deferred {+ // Only in the document the shortcut was pressed in.+ if self.active_ids().map(|(_, active)| active) == doc {+ self.execute(id);+ }+ }+ }+ self.poll_export();+ self.auto_ocr_scanned_page();+ self.poll_ocr();+ self.poll_optimize();+ self.poll_action();+ self.process_file_requests();+ #[cfg(not(target_arch = "wasm32"))]+ self.process_picked();+ // Last, after everything that can open or answer the "save changes?" question.+ self.attend_save_prompt(ctx);+ self.sync_native_menu(ctx);+ }++ fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {+ let ctx = ui.ctx().clone();+ i18n::set_current(i18n::Lang::from_pref(&self.language));+ // A language change switches stock chrome between LTR and RTL before anything is drawn.+ theme::sync_direction(&ctx);+ // Fonts registered via set_fonts only take effect next frame; named families would panic now.+ if !self.fonts_ready {+ ctx.request_repaint();+ return;+ }+ // Before any widget reads this frame's wheel input or draws.+ self.motion.begin_pass(&ctx, self.animation_effects);+ // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state.+ migrate_panel_state(ui);+ for view in &mut self.views {+ view.begin_render_frame();+ }+ // The window shows the active document's name (or title, if it asks for that).+ let title = self+ .active+ .and_then(|i| crate::canvas::tab_label(self, i))+ .or_else(|| self.combine_showing().then(|| tl!("Combine files").to_owned()))+ .map_or_else(|| "PdfCraft".to_owned(), |name| format!("{name} — PdfCraft"));+ if title != self.window_title {+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));+ self.window_title = title;+ }+ // The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on+ // Windows) can tell it apart (#4614). egui builds the root node afresh every pass.+ ctx.accesskit_node_builder(egui::accesskit_root_id(), |root| root.set_label(self.window_title.as_str()));+ if self.full_screen && self.active.is_some() {+ // Full screen: the page on black, nothing else, as Acrobat's Full Screen Mode (Esc+ // or ⌘L to leave).+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK)).show(ui, |ui| {+ if let Some(i) = self.active {+ match compare_ui::side_by_side(self, i) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, i, ui),+ }+ }+ });+ dialogs::show(self, &ctx);+ // Notices too: a refused field value or a failed save must be seen in full screen.+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ return;+ }+ self.sync_window_frame(&ctx);+ if self.draws_window_frame() {+ window_controls::resize_edges(&ctx);+ }+ chrome::tab_strip(self, ui);+ chrome::mode_bar(self, ui);+ // Whichever way another tab came to the front, it shows instead of the expanded view.+ if self.all_tools_full && self.all_tools_tab != self.shown_tab() {+ self.all_tools_full = false;+ }+ side_panels::show(self, ui);+ let t = theme::Tokens::get(&ctx);+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| {+ if self.mode == Mode::AllTools && self.all_tools_full {+ all_tools_ui::show(self, ui);+ } else {+ match self.active {+ None if self.combine_showing() => combine_ui::page(self, ui),+ None => home::show(self, ui),+ Some(index) => match compare_ui::side_by_side(self, index) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, index, ui),+ },+ }+ }+ });+ self.process_pending_edits();+ palette::show(self, &ctx);+ dialogs::show(self, &ctx);+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ // Screenshots are issued only after a settled pass that really drew the window.+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ }+ }diff --cc crates/ui-egui/src/app/clipboard.rsindex 000000000,6641d93a8..da9cc1715mode 000000,100644..100644--- a/crates/ui-egui/src/app/clipboard.rs+++ b/crates/ui-egui/src/app/clipboard.rs@@@ -1,0 -1,81 +1,143 @@@+ use super::*;++ /// Why nothing can be copied out of the document: its security doesn't allow it (Table 22,+ /// bit 5; #568).+ pub(crate) fn copy_refused() -> &'static str {+ tl!("The document's security settings don't allow copying text and images")+ }++ pub(crate) fn print_refused() -> &'static str {+ tl!("The document's security settings don't allow printing")+ }++ impl PdfCraftApp {+ /// Whether text and images may be copied out of document `id`; says why not when they may+ /// not. Reading aloud and accessibility tools don't ask (assistive technology may read+ /// anything, §7.6.4.2).+ pub(crate) fn may_copy(&mut self, id: DocId) -> bool {+ if self.session.get(id).is_none_or(pdfcraft_engine::Document::allows_copying) {+ return true;+ }+ self.notify(copy_refused().to_string());+ false+ }++ /// ⌘C copies the selected text, unless a text field has the keyboard (it copies its own).+ pub(super) fn copy_key(&mut self, i: usize, ctx: &egui::Context) {+ // ⌘C arrives as a Copy event on most platforms.+ let copy = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Copy)));+ if !copy || ctx.egui_wants_keyboard_input() {+ return;+ }+ self.copy_selected_text(i, ctx);+ }+++ /// ⌘C / ⌘X / ⌘V copy, cut and paste text or images on canvas (unless a text field has focus).++ pub(super) fn clipboard_keys(&mut self, i: usize, ctx: &egui::Context, pasted: bool) {++ use egui::{Key, KeyboardShortcut, Modifiers};++ let free = self.dialog.is_none() && !self.palette_open && !ctx.egui_wants_keyboard_input() && !self.is_preparing();++ if !free || self.views.get(i).is_some_and(|v| v.forms.focus.is_some() || v.organize) {++ return;++ }++ let copy = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Copy)))++ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::C)));++ let cut = ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Cut)))++ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::X)));++ let paste_event_text = ctx.input(|input| {++ input.events.iter().find_map(|e| match e {++ egui::Event::Paste(text) if !text.is_empty() => Some(text.clone()),++ _ => None,++ })++ });++ let paste = pasted++ || ctx.input(|input| input.events.iter().any(|e| matches!(e, egui::Event::Paste(_))))++ || ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::V)));++++ if copy++ && !self.copy_selected_text(i, ctx)++ && let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone())++ && let Some(id) = self.views.get(i).map(|v| v.id)++ && self.may_copy(id)++ {++ self.copy_page_image(sel.page, sel.index);++ }++ if cut++ && let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone())++ && let Some(id) = self.views.get(i).map(|v| v.id)++ && self.may_copy(id)++ {++ if let Some(v) = self.views.get_mut(i) {++ v.image_selection = None;++ }++ self.cut_page_image(sel.page, sel.index);++ }++ if paste {++ let has_override_image = matches!(self.clipboard_override, Some(crate::create_ui::Clip::Image { .. }));++ #[cfg(not(target_arch = "wasm32"))]++ let system_has_text = if !has_override_image && self.system_clipboard {++ crate::os_clipboard::with(|cb| cb.get_text()).map(|t| !t.is_empty()).unwrap_or(false)++ } else {++ false++ };++ #[cfg(target_arch = "wasm32")]++ let system_has_text = false;++++ if !has_override_image && (paste_event_text.is_some() || system_has_text) {++ self.last_copied_image = None;++ self.last_copied_file = None;++ self.last_copied_image_rect = None;++ return;++ }++++ let page = self.views.get(i).map_or(0, |v| v.current);++ self.paste_image(page, None);++ }++ }+++ /// Shared permission gate for copying selected page text from menus and keyboard events.+ /// After Select All of the document (#2639), pages whose text wasn't read for display are read+ /// off the UI thread ([`DocumentCopy`]), and the clipboard gets the text when they're done.+ pub(crate) fn copy_selected_text(&mut self, i: usize, ctx: &egui::Context) -> bool {+ // A newer copy wins: a whole-document copy still reading must not replace it later.+ self.document_copy = None;+ let Some(v) = self.views.get(i) else { return false };+ let id = v.id;+ if v.all_text && !v.pages_without_text().is_empty() {+ // Checked before any page is read: a document that refuses copying reads nothing.+ if !self.may_copy(id) {+ return false;+ }+ let Some(job) = self.views.get(i).and_then(|v| Some(DocumentCopyJob::of(v, self.session.get(id)?))) else { return false };+ self.document_copy = Some(DocumentCopy::start(id, job, ctx));+ return true;+ }+ let Some(text) = v.selected_text().filter(|text| !text.is_empty()) else { return false };+ if !self.may_copy(id) {+ return false;+ }+ ctx.copy_text(text);+ true+ }++ /// The clipboard text of a whole-document copy, once its pages are read; dropped with the+ /// document it was copied from, and by any later copy (a text field's, a comment's), which+ /// it must not replace. Run at the end of the frame, so it sees this frame's copies.+ pub(crate) fn finish_document_copy(&mut self, ctx: &egui::Context) {+ let Some(c) = &self.document_copy else { return };+ let copied = ctx.output(|o| o.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_) | egui::OutputCommand::CopyImage(_))));+ if copied || !self.views.iter().any(|v| v.id == c.doc) {+ self.document_copy = None;+ return;+ }+ match c.rx.try_recv() {+ Ok(text) => {+ self.document_copy = None;+ if !text.is_empty() {+ ctx.copy_text(text);+ }+ }+ Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(50)),+ Err(std::sync::mpsc::TryRecvError::Disconnected) => self.document_copy = None,+ }+ }+ }diff --cc crates/ui-egui/src/app/keys.rsindex 000000000,cdc696f95..994f71031mode 000000,100644..100644--- a/crates/ui-egui/src/app/keys.rs+++ b/crates/ui-egui/src/app/keys.rs@@@ -1,0 -1,116 +1,115 @@@+ use super::*;++ impl PdfCraftApp {+ pub(super) fn shortcuts(&mut self, ctx: &egui::Context) {+ use egui::Key;+ let pasted = self.paste_key_released(ctx);+ // "Save changes?" is modal: its keys are its own (⌘D is Don't save there, not Document+ // properties; Escape cancels it rather than clearing a selection), and nothing may run+ // underneath it. They are read here, before the canvas can consume them.+ if self.close_request.is_some() {+ // These dialogs are drawn after the save prompt and own the keyboard while open.+ // Don't let Escape or Return resolve unsaved work underneath one.+ let covered = self.pending_link.is_some()+ || self.pending_remote_link.is_some()+ || self.pending_full_screen.is_some()+ || self.updates.open+ || self.dialog.is_some()+ || self.unlock_prompt.is_some();+ if !covered && let Some(choice) = dialogs::save_prompt_key(ctx, &mut self.save_prompt_button) {+ self.resolve_close(ctx, choice);+ }+ return;+ }+ // The other dialogs and prompts are modal too (⌘W closed the file behind Preferences,+ // #870).+ if self.modal_open() {+ return;+ }+ if let Some(view) = self.active.and_then(|i| self.views.get_mut(i))+ && view.auto_scroll.escape(ctx)+ {+ return;+ }+ // The in-window menu bar holds the keys while one of its menus is open or it has the+ // keyboard (Alt, F10); a command shortcut leaves it and runs.+ craft_menu::bar::leave_for_shortcut(ctx);+ if !craft_menu::bar::is_open(ctx) && !craft_menu::bar::is_focused(ctx) {+ self.registry_shortcuts(ctx);+ }+ // (Esc closes a Combine file shown large first.)+ if self.full_screen && self.combine_tab.preview.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) {+ self.set_full_screen(ctx, false);+ }+ if let Some(i) = self.active {+ // Select all belongs to the document or page grid, unless a text field or+ // overlay owns the keyboard. Other canvas shortcuts keep their own handling.+ if self.dialog.is_none()+ && !self.palette_open+ && !ctx.egui_wants_keyboard_input()+ && ctx.input_mut(|input| input.consume_shortcut(&egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, Key::A)))+ {+ if self.is_preparing() {+ if let Some(doc) = self.session.get(self.views[i].id) {+ prepare::select_all(&mut self.views[i], &doc.form);+ }+ } else {+ self.views[i].select_all();+ }+ }+ self.tool_keys(i, ctx);+ if self.quick_tool == QuickTool::EditText+ && let Some(doc) = self.session.get(self.views[i].id).filter(|d| d.allows_modification())+ {+ object_ui::nudge_keys(ctx, &mut self.views[i], doc);+ object_ui::delete_keys(ctx, &mut self.views[i]);+ } else if let Some(doc) = self.session.get(self.views[i].id).filter(|d| d.allows_annotation()) {+ comments::nudge_keys(ctx, &mut self.views[i], &doc.info);+ }+ // A selected field moves with the arrows too (Prepare a form, #2608), before the view+ // turns the page with them.+ if self.is_preparing()+ && let Some(doc) = self.session.get(self.views[i].id).filter(|d| d.allows_modification())+ {+ prepare::nudge_keys(ctx, &mut self.views[i], doc);+ }+ canvas::shortcuts(&mut self.views[i], ctx, self.scroll_speed);- self.copy_key(i, ctx);- self.paste_image_key(i, ctx, pasted);++ self.clipboard_keys(i, ctx, pasted);+ self.image_pick_keys(i, ctx);+ }+ }+ }++ impl PdfCraftApp {+ /// The quick tools' keys, as in Acrobat: V selects, H pans, and holding Space pans until it+ /// is released. Plain letters, so not while a text field, a form field, a dialog or the+ /// palette has the keyboard.+ fn tool_keys(&mut self, i: usize, ctx: &egui::Context) {+ use egui::Key;+ let free = self.dialog.is_none() && !self.palette_open && !ctx.egui_wants_keyboard_input() && self.views[i].forms.focus.is_none();+ let (plain, space) = ctx.input(|input| (input.modifiers.is_none(), input.key_down(Key::Space)));+ if let Some(previous) = self.space_hand+ && !space+ {+ self.space_hand = None;+ if self.quick_tool == QuickTool::Hand {+ self.quick_tool = previous;+ }+ }+ if !free || !plain {+ return;+ }+ if ctx.input(|input| input.key_pressed(Key::V)) {+ self.quick_tool = QuickTool::Select;+ self.space_hand = None;+ }+ if ctx.input(|input| input.key_pressed(Key::H)) {+ self.quick_tool = QuickTool::Hand;+ self.space_hand = None;+ }+ if space && self.space_hand.is_none() && self.quick_tool != QuickTool::Hand {+ self.space_hand = Some(self.quick_tool);+ self.quick_tool = QuickTool::Hand;+ }+ }+ }diff --cc crates/ui-egui/src/app/prefs.rsindex 000000000,ac8ac644e..eb9499989mode 000000,100644..100644--- a/crates/ui-egui/src/app/prefs.rs+++ b/crates/ui-egui/src/app/prefs.rs@@@ -1,0 -1,337 +1,350 @@@+ use super::*;++ /// [`PdfCraftApp::date_text`] for callers that already borrow other parts of the app.+ pub(crate) fn date_text(session: &Session, fmt: Option<&str>) -> Result<String, String> {+ let lang = session.date_language().unwrap_or(i18n::current().code());+ session.today_text(fmt, Some(lang))+ }++ /// Today in Preferences ▸ Date format for stamping into a PDF; refused when it has characters+ /// Fill & Sign can't write yet (see [`pdfcraft_engine::dates::unwritable`]).+ pub(crate) fn date_text_for_pdf(session: &Session) -> Result<String, String> {+ let lang = session.date_language().unwrap_or(i18n::current().code());+ session.today_text_for_pdf(None, Some(lang))+ }++ /// The longest author name kept (Preferences ▸ Identity, restored settings).+ pub(crate) const MAX_AUTHOR_CHARS: usize = 200;++ /// A restored colour: an `[r, g, b]` array of finite numbers, each clamped to 0–1 (restored+ /// settings are untrusted). Anything else (a string, a wrong length, a null or a non-finite+ /// number) is refused whole, so the caller keeps its default.+ fn rgb_triple(v: &serde_json::Value) -> Option<[f64; 3]> {+ let a = v.as_array()?;+ if a.len() != 3 {+ return None;+ }+ let mut out = [0.0f64; 3];+ for (slot, x) in out.iter_mut().zip(a.iter()) {+ let n = x.as_f64()?;+ if !n.is_finite() {+ return None;+ }+ *slot = n.clamp(0.0, 1.0);+ }+ Some(out)+ }++ impl PdfCraftApp {+ pub fn set_theme_preference(&mut self, preference: ThemePreference) {+ self.theme_preference = preference;+ if let Some(ctx) = self.ctx.clone() {+ self.sync_theme(&ctx);+ theme::apply(&ctx, self.theme);+ } else {+ self.theme = preference.resolve(None, ThemeKind::Light);+ }+ }++ /// The app-wide reading-colours preference: sets it and applies it to every open document,+ /// not just the active one (Preferences ▸ Reading colours, Acrobat's Replace Document+ /// Colors). A document the change actually touches re-renders.+ pub fn set_reading_colors(&mut self, colors: pdfcraft_render::ReadingColors) {+ self.reading_colors = colors;+ for i in 0..self.views.len() {+ // Idempotent per document: the engine says whether anything changed.+ if self.session.set_reading_colors(self.views[i].id, colors) {+ self.views[i].invalidate_content();+ }+ }+ }++ /// Enable the Linux desktop portal in a native window. Headless contexts keep+ /// their supplied input and never connect to the user's session bus.+ #[cfg(target_os = "linux")]+ pub fn enable_desktop_theme(&mut self) {+ self.desktop_theme_enabled = true;+ }++ /// Today in `fmt` (or Preferences ▸ Date format), with month and weekday names in the date+ /// language, or the interface language when it follows that.+ pub fn date_text(&self, fmt: Option<&str>) -> Result<String, String> {+ date_text(&self.session, fmt)+ }++ /// Serialize the user's persistent state (recent files, theme). Local only.+ pub fn persist(&self) -> String {+ let trusted: Vec<String> = self.session.trusted_certificates().iter().map(pdfcraft_engine::sign::x509::to_pem).collect();+ let mut v = serde_json::json!({+ "side_panels": self.side_panels.to_json(self.left_open),+ "docking_right": self.right,+ "recent": self.recent,+ "reopen_last_session": self.reopen_last_session,+ "restore_last_view": self.restore_last_view,+ "last_views": self.last_views_to_save(),+ // Kept only while the preference is on.+ "last_session": self.reopen_last_session.then(|| self.session_to_save()),+ "reload_changed_files": self.reload_changed_files,+ "system_title_bar": self.system_title_bar,+ "pinned_folders": self.pinned.folders,+ "theme": self.theme_preference,+ "scroll_speed": self.scroll_speed,+ "animation_effects": self.animation_effects,+ "default_mode": self.default_mode,+ "default_layout": canvas::display_token(self.view_defaults.layout, self.view_defaults.continuous),+ "default_zoom": self.view_defaults.zoom_name(),+ "always_default_view": self.always_default_view,+ "highlight_fields": self.view_defaults.highlight_fields,+ "units": self.units,+ "language": self.language,+ "reading_colors": self.reading_colors,+ // Null follows the system's text scaling.+ "ui_scale": self.ui_scale,+ "flatten_fill_sign": self.flatten_fill_sign_on_save,+ "fill_text_size": self.fill_text_size,+ "date_format": self.session.date_format(),+ // Null follows the interface language.+ "date_language": self.session.date_language(),+ "author": self.comment_prefs.author,+ // Per-tool comment defaults (colours, opacity, widths), so Make Current+ // Properties Default survives a restart (#340).+ "comment_styles": self+ .comment_prefs+ .styles()+ .map(|(t, s)| serde_json::json!({+ "tool": t.command(),+ "color": s.color,+ "opacity": s.opacity,+ "width": s.width,+ "fill": s.fill,+ }))+ .collect::<Vec<_>>(),+ // Drawn signatures keep their original form (older settings read the same).+ "signature": match &self.signature { Some(fill_sign::SavedSig::Drawn(s)) => Some(s), _ => None },+ "signature_text": match &self.signature { Some(fill_sign::SavedSig::Typed(t)) => Some(t), _ => None },+ "signature_image": match &self.signature { Some(s @ fill_sign::SavedSig::Image(_)) => Some(s), _ => None },+ "initials": self.initials,+ "sign_graphic": self.sign_graphic,+ // macOS Keychain and Windows store identities are read from their OS key stores each time.+ "digital_ids": self.digital_ids.iter().filter(|e| !e.path.starts_with("keychain:") && !e.path.starts_with("windows:")).collect::<Vec<_>>(),+ "trusted": trusted,+ "custom_stamps": stamps_ui::encode(&self.custom_stamps),+ "javascript": self.session.javascript(),+ "actions": actions_ui::encode(&self.custom_actions),+ "combine_columns": self.combine_columns.to_json(),+ "combine_view": self.combine_view.as_str(),+ "combine_zoom": self.combine_zoom,+ "comments_panel_closed": self.comments_panel_closed,+ "right_panel_closed": self.right_panel_closed,+ });+ // Set apart: one more key inside the macro above passes serde_json's recursion limit.+ v["default_page_gaps"] = serde_json::Value::Bool(self.view_defaults.show_page_gaps);+ v["redact_prefs"] = self.redact_defaults.to_json();++ v["pinned_tools"] = serde_json::json!(self.pinned_tools);+ // Set outside json! above, which is at serde_json's macro recursion limit.+ v["hide_empty_highlight_hover"] = serde_json::Value::Bool(self.comment_prefs.hide_empty_highlight_hover);+ v["comment_tool_pinned"] = serde_json::Value::Bool(self.comment_prefs.pinned);+ v["show_secured_notice"] = serde_json::Value::Bool(self.show_secured_notice);+ v["organize_zoom"] = serde_json::json!(self.organize_zoom);+ // Canonical names survive changes to the order of PAPERS and do not depend on UI language.+ v["print_paper"] = serde_json::json!(pdfcraft_engine::print::PAPERS.get(self.print_draft.paper).map(|(name, _)| *name));+ v.to_string()+ }++ /// Restore state written by `persist`. Unknown or malformed data is ignored.+ pub fn restore(&mut self, json: &str) {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return };+ let panels = side_panels::restore(&v);+ self.side_panels = panels.panels;+ if let Some(open) = panels.tools_open {+ self.left_open = open;+ }+ if let Some(right) = v.get("docking_right") {+ self.right = serde_json::from_value(right.clone()).ok().flatten().filter(|_| !panels.side_closed);+ }+ self.combine_columns = combine_ui::Columns::from_json(&v["combine_columns"]);+ if let Some(view) = v["combine_view"].as_str().and_then(combine_ui::CombineView::parse) {+ self.combine_view = view;+ }+ if let Some(zoom) = v["combine_zoom"].as_f64() {+ self.set_combine_zoom(zoom as f32);+ }+ // Clamped like any grid zoom when the grid next shows; nonsense keeps the usual size.+ if let Some(zoom) = v["organize_zoom"].as_f64().map(|z| z as f32).filter(|z| z.is_finite()) {+ self.organize_zoom = zoom.clamp(*canvas::GRID_ZOOM_RANGE.start(), *canvas::GRID_ZOOM_RANGE.end());+ }+ if let Ok(r) = serde_json::from_value::<Vec<RecentFile>>(v["recent"].clone()) {+ // Only keep entries whose files still exist.+ #[cfg(not(target_arch = "wasm32"))]+ let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();+ self.recent = r;+ }+ if let Some(on) = v["reopen_last_session"].as_bool() {+ self.reopen_last_session = on;+ }+ if let Some(on) = v["restore_last_view"].as_bool() {+ self.restore_last_view = on;+ }+ self.restore_last_views(&v["last_views"]);+ self.last_session = last_session::LastSession::from_json(&v["last_session"]);+ if let Some(on) = v["system_title_bar"].as_bool() {+ self.system_title_bar = on;+ }+ if let Some(on) = v["reload_changed_files"].as_bool() {+ self.reload_changed_files = on;+ }+ if let Some(on) = v["show_secured_notice"].as_bool() {+ self.show_secured_notice = on;+ }+ self.pinned.restore(&v["pinned_folders"]);++ if let Some(items) = v.get("pinned_tools").and_then(serde_json::Value::as_array) {++ let mut tools = Vec::new();++ for item in items {++ if let Some(id) = item.as_str()++ && pdfcraft_engine::catalog::group(id).is_some()++ && !tools.iter().any(|t| t == id)++ {++ tools.push(id.to_string());++ }++ }++ self.pinned_tools = tools;++ }+ if let Ok(preference) = serde_json::from_value::<ThemePreference>(v["theme"].clone()) {+ self.set_theme_preference(preference);+ }+ if let Ok(speed) = serde_json::from_value::<scroll_speed::ScrollSpeed>(v["scroll_speed"].clone()) {+ self.scroll_speed = speed;+ }+ if let Ok(effects) = serde_json::from_value::<motion::AnimationEffects>(v["animation_effects"].clone()) {+ self.animation_effects = effects;+ }+ if let Ok(mode) = serde_json::from_value::<Mode>(v["default_mode"].clone()) {+ self.default_mode = mode;+ }+ if let Some((layout, continuous)) = v["default_layout"].as_str().and_then(canvas::parse_display_token) {+ (self.view_defaults.layout, self.view_defaults.continuous) = (layout, continuous);+ }+ if let Some(show) = v["default_page_gaps"].as_bool() {+ self.view_defaults.show_page_gaps = show;+ }+ if let Ok(units) = serde_json::from_value::<units::Unit>(v["units"].clone()) {+ self.units = units;+ }+ if let Some(on) = v["always_default_view"].as_bool() {+ self.always_default_view = on;+ }+ if let Some(paper) = v+ .get("print_paper")+ .and_then(serde_json::Value::as_str)+ .and_then(|name| pdfcraft_engine::print::PAPERS.iter().position(|(canonical, _)| *canonical == name))+ {+ self.print_draft.paper = paper;+ }+ if let Some(on) = v["highlight_fields"].as_bool() {+ self.view_defaults.highlight_fields = on;+ }+ if let Some(closed) = v["comments_panel_closed"].as_bool() {+ self.comments_panel_closed = closed;+ }+ if let Some(closed) = v["right_panel_closed"].as_bool() {+ self.right_panel_closed = closed;+ }+ if let Some(defaults) = v["default_zoom"].as_str().and_then(|zoom| self.view_defaults.with_zoom(zoom)) {+ self.view_defaults = defaults;+ }+ if let Some(language) = v["language"].as_str().and_then(i18n::normalize_pref) {+ self.language = language.to_string();+ }+ if let Some(on) = v["flatten_fill_sign"].as_bool() {+ self.flatten_fill_sign_on_save = on;+ }+ if let Some(size) = v["fill_text_size"].as_f64().and_then(fill_sign::valid_text_size) {+ self.fill_text_size = size;+ }+ if let Some(prefs) = RedactPrefs::from_json(&v["redact_prefs"]) {+ self.redact_prefs = prefs.clone();+ self.redact_defaults = prefs;+ }+ // Settings are untrusted: an unreadable value (a colour that isn't three bytes, say)+ // fails to deserialize and keeps Off.+ if let Ok(colors) = serde_json::from_value::<pdfcraft_render::ReadingColors>(v["reading_colors"].clone()) {+ self.reading_colors = colors;+ }+ // Settings are untrusted: a size out of range follows the system instead.+ self.ui_scale = v["ui_scale"].as_f64().and_then(ui_scale::valid);+ // Settings are untrusted: an unusable pattern keeps the default.+ if let Some(f) = v["date_format"].as_str() {+ let _ = self.session.set_date_format(f);+ }+ if let Some(l) = v["date_language"].as_str() {+ let _ = self.session.set_date_language(Some(l));+ }+ // An empty or missing name keeps the login-name default; settings are untrusted, so the+ // name is cut to a sane length.+ if let Some(author) = v["author"].as_str().map(str::trim).filter(|a| !a.is_empty()) {+ self.comment_prefs.author = author.chars().take(MAX_AUTHOR_CHARS).collect();+ }+ if let Some(hide) = v["hide_empty_highlight_hover"].as_bool() {+ self.comment_prefs.hide_empty_highlight_hover = hide;+ }+ if let Some(pinned) = v["comment_tool_pinned"].as_bool() {+ self.comment_prefs.pinned = pinned;+ }+ // Per-tool comment styles (#340): each field goes through its clamping setter, so a+ // malformed or hostile entry is clamped or ignored rather than trusted.+ if let Some(styles) = v["comment_styles"].as_array() {+ for e in styles {+ let Some(tool) = e["tool"].as_str().and_then(crate::comments::CommentTool::from_command) else { continue };+ if let Some(c) = rgb_triple(&e["color"]) {+ self.comment_prefs.set_color(tool, c);+ }+ if let Some(o) = e["opacity"].as_f64() {+ self.comment_prefs.set_opacity(tool, o);+ }+ if let Some(w) = e["width"].as_f64() {+ self.comment_prefs.set_width(tool, w);+ }+ // `"fill": null` is a saved "no fill", which clears a tool's default fill; a+ // missing or malformed fill keeps it.+ let fill = match e.get("fill") {+ Some(serde_json::Value::Null) => Some(None),+ Some(v) => rgb_triple(v).map(Some),+ None => None,+ };+ if let Some(fill) = fill {+ let mut s = self.comment_prefs.style(tool);+ s.fill = fill;+ self.comment_prefs.set_style(tool, s);+ }+ }+ }+ if let Ok(s) = serde_json::from_value::<Vec<Vec<[f32; 2]>>>(v["signature"].clone())+ && s.iter().all(|st| st.iter().all(|p| p.iter().all(|x| x.is_finite())))+ {+ self.signature = Some(fill_sign::SavedSig::Drawn(s));+ }+ if let Some(t) = v["signature_text"].as_str().filter(|t| !t.trim().is_empty()) {+ self.signature = Some(fill_sign::SavedSig::Typed(t.to_string()));+ }+ if let Ok(s @ fill_sign::SavedSig::Image(_)) = serde_json::from_value::<fill_sign::SavedSig>(v["signature_image"].clone()) {+ self.signature = Some(s);+ }+ if let Ok(i) = serde_json::from_value::<fill_sign::SavedSig>(v["initials"].clone()) {+ self.initials = Some(i);+ }+ // An unreadable choice (a damaged image) falls back to the name.+ self.sign_graphic = serde_json::from_value(v["sign_graphic"].clone()).unwrap_or_default();+ if let Ok(ids) = serde_json::from_value::<Vec<DigitalIdEntry>>(v["digital_ids"].clone()) {+ self.digital_ids = ids;+ }+ self.custom_stamps = stamps_ui::decode(&v["custom_stamps"]);+ self.custom_actions = actions_ui::decode(&v["actions"]);+ if let Some(on) = v["javascript"].as_bool() {+ self.session.set_javascript(on);+ }+ if let Ok(pems) = serde_json::from_value::<Vec<String>>(v["trusted"].clone()) {+ let certs = pems.iter().filter_map(|p| pdfcraft_engine::sign::x509::load_certificates(p.as_bytes()).ok()).flatten().collect();+ self.apply_trusted_certificates(certs);+ }+ }+ }diff --cc crates/ui-egui/src/canvas.rsindex 8c881ae33,edcd64569..a08556bb0--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1,8851 -1,2664 +1,3419 @@@--//! The document area: page layout, zoom, render scheduling, overlays (links, annotation hovers,--//! form-field highlights), and the organize-pages grid.--//!--//! Page images come from the engine's render pool as whole-page rasters at the current zoom;--//! stale rasters are shown stretched until the sharp one arrives (tiling comes in M3.3).----use std::collections::{BTreeSet, HashMap, HashSet};--use std::ops::Range;--use std::sync::Arc;----use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2};--use pdfcraft_engine::{DocId, Edit};--use pdfcraft_render::{DestView, DocInfo, LayerOp, LinkTarget, PRINT_TAG, PageText, RenderPool, RenderRequest, RequestKind, Tile, device_pixels};----use crate::page_pointer::PagePointer;--use crate::theme::{self, Tokens};--use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};--mod area;-pub(super) mod autoscroll;-mod bars;-mod cache;-pub(super) mod crop;-mod find;-pub(super) mod fling;-pub(super) mod image_pick;-mod navigation;-mod organize;-pub(super) mod page_pointer;-pub mod scroll_speed;-mod selection;-pub(super) mod signature_drag;-pub(super) mod wheel_boost;-pub(super) mod wheel_pager;-mod xform;-mod zoom;-pub(super) mod zoom_snap;--pub(crate) use area::signature_badges;-use area::{- SUPPRESS_SECS, SUPPRESS_TAIL_SECS, annotation_hover_text, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button,- set_layers, zoom_anchor,-};-#[cfg(test)]-use bars::in_size_hint_zone;-use bars::{Notice, notices, page_size_hint, quick_bar};-pub use cache::RasterMemory;-pub(crate) use cache::{BASE_SIDE, TILE_THRESHOLD, texture_image, thumbnail_rows};-#[cfg(test)]-use cache::{- GRAYSCALE_TAG, GRID_TAG, MAX_CACHED_TEXT_PAGES, MAX_THUMB_DEMAND, PAGE_BYTES, THUMB_BYTES, THUMB_H, THUMB_TAG, THUMB_W, TILE, grayscale,- rgba_bytes,-};-use cache::{OLD_TILES, PageTex, STALE_TAG, TEXT_TAG, TILE_BYTES, scale_tag, tag_scale, texture_bytes, tile_side};-pub use find::Find;-use find::find_bar;-pub use navigation::shortcuts;-pub(crate) use organize::drop_gap;-#[cfg(test)]-pub(crate) use organize::grid_page_rect;-use organize::organize_grid;-#[cfg(test)]-use organize::sharp_enough;-use selection::{Selection, Span, click_unit, selection_actions};-pub use xform::PageXform;-use xform::snap_to_pixels;-use zoom::anchored_scroll;-pub use zoom::{GRID_ZOOM_RANGE, THUMBNAIL_ZOOM_RANGE};----/// Logical pixels per PDF point at 100% (96 dpi, like browsers).--pub const PT: f32 = 96.0 / 72.0;--const GAP: f32 = 14.0;--const MARGIN: f32 = 28.0;--/// Horizontal gutter that keeps pages clear of the floating quick-action bar.--const SIDE: f32 = 70.0;- const THUMB_TAG: u64 = 1 << 63;- const TEXT_TAG: u64 = 1 << 62;- /// A page rendered for the organize grid at the size it is drawn there.- 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.- const GRAYSCALE_TAG: u64 = 1 << 59;- /// The tag of a raster that is out of date (shown until its replacement arrives).- const STALE_TAG: u64 = u64::MAX;- /// 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.- 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.- const THUMB_W: f32 = 240.0;- const THUMB_H: f32 = 320.0;- const THUMB_BYTES: usize = 24 * 1024 * 1024;- const PAGE_BYTES: usize = 128 * 1024 * 1024;- 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.- 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.- const MAX_CACHED_TEXT_PAGES: usize = 24;-- fn rgba_bytes(width: usize, height: usize) -> usize {- width.saturating_mul(height).saturating_mul(4)- }-- fn texture_bytes(tex: &TextureHandle) -> usize {- let [w, h] = tex.size();- rgba_bytes(w, h)- }-- use crate::edit_text_ui::ImageHandle;-- /// Extension trait on `egui::Painter` to draw polygons.- pub trait PainterExt {- fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx;- }-- impl PainterExt for egui::Painter {- fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx {- self.add(egui::Shape::convex_polygon(points, fill, stroke))- }- }-- /// User-space selectable bounding box for an image object.- /// If the image object has an active clipping path applied to it (the crop box),- /// this is the mathematical intersection of the full CTM-derived rect and the clipping path's rect.- pub fn image_selectable_bounds(im: &pdfcraft_engine::PageImage) -> [f64; 4] {- if let Some(clip) = im.clip_rect {- let r = [im.rect[0].max(clip[0]), im.rect[1].max(clip[1]), im.rect[2].min(clip[2]), im.rect[3].min(clip[3])];- if r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1] {- return r;- }- }- im.visible_rect.unwrap_or(im.rect)- }-- /// Screen-space selectable bounding box for an image object.- /// If the image object has an active clipping path applied to it (the crop box),- /// the final selectable `egui::Rect` is the mathematical intersection of the image's- /// full CTM-derived rect and the clipping path's rect.- pub fn image_screen_rect(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Rect {- let full = xf.user_rect_f64(info, page, im.rect);- if let Some(clip) = im.clip_rect {- let clip_r = xf.user_rect_f64(info, page, clip);- let inter = full.intersect(clip_r);- if inter.is_positive() {- return inter;- }- }- if let Some(vr) = im.visible_rect {- let r = xf.user_rect_f64(info, page, vr);- if r.is_positive() {- return r;- }- }- full- }-- /// An Oriented Bounding Box (OBB) representing a rotated rectangle in screen space,- /// with 8 resize handles and rotated local axes.- #[derive(Clone, Copy, Debug, PartialEq)]- pub struct ImageObb {- pub s00: Pos2,- pub s10: Pos2,- pub s11: Pos2,- pub s01: Pos2,- pub s_bc: Pos2,- pub s_rc: Pos2,- pub s_tc: Pos2,- pub s_lc: Pos2,- pub s_rot: Pos2,- pub screen_center: Pos2,- pub width: f32,- pub height: f32,- pub theta: f32,- pub u_axis: (f64, f64),- pub v_axis: (f64, f64),- pub is_rotated: bool,- }-- impl ImageObb {- /// Calculates the 4 rotated corners manually using center, width, height, and rotation angle (θ).- /// Local axes: `u_axis = (cos θ, sin θ)` and `v_axis = (-sin θ, cos θ)`.- /// Places the 8 resize handles exactly at these rotated vertices and midpoints.- pub fn from_center_size_angle(center: Pos2, width: f32, height: f32, theta: f32) -> Self {- let cos_t = theta.cos();- let sin_t = theta.sin();- let u_axis = (cos_t as f64, sin_t as f64);- let v_axis = (-sin_t as f64, cos_t as f64);- let u_vec = vec2(cos_t, sin_t);- let v_vec = vec2(-sin_t, cos_t);- let hw = width * 0.5;- let hh = height * 0.5;-- let s00 = center - u_vec * hw - v_vec * hh;- let s10 = center + u_vec * hw - v_vec * hh;- let s11 = center + u_vec * hw + v_vec * hh;- let s01 = center - u_vec * hw + v_vec * hh;-- let s_bc = center - v_vec * hh;- let s_rc = center + u_vec * hw;- let s_tc = center + v_vec * hh;- let s_lc = center - u_vec * hw;-- let s_rot = s_tc + v_vec * 24.0;- let is_rotated = theta.abs() > 1e-4;-- Self { s00, s10, s11, s01, s_bc, s_rc, s_tc, s_lc, s_rot, screen_center: center, width, height, theta, u_axis, v_axis, is_rotated }- }-- pub fn new(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {- Self::from_matrix(matrix, xf, info, page)- }-- pub fn from_matrix(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {- let m = crate::edit_text_ui::Matrix(matrix);- let p00 = m.apply(0.0, 0.0);- let p10 = m.apply(1.0, 0.0);- let p11 = m.apply(1.0, 1.0);- let p01 = m.apply(0.0, 1.0);-- let s00 = crate::edit_text_ui::user_to_screen(xf, info, page, p00.0, p00.1);- let s10 = crate::edit_text_ui::user_to_screen(xf, info, page, p10.0, p10.1);- let s11 = crate::edit_text_ui::user_to_screen(xf, info, page, p11.0, p11.1);- let s01 = crate::edit_text_ui::user_to_screen(xf, info, page, p01.0, p01.1);-- let s_bc = Pos2::new((s00.x + s10.x) * 0.5, (s00.y + s10.y) * 0.5);- let s_rc = Pos2::new((s10.x + s11.x) * 0.5, (s10.y + s11.y) * 0.5);- let s_tc = Pos2::new((s01.x + s11.x) * 0.5, (s01.y + s11.y) * 0.5);- let s_lc = Pos2::new((s00.x + s01.x) * 0.5, (s00.y + s01.y) * 0.5);-- let screen_center = Pos2::new((s00.x + s10.x + s11.x + s01.x) * 0.25, (s00.y + s10.y + s11.y + s01.y) * 0.25);- let out_dir = s_tc - screen_center;- let out_len = out_dir.length().max(1e-4);- let out_norm = out_dir / out_len;- let s_rot = s_tc + out_norm * 24.0;-- let [a, b, c, d, ..] = matrix;- let w_u = (a * a + b * b).sqrt().max(1e-6);- let h_v = (c * c + d * d).sqrt().max(1e-6);- let u_axis = (a / w_u, b / w_u);- let v_axis = (c / h_v, d / h_v);- let theta = (b).atan2(a) as f32;- let is_rotated = b.abs() > 1e-4 || c.abs() > 1e-4;-- Self {- s00,- s10,- s11,- s01,- s_bc,- s_rc,- s_tc,- s_lc,- s_rot,- screen_center,- width: (s10 - s00).length(),- height: (s01 - s00).length(),- theta,- u_axis,- v_axis,- is_rotated,- }- }-- pub fn from_image(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Self {- let [_, b, c, ..] = im.matrix;- let is_rot = b.abs() > 1e-4 || c.abs() > 1e-4;- let bounds = image_selectable_bounds(im);- let matrix = if !is_rot && bounds[2] > bounds[0] && bounds[3] > bounds[1] {- [bounds[2] - bounds[0], 0.0, 0.0, bounds[3] - bounds[1], bounds[0], bounds[1]]- } else {- im.matrix- };- Self::from_matrix(matrix, xf, info, page)- }-- pub fn handles(&self) -> [(ImageHandle, Pos2); 8] {- [- (ImageHandle::TopLeft, self.s01),- (ImageHandle::TopCenter, self.s_tc),- (ImageHandle::TopRight, self.s11),- (ImageHandle::RightCenter, self.s_rc),- (ImageHandle::BottomRight, self.s10),- (ImageHandle::BottomCenter, self.s_bc),- (ImageHandle::BottomLeft, self.s00),- (ImageHandle::LeftCenter, self.s_lc),- ]- }-- pub fn handle_pos(&self, handle: ImageHandle) -> Pos2 {- match handle {- ImageHandle::TopLeft => self.s01,- ImageHandle::TopCenter => self.s_tc,- ImageHandle::TopRight => self.s11,- ImageHandle::RightCenter => self.s_rc,- ImageHandle::BottomRight => self.s10,- ImageHandle::BottomCenter => self.s_bc,- ImageHandle::BottomLeft => self.s00,- ImageHandle::LeftCenter => self.s_lc,- }- }-- pub fn handle_id(&self, base_id: egui::Id, handle: ImageHandle) -> egui::Id {- base_id.with(match handle {- ImageHandle::TopLeft => "handle_tl",- ImageHandle::TopCenter => "handle_tc",- ImageHandle::TopRight => "handle_tr",- ImageHandle::RightCenter => "handle_rc",- ImageHandle::BottomRight => "handle_br",- ImageHandle::BottomCenter => "handle_bc",- ImageHandle::BottomLeft => "handle_bl",- ImageHandle::LeftCenter => "handle_lc",- })- }-- pub fn handles_with_ids(&self, base_id: egui::Id) -> [(ImageHandle, Pos2, egui::Id); 8] {- [- (ImageHandle::TopLeft, self.s01, self.handle_id(base_id, ImageHandle::TopLeft)),- (ImageHandle::TopCenter, self.s_tc, self.handle_id(base_id, ImageHandle::TopCenter)),- (ImageHandle::TopRight, self.s11, self.handle_id(base_id, ImageHandle::TopRight)),- (ImageHandle::RightCenter, self.s_rc, self.handle_id(base_id, ImageHandle::RightCenter)),- (ImageHandle::BottomRight, self.s10, self.handle_id(base_id, ImageHandle::BottomRight)),- (ImageHandle::BottomCenter, self.s_bc, self.handle_id(base_id, ImageHandle::BottomCenter)),- (ImageHandle::BottomLeft, self.s00, self.handle_id(base_id, ImageHandle::BottomLeft)),- (ImageHandle::LeftCenter, self.s_lc, self.handle_id(base_id, ImageHandle::LeftCenter)),- ]- }-- pub fn corners(&self) -> [Pos2; 4] {- [self.s00, self.s10, self.s11, self.s01]- }-- /// Resizes the OBB proportionally along its local axes using projected mouse delta,- /// locking the diagonally opposite corner as the fixed anchor point.- pub fn scale_proportional(&self, handle: ImageHandle, delta: Vec2, min_size: f32) -> Self {- let u_vec = vec2(self.u_axis.0 as f32, self.u_axis.1 as f32);- let v_vec = vec2(self.v_axis.0 as f32, self.v_axis.1 as f32);- let delta_u = delta.dot(u_vec);- let delta_v = delta.dot(v_vec);- let min_s = min_size.max(5.0);-- match handle {- ImageHandle::TopRight => {- let anchor = self.s00;- let s_u = (self.width + delta_u) / self.width.max(1e-4);- let s_v = (self.height + delta_v) / self.height.max(1e-4);- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));- let nw = self.width * s;- let nh = self.height * s;- let new_center = anchor + u_vec * (nw * 0.5) + v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, nw, nh, self.theta)- }- ImageHandle::TopLeft => {- let anchor = self.s10;- let s_u = (self.width - delta_u) / self.width.max(1e-4);- let s_v = (self.height + delta_v) / self.height.max(1e-4);- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));- let nw = self.width * s;- let nh = self.height * s;- let new_center = anchor - u_vec * (nw * 0.5) + v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, nw, nh, self.theta)- }- ImageHandle::BottomLeft => {- let anchor = self.s11;- let s_u = (self.width - delta_u) / self.width.max(1e-4);- let s_v = (self.height - delta_v) / self.height.max(1e-4);- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));- let nw = self.width * s;- let nh = self.height * s;- let new_center = anchor - u_vec * (nw * 0.5) - v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, nw, nh, self.theta)- }- ImageHandle::BottomRight => {- let anchor = self.s01;- let s_u = (self.width + delta_u) / self.width.max(1e-4);- let s_v = (self.height - delta_v) / self.height.max(1e-4);- let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };- let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));- let nw = self.width * s;- let nh = self.height * s;- let new_center = anchor + u_vec * (nw * 0.5) - v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, nw, nh, self.theta)- }- ImageHandle::RightCenter => {- let anchor = self.s_lc;- let nw = (self.width + delta_u).max(min_s);- let new_center = anchor + u_vec * (nw * 0.5);- Self::from_center_size_angle(new_center, nw, self.height, self.theta)- }- ImageHandle::LeftCenter => {- let anchor = self.s_rc;- let nw = (self.width - delta_u).max(min_s);- let new_center = anchor - u_vec * (nw * 0.5);- Self::from_center_size_angle(new_center, nw, self.height, self.theta)- }- ImageHandle::TopCenter => {- let anchor = self.s_bc;- let nh = (self.height + delta_v).max(min_s);- let new_center = anchor + v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, self.width, nh, self.theta)- }- ImageHandle::BottomCenter => {- let anchor = self.s_tc;- let nh = (self.height - delta_v).max(min_s);- let new_center = anchor - v_vec * (nh * 0.5);- Self::from_center_size_angle(new_center, self.width, nh, self.theta)- }- }- }- }-- /// Projects mouse delta onto local unit axes `u_axis` and `v_axis` using the dot product.- pub fn project_delta(delta: Vec2, u_axis: (f64, f64), v_axis: (f64, f64)) -> (f64, f64) {- let dx = delta.x as f64;- let dy = delta.y as f64;- (dx * u_axis.0 + dy * u_axis.1, dx * v_axis.0 + dy * v_axis.1)- }-- /// Visible grid rows, plus one adjacent row in either direction. Work is independent of- /// document length, including after a large scroll jump.- pub(crate) fn thumbnail_rows(top: f32, bottom: f32, row_height: f32, rows: usize) -> Range<usize> {- let first = (top.max(0.0) / row_height).floor() as usize;- let end = (bottom.max(0.0) / row_height).ceil() as usize;- first.saturating_sub(1).min(rows)..end.saturating_add(1).min(rows)- }----#[derive(Clone, Copy, Debug, PartialEq, Eq)]--pub enum Fit {-- Width,-- Page,-- Height,-- None,--}----/// The page display as it was before full screen, put back on leaving it--/// ([`DocView::enter_presentation`]).--#[derive(Clone, Copy, Debug, PartialEq)]--pub struct SavedDisplay {-- pub layout: PageLayout,-- pub continuous: bool,-- pub cover: bool,-- pub fit: Fit,-- pub zoom: f32,--}----/// The base page display: one page across, or a two-page spread. Whether it scrolls continuously--/// is a separate flag (`continuous`), as in Acrobat, so every combination is reachable (#752).--#[derive(Clone, Copy, Debug, PartialEq, Eq)]--pub enum PageLayout {-- Single,-- TwoUp,--}----impl PageLayout {-- /// The base page displays, in the order the View menu, the rail's Page display button and-- /// Preferences list them.-- pub const ORDER: [Self; 2] = [Self::Single, Self::TwoUp];---- /// The name settings and view options use for the base layout: `single` or `two-up`.-- pub fn as_str(self) -> &'static str {-- match self {-- Self::Single => "single",-- Self::TwoUp => "two-up",-- }-- }---- /// The base layout an [`as_str`](Self::as_str) name stands for, in any case. `None` for-- /// anything else, so callers can reject a typo rather than switch layouts silently.-- pub fn try_parse(value: &str) -> Option<Self> {-- Self::ORDER.into_iter().find(|l| l.as_str().eq_ignore_ascii_case(value.trim()))-- }---- /// Rail icon for this layout.-- pub fn icon(self) -> &'static str {-- match self {-- Self::Single => "file-text",-- Self::TwoUp => "columns-2",-- }-- }---- /// Registry command that switches to this base layout (`PdfCraftApp::execute`).-- pub fn command(self) -> &'static str {-- match self {-- Self::Single => "view.layout.single",-- Self::TwoUp => "view.layout.two_up",-- }-- }---- /// The base layout a [`command`](Self::command) id switches to.-- pub fn from_command(id: &str) -> Option<Self> {-- Self::ORDER.into_iter().find(|l| l.command() == id)-- }---- /// Menu label: the label of [`command`](Self::command), which the catalogs translate.-- pub fn label(self) -> &'static str {-- match self {-- Self::Single => "Single page",-- Self::TwoUp => "Two-page view",-- }-- }--}----/// The single page-display token settings and the control channel use, combining the base layout--/// with continuous scrolling. `single` and `two-page` show one page or one spread at a time;--/// `continuous` (Single, scrolling) and `two-up` (Two-page, scrolling) keep their earlier names--/// for back-compat.--pub fn display_token(layout: PageLayout, continuous: bool) -> &'static str {-- match (layout, continuous) {-- (PageLayout::Single, false) => "single",-- (PageLayout::Single, true) => "continuous",-- (PageLayout::TwoUp, true) => "two-up",-- (PageLayout::TwoUp, false) => "two-page",-- }--}----/// The base layout and continuous flag a [`display_token`] names, in any case. `None` for a typo.--pub fn parse_display_token(value: &str) -> Option<(PageLayout, bool)> {-- match value.trim().to_ascii_lowercase().as_str() {-- "single" => Some((PageLayout::Single, false)),-- "continuous" => Some((PageLayout::Single, true)),-- "two-up" => Some((PageLayout::TwoUp, true)),-- "two-page" | "two-up-single" => Some((PageLayout::TwoUp, false)),-- _ => None,-- }--}----/// How a newly opened document is shown (Preferences ▸ Documents and view). A PDF that asks--/// for its own layout or zoom gets that instead.--#[derive(Clone, Copy, Debug, PartialEq)]--pub struct ViewDefaults {-- pub layout: PageLayout,-- /// Whether the base layout scrolls continuously.-- pub continuous: bool,-- /// Separate pages with a gutter and shadow; off joins adjacent page edges.-- pub show_page_gaps: bool,-- /// [`Fit::Width`] or [`Fit::Page`], or [`Fit::None`] for a fixed `zoom`.-- pub fit: Fit,-- /// The zoom with [`Fit::None`] (1.0 = 100%).-- pub zoom: f32,-- /// Highlight existing fields: a preference in Acrobat, so it carries over to the next-- /// document and the next session. On for new settings; a stored choice wins.-- pub highlight_fields: bool,--}----impl Default for ViewDefaults {-- fn default() -> Self {-- // Single page, scrolling continuously at fit width: the earlier "continuous" default.-- Self { layout: PageLayout::Single, continuous: true, show_page_gaps: true, fit: Fit::Width, zoom: 1.0, highlight_fields: true }-- }--}----impl ViewDefaults {-- /// The zoom as settings and view options name it: `fit-width`, `fit-page` or a percentage.-- pub fn zoom_name(&self) -> String {-- match self.fit {-- Fit::Page => "fit-page".into(),-- Fit::None => format!("{}%", (self.zoom * 100.0).round()),-- Fit::Width | Fit::Height => "fit-width".into(),-- }-- }---- /// These defaults with the zoom a [`zoom_name`](Self::zoom_name) names, in any case. `None`-- /// for anything else, including a percentage outside the 8–6400% the view can show.-- pub fn with_zoom(self, name: &str) -> Option<Self> {-- let name = name.trim();-- let (fit, zoom) = if name.eq_ignore_ascii_case("fit-width") {-- (Fit::Width, self.zoom)-- } else if name.eq_ignore_ascii_case("fit-page") {-- (Fit::Page, self.zoom)-- } else {-- let percent = name.strip_suffix('%').unwrap_or(name).trim().parse::<f32>().ok().filter(|p| (8.0..=6400.0).contains(p))?;-- (Fit::None, percent / 100.0)-- };-- Some(Self { fit, zoom, ..self })- }- }-- /// The find bar (⌘F): query, matches across the document, current match.- #[derive(Default)]- pub struct Find {- pub query: String,- /// (page, glyph range) in document order.- pub matches: Vec<(usize, Range<usize>)>,- pub current: Option<usize>,- /// The page a search started from while its match is picked automatically: a text layer- /// that arrives out of order can still supply an earlier match, and the automatic choice- /// follows this page. Cleared when the user picks a match or moves the view themselves.- pub auto_from: Option<usize>,- /// The page the automatic choice last put the view on (the search's starting page until it- /// chose anything). Compared with the viewed page, it tells an automatic scroll from one- /// the reader made themselves; `None` with `auto_from` once the choice is the user's.- pub auto_page: Option<usize>,- /// The reader ended automatic following (by navigating, scrolling, or picking a match).- /// This is distinct from a search that never followed: a late match must be listed without- /// being revealed by scrolling, even when the reader moved before the first match arrived.- pub follow_ended: bool,- pub focus: bool,- pub case_query: String,- /// Find options (Acrobat's: case-sensitive, whole words only).- pub case_sensitive: bool,- pub whole_words: bool,- /// Shown in the Search panel (Advanced Search) instead of the find bar.- pub in_panel: bool,- }-- /// What a text layer arriving after a search began may do with the automatic choice.- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- enum Follow {- /// The reader has not moved the view since the automatic choice: it may follow `from`.- Active(usize),- /// The reader navigated, scrolled or picked a match, so no automatic choice may reveal.- Ended,- /// No automatic choice is being followed (the search has not started, or the reader chose).- Never,- }-- impl Find {- /// The first match at or after `page`, or the first match when none follows (the search- /// wraps round the document).- fn first_at_or_after(&self, page: usize) -> Option<usize> {- self.matches.iter().position(|(p, _)| *p >= page).or_else(|| (!self.matches.is_empty()).then_some(0))- }-- /// How a text layer arriving now relates to the automatic choice. Once the reader has moved- /// the view (page box, Pages panel, outline, view history or any scrolling), automatic- /// following ends: a later layer must not pull them back to an anchor-derived match.- /// `Ended` is deliberately distinct from `Never`, so a first match arriving after that move- /// is not revealed by a flash meant only for a search that is still following.- fn follow_page(&mut self, viewed: usize) -> Follow {- if self.follow_ended {- return Follow::Ended;- }- match (self.auto_from, self.auto_page) {- (Some(from), Some(page)) if page == viewed => Follow::Active(from),- (Some(_), _) | (_, Some(_)) => {- self.stop_following();- Follow::Ended- }- (None, None) => Follow::Never,- }- }-- /// Ends automatic following: the selected match is now the user's choice to keep.- fn stop_following(&mut self) {- self.auto_from = None;- self.auto_page = None;- self.follow_ended = true;- }- }-- /// A text selection on one page.- #[derive(Clone, Copy, Debug, PartialEq)]- struct Selection {- page: usize,- span: Span,- }-- #[derive(Clone, Copy, Debug, PartialEq)]- enum Span {- /// Reading order, between two glyph indices.- Run { anchor: usize, head: usize },- /// Column select (#740): the glyphs inside a rectangle in page view space, drawn from the- /// corner the drag started at (`rect[0..2]`) to the pointer (`rect[2..4]`).- Column { rect: [f32; 4] },- }-- impl Selection {- fn run(page: usize, anchor: usize, head: usize) -> Self {- Self { page, span: Span::Run { anchor, head } }- }-- fn range(anchor: usize, head: usize) -> Range<usize> {- anchor.min(head)..anchor.max(head).saturating_add(1)- }-- /// One rectangle per selected piece of a line, in view space (highlighting, markup quads).- fn rects(&self, text: &PageText) -> Vec<[f32; 4]> {- match self.span {- Span::Run { anchor, head } => text.line_rects(Self::range(anchor, head)),- Span::Column { rect } => text.glyph_rects(&text.glyphs_in(rect)),- }- }-- /// The selected text, as Copy puts it on the clipboard.- fn text(&self, text: &PageText) -> String {- match self.span {- Span::Run { anchor, head } => text.text_of(Self::range(anchor, head)),- Span::Column { rect } => text.column_text(&text.glyphs_in(rect)),- }- }- }-- /// The glyphs `clicks` quick clicks select around glyph `a`: two the word, three the line, more- /// the page.- fn click_unit(text: &PageText, clicks: u32, a: usize) -> Option<(usize, usize)> {- match clicks {- 2 => text.word_at(a),- 3 => text.line_at(a),- _ => text.glyphs.len().checked_sub(1).map(|last| (0, last)),-- }- }-- struct PageTex {- tag: u64,- 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,--}----/// A historical snapshot opened from another document: View signed version opens the bytes--/// a signature covers, View revision an earlier incremental revision. Repeats reuse the tab,--/// and the tab and notice bar name what it is, instead of piling up identical tabs.--/// What a historical snapshot shows: the bytes a signature covers, or an earlier--/// incremental revision.--#[derive(Clone, Copy, Debug, PartialEq, Eq)]--pub enum SnapshotKind {-- SignedVersion,-- Revision,--}----#[derive(Clone, Debug)]--pub struct Snapshot {-- pub kind: SnapshotKind,-- /// The 1-based revision shown.-- pub revision: usize,-- /// The name of the document it was opened from.-- pub from: String,- }-- /// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.- pub(crate) struct SignatureBadge {- pub rect: [f64; 4],- pub status: pdfcraft_engine::SignatureStatus,- pub summary: &'static str,- }-- /// The validation badges drawn over one page's signature widgets: signed, visible widgets- /// on this page with coordinates that survive the cast to screen space. Hostile files can- /// carry NaN, infinite or gigantic rectangles, which must never reach the painter.- pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], page: usize) -> Vec<SignatureBadge> {- signatures- .iter()- .filter(|s| s.signed && s.visible && s.page == Some(page))- .filter_map(|s| {- s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|rect| SignatureBadge {- rect,- status: s.status,- summary: s.summary(),- })- })- .collect()--}----/// The name shown for a document tab, the window title and the Combine picker.--/// A snapshot reads like its source document, plus the snapshot suffix that tells--/// the tabs apart. Without a title the file name (which already carries the suffix)--/// is enough.--pub(crate) fn tab_label(app: &PdfCraftApp, index: usize) -> Option<String> {-- let view = app.views.get(index)?;-- let doc = app.session.get(view.id)?;-- let Some(snap) = view.snapshot.as_ref() else { return Some(doc.display_name()) };-- Some(snapshot_tab_name(&doc.display_name(), &doc.name, snap))--}----/// A snapshot's tab name from its source title, file name and marker. Pure so the--/// tab strip, window title and picker cannot disagree with each other.--pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapshot) -> String {-- if title == file_name {-- return file_name.into();-- }-- if snapshot.kind == SnapshotKind::SignedVersion {-- format!("{title} (signed version)")-- } else {-- format!("{title} (revision {})", snapshot.revision)-- }--}----pub struct DocView {-- pub id: DocId,-- pub zoom: f32,-- pub fit: Fit,-- pub layout: PageLayout,-- /// Whether the base layout scrolls continuously (independent of `layout`, as in Acrobat).-- pub continuous: bool,-- pub show_page_gaps: bool,-- /// View rotation in degrees clockwise (0, 90, 180, 270); display only, never saved.-- pub rotation: u16,-- pub current: usize,-- pub organize: bool,-- pub highlight_fields: bool,-- pub page_input: String,-- /// Select the replacement page label once if its editor remains focused.-- pub(crate) page_input_reselect: bool,-- pub notice_dismissed: bool,-- /// The user has been told that the form's scripts were turned off (it is said once).-- pub scripts_off_noted: bool,-- /// The file changed on disk while this document had unsaved changes: the notice bar asks-- /// before replacing it (#431).-- pub disk_changed: bool,-- /// The snapshot notice bar's Close was clicked: the tab closes at the top of the next-- /// frame, where no document borrow is held (the bar itself can't close it).-- pub close_requested: bool,-- /// A historical snapshot of another document (see [`Snapshot`]): `None` for real documents.-- pub snapshot: Option<Snapshot>,-- /// Two-page view: show the first page alone, as a cover (View ▸ Page display).-- pub cover: bool,-- /// Previous view / Next view: pages visited before (and after, once going back).-- pub back: Vec<usize>,-- pub forward: Vec<usize>,-- /// Pending navigation: page and fraction down the page to align with the viewport top.-- pub goto: Option<(usize, f32)>,-- /// Pending position within that page from a destination ([`Self::go_to_dest`]): the point-- /// (fractions of the displayed page; `None` leaves that axis to `goto`) to put `rel` points-- /// from the viewport's top-left corner.-- goto_point: Option<(usize, Option<f32>, Option<f32>, Vec2)>,-- /// Pending keyboard scrolling, in points down (negative: up): ↓ / ↑, and Page Down /-- /// Page Up where the pages scroll.-- pub key_scroll: f32,-- /// Single-page view, as last drawn: the page shown and whether the view was at its top and-- /// at its bottom, so ↑ / ↓ turn the page there instead of doing nothing (#273).-- single_edges: Option<(usize, bool, bool)>,-- /// Briefly outline an annotation after navigating to it from a panel.-- pub flash: Option<(usize, [f32; 4], f64)>,-- /// Compare files: differences shaded on this document's pages (page, user-space box, colour).-- pub compare_marks: Vec<(usize, [f32; 4], Color32)>,-- /// Full screen (Acrobat's Full Screen Mode): the display saved on entering it, while the view-- /// shows one page or spread at a time, fitted to the screen. `None` outside full screen.-- presentation: Option<SavedDisplay>,-- pages: HashMap<usize, PageTex>,-- /// Pages the renderer could not draw, with the reason (never re-requested).-- errors: HashMap<usize, String>,-- /// When each still-missing page was first shown, to flag unusually slow renders.-- waiting_since: HashMap<usize, f64>,-- thumbs: HashMap<usize, PageTex>,-- /// This frame's consumers, with visible cells ahead of prefetch.-- thumb_demand: HashMap<usize, bool>,-- frame_queue: Vec<RenderRequest>,-- /// A page-list edit after layout invalidates this frame's scales and page indexes.-- frame_geometry_changed: bool,-- /// Pages on screen this frame. Their rasters and tiles are always admitted: the viewport-- /// bounds them, and the byte and count limits apply to prefetch only.-- frame_visible: HashSet<usize>,-- /// Thumbnails that are out of date (still shown until their replacement arrives).-- stale_thumbs: HashSet<usize>,-- /// Tiles that are out of date (still shown until their replacement arrives).-- stale_tiles: HashSet<(usize, u64, u32, u32)>,-- /// Scale tag of the current zoom level, as last drawn.-- current_scale_tag: u64,-- /// Print dialog: the current sheet's pages at the preview pane's device resolution.-- print_pages: HashMap<usize, (u64, TextureHandle)>,-- /// Print dialog: preview rasters become luminance when Print ▸ Print in grayscale is on.-- grayscale: bool,-- /// Sharp tiles of large pages: (page, scale tag, tile x, tile y) → texture. Tiles of an-- /// earlier zoom stay, drawn stretched, until those of the current one cover the page.-- tiles: HashMap<(usize, u64, u32, u32), TextureHandle>,-- /// Text layers, extracted in the background on demand (selection, find, copy).-- pub(crate) texts: HashMap<usize, Arc<PageText>>,-- pub(crate) text_failed: HashSet<usize>,-- pub find: Option<Find>,-- selection: Option<Selection>,-- /// Select All while scrolling continuously (#2639): the text of every page of the document,-- /// highlighted on each page as its text arrives and copied whole ([`DocView::whole_text`]).-- pub(crate) all_text: bool,-- /// The selection whose action bar was closed by its Copy button: the bar stays hidden-- /// until the selection changes, as it does once a markup button consumes the selection.-- actions_dismissed: Option<Selection>,-- /// The drag in progress started a text selection: the wheel scrolls the page during it-- /// (#721), which egui's scroll area refuses while anything is dragged.-- selection_drag: bool,-- /// Clicks in the current run on the text layer: two select a word, three the line, four the page.-- clicks: u32,-- last_press_time: f64,-- last_press_pos: Option<Pos2>,-- /// Full screen: a click's page turn, when it falls due (input time) and which way. It waits-- /// out the double-click time, as the click may be the first of a double-click selecting a word.-- present_turn: Option<(f64, bool)>,-- last_queue: Vec<RenderRequest>,-- /// Finished renders wait in the pool instead of reaching the view (tests): what the view-- /// shows before a raster arrives can be looked at however fast the renderer is.-- pub hold_rasters: bool,-- viewport_w: f32,-- viewport_h: f32,-- page_count: usize,-- /// Page heights in points (view space), for mapping text positions to scroll offsets.-- page_heights: Vec<f32>,-- /// Screen rects of the pages drawn last frame (hit-testing, tests, automation).-- screen_rects: Vec<(usize, Rect)>,-- screen_xforms: Vec<(usize, PageXform)>,-- /// The scroll viewport on screen last frame.-- viewport_screen: Rect,-- /// Pending zoom anchor: page, fractional position (also in gutters), and viewport offset.-- zoom_anchor: Option<(usize, f32, f32, Vec2)>,-- /// The page view has been shown, so its scroll offset in egui's memory is this document's.-- shown: bool,-- /// Pages that Edit already tried to turn into editable text (once each, so Undo sticks).-- pub(crate) auto_ocr_tried: std::collections::HashSet<usize>,-- /// Pages Edit looked at and found not to be a scan, with the document's edit generation then:-- /// they are looked at again only after the document changes (an image added, say).-- pub(crate) auto_ocr_skipped: std::collections::HashMap<usize, u64>,-- /// Turns wheel input into page turns in single-page view.-- wheel: crate::wheel_pager::WheelPager,-- /// Until this time, apply precise (touchpad) wheel input 1:1 and suppress egui's eased copy.-- /// A precision touchpad sends pixel-precise `MouseWheel` events; on Windows they arrive with-- /// no `TouchPhase::Start`, so egui eases deltas of 8 px or more and the page lags the finger-- /// (#759). The window outlasts a single frame so egui's internal easing tail is suppressed as-- /// it decays, instead of adding on top of the 1:1 motion.-- precise_scroll_until: f64,-- /// Per-axis line-wheel state; horizontal input cannot extend a vertical burst.-- wheel_boost_x: crate::wheel_boost::WheelBoost,-- wheel_boost_y: crate::wheel_boost::WheelBoost,-- /// Touchpad momentum after the fingers lift (#531).-- fling: crate::fling::Fling,-- pub(crate) auto_scroll: crate::autoscroll::AutoScroll,-- /// Pages selected in the organize grid or the Pages panel (0-based). Empty means "the current page".-- pub selected: BTreeSet<usize>,-- pub(crate) organize_range: crate::page_selection_ui::PageSelectionInput,-- /// Anchor for ⇧-click range selection in the organize grid.-- select_anchor: Option<usize>,-- /// An edit requested by the view (organize toolbar, keys), applied by the app this frame.-- pub pending_edit: Option<Edit>,-- /// Edit text: the lines per page (with the document generation they were read at), and the-- /// line being edited.-- pub(crate) edit_lines: HashMap<usize, (u64, Vec<pdfcraft_engine::TextBlock>)>,-- pub line_editor: Option<crate::edit_text_ui::LineEditor>,-- /// The paragraph editor whose edit was just queued. It opens again with its typing if the-- /// edit fails, as a refused form field does.-- pub(crate) applied_editor: Option<crate::edit_text_ui::LineEditor>,-- /// The box a click switched to while another paragraph was being edited: it opens once the-- /// queued edit has applied, so its index and geometry come from the document it now is (#2022).-- /// It is held as the paragraph's text and box, not an index: the edit can regroup the page.-- pub(crate) pending_text_open: Option<(usize, pdfcraft_engine::BlockKey)>,-- pub(crate) text_background: crate::edit_text_ui::TextBackground,-- pub(crate) move_background: crate::content_ui::MoveBackground,-- /// Edit text & images: the images per page (by document generation), and the selected one.-- pub(crate) edit_images: HashMap<usize, (u64, Vec<pdfcraft_engine::PageImage>)>,-- pub(crate) objects: crate::object_ui::ObjectSelection,-- pub image_selection: Option<crate::edit_text_ui::ImageSelection>,-- /// Select tool: the picture clicked, to copy in its original format.-- pub picked_image: Option<crate::image_pick::PickedImage>,-- /// A paragraph box being dragged (moved, or resized from its right edge) in Edit text.-- pub block_drag: Option<crate::edit_text_ui::BlockDrag>,-- /// Commenting state: selected comment, gestures, composer.-- pub comments: crate::comments::CommentView,-- pub measure: crate::measure_ui::MeasureView,-- /// Form filling state: the focused field.-- pub forms: crate::forms_ui::FormView,-- /// Prepare a form: the selected field and the gesture in progress.-- pub prepare: crate::prepare::PrepareView,-- /// Prepare a form ▸ Calculation order.-- pub(crate) calc_order: crate::calc_order_ui::CalcOrderView,-- /// Edit a PDF: the selected added item, the text being typed.-- pub content: crate::content_ui::ContentView,-- /// Edit a PDF ▸ Link tool state.-- pub links: crate::link_ui::LinkView,-- /// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.-- pub redact_drag: crate::redact_ui::AreaDrag,-- pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,-- /// A crop rectangle being dragged (Crop tool).-- pub crop_drag: crate::crop::CropDrag,-- /// Enhance ▸ Camera image: the quadrilateral being placed.-- pub camera: Option<crate::camera_ui::CameraQuad>,-- /// Enhance ▸ Camera image: the page just enhanced, while the bar offers rotate, crop and-- /// organize.-- pub camera_done: Option<crate::camera_ui::CameraDone>,-- /// Use a certificate: a signature rectangle being drawn, or an empty signature field clicked.-- pub sign: crate::sign_ui::SignView,-- /// Organize: the pages being dragged to a new place.-- pub org_drag: Option<Vec<usize>>,-- /// Pages panel: the pages being dragged to a new place.-- pub panel_drag: Option<Vec<usize>>,-- /// Marquee Zoom / Snapshot: the rectangle being dragged (page, start), and a finished one.-- pub marquee: Option<(usize, Pos2)>,-- pub marquee_done: Option<crate::zoom_snap::Marquee>,-- /// Fill & Sign text being typed.-- pub fill_text: Option<crate::fill_sign::TypeBox>,-- /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.-- pub(crate) fill_signature_page: Option<usize>,-- pub(crate) signature_drag: crate::signature_drag::SignatureDrag,-- /// A non-edit action requested by the organize toolbar, handled by the app.-- pub pending_action: Option<ViewAction>,-- /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they-- /// go after the selection.-- pub insert_at: Option<usize>,-- /// The page-grid gap under the pointer this frame (where dropped files go), when it can-- /// take pages.-- pub grid_gap: Option<usize>,-- /// The visible part of the Pages panel as last drawn, when it can take dropped files-- /// (cleared each frame before the panels draw).-- pub pages_panel: Option<Rect>,-- /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages.-- pub panel_gap: Option<usize>,-- /// The current page the Pages panel last followed: it scrolls to the current page's-- /// thumbnail only when the page changes.-- pub(crate) panel_followed: Option<usize>,-- /// Scale of the thumbnails in the Pages inspector, independent of document and grid zoom.-- thumbnail_zoom: f32,-- /// How large the page grid draws its pages (1.0 = the usual thumbnails).-- grid_zoom: f32,-- /// A zoom asked for this frame (toolbar, pinch, keys); the grid applies it once it has laid-- /// out, so it can keep the same pages in view.-- grid_zoom_request: Option<f32>,-- /// The page to keep in place after a grid zoom, and how far below the top of the grid its-- /// cell was.-- grid_anchor: Option<(usize, f32)>,-- /// The page the grid scrolls into view on its next frame (Organize just opened on it).-- grid_reveal: Option<usize>,-- /// Sharp renders of the pages the grid shows larger than a thumbnail: only those in view,-- /// at the size drawn (device pixels wide).-- grid_pages: HashMap<usize, (u32, TextureHandle)>,-- /// Zoom-settle debounce for heavy pages: the last requested device scale, and the egui-- /// time until which sharp whole-page/tile re-renders are held back. While the zoom is-- /// still moving, every frame would otherwise cancel the in-flight full-page interpret-- /// (seconds on image-heavy CAD plots) and start it over, so a sharp raster never-- /// arrives. The stale raster stays on screen stretched meanwhile.-- last_scale: f32,-- sharp_hold_until: f64,-- /// Pan-settle debounce for tiled pages: the scroll offset last frame, and the egui time-- /// until which sharp tile re-renders are held back. Each tile costs a full page-- /// interpret, so a drag would otherwise queue a storm of them (one per frame) while the-- /// in-flight ones cannot be cancelled mid-operator. Older tiles and the backdrop stay-- /// stretched meanwhile; fresh tiles go out once the pan settles.-- pub(crate) last_scroll: Vec2,-- /// Side-by-side compare: scroll to here this frame, following the other half.-- pub(crate) sync_scroll: Option<Vec2>,-- /// The page widget's id, by which the Hand tool finds its drag before the pages are laid out.-- page_widget: Option<egui::Id>,-- pan_hold_until: f64,-- /// Pages whose raster proved slow (see `SLOW_MILLIS`): only these get the zoom/pan-- /// settle holds. Fast pages render straight through, with no added latency.-- slow_pages: HashSet<usize>,- }-- /// 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;- const GRID_ZOOM_STEP: f32 = 1.25;- /// How far a sharp grid render may be from the size drawn before it is redone: a pinch changes- /// the size on every frame, and a slightly soft or slightly large image is fine meanwhile.- const GRID_SHARP: std::ops::RangeInclusive<f32> = 0.9..=1.6;-- /// Whether an image `have` device pixels wide is good enough to draw `want` pixels wide.- fn sharp_enough(have: u32, want: f32) -> bool {- want > 0.0 && GRID_SHARP.contains(&(have as f32 / want))- }-- /// Thumbnail device-pixel density when `demand` pages share the thumbnail allowance.- 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)- }-- fn thumbnail_scale(width: f32, height: f32, density: f32) -> f32 {- (THUMB_W / width.max(1.0)).min(THUMB_H / height.max(1.0)) * density--}----/// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs).--#[derive(Clone, Copy, Debug, PartialEq, Eq)]--pub enum ViewAction {-- InsertFromFile,-- /// Insert files at a gap of the page grid (0 = before the first page).-- InsertFromFileAt(usize),-- /// Replace the selected pages with pages from another file.-- ReplacePages,-- /// Save the document as the grid shows it.-- Save,-- Extract,-- Split,-- /// Split before each selected page: opens Split on that mode.-- SplitBeforeSelected,-- /// Copy the selected pages (Cut also deletes them).-- CopyPages {-- cut: bool,-- },-- /// Paste copied pages after the selection.-- PastePages,-- /// Enhance ▸ Camera image: straighten what the corners enclose.-- EnhanceCamera,-- /// Leave Enhance ▸ Camera image (Cancel before Enhance page, Done after it).-- CancelCamera,-- /// After Enhance page: turn the enhanced page a quarter.-- CameraRotate {-- clockwise: bool,-- },-- /// After Enhance page: enhance again at the slider's clean-up level.-- CameraLevel,-- /// After Enhance page: leave the tool for this command (Crop pages, Organize pages).-- CameraNext(&'static str),- }-- /// Default page right-click menu actions.- #[derive(Clone, Debug, PartialEq)]- pub(crate) enum PageMenuAction {- RotateCCW(usize),- RotateCW(usize),- Print,- SelectTool,- HandTool,- MarqueeZoom,- Copy,- Paste(usize, [f64; 2]),- AddComment(usize, [f64; 2]),- AddBookmark(usize),- TakeSnapshot,- EditPdf,- AddText,- AddImage,- DeletePage(usize),- ExportPdf,- Find,- DocProperties,- FlattenComments,- }-- pub(crate) struct PageMenuPerms {- pub can_modify: bool,- pub can_assemble: bool,- pub can_annotate: bool,- pub can_print: bool,- pub can_copy: bool,- pub can_paste: bool,- pub has_annotations: bool,- }-- pub(crate) fn default_page_context_menu(ui: &mut egui::Ui, page: usize, at: [f64; 2], perms: PageMenuPerms, action: &mut Option<PageMenuAction>) {- // Top horizontal icon bar: Rotate CCW, Print, Select tool, Hand tool, Marquee Zoom- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = 4.0;- if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate view counterclockwise")).clicked() {- *action = Some(PageMenuAction::RotateCCW(page));- ui.close();- }- ui.add_enabled_ui(perms.can_print, |ui| {- if crate::icons::button(ui, "printer", 24.0, false, tl!("Print")).clicked() {- *action = Some(PageMenuAction::Print);- ui.close();- }- });- if crate::icons::button(ui, "mouse-pointer-2", 24.0, false, tl!("Select Tool")).clicked() {- *action = Some(PageMenuAction::SelectTool);- ui.close();- }- if crate::icons::button(ui, "hand", 24.0, false, tl!("Hand Tool")).clicked() {- *action = Some(PageMenuAction::HandTool);- ui.close();- }- if crate::icons::button(ui, "zoom-in", 24.0, false, tl!("Marquee Zoom")).clicked() {- *action = Some(PageMenuAction::MarqueeZoom);- ui.close();- }- });-- ui.separator();-- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Copy")).shortcut_text("Ctrl+C")).clicked() {- *action = Some(PageMenuAction::Copy);- ui.close();- }- if ui.add_enabled(perms.can_paste, egui::Button::new(tl!("Paste")).shortcut_text("Ctrl+V")).clicked() {- *action = Some(PageMenuAction::Paste(page, at));- ui.close();- }-- ui.separator();-- if ui.add_enabled(perms.can_annotate, egui::Button::new(tl!("Add comment"))).clicked() {- *action = Some(PageMenuAction::AddComment(page, at));- ui.close();- }- if perms.has_annotations && ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Flatten comments"))).clicked() {- *action = Some(PageMenuAction::FlattenComments);- ui.close();- }- if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Add bookmark"))).clicked() {- *action = Some(PageMenuAction::AddBookmark(page));- ui.close();- }- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Take a snapshot"))).clicked() {- *action = Some(PageMenuAction::TakeSnapshot);- ui.close();- }-- ui.separator();-- if ui.add_enabled(perms.can_modify, egui::Button::new(egui::RichText::new(tl!("Edit this PDF")).strong())).clicked() {- *action = Some(PageMenuAction::EditPdf);- ui.close();- }- if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add text"))).clicked() {- *action = Some(PageMenuAction::AddText);- ui.close();- }- if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add image"))).clicked() {- *action = Some(PageMenuAction::AddImage);- ui.close();- }- if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Delete page"))).clicked() {- *action = Some(PageMenuAction::DeletePage(page));- ui.close();- }- if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Export this PDF"))).clicked() {- *action = Some(PageMenuAction::ExportPdf);- ui.close();- }-- ui.separator();-- if ui.button(tl!("Find text or tools")).clicked() {- *action = Some(PageMenuAction::Find);- ui.close();- }- if ui.button(tl!("Rotate view clockwise")).clicked() {- *action = Some(PageMenuAction::RotateCW(page));- ui.close();- }- if ui.button(tl!("Document properties…")).clicked() {- *action = Some(PageMenuAction::DocProperties);- ui.close();- }--}----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(),- }- }-- /// Where `page` is drawn on screen this frame (`None` when it is not on screen).- pub fn page_screen_rect(&self, page: usize) -> Option<Rect> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| xf.rect)- }-- /// The document area on screen.- pub fn viewport_rect(&self) -> Rect {- self.viewport_screen- }--- /// Whether a middle-button scrolling gesture is active (tests and automation).-- pub fn auto_scrolling(&self) -> bool {-- self.auto_scroll.active()-- }---- /// Whether a held middle-button pan is active, outside Linux (tests and automation).-- pub fn middle_panning(&self) -> bool {-- self.auto_scroll.panning()-- }---- /// Abandon only pointer previews: clearing egui's held button must not commit an app-owned-- /// grab through a tool's `!primary_down` fallback. Keep selections, text drafts and edits-- /// that were already completed before cancellation.-- pub(crate) fn cancel_pointer_gestures(&mut self) {-- self.marquee = None;-- self.marquee_done = None;-- self.comments.gesture = None;-- self.links.drag = None;-- self.sign.drag = None;-- self.redact_drag = None;-- self.crop_drag = None;-- self.block_drag = None;-- self.org_drag = None;-- self.panel_drag = None;-- self.selection_drag = false;-- self.auto_scroll.cancel();-- self.prepare.cancel_pointer_gesture();-- self.content.cancel_pointer_gesture();-- self.objects.cancel_pointer_gesture();-- if let Some(image) = &mut self.image_selection {-- image.cancel_pointer_gesture();-- }- }-- /// 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-- }---- /// A view of a newly opened document, shown as `defaults` say. Opening a file then applies-- /// any layout or zoom the PDF itself asks for.-- pub fn new(id: DocId, info: &DocInfo, defaults: ViewDefaults) -> Self {-- Self {-- id,-- zoom: defaults.zoom,-- fit: defaults.fit,-- layout: defaults.layout,-- continuous: defaults.continuous,-- show_page_gaps: defaults.show_page_gaps,-- rotation: 0,-- current: 0,-- organize: false,-- highlight_fields: defaults.highlight_fields,-- page_input: "1".into(),-- page_input_reselect: false,-- notice_dismissed: false,-- scripts_off_noted: false,-- disk_changed: false,-- close_requested: false,-- snapshot: None,-- cover: false,-- back: Vec::new(),-- forward: Vec::new(),-- goto: None,-- goto_point: None,-- key_scroll: 0.0,-- single_edges: None,-- flash: None,-- compare_marks: Vec::new(),-- presentation: None,-- pages: HashMap::new(),-- errors: HashMap::new(),-- waiting_since: HashMap::new(),-- thumbs: HashMap::new(),-- thumb_demand: HashMap::new(),-- frame_queue: Vec::new(),-- frame_geometry_changed: false,-- frame_visible: HashSet::new(),-- stale_thumbs: HashSet::new(),-- stale_tiles: HashSet::new(),-- current_scale_tag: 0,-- print_pages: HashMap::new(),-- grayscale: false,-- tiles: HashMap::new(),-- texts: HashMap::new(),-- text_failed: HashSet::new(),-- find: None,-- selection: None,-- all_text: false,-- actions_dismissed: None,-- selection_drag: false,-- clicks: 0,-- last_press_time: 0.0,-- last_press_pos: None,-- present_turn: None,-- last_queue: Vec::new(),-- hold_rasters: false,-- viewport_w: 800.0,-- viewport_h: 600.0,-- page_count: info.pages.len(),-- page_heights: info.pages.iter().map(|p| p.height).collect(),-- screen_rects: Vec::new(),-- screen_xforms: Vec::new(),-- viewport_screen: Rect::NOTHING,-- zoom_anchor: None,-- shown: false,-- auto_ocr_tried: Default::default(),-- auto_ocr_skipped: Default::default(),-- wheel: Default::default(),-- precise_scroll_until: 0.0,-- wheel_boost_x: Default::default(),-- wheel_boost_y: Default::default(),-- fling: Default::default(),-- auto_scroll: Default::default(),-- selected: BTreeSet::new(),-- select_anchor: None,-- organize_range: Default::default(),-- pending_edit: None,-- edit_lines: HashMap::new(),-- line_editor: None,-- applied_editor: None,-- pending_text_open: None,-- text_background: Default::default(),-- move_background: Default::default(),-- edit_images: HashMap::new(),-- objects: Default::default(),-- image_selection: None,-- picked_image: None,-- block_drag: None,-- pending_action: None,-- insert_at: None,-- grid_gap: None,-- pages_panel: None,-- panel_gap: None,-- panel_followed: None,-- thumbnail_zoom: 1.0,-- grid_zoom: 1.0,-- grid_zoom_request: None,-- grid_anchor: None,-- grid_reveal: None,-- grid_pages: HashMap::new(),-- last_scale: 0.0,-- sharp_hold_until: 0.0,-- last_scroll: Vec2::ZERO,-- sync_scroll: None,-- page_widget: None,-- pan_hold_until: 0.0,-- slow_pages: HashSet::new(),-- comments: Default::default(),-- measure: Default::default(),-- forms: Default::default(),-- prepare: Default::default(),-- calc_order: Default::default(),-- content: Default::default(),-- links: Default::default(),-- redact_drag: None,-- pending_redaction: None,-- crop_drag: None,-- camera: None,-- camera_done: None,-- sign: Default::default(),-- org_drag: None,-- panel_drag: None,-- marquee: None,-- marquee_done: None,-- fill_text: None,-- fill_signature_page: None,-- signature_drag: Default::default(),-- }-- }---- /// The document's content or page list changed (an edit, undo or redo): drop caches and-- /// adopt the new page geometry, keeping the reader's place where possible.-- pub fn document_changed(&mut self, info: &DocInfo) {-- self.invalidate_content();-- self.frame_geometry_changed = true;-- self.page_count = info.pages.len();-- self.page_heights = info.pages.iter().map(|p| p.height).collect();-- let last = self.page_count.saturating_sub(1);-- self.current = self.current.min(last);-- self.selected.retain(|p| *p <= last);-- // Text being typed on a page that no longer exists goes with the page.-- if self.content.draft.as_ref().is_some_and(|d| d.page > last || self.page_count == 0) {-- self.content.draft = None;-- }-- if self.select_anchor.is_some_and(|a| a > last) {-- self.select_anchor = None;-- }-- self.goto = None;-- self.goto_point = None;-- self.zoom_anchor = None;-- self.flash = None;-- // Thumbnail drags hold page indexes from before the change.-- self.panel_drag = None;-- self.org_drag = None;-- self.reset_coarse_state();-- }---- /// The document was replaced by a newer version of its file (#431). The reader's place-- /// stays: zoom, layout, rotation, page, scroll, full screen, view history and the find bar,-- /// the snapshot marker and its pending close, and the page images on screen until their-- /// replacements are drawn, so nothing flashes. Everything that pointed into the old version (a selected-- /// comment, a field being typed in, text being edited, a drag, page selection) starts-- /// afresh, so no stale index reaches the new one.-- pub fn document_replaced(&mut self, info: &DocInfo) {-- let mut fresh = Self::new(self.id, info, ViewDefaults::default());-- fresh.zoom = self.zoom;-- fresh.fit = self.fit;-- fresh.layout = self.layout;-- fresh.continuous = self.continuous;-- fresh.show_page_gaps = self.show_page_gaps;-- fresh.rotation = self.rotation;-- fresh.current = self.current;-- fresh.organize = self.organize;-- fresh.grid_zoom = self.grid_zoom;-- fresh.thumbnail_zoom = self.thumbnail_zoom;-- // Same document id, so the scroll offset egui keeps for it is still this document's.-- fresh.shown = self.shown;-- fresh.highlight_fields = self.highlight_fields;-- fresh.notice_dismissed = self.notice_dismissed;-- fresh.snapshot = self.snapshot.clone();-- fresh.close_requested = self.close_requested;-- fresh.cover = self.cover;-- // Still presenting, with the display to go back to on leaving.-- fresh.presentation = self.presentation.take();-- fresh.back = std::mem::take(&mut self.back);-- fresh.forward = std::mem::take(&mut self.forward);-- fresh.find = self.find.take();-- fresh.pages = std::mem::take(&mut self.pages);-- fresh.thumbs = std::mem::take(&mut self.thumbs);-- fresh.viewport_w = self.viewport_w;-- fresh.viewport_h = self.viewport_h;-- fresh.viewport_screen = self.viewport_screen;-- *self = fresh;-- // Marks the kept images out of date and clamps the page to the new page count.-- self.document_changed(info);-- self.page_input = self.current_page_label(info.pages.get(self.current).map(|page| page.label.as_str()));-- self.page_input_reselect = true;- }-- /// Open Organize Pages on the page being read (issue #1910). An empty selection means the- /// current page, so a selection left from earlier that does not include it is dropped, and- /// the grid scrolls its cell into view. Every way into the grid goes through here; closing- /// it is a plain `organize = false`.- pub fn open_organize(&mut self) {- self.organize = true;- if !self.selected.is_empty() && !self.selected.contains(&self.current) {- self.clear_page_selection(Some(self.current));- }- self.grid_reveal = Some(self.current);- }-- /// Pages an organize command acts on: the selection, or the current page.- pub fn target_pages(&self) -> Vec<usize> {- if self.selected.is_empty() { vec![self.current] } else { self.selected.iter().copied().collect() }-- }---- /// Select pages in the organize grid (tests, automation). Empty clears the selection.-- pub(crate) fn page_count(&self) -> usize {-- self.page_count- }-- pub fn select_pages(&mut self, pages: &[usize]) {- self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();- if let Some(first) = self.selected.first() {- self.current = *first;- }- }-- /// A click on page `i`'s thumbnail, in the organize grid or the Pages panel. ⇧ selects the- /// range from the anchor (or the current page); ⌘/Ctrl toggles the page; a plain click- /// selects only it. `seed_current` is for the Pages panel, where an empty selection means- /// the current page: the first ⌘-click on another page keeps the current one selected too.- pub fn click_page(&mut self, i: usize, modifiers: egui::Modifiers, seed_current: bool) {- if i >= self.page_count {- return;- }- if modifiers.shift {- let a = self.select_anchor.unwrap_or(self.current);- self.selected = (a.min(i)..=a.max(i)).collect();- } else if modifiers.command {- if seed_current && self.selected.is_empty() && i != self.current {- self.selected.insert(self.current);- }- if !self.selected.remove(&i) {- self.selected.insert(i);- }- self.select_anchor = Some(i);- } else {- self.selected = [i].into();- self.select_anchor = Some(i);- }- }-- /// Drop the page selection; a later ⇧-click ranges from `anchor`.- pub fn clear_page_selection(&mut self, anchor: Option<usize>) {- self.selected.clear();- self.select_anchor = anchor.filter(|a| *a < self.page_count);- }-- 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- }-- /// 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- /// 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.forms.unbaked.clear();- self.texts.clear();- self.text_failed.clear();- self.errors.clear();- self.slow_pages.clear();- self.waiting_since.clear();- self.last_queue.clear();- self.selection = 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.- if let Some(f) = self.find.as_mut() {- f.matches.clear();- f.current = None;- }- }-- /// 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.- 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.texts.remove(&page);- self.text_failed.remove(&page);- self.errors.remove(&page);- self.last_queue.clear();- if self.selection.is_some_and(|s| s.page == page) {- self.selection = None;- }- }-- /// Pages drawn last frame and their screen rectangles.- pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {- self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()- }-- /// Where `page` is drawn this frame, with its coordinate mapping.- pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)- }-- /// The text selection as markup quadrilaterals in user space: (page, quads).- pub(crate) fn selection_quads(&self, info: &DocInfo) -> Option<(usize, Vec<[f64; 8]>)> {- let s = self.selection?;- let text = self.texts.get(&s.page)?;- let page = info.pages.get(s.page)?;- let quads: Vec<[f64; 8]> = s.rects(text).into_iter().map(|r| page.view_rect_to_quad(r)).collect();- (!quads.is_empty()).then_some((s.page, quads))- }-- /// Where a bookmark made now should go: the page and the `/XYZ` position `[left, top]` in user- /// space. With text selected it is the corner of the selection that shows at its top-left- /// (its page, both coordinates); otherwise the top of the window (the page showing there, and- /// only the position along the window's vertical, so the reader's other scroll position and- /// zoom are kept). `None` before the first frame has laid pages out, when the bookmark just- /// goes to the current page.- pub(crate) fn bookmark_position(&self, info: &DocInfo) -> Option<(usize, [Option<f32>; 2])> {- if let Some(sel) = self.selection- && let Some(text) = self.texts.get(&sel.page)- && let Some(p) = info.pages.get(sel.page)- {- // The selection's bounds in view space, which View ▸ Rotate View leaves unturned: the- // corner at the screen's top-left is a different one for each quarter turn.- let [x0, y0, x1, y1] = sel.rects(text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| {- [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])]- });- let (x, y) = match self.rotation {- 90 => (x0, y1),- 180 => (x1, y1),- 270 => (x1, y0),- _ => (x0, y0),- };- if x.is_finite() && y.is_finite() {- return Some((sel.page, p.xyz_for_view(Some(x), Some(y))));- }- }- // The page showing at the window's top edge: one that crosses it (the first, in a spread- // of pages of different heights, whose shorter page can start below it), else the- // nearest one below.- let top = self.viewport_screen.top();- let showing = || self.screen_xforms.iter().filter(|(_, xf)| xf.rect.bottom() > top);- let (page, xf) = showing()- .filter(|(_, xf)| xf.rect.top() <= top)- .min_by_key(|(p, _)| *p)- .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0))))?;- let p = info.pages.get(*page)?;- // Above the page (in the gap before it) is the page's own top. The window's vertical is- // the view's y, or its x when the view is turned a quarter.- let (x, y) = xf.screen_to_view(pos2(xf.rect.center().x, top.max(xf.rect.top())));- let at = if xf.rot.is_multiple_of(180) {- p.xyz_for_view(None, Some(y.clamp(0.0, p.height)))- } else {- p.xyz_for_view(Some(x.clamp(0.0, p.width)), None)- };- Some((*page, at))- }-- /// The user-space `[left, top]` at the window's top-left (where `/XYZ` puts its point), on the- /// page showing there: what a destination's null coordinate keeps (ISO 32000-2 §12.3.2.2).- /// Acrobat keeps the place this way across pages, so a CAD sheet's cross-reference opens the- /// next sheet where the reader was looking. A coordinate is `None` along a screen axis the- /// page fits, which keeps the layout's own placement (centred, or the page's top); the whole- /// place is `None` before the first frame has laid pages out.- fn place_at_corner(&self, info: &DocInfo) -> Option<[Option<f32>; 2]> {- let area = self.viewport_screen;- if !area.is_positive() {- return None;- }- let corner = area.min + vec2(SIDE, 0.0);- let (page, xf) = self- .screen_xforms- .iter()- .filter(|(_, xf)| xf.rect.is_positive())- .min_by(|a, b| a.1.rect.distance_sq_to_pos(corner).total_cmp(&b.1.rect.distance_sq_to_pos(corner)).then(a.0.cmp(&b.0)))?;- let p = info.pages.get(*page)?;- let (x, y) = xf.screen_to_view(corner.clamp(xf.rect.min, xf.rect.max));- // `max` drops a NaN size, so the bounds stay ordered and `clamp` can't panic.- let (x, y) = (x.clamp(0.0, p.width.max(0.0)), y.clamp(0.0, p.height.max(0.0)));- // The page counts with its side gutters, as the layout places it.- let wide = xf.rect.width() + 2.0 * SIDE > area.width();- let tall = xf.rect.height() > area.height();- // The view's x runs across the screen unless the view is turned a quarter.- let (keep_x, keep_y) = if xf.rot.is_multiple_of(180) { (wide, tall) } else { (tall, wide) };- Some(p.xyz_for_view(keep_x.then_some(x), keep_y.then_some(y)))- }-- /// 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())- }-- /// 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()- }-- /// Whether `page`'s text layer has arrived from the renderer. Selecting text, the I-beam and- /// find matches on a page all wait for it (tests and automation).- pub fn has_page_text(&self, page: usize) -> bool {- self.texts.contains_key(&page)- }-- pub(crate) fn clear_selection(&mut self) {- self.selection = None;- self.actions_dismissed = None;- }-- /// Select text on `page` from glyph `from` to glyph `to` (tests and automation).- pub fn select_text(&mut self, page: usize, from: usize, to: usize) {- self.all_text = false;- self.selection = Some(Selection::run(page, from, to));- }-- /// Open the find bar (or focus it if already open).- pub fn open_find(&mut self) {- let f = self.find.get_or_insert_with(Find::default);- f.focus = true;- }-- /// Re-run the search on all pages whose text is known (after the query changed).- pub fn rerun_find(&mut self) {- let Some(f) = self.find.as_mut() else { return };- f.case_query = f.query.clone();- f.matches.clear();- f.current = None;- // Refining the query keeps the page the reader started searching from, even when an- // automatic choice has already scrolled them to a match. Only a view the reader moved- // themselves re-anchors the search on the page now shown.- let from = match (f.auto_from, f.auto_page) {- (Some(from), Some(page)) if !f.follow_ended && page == self.current => from,- _ => self.current,- };- f.auto_from = Some(from);- f.auto_page = Some(self.current);- f.follow_ended = false;- if f.case_query.trim().is_empty() {- return;- }- let mut pages: Vec<usize> = self.texts.keys().copied().collect();- pages.sort();- for &p in &pages {- if let Some(text) = self.texts.get(&p) {- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r)));- }- }- f.matches.sort_by_key(|(p, r)| (*p, r.start));- // First match at or after the page the search started from.- if let Some(i) = f.first_at_or_after(from)- && let Some(&(p, _)) = f.matches.get(i)- {- f.current = Some(i);- f.auto_page = Some(p);- self.flash_match(p);- }- }-- fn refresh_find_page(&mut self, page: usize) {- let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };- if f.case_query.trim().is_empty() {- return;- }- let previous = f.current.and_then(|c| f.matches.get(c).cloned());- // An automatic choice follows the page it was anchored on, so a page whose text- // arrives late can still supply an earlier match. Once the reader has moved the view,- // this arrival must not pull them back; the choice then becomes theirs to keep.- let follow = f.follow_page(self.current);- f.matches.retain(|(p, _)| *p != page);- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));- f.matches.sort_by_key(|(p, r)| (*p, r.start));- if let Follow::Active(from) = follow {- f.current = f.first_at_or_after(from);- let selected = f.current.and_then(|i| f.matches.get(i).cloned());- // Follow a changed automatic choice; the view is still where the last one left it.- if selected != previous- && let Some((p, _)) = selected- {- f.auto_page = Some(p);- self.flash_match(p);- }- return;- }- // A match the user picked keeps its identity, exactly as before automatic following.- // When it is gone (or none was picked), the first match at or after the viewed page is- // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic- // choice to reveal, and a reader who moved before the first layer arrived must not be- // pulled back by that late match.- 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));- }-- /// Go to match `i` (the Search panel's results).- pub fn go_to_match(&mut self, i: usize) {- let Some(f) = self.find.as_mut() else { return };- let Some(&(p, _)) = f.matches.get(i) else { return };- f.current = Some(i);- f.stop_following();- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);- }-- /// Move to the next/previous match.- pub fn find_step(&mut self, forward: bool) {- let Some(f) = self.find.as_mut() else { return };- if f.matches.is_empty() {- return;- }- let n = f.matches.len();- let c = f.current.unwrap_or(0);- let next = if forward { (c + 1) % n } else { (c + n - 1) % n };- f.current = Some(next);- f.stop_following();- let p = f.matches[next].0;- // Only explicit search navigation joins history; background refresh uses flash_match alone.- self.go_to_page(p);- self.goto_point = None;- self.flash_match(p);- }-- fn flash_match(&mut self, page: usize) {- let frac = self- .find- .as_ref()- .and_then(|f| f.current.and_then(|c| f.matches.get(c)))- .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1]))- .zip(self.page_heights.get(page).copied())- .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0))- .unwrap_or(0.0);- self.goto = Some((page, frac));- self.current = page;- self.reset_coarse_state();- }-- /// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its- /// text layer is loaded (used by UI tests and automation to aim pointer input).- pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {- let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;- let g = self.texts.get(&page)?.glyphs.get(glyph)?;- Some(xf.view_rect(g.rect).center())- }-- /// Selected text, if any (⌘C).- /// The selected text: of the pages read so far, after Select All of the document (Copy reads- /// the others, [`DocView::pages_without_text`]).- pub fn selected_text(&self) -> Option<String> {- if self.all_text {- return Some(self.whole_text(&HashMap::new())).filter(|x| !x.is_empty());- }- let s = self.selection?;- let t = self.texts.get(&s.page)?;- Some(s.text(t)).filter(|x| !x.is_empty())- }-- pub fn thumb(&self, page: usize) -> Option<&TextureHandle> {- self.thumbs.get(&page).map(|t| &t.tex)-- }---- /// Drops wheel state after a discontinuous jump so the destination cannot-- /// inherit momentum from the previous viewport.-- fn reset_coarse_state(&mut self) {-- self.wheel.clear_motion();-- self.wheel_boost_x.reset();-- self.wheel_boost_y.reset();- }-- /// Ends automatic search following after the reader navigated or scrolled the view. A- /// programmatic search flash never comes through here; it sets `goto` and `current` directly- /// so that its own scroll cannot be mistaken for the reader's.- fn end_find_following(&mut self) {- if let Some(f) = self.find.as_mut() {- f.stop_following();- }- }-- pub fn go_to_page(&mut self, page: usize) {- let page = page.min(self.page_count.saturating_sub(1));- self.end_find_following();- if page != self.current {- // The view history (Previous view / Next view).- if self.back.last() != Some(&self.current) {- self.back.push(self.current);- if self.back.len() > 200 {- self.back.remove(0);- }- }- self.forward.clear();- }- // Partial wheel motion belongs to the old place.- self.reset_coarse_state();- self.goto = Some((page, 0.0));- self.current = page;- }-- /// Reveal a user-space rectangle without changing zoom, centred where the scroll bounds allow.- pub(crate) fn reveal_rect(&mut self, page: usize, rect: [f32; 4], info: &DocInfo) {- self.go_to_page(page);- self.goto_point = None;- let Some(p) = info.pages.get(self.current) else { return };- if !rect.iter().all(|v| v.is_finite()) {- return;- }- // Halve before adding so even large finite coordinates cannot overflow the midpoint.- let x = rect[0] * 0.5 + rect[2] * 0.5;- let y = rect[1] * 0.5 + rect[3] * 0.5;- let [fx, fy] = p.dest_fraction(Some(x), Some(y), self.rotation);- self.goto_point = Some((self.current, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0));- }-- /// Go to a destination, a bookmark's or a link's (ISO 32000-2 §12.3.2.2): its page, scrolled- /// and zoomed as `dest` asks, as Acrobat does. `/XYZ` puts (left, top) at the window's- /// top-left at its zoom (null or 0 keeps the zoom); `/Fit`, `/FitH` and `/FitV` switch to fit- /// page, width and height with `top` or `left` at the window's edge; `/FitR` zooms so the- /// rectangle fits, centred. The `B` (content box) forms are read as the page. A null `/XYZ`- /// coordinate keeps the reader's place: the same user-space point stays at the window's- /// top-left on the new page, as Acrobat does. A point past the end of the document scrolls- /// as far as it can.- pub fn go_to_dest(&mut self, page: usize, dest: DestView, info: &DocInfo) {- // Read before the jump: it is where the reader is now.- let kept = match dest {- DestView::Xyz { left, top, .. } if left.is_none() || top.is_none() => self.place_at_corner(info),- _ => None,- };- self.go_to_page(page);- let page = self.current;- self.goto_point = None;- let Some(p) = info.pages.get(page) else { return };- let point = |x: Option<f32>, y: Option<f32>| p.dest_fraction(x, y, self.rotation);- // The window's top-left as far as pages go: its left edge is the gutter that keeps them- // clear of the floating quick-action bar, so `left` 0 shows the page's edge beside it.- let corner = vec2(SIDE, 0.0);- let (fx, fy, rel) = match dest {- DestView::Top => return,- DestView::Xyz { left, top, zoom } => {- if let Some(z) = zoom {- self.zoom = z.clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- let [kept_left, kept_top] = kept.unwrap_or([None, None]);- let [fx, fy] = point(left.or(kept_left), top.or(kept_top));- (fx, fy, corner)- }- DestView::Fit => {- self.fit = Fit::Page;- return;- }- DestView::FitH { top } => {- self.fit = Fit::Width;- let [fx, fy] = point(None, top);- (fx, fy, corner)- }- DestView::FitV { left } => {- self.fit = Fit::Height;- let [fx, fy] = point(left, None);- (fx, fy, corner)- }- DestView::FitR { rect } => {- let ([Some(ax), Some(ay)], [Some(bx), Some(by)]) = (point(Some(rect[0]), Some(rect[3])), point(Some(rect[2]), Some(rect[1]))) else {- return;- };- // The rectangle as displayed, in points (it can be turned a quarter).- let (dw, dh) = self.display_size(p);- let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh);- if w >= 1.0 && h >= 1.0 && self.viewport_w >= 1.0 && self.viewport_h >= 1.0 {- self.zoom = (self.viewport_w / (w * PT)).min(self.viewport_h / (h * PT)).clamp(0.08, 64.0);- self.fit = Fit::None;- self.zoom_anchor = None;- }- (Some((ax + bx) / 2.0), Some((ay + by) / 2.0), vec2(self.viewport_w, self.viewport_h) / 2.0)- }- };- if fx.is_some() || fy.is_some() {- self.goto_point = Some((page, fx, fy, rel));- }- }-- /// Next page (`true`) or previous page. In two-page view this moves a whole spread: the other- /// page of the spread is already on screen, so stepping to it wouldn't move the view (#70).- pub fn step_page(&mut self, forward: bool) {- let c = self.current;- let last = self.page_count.saturating_sub(1);- let (target, first) = match self.layout {- PageLayout::TwoUp => {- let first = self.spread_first(c);- let target = match (forward, self.cover && c == 0) {- (true, true) => 1,- (true, false) => first.saturating_add(2),- (false, _) if self.cover && first <= 1 => 0,- (false, _) => first.saturating_sub(2),- };- (target, first)- }- PageLayout::Single if forward => (c + 1, c),- PageLayout::Single => (c.saturating_sub(1), c),- };- // Past either end there is nowhere to go: stay put rather than re-align the view, which- // would scroll the page back to its top.- if if forward { target > last } else { first == 0 } {- return;- }- self.go_to_page(target);- }-- /// Page-editor focus and drafts belong to a document, even while another tab is active.- pub(crate) fn page_input_id(&self) -> egui::Id {- egui::Id::unique(("page-input", self.id.0))- }-- /// The idle page box and unchanged-input lookup share the same label fallback.- pub(crate) fn current_page_label(&self, label: Option<&str>) -> String {- label.filter(|l| !l.is_empty()).map(str::to_owned).unwrap_or_else(|| (self.current + 1).to_string())- }-- /// Retain the current page when `typed` exactly matches its displayed label, even if- /// another page has that label. Otherwise resolve a trimmed label (case-insensitive),- /// then a physical page number. `false` when it names no page.- pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool {- // Compare the displayed value before trimming: a label may itself contain spaces.- // Repeated labels occur in restarted sections and prefix-only ranges.- if self.current < self.page_count && self.current_page_label(labels.get(self.current).map(String::as_str)) == typed {- return true;- }- let t = typed.trim();- let page = labels- .iter()- .position(|l| !l.is_empty() && l.eq_ignore_ascii_case(t))- .or_else(|| t.parse::<usize>().ok().filter(|n| *n >= 1).map(|n| n - 1));- match page {- Some(p) if p < self.page_count => {- self.go_to_page(p);- true- }- _ => false,- }- }-- /// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).- pub fn view_history(&mut self, forward: bool) -> bool {- let has_target = if forward { !self.forward.is_empty() } else { !self.back.is_empty() };- if !has_target {- return false;- }- self.end_find_following();- let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };- let Some(page) = from.pop() else { return false };- to.push(self.current);- let page = page.min(self.page_count.saturating_sub(1));- self.goto = Some((page, 0.0));- self.current = page;- self.reset_coarse_state();- true- }-- /// Select all: every page in Organize, or every word on the current page.- pub fn select_all(&mut self) -> bool {- if self.organize {- self.selected = (0..self.page_count).collect();- // Keep the current page as the anchor for the next Shift-click.- self.select_anchor = (self.page_count > 0).then_some(self.current);- return !self.selected.is_empty();- }- // Scrolling continuously, Select All takes the whole document's text (#2639); one page at- // a time, the page shown.- // Like the page's, true once some text is selected: the pages whose text isn't read yet are- // read when the selection is copied.- if self.continuous && self.page_count > 1 {- self.selection = None;- self.all_text = true;- return self.selected_text().is_some();- }- self.all_text = false;- let page = self.current;- let Some(t) = self.texts.get(&page) else { return false };- if t.glyphs.is_empty() {- return false;- }- self.selection = Some(Selection::run(page, 0, t.glyphs.len() - 1));- true- }-- /// Pages whose text [`DocView::whole_text`] still needs: not read yet, nor failed.- pub(crate) fn pages_without_text(&self) -> Vec<usize> {- (0..self.page_count).filter(|p| !self.texts.contains_key(p) && !self.text_failed.contains(p)).collect()- }-- /// The whole document's text in page order, one page after another on new lines, from the- /// pages' text read so far and `more` (pages read for this, keyed by page).- pub(crate) fn whole_text(&self, more: &HashMap<usize, Arc<PageText>>) -> String {- let mut out = String::new();- for p in 0..self.page_count {- let Some(t) = self.texts.get(&p).or_else(|| more.get(&p)) else { continue };- let text = t.text_of(0..t.glyphs.len());- if text.is_empty() {- continue;- }- if !out.is_empty() {- out.push('\n');- }- out.push_str(&text);- }- out- }-- /// 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();- }-- /// Full screen, as Acrobat's Full Screen Mode (#379, #1459): one page at a time (or one- /// spread, when two-page view was on: #1353), fitted to the screen, from the current page.- /// The display it replaces is kept for [`Self::leave_presentation`]. A no-op while presenting.- pub fn enter_presentation(&mut self) {- 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.goto = Some((self.current, 0.0));- }-- /// 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.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));- }-- /// 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,- })- }-- /// Whether the view is in full screen's one-page-at-a-time display.- pub fn presenting(&self) -> bool {- self.presentation.is_some()- }-- /// 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.- 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();- }- }-- /// Whether the cover page setting applies: only two-page view has a cover page.- pub fn cover_applies(&self) -> bool {- self.layout == PageLayout::TwoUp- }-- /// One wheel event in a non-continuous view, where the wheel turns pages or spreads (the- /// rules are in `wheel_pager`): `dy` is its vertical delta (negative scrolls down) and `now`- /// is egui time. With `can_turn` false the gesture is followed but the page stays. Returns- /// whether the page turned.- pub fn single_page_wheel(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- let Some(forward) = self.wheel.feed(unit, dy, phase, now, can_turn) else { return false };- let before = self.current;- self.step_page(forward);- self.current != before- }-- /// One wheel event in a non-continuous view whose page is taller than the window, where the- /// wheel pans (#1924). Once the view is at the bottom (top) edge, scrolling on turns to the- /// next (previous) page, which shows its top (bottom). A smooth gesture that panned the page- /// has to end first (see `WheelPager::feed_edge`). `can_turn` is false when something else- /// owns the wheel. Returns whether the page turned.- pub fn single_page_wheel_edge(&mut self, unit: egui::MouseWheelUnit, dy: f32, phase: egui::TouchPhase, now: f64, can_turn: bool) -> bool {- if self.continuous {- return false;- }- // Only an up-to-date view counts: the page drawn is the shown one, with no jump pending.- let edge = self.goto.is_none()- && self.goto_point.is_none()- && self.single_edges.is_some_and(|(page, top, bottom)| page == self.current && if dy < 0.0 { bottom } else { top });- let Some(forward) = self.wheel.feed_edge(unit, dy, phase, now, can_turn && edge) else { return false };- let before = self.current;- self.step_page(forward);- if self.current == before {- return false;- }- if !forward {- // Going back lands on the bottom of the previous page.- self.goto = Some((self.current, 1.0));- }- self.single_edges = None;- true- }-- /// Displayed page size in points for this view rotation.- 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.- 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());- }- }-- /// 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)- }-- /// 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;- }- // 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 =- 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)),- }- }-- /// 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.- 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);- }- }-- /// 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;- }- 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) {- 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();- if !self.last_queue.is_empty() {- pool.set_queue(Vec::new());- self.last_queue.clear();- }- // 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() {}- }- }-- 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.- 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);- 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);- 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);- }- 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;- }- 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_BYTES || 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));- 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_BYTES {- 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.- 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:- /// 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) {- 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 {- keep.insert(s.page);- }- if let Some(f) = self.find.as_ref() {- keep.extend(f.matches.iter().map(|(p, _)| *p));- }- 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));- keep.extend(rest.into_iter().take(MAX_CACHED_TEXT_PAGES));- 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());- if queue != self.last_queue {- 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));- }- }-- /// 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) {- 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(self.receive_result(ctx, 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;- }- }- }-- 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();- 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.- 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 (cache, limit) = if thumb { (&mut self.thumbs, THUMB_BYTES) } else { (&mut self.pages, PAGE_BYTES) };- 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 {- let Some(page) = cache.keys().copied().filter(|p| !on_screen(p)).max_by_key(|p| p.abs_diff(self.current)) else { break };- if let Some(old) = cache.remove(&page) {- retained = retained.saturating_sub(texture_bytes(&old.tex));- }- }- visible || bytes <= limit.saturating_sub(retained)- }- }-- /// 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], ….- fn spread_first(&self, c: usize) -> usize {- if self.cover { c.saturating_sub((c + 1) % 2) } else { c - c % 2 }- }-- 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.- 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).- 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- }-- 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- }-- /// 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 });- }- }- }- }-- /// The hover popup for an annotation. Replies and Fill & Sign marks (typed text, checks, signatures)- /// show none: they are page content being edited, not comments.- /// If `display_author_no_comment` is false, highlighted text markup with no comment body shows no popup.- fn annotation_hover_text(a: &pdfcraft_render::Annotation) -> Option<String> {- if a.is_reply() || a.fill_sign {- return None;- }- let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());- let body = a.contents.clone().unwrap_or_default();- Some(if body.is_empty() { who } else { format!("{who}\n{body}") })- }-- /// 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).- 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))- }-- /// The request tag for a raster at `scale`: equal tags mean the same scale (to 1/65536).- fn scale_tag(scale: f32) -> u64 {- (f64::from(scale) * 65536.0).round() as u64- }-- /// The scale of a raster tagged by [`scale_tag`].- 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.- 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.- 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;-- /// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there- /// maps texel for texel onto the screen.- fn snap_to_pixels(r: Rect, ppp: f32) -> Rect {- let snap = |v: f32| (v * ppp).round() / ppp;- Rect::from_min_size(pos2(snap(r.min.x), snap(r.min.y)), r.size())- }-- /// Maps between a page's coordinate spaces and the screen, including view rotation.- ///- /// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);- /// normalised page coordinates `(u, v)` are view space divided by the page size. The view- /// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.- #[derive(Clone, Copy)]- pub struct PageXform {- /// The page's rectangle on screen (already rotated, so width/height may be swapped).- pub rect: Rect,- pub rot: u16,- /// Page size in view space (unrotated by the view).- pub pw: f32,- pub ph: f32,- }-- impl PageXform {- /// Screen pixels per page point. The view's rotation swaps the rectangle's sides, so a page- /// turned a quarter shows its width down the screen.- pub(crate) fn zoom(&self) -> f32 {- let across = if self.rot % 180 == 90 { self.rect.height() } else { self.rect.width() };- across / self.pw.max(1.0)- }-- /// Draw an image in the PDF user-space `rect` as a custom stamp's appearance draws it: turned- /// back by `turn` (the page /Rotate it was placed for), so with the page's own rotation it- /// reads upright as displayed.- pub(crate) fn paint_user_image(- &self,- painter: &egui::Painter,- tex: egui::TextureId,- p: &pdfcraft_render::PageInfo,- rect: [f64; 4],- turn: i64,- color: Color32,- ) {- let mut mesh = egui::Mesh::with_texture(tex);- let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);- let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) };- let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect);- for (u, v) in [(0.0_f32, 0.0_f32), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {- // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space.- let (dx, dy) = (f64::from(u) * shown_w, f64::from(1.0 - v) * shown_h);- let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f);- let q = p.user_to_view(x as f32, y as f32);- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(q[0] / self.pw, q[1] / self.ph), uv: pos2(u, v), color });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }- pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {- let (a, b) = match self.rot {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- };- pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())- }-- pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {- let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));- match self.rot {- 90 => (b, 1.0 - a),- 180 => (1.0 - a, 1.0 - b),- 270 => (1.0 - b, a),- _ => (a, b),- }- }-- /// Screen point → view space (points).- pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {- let (u, v) = self.screen_to_norm(p);- (u * self.pw, v * self.ph)- }-- /// A view-space rect [x0, y0, x1, y1] → screen rect.- pub fn view_rect(&self, g: [f32; 4]) -> Rect {- Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))- }-- /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.- pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {- let p = &info.pages[page];- let [cx0, cy0, cx1, cy1] = p.crop;- let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));- let norm = |x: f32, y: f32| -> (f32, f32) {- let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);- match p.rotation {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- }- };- let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));- Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))- }-- /// A PDF user-space rect with f64 precision (crop box, document `/Rotate`) -> screen rect.- pub fn user_rect_f64(&self, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {- let p = &info.pages[page];- let [cx0, cy0, cx1, cy1] = p.crop.map(f64::from);- let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));- let norm = |x: f64, y: f64| -> (f64, f64) {- let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);- match p.rotation {- 90 => (1.0 - v, u),- 180 => (1.0 - u, 1.0 - v),- 270 => (v, 1.0 - u),- _ => (u, v),- }- };- let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));- Rect::from_two_pos(self.norm_to_screen(a.0 as f32, a.1 as f32), self.norm_to_screen(b.0 as f32, b.1 as f32))- }-- /// This transform resized to a raster of `px` device pixels (width, height before the view- /// rotation), so each of its texels covers one screen pixel. The rectangle's corner must- /// already be on a whole pixel ([`snap_to_pixels`]).- fn texel_aligned(&self, px: [usize; 2], ppp: f32) -> PageXform {- let (w, h) = (px[0] as f32 / ppp, px[1] as f32 / ppp);- let size = if self.rot % 180 == 90 { vec2(h, w) } else { vec2(w, h) };- PageXform { rect: Rect::from_min_size(self.rect.min, size), ..*self }- }-- /// Draw a texture covering the normalised page region, rotated with the view.- pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {- let mut mesh = egui::Mesh::with_texture(tex);- let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];- for (u, v, tu, tv) in corners {- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }-- /// Draw a sub-region of a texture covering the normalised page region.- #[allow(clippy::too_many_arguments)]- pub fn paint_image_region(- &self,- painter: &egui::Painter,- tex: egui::TextureId,- pu0: f32,- pv0: f32,- pu1: f32,- pv1: f32,- tu0: f32,- tv0: f32,- tu1: f32,- tv1: f32,- ) {- let mut mesh = egui::Mesh::with_texture(tex);- let corners = [(pu0, pv0, tu0, tv0), (pu1, pv0, tu1, tv0), (pu1, pv1, tu1, tv1), (pu0, pv1, tu0, tv1)];- for (u, v, tu, tv) in corners {- mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- painter.add(egui::Shape::mesh(mesh));- }-- /// Draw a sub-rectangle of a whole-page raster texture, where UV space matches page normalized space.- pub fn paint_page_texture_rect(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {- self.paint_image_region(painter, tex, u0, v0, u1, v1, u0, v0, u1, v1);- }- }-- #[allow(clippy::too_many_arguments)]- fn paint_image_suppressed(- xf: &PageXform,- painter: &egui::Painter,- tex: egui::TextureId,- u0: f32,- v0: f32,- u1: f32,- v1: f32,- suppress: Option<[f32; 4]>,- is_full_page_tex: bool,- ) {- let Some([su0, sv0, su1, sv1]) = suppress else {- if is_full_page_tex {- xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1);- } else {- xf.paint_image(painter, tex, u0, v0, u1, v1);- }- return;- };- let iu0 = u0.max(su0);- let iu1 = u1.min(su1);- let iv0 = v0.max(sv0);- let iv1 = v1.min(sv1);- if iu0 >= iu1 || iv0 >= iv1 {- if is_full_page_tex {- xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1);- } else {- xf.paint_image(painter, tex, u0, v0, u1, v1);- }- return;- }- let map_uv = |pu: f32, pv: f32| -> (f32, f32) {- if is_full_page_tex {- (pu, pv)- } else {- let du = (u1 - u0).max(1e-6);- let dv = (v1 - v0).max(1e-6);- ((pu - u0) / du, (pv - v0) / dv)- }- };- let draw_strip = |pu0: f32, pv0: f32, pu1: f32, pv1: f32| {- if pu1 <= pu0 || pv1 <= pv0 {- return;- }- let (tu0, tv0) = map_uv(pu0, pv0);- let (tu1, tv1) = map_uv(pu1, pv1);- xf.paint_image_region(painter, tex, pu0, pv0, pu1, pv1, tu0, tv0, tu1, tv1);- };-- if iv0 > v0 {- draw_strip(u0, v0, u1, iv0);- }- if v1 > iv1 {- draw_strip(u0, iv1, u1, v1);- }- if iu0 > u0 {- draw_strip(u0, iv0, iu0, iv1);- }- if u1 > iu1 {- draw_strip(iu1, iv0, u1, iv1);- }- }-- pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {- use egui::{Key, KeyboardShortcut, Modifiers};- if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {- view.open_find();- }- let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);- let pressed = |s: KeyboardShortcut| ctx.input_mut(|i| i.consume_shortcut(&s));- // ⌘G / ⇧⌘G step through the matches from the find field too, as in Acrobat and Preview- // (#2669): ahead of the text-input check, but only while there is a search to step.- if view.find.is_some() {- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {- view.find_step(false);- } else if pressed(cmd(Key::G)) {- view.find_step(true);- }- }- // A focused check box or radio button holds egui's keyboard focus only for Space, and a- // radio button for the arrows that move within its group: the other page keys still work.- let form_box = view.forms.keys.filter(|(id, _)| ctx.memory(|m| m.focused()) == Some(*id));- if ctx.egui_wants_keyboard_input() && form_box.is_none() {- return;- }- let arrows = !form_box.is_some_and(|(_, radio)| radio);- // Rotation first: egui matches ⌘+ loosely with respect to Shift.- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus))- || pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Equals))- {- view.rotate_view(true);- }- if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::Minus)) {- view.rotate_view(false);- }- // In the page grid ⌘+ / ⌘− / ⌘0 size its pages instead (looking is always allowed).- let (zoom_in, zoom_out, zoom_reset) = (pressed(cmd(Key::Plus)) || pressed(cmd(Key::Equals)), pressed(cmd(Key::Minus)), pressed(cmd(Key::Num0)));- if view.organize {- if zoom_in {- view.grid_zoom_request = Some(view.grid_zoom * GRID_ZOOM_STEP);- }- if zoom_out {- view.grid_zoom_request = Some(view.grid_zoom / GRID_ZOOM_STEP);- }- if zoom_reset {- view.grid_zoom_request = Some(1.0);- }- } else {- if zoom_in {- view.zoom_step(true);- }- if zoom_out {- view.zoom_step(false);- }- if zoom_reset {- view.fit = Fit::Page;- view.goto = Some((view.current, 0.0));- }- }- if pressed(cmd(Key::Num1)) {- view.set_zoom(1.0);- }- if pressed(cmd(Key::Num2)) {- view.fit = Fit::Width;- view.goto = Some((view.current, 0.0));- }- if pressed(cmd(Key::OpenBracket)) {- view.view_history(false);- }- if pressed(cmd(Key::CloseBracket)) {- view.view_history(true);- }- let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));- // An open menu takes Escape first and closes; the selection stays for the next one (#3535).- if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {- if view.camera.is_some() || view.camera_done.is_some() {- view.pending_action = Some(ViewAction::CancelCamera);- } else if view.selection.is_some() || view.all_text {- view.selection = None;- view.all_text = false;- } else {- view.find = None;- }- }- if key(Key::Home) {- view.go_to_page(0);- }- if key(Key::End) {- view.go_to_page(usize::MAX);- }- // Full screen: Space and Enter go forward a page and Backspace back, as in Acrobat (the- // arrows and Page Up / Page Down already turn pages where nothing scrolls, below).- if view.presentation.is_some() {- if key(Key::Space) || key(Key::Enter) {- view.step_page(true);- }- if key(Key::Backspace) {- view.step_page(false);- }- }- // As in Acrobat: → / ← go to the next / previous page in every layout (#185), and so do- // ⌘Page Down / ⌘Page Up, or plain Page Down / Page Up in single-page view.- let command = ctx.input(|i| i.modifiers.command);- let scrolls = view.continuous;- if key(Key::ArrowRight) || (key(Key::PageDown) && (command || !scrolls)) {- view.step_page(true);- }- if key(Key::ArrowLeft) || (key(Key::PageUp) && (command || !scrolls)) {- view.step_page(false);- }- // ↓ / ↑ scroll a line, and Page Down / Page Up a screen where the pages scroll. In- // single-page view, ↓ / ↑ turn the page once there is nothing left to scroll that way, as- // the wheel does (#273): always on a page that fits.- // The Scroll speed preference sets how far ↓ / ↑ go as well as the wheel (#985); Page Down /- // Page Up keep a screen.- if !command {- let line = KEY_SCROLL_LINE * speed.factor();- let screen = (view.viewport_h - KEY_SCROLL_LINE).max(KEY_SCROLL_LINE);- let steps = [(Key::ArrowDown, line), (Key::ArrowUp, -line), (Key::PageDown, screen), (Key::PageUp, -screen)];- for (k, by) in steps {- let arrow = matches!(k, Key::ArrowDown | Key::ArrowUp);- if !key(k) || !(scrolls || arrow) {- continue;- }- let forward = k == Key::ArrowDown;- // Only an up-to-date view counts: the page drawn is the current one, with no jump pending.- let at_end = !scrolls- && view.goto.is_none()- && view.single_edges.is_some_and(|(page, top, bottom)| page == view.current && if forward { bottom } else { top });- if at_end {- let before = view.current;- view.step_page(forward);- if !forward && view.current != before {- // Going back up lands on the bottom of the previous page.- view.goto = Some((view.current, 1.0));- }- view.single_edges = None;- } else {- view.key_scroll += by;- }- }-- }- }-- /// How far ↓ / ↑ scroll at Normal speed (Scroll speed halves or doubles it). Page Down / Page Up- /// keep this much of the previous screen in view.- const KEY_SCROLL_LINE: f32 = 40.0;- /// Suppression window for egui's eased copy of point input.- ///- /// egui 0.36.2 drains `WheelState::after_events` tail deltas by 90% per 0.1 s.- const SUPPRESS_SECS: f64 = 0.25;- /// Short rolling extension while egui still has an unprocessed wheel tail.- const SUPPRESS_TAIL_SECS: f64 = 0.05;-- // Keep the viewer's scroll identity tied to the document instead of its parent UI.- fn page_scroll<R>(- ui: &mut egui::Ui,- scroll: egui::ScrollArea,- id: egui::Id,- draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,- ) -> egui::scroll_area::ScrollAreaOutput<R> {- ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner--}----/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a--/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.--pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {-- let t = Tokens::get(ui.ctx());-- // Keyboard scrolling applies to this frame's page view only, never later.-- let key_scroll = std::mem::take(&mut app.views[index].key_scroll);-- if key_scroll != 0.0 {-- app.views[index].end_find_following();-- }-- // The Search panel closed: its search moves to the find bar.-- let search_open = app.right == Some(crate::RightPanel::Search);-- if let Some(f) = app.views[index].find.as_mut()-- && f.in_panel-- && !search_open-- {-- f.in_panel = false;-- }-- // The snapshot notice bar's Close was clicked: close here, where no document borrow is-- // held. The tab is looked up by id: indices may have shifted since the click, and the-- // flag rides its own view, so a stale flag can never close the wrong tab.-- let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));-- if let Some(i) = pending {-- app.views[i].close_requested = false;-- if app.has_unsaved_work(i) {-- app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));-- } else {-- app.close_tab(i);-- }-- return;-- }-- let Some(doc) = app.session.get(app.views[index].id) else { return };-- let info = &doc.info;-- let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {-- let [r, g, b] = p.background;-- Color32::from_rgb(r, g, b)-- });-- if info.pages.is_empty() {-- app.views[index].auto_scroll.cancel();-- ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));-- return;-- }-- // The print dialog queues its own rasters later in the frame. Closing it drops them.-- if app.dialog != Some(crate::Dialog::Print) {-- app.views[index].print_pages.clear();-- }-- // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.-- let preparing = app.is_preparing();-- // Prepare a form ▸ Calculation order: the order's steps and links on the page.-- let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;-- // Edit a PDF: added text and images can be selected, moved and edited.-- let editing_content =-- (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);-- let text_style = app.text_style.clone();-- let show_secured_notice = app.show_secured_notice;- // Asking means opening the system clipboard (and decoding any image on it), so it's asked- // once when a right-click opens a menu, not on every frame.- let can_paste_key = egui::Id::unique("can-paste-image");- let can_paste_image = if ui.input(|i| i.pointer.secondary_pressed()) {- let can = app.can_paste_image();- ui.data_mut(|d| d.insert_temp(can_paste_key, can));- can- } else {- ui.data(|d| d.get_temp(can_paste_key)).unwrap_or(false)- };-- let view = &mut app.views[index];-- // Opened without the owner password and something is restricted. The notice says so unless-- // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸-- // Security, stay as they are.-- let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));-- let repaired = !doc.repair_log().is_empty();-- match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {-- #[cfg(not(target_arch = "wasm32"))]-- Some(Notice::Reload) => app.watch.reload_request = Some(view.id),-- #[cfg(target_arch = "wasm32")]-- Some(Notice::Reload) => {}-- Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),-- Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),-- Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),-- // Flags the view: the tab closes at the top of the next frame, where no document-- // borrow is held.-- Some(Notice::Close) => {-- if let Some(view) = app.views.get_mut(index) {-- view.close_requested = true;-- }-- }-- Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),-- Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,-- Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),-- // Back on in Preferences ▸ General.-- Some(Notice::HideSecured) => app.show_secured_notice = false,-- None => {}-- }-- // No dialog, close prompt or palette over the page: only then does page input count.-- let modal = app.modal_open();-- let unobstructed = !modal && !app.palette_open;-- let organize_zoom = app.organize_zoom;-- let view = &mut app.views[index];-- if view.organize {-- // One remembered grid size for every document, kept in the settings.-- view.set_grid_zoom(organize_zoom);-- organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);-- app.organize_zoom = view.grid_zoom();-- return;-- }---- let avail = ui.available_rect_before_wrap();-- view.viewport_w = avail.width();-- view.viewport_h = avail.height();-- let old_zoom = view.zoom;-- view.fit_zoom(info);-- if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {-- let prev_viewport = view.viewport_screen;-- let top_y = prev_viewport.min.y;-- let anchor = view-- .screen_rects-- .iter()-- .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)-- .map(|(p, r)| {-- let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };-- (*p, fy, 0.0f32)-- })-- .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))-- .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));-- if let Some((page, fy, rel_y)) = anchor {-- view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));-- } else {-- view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));-- }-- }---- // Pinch / ctrl+scroll zoom, anchored on the current page.-- let zoom_delta = crate::motion::zoom_delta(ui.ctx());-- // Exclude the previous frame's scrollbar tracks from gesture activation.-- let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };-- let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);-- // Full screen: a click on the document goes forward a page and a shift-click back, as in-- // Acrobat, unless the click did something else (a link, a word selected). Decided below,-- // once the pages have had the click.-- let present_click =-- view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;-- // Shift as held now, or as the click's own event carried it (a synthetic click).-- let present_back = present_click-- && ui.input(|i| {-- i.modifiers.shift-- || i.events.iter().any(|e| {-- matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)-- })-- });-- if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {-- let z = view.zoom * zoom_delta;-- match zoom_anchor(ui) {-- Some(p) => view.zoom_at(z, p),-- None => view.set_zoom(z),-- }-- }-- view.viewport_screen = avail;-- let auto_delta = if unobstructed {-- view.auto_scroll.update(ui, avail, false)-- } else {-- view.auto_scroll.cancel();-- Vec2::ZERO-- };---- // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view-- // that way, so a point beyond what is shown can be reached without letting go of the tool.-- let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {-- let (pointer, dt) = drawing_edge_pointer(ui);-- crate::autoscroll::edge_scroll(pointer, avail, dt)-- } else {-- Vec2::ZERO-- };-- if edge_delta != Vec2::ZERO {-- ui.ctx().request_repaint();-- }---- let content_w = view.content_width(info, avail.width());-- let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());-- // When not scrolling continuously, only one row is shown at a time: the current page, or the-- // current two-page spread (with the cover rule). These indices drive paging, which pages are-- // drawn, and the content height (#752). Empty for a document with no pages.-- let shown_row = |view: &DocView| -> Vec<usize> {-- if rects.is_empty() {-- return Vec::new();-- }-- let last = rects.len() - 1;-- let cur = view.current.min(last);-- match view.layout {-- PageLayout::Single => vec![cur],-- PageLayout::TwoUp if view.cover && cur == 0 => vec![0],-- PageLayout::TwoUp => {-- let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };-- if first < last { vec![first, first + 1] } else { vec![first] }-- }-- }-- };-- let row = shown_row(view);-- let middle_gesture = view.auto_scroll.blocks_input();-- // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns-- // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on-- // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with-- // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow-- // keys. Runs before `visible_pages` so the frame that turns the page draws it.-- let mut single_paging = false;-- let mut edge_turned = false;-- if !view.continuous {-- // The row's bounding box on screen (one page, or a two-page spread).-- let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);-- // Within a point, so layout rounding can't stop a fitting page from turning.-- let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);-- let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);-- single_paging = can_turn && fits;-- // Every wheel event goes to the pager, so it follows each trackpad touch to its end-- // even while the page can't turn.-- ui.input(|i| {-- for e in &i.events {-- if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {-- // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.-- let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };-- if fits {-- view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);-- } else {-- edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);-- }-- }-- }-- });-- if single_paging {-- // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways-- // part, as `ScrollArea` itself handles each axis.-- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);-- }-- }-- // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,-- // smoothed base and adds only the accelerated surplus. While point suppression is active,-- // reconstruct line and page input here so current coarse events survive without exposing an-- // older eased tail.-- let now = ui.input(|i| i.time);-- let input = if ui.rect_contains_pointer(avail) {-- // Match the line distance used by egui's other scroll areas.-- let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);-- let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };-- ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))-- } else {-- crate::wheel_boost::FrameInput::default()-- };-- let mut precise_scroll = input.precise;-- let mut line_base = input.line;-- let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);-- let has_page = input.page != Vec2::ZERO;-- if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {-- view.precise_scroll_until = now + SUPPRESS_SECS;-- }-- if edge_turned {-- // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not-- // scroll the page just shown away from its top (or bottom).-- view.precise_scroll_until = now + 0.25;- view.fling.stop();-- }- // Paging owns the vertical axis in single-page view; leave it to the pager.- // The rest of a gesture that turned the page is swallowed too, or it would pan the new page- // away from the edge it was shown at.-- let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());-- if paging_owns_vertical {-- precise_scroll.y = 0.0;-- line_base.y = 0.0;-- boost_extra.y = 0.0;-- }-- // egui smooths a Point event that moved at least 8 points, keeping part of it for later-- // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,-- // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held-- // point input measured 33 points for a 30-point event). Keep hiding the eased copy until-- // egui says the action is over, then forget the suppression.-- let scrolling = ui.input(|i| i.is_scrolling());-- if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {-- if scrolling {-- // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace-- // avoids a delayed duplicate without prolonging suppression after the tail is gone.-- view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);-- }-- ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);-- // The point path suppresses every eased wheel delta. Restore the line base through the-- // same un-eased path as its surplus; paging-owned axes were cleared above.-- boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);-- if has_page {-- // Page units normally stay on egui's viewport-sized path. During suppression only,-- // reproduce the current event directly so an older hidden tail stays hidden.-- let page_scale = ui.input(|i| i.viewport_rect().height());-- let mut page_delta =-- if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };-- if paging_owns_vertical {-- page_delta.y = 0.0;-- }-- boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);-- }-- } else {-- precise_scroll = Vec2::ZERO;-- // Selection handling below uses zero to distinguish an inactive window. Clearing a past-- // deadline also keeps a later line/page action from being mistaken for the old tail.-- view.precise_scroll_until = 0.0;-- }-- if has_page && paging_owns_vertical {-- // Page input belongs to egui on the free axis; the pager still owns vertical motion.-- ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);-- }-- // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a-- // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or-- // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.-- // Asked of the preference, not of egui's animation time, which test harnesses zero.-- let animates = app.animation_effects.animates(app.motion.reduced);-- let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;-- let over_page = ui.rect_contains_pointer(avail);-- ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));-- let interrupted = glide_interrupted(ui);-- if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {-- view.fling.stop();-- }-- let glide = view.fling.step(now);-- if view.fling.gliding() {-- ui.ctx().request_repaint();-- }-- // Any reader-owned motion ends automatic search following, even when it stays on the same-- // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the-- // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so-- // its programmatic scroll is never mistaken for a reader action.-- let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;-- if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {-- view.end_find_following();-- }-- // The wheel may have turned the page above: draw the row it turned to. Measured from the old-- // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.-- let row = shown_row(view);-- let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };-- let (y_shift, content_h) = if view.continuous {-- (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))-- } else {-- // Only the current row scrolls into view; the content is its bounding box plus margins.-- match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {-- Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),-- None => (0.0, 0.0),-- }-- };---- let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {-- drag: if middle_gesture {-- egui::scroll_area::DragScroll::Never-- } else if app.quick_tool == QuickTool::Hand {-- egui::scroll_area::DragScroll::Always-- } else {-- egui::scroll_area::DragScroll::OnTouch-- },-- ..Default::default()-- });-- // Each document keeps its own scroll position when switching tabs (#189).-- scroll = scroll.id_salt(("page-view", view.id));- // When a page jump or programmatic reposition occurs, or in non-continuous page display- // where single-page wheel turns jump to the page edge, disable animation so egui's- // queued target does not overwrite or ease the jump. For continuous page scrolling,- // animate if motion effects are enabled.- let has_jump = !view.shown- || edge_turned- || view.goto.is_some()- || view.goto_point.is_some()- || view.zoom_anchor.is_some()- || view.sync_scroll.is_some()- || (app.quick_tool == QuickTool::Hand && !middle_gesture && view.page_widget.is_some_and(|id| ui.ctx().is_being_dragged(id)));- scroll = scroll.animated(view.continuous && animates && !has_jump);- // Every scroll here asks for no animation. An animated area would still queue a zero-length- // offset target for the next frame, which overwrites the jump a page turn just set.- scroll = scroll.animated(false);-- // A newly opened document starts at the top. eframe saves egui's memory with the settings-- // and document ids start again at 1 every launch, so the offset stored under this id can be-- // where an earlier session left another document.-- if !std::mem::replace(&mut view.shown, true) {-- scroll = scroll.scroll_offset(Vec2::ZERO);-- }-- // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer-- // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the-- // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a-- // click, the page catches up with all the pointer has moved since the press. A jump asked for-- // below still wins.-- if app.quick_tool == QuickTool::Hand-- && !middle_gesture-- && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))-- {-- let moved = if ui.ctx().drag_started_id() == Some(id) {-- ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)-- } else {-- ui.input(|i| i.pointer.delta())-- };-- if moved != Vec2::ZERO {-- view.end_find_following();-- }-- // Within the content, as egui keeps it: past an end the page would show there for a-- // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.-- let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));-- scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));-- }-- if let Some(v) = view.sync_scroll.take() {-- scroll = scroll.scroll_offset(v);-- }-- if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {-- let r = rects[page.min(rects.len() - 1)];-- let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());-- scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));-- } else if let Some((page, frac)) = view.goto.take() {-- let page = page.min(rects.len() - 1);-- let r = rects[page];-- // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()-- // too high for a frame and then hopped into place. (`avail` is the viewport, as the-- // scroll bars float.)-- let max_y = (content_h - avail.height()).max(0.0);-- scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));-- // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off-- // to one side. A page already shown whole, or one filling the window's width, keeps the-- // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a-- // page that fits is centred, and a wider one scrolled just far enough to fill the window.-- // The page counts with its side gutters, which keep its edge clear of the floating-- // quick-action bar as the layout does.-- let (x, w) = (view.last_scroll.x, avail.width());-- let (left, right) = (r.left() - SIDE, r.right() + SIDE);-- let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };-- if (target - x).abs() > 0.5 {-- scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));-- }-- }-- let ppp = ui.ctx().pixels_per_point();-- let scale = view.render_scale(ppp);-- let tag = scale_tag(scale);-- // Hold sharp re-renders while the zoom is still moving: a new scale every frame would-- // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD-- // plot with ~1000 images renders for seconds) the sharp raster never arrives and the-- // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the-- // sharp request goes out once the zoom settles.-- let now_scale = ui.input(|i| i.time);-- if (scale - view.last_scale).abs() > f32::EPSILON {-- view.last_scale = scale;-- view.sharp_hold_until = now_scale + 0.35;-- ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));-- }-- let sharp_held = now_scale < view.sharp_hold_until;-- view.current_scale_tag = tag;-- let hand = app.quick_tool == QuickTool::Hand;-- let tool = app.quick_tool;-- // Text selection runs for the Select tool and for the markup tools (highlight…).-- let selects_text = match tool {-- QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,-- QuickTool::Select => !preparing,-- QuickTool::Redact | QuickTool::ColumnSelect => true,-- QuickTool::Hand-- | QuickTool::Measure(_)-- | QuickTool::Crop-- | QuickTool::EnhanceCamera-- | QuickTool::Fill(_)-- | QuickTool::Field(_)-- | QuickTool::AddText-- | QuickTool::EditText-- | QuickTool::Stamp(_)-- | QuickTool::CustomStamp(_)-- | QuickTool::Link-- | QuickTool::SignArea { .. }-- | QuickTool::MarqueeZoom-- | QuickTool::Snapshot => false,-- };-- let prefs = &app.comment_prefs;-- let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);-- let units = app.units;-- let allowed = doc.allows_annotation();-- let can_copy = doc.allows_copying();-- let mut copy_selected = false;-- let comments_hidden = doc.comments_hidden();-- let form = doc.form.clone();-- let generation = doc.edit_generation();-- let can_fill = doc.allows_form_filling();-- let can_crop = doc.allows_assembly();-- let mut open_boxes = false;-- let signature = app.signature.clone();-- let initials = app.initials.clone();-- let mut open_initials = false;-- let author = app.comment_prefs.author.clone();-- let today = app.session.today();-- // In Preferences ▸ Date format, or why it can't be stamped into the PDF.-- let date_text = crate::date_text_for_pdf(&app.session);-- let mut refused: Option<String> = None;-- let by_line = app.session.stamp_by_line(&author);-- let mut stamp_placed = false;-- let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;-- let custom_stamp = match app.quick_tool {-- QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),-- _ => None,-- };-- let mut open_signature = false;-- let mut hover_text: Option<(Pos2, String)> = None;-- let mut badge_hover: Option<(Pos2, String)> = None;-- let mut clicked_link: Option<LinkTarget> = None;-- let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;-- let mut canvas_action: Option<comments::CanvasAction> = None;- let mut page_action: Option<PageMenuAction> = None;-- let mut field_menu: Option<FieldMenu> = None;-- let mut open_props: Option<(usize, usize)> = None;-- let mut field_props = false;-- let mut field_placed = false;-- let mut open_table: Option<(usize, [f64; 4])> = None;-- // The table being set up in its window, shown on its own document's page.-- let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));-- let can_modify = doc.allows_modification();-- if preparing {-- crate::prepare::after_refresh(view, &form);-- } else {-- view.prepare.selected = None;-- }-- view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());-- view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);-- let added = if editing_content { doc.added().to_vec() } else { Vec::new() };-- let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };-- if editing_content {-- crate::content_ui::after_refresh(view, &added);-- } else {-- view.content.selected = None;-- }-- view.move_background.prepare(ui.ctx(), doc, &view.content, scale);---- // A destination's position (bookmarks, links) refines `goto`: its point at the window's-- // top-left, or the centre of a /FitR rectangle at the window's centre.-- if let Some((page, fx, fy, rel)) = view.goto_point.take() {-- let r = rects[page.min(rects.len() - 1)];-- // Within the content, so an unreachable point never shows a frame scrolled past the end.-- let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));-- if let Some(fx) = fx {-- scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));-- }-- if let Some(fy) = fy {-- scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));-- }-- }-- let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);-- let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {-- // egui's drag responses accept every pointer button. Keep a wheel gesture from also-- // selecting text, drawing a mark, or panning with the Hand tool.-- if middle_gesture {-- let opacity = ui.opacity();-- ui.disable();-- // Only interactions pause; the document must keep its original colours.-- ui.set_opacity(opacity);-- }-- // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide-- // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y-- // moves the content down. All scroll without easing, unlike egui's wheel default.-- // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution-- // until after the text widgets when a selection owns that drag.-- let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };-- let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;-- if delta != Vec2::ZERO && delta.is_finite() {- let anim = if animates && key_scroll != 0.0 { ui.style().scroll_animation } else { egui::style::ScrollAnimation::none() };- ui.scroll_with_delta_animation(delta, anim);- ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());-- }-- let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());-- view.page_widget = Some(resp.id);-- // A drag lasts only while egui reports it, so the mark can't outlive one.-- if !resp.dragged_by(egui::PointerButton::Primary) {-- view.selection_drag = false;-- }-- // The Hand tool pans by this widget's drag, before the pages are laid out (above).-- if hand {-- if resp.dragged() {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);-- } else if resp.hovered() {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);-- }-- }-- let origin = resp_rect.min - vec2(0.0, y_shift);-- let painter = ui.painter();-- let visible = viewport.translate(resp_rect.min.to_vec2());-- let mut wanted = Vec::new();-- let mut visible_now = Vec::new();-- view.screen_rects.clear();-- view.screen_xforms.clear();- for &i in &visible_pages {- let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);- if r.intersects(visible) {- view.screen_rects.push((i, r));- view.screen_xforms- .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));- }- }-- // Visible heights (points) closer than this are equal: one page size can meet the-- // viewport a fraction of a point differently once the scroll offset is applied.-- const TIE: f32 = 0.5;-- let mut current = view.current;-- let mut best_overlap = -1.0f32;-- let mut current_overlap = -1.0f32;-- let mut current_height = f32::INFINITY;-- // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),-- // or a press they hold. The page modules read it rather than egui's raw pointer state.-- let ptr = PagePointer::read(ui, &resp, modal);-- let pointer = ptr.pos;-- // A press on a page makes it the current one (as in Acrobat), so a page command with-- // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page-- // gone to earlier that still shows whole beside it.-- let pressed = unobstructed && ptr.pressed().is_some();-- let mut pressed_page = None;-- if resp.secondary_clicked() {-- // Set again below when the right-click lands on a link.-- view.links.context = None;- let mut over_image = false;- if tool == QuickTool::EditText {- let pointer_pos = ptr.pos;- if let Some(p) = pointer_pos {- for (page_idx, xf) in &view.screen_xforms {- let images = doc.page_images(*page_idx);- for (idx, img) in images.iter().enumerate().rev() {- let obb = ImageObb::from_image(img, xf, info, *page_idx);- let b = image_screen_rect(img, xf, info, *page_idx);- if (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p) {- over_image = true;- if view.image_selection.as_ref().is_none_or(|s| s.page != *page_idx || s.index != idx) {- view.image_selection = Some(crate::edit_text_ui::ImageSelection {- page: *page_idx,- index: idx,- drag: None,- crop: None,- crop_mode: false,- crop_rect: None,- turning: false,- settled: None,- });- }- break;- }- }- if over_image {- break;- }- }- }- }- ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), over_image));-- }-- let mut calc_hover = None;-- for &i in &visible_pages {-- badge_hover = None;-- let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);-- if !r.intersects(visible.expand(400.0)) {-- continue;-- }-- if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {-- pressed_page = Some(i);-- }-- if r.intersects(visible) {-- visible_now.push(i);- view.screen_rects.push((i, r));- view.screen_xforms- .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));-- }-- let overlap = r.intersect(visible).height();-- if i == view.current {-- current_overlap = overlap;-- current_height = r.height();-- }-- // Pages shown equally (two rows wholly on screen) differ only by rounding: the-- // topmost one counts.-- if overlap > best_overlap + TIE {-- best_overlap = overlap;-- current = i;-- }-- let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };-- // Shadows would darken the preceding page when pages touch.-- if view.show_page_gaps {-- painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));-- }-- painter.rect_filled(r, CornerRadius::ZERO, paper);-- if let Some(err) = view.errors.get(&i) {-- painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));-- icons::paint(-- ui,-- Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),-- "triangle-alert",-- 26.0,-- Color32::from_rgb(0xC8, 0x3A, 0x3A),-- );-- let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);-- let msg =-- ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));-- painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);-- } else {-- let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));-- // A GPU may take smaller textures than these (OpenGL drivers report as little as-- // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.-- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;-- let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);-- // Whole-page raster: sharp when small, a low-res backdrop when tiled.-- let (want_scale, want_tag) = if tiled {-- let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);-- (bs, scale_tag(bs))-- } else {-- (scale, tag)-- };-- // Under tiles, a whole-page raster sharper than the backdrop (from before the page-- // grew past the tiling size) is a better backdrop: keep demanding it as it is.-- match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {-- Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),-- None => wanted.push((i, want_scale, want_tag, None)),-- }- let active_drag_suppress = if let Some(sel) = view.image_selection.as_ref()- && sel.page == i- && sel.drag.is_some()- {- let images = doc.page_images(i);- if let Some(img) = images.get(sel.index) {- let obb = ImageObb::from_image(img, &xf, info, i);- let uvs = obb.corners().map(|c| xf.screen_to_norm(c));- let u0 = uvs.iter().map(|(u, _)| *u).fold(1.0f32, f32::min).clamp(0.0, 1.0);- let u1 = uvs.iter().map(|(u, _)| *u).fold(0.0f32, f32::max).clamp(0.0, 1.0);- let v0 = uvs.iter().map(|(_, v)| *v).fold(1.0f32, f32::min).clamp(0.0, 1.0);- let v1 = uvs.iter().map(|(_, v)| *v).fold(0.0f32, f32::max).clamp(0.0, 1.0);- if u1 > u0 && v1 > v0 { Some([u0, v0, u1, v1]) } else { None }- } else {- None- }- } else {- None- };-- match view.pages.get(&i) {-- Some(p) => {-- if !tiled && p.tag == want_tag {- paint_image_suppressed(- &xf.texel_aligned(p.tex.size(), ppp),- painter,- p.tex.id(),- 0.0,- 0.0,- 1.0,- 1.0,- active_drag_suppress,- true,- );- xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);-- } else {-- // A backdrop, or a raster at an older scale until the new one arrives.- paint_image_suppressed(&xf, painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0, active_drag_suppress, true);- xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);-- }-- }-- None => {-- let now = ui.input(|inp| inp.time);-- let since = *view.waiting_since.entry(i).or_insert(now);-- let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };-- painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);-- }-- }-- if tiled && r.intersects(visible) {-- // Device-pixel geometry of the scaled page, and the visible part of it-- // (found by mapping the visible screen corners back into the page). Sides round-- // up as whole-page rasters do, so the last partial row and column get tiles.-- let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));-- // Adaptive tile side for this zoom and page, within the GPU texture limit:-- // a zoomed viewport or a giant sheet is covered by a few large tiles-- // instead of many small ones, and each tile costs one full page interpret.-- // Never zero (u32 division below).-- let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);-- let vis = r.intersect(visible);-- let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));-- let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));-- let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));-- let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);-- let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));-- // Tiles of earlier zooms first, stretched, the nearest scale last (on top):-- // until the current tiles arrive, a zoom shows them rather than the backdrop.-- let mut older: Vec<(f32, u32, u32, &TextureHandle)> = view-- .tiles-- .iter()-- .filter(|((p, t, _, _), _)| *p == i && *t != tag)-- .map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex))-- .collect();-- older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));-- for (s, ox, oy, tex) in older {-- let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);-- let [w, h] = tex.size();-- let (x, y) = (ox as f32, oy as f32);- paint_image_suppressed(- &xf,- painter,- tex.id(),- x / ow,- y / oh,- (x + w as f32) / ow,- (y + h as f32) / oh,- active_drag_suppress,- false,- );- xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);-- }-- // Visible tiles, nearest the viewport centre first: each tile costs a full-- // page interpret, so the workers sharpen what is looked at before the edges.-- let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);-- let mut coords: Vec<(u32, u32)> = Vec::new();-- for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {-- for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {-- coords.push((tx, ty));-- }-- }-- coords.sort_by(|a, b| {-- let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();-- let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();-- da.total_cmp(&db)-- });-- for (tx, ty) in coords {-- let (x, y) = (tx * ts, ty * ts);-- let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));-- if w == 0 || h == 0 {-- continue;-- }-- wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));-- if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {-- let (fw, fh) = (dw as f32, dh as f32);- paint_image_suppressed(- &xf.texel_aligned([dw as usize, dh as usize], ppp),- xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(-- painter,-- tex.id(),-- x as f32 / fw,-- y as f32 / fh,-- (x + w) as f32 / fw,-- (y + h) as f32 / fh,- active_drag_suppress,- false,-- );-- }-- }-- }-- }-- view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());-- if editing_content {-- view.move_background.paint(painter, &xf, i, info, &view.content, pointer);-- }-- if view.show_page_gaps {-- painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);-- }---- // Comments: tools, selection, moving and resizing come before text selection.-- let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };-- if let QuickTool::Measure(measure_tool) = tool {-- crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);-- }---- // Form fields take clicks first with the Select tool (as Acrobat fills fields in-- // every viewing mode); then comments; then text selection.-- if let QuickTool::Stamp(kind) = tool-- && allowed-- && let Some(p) = ptr.within(xf.rect)-- {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);-- if resp.clicked() {-- // Centred on the click, upright as the page is shown.-- let (vx, vy) = xf.screen_to_view(p);-- let (w, h) = kind.size();-- let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];-- let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();-- let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];-- let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());-- let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };-- view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {-- page: i,-- style: pdfcraft_engine::Style::default_for(&shape),-- shape,-- contents: String::new(),-- author: author.clone(),-- }));-- stamp_placed = true;-- }-- }-- if let Some(cs) = custom_stamp.as_ref()-- && allowed-- && let Some(p) = ptr.within(xf.rect)-- {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);-- if resp.clicked() {-- // Centred on the click at its natural size (the engine sizes it).-- let (vx, vy) = xf.screen_to_view(p);-- let u = info.pages[i].view_to_user(vx, vy);-- let (x, y) = (u[0] as f64, u[1] as f64);-- view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {-- page: i,-- rect: [x, y, x, y],-- name: cs.name.clone(),-- file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },-- author: author.clone(),-- });-- stamp_placed = true;-- }-- }-- // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).-- if let QuickTool::Fill(ft) = tool-- && allowed-- && !comments::fill_grabs(&pcx, view)-- {-- match crate::fill_sign::page_input(-- ui,-- &resp,-- &xf,-- &ptr,-- i,-- info,-- ft,-- app.fill_text_size,-- view,-- signature.as_ref(),-- initials.as_ref(),-- &mut app.signature_preview,-- &author,-- &date_text,-- ) {-- Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),-- Some(crate::fill_sign::FillAction::Signature(e)) => {-- view.pending_edit = Some(*e);-- view.fill_signature_page = Some(i);-- }-- Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,-- Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,-- Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),-- None => {}-- }-- }-- if matches!(tool, QuickTool::SignArea { .. }) {-- crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);-- }-- if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {-- crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);-- }-- if tool == QuickTool::EnhanceCamera {-- crate::camera_ui::page_input(ui, &resp, &xf, &ptr, i, view, can_modify);-- }-- if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {-- view.current = i;-- open_boxes = true;-- }-- // `over_field`: a form field is under the pointer and has set its cursor.-- let (on_field, over_field) = if preparing {-- let field_tool = match tool {-- QuickTool::Field(f) => Some(f),-- _ => None,-- };-- // While a table is being set up, nothing else is drawn or moved.-- let allowed = can_modify && table_preview.is_none() && open_table.is_none();-- let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);-- field_props |= o.properties;-- field_placed |= o.placed;-- open_table = open_table.or(o.table);-- (o.consumed || field_tool.is_some(), false)-- } else {-- use crate::forms_ui::FieldPointer;-- let field = if tool == QuickTool::Select-- && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))-- && !comments::select_grabs(&pcx, view)-- {-- crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)-- } else {-- FieldPointer::Away-- };-- (field == FieldPointer::Owned, field == FieldPointer::Over)-- };-- // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).-- let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;-- let boxing = area_tool && {-- let text = view.page_text(i);-- let over_text = |p: Pos2| {-- let (vx, vy) = xf.screen_to_view(p);-- text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))-- };-- crate::redact_ui::page_input(ui, &resp, &xf, &ptr, i, info, over_text, view)-- };-- let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);-- let on_objects =-- !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);-- let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {-- let generation = doc.edit_generation();-- match view.edit_lines.get(&i) {-- Some((g, l)) if *g == generation => l.clone(),-- _ => {-- let l = doc.text_blocks(i);-- view.edit_lines.insert(i, (generation, l.clone()));-- l-- }-- }-- } else {-- Vec::new()-- };-- let over_source = tool == QuickTool::AddText-- && pointer.is_some_and(|p| {-- !crate::content_ui::hits_added(&xf, info, i, &added, p)-- && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))-- });-- let source_blocked = over_source && view.content.hold_blocked();-- if over_source && resp.clicked() && !source_blocked {-- if let Some(edit) = view.content.finish_draft(&added) {-- view.pending_edit = Some(edit);-- }-- view.content.selected = None;-- }-- let on_content = !on_objects && editing_content && can_modify && {-- source_blocked-- || crate::content_ui::page_input(-- ui,-- &resp,-- &xf,-- &ptr,-- i,-- info,-- &added,-- tool == QuickTool::AddText && !over_source,-- matches!(tool, QuickTool::AddText | QuickTool::EditText),-- &text_style,-- view,-- )-- || tool == QuickTool::AddText && !over_source-- };-- // Added content owns its gesture; its source text must not queue a second edit.-- // Edit text & images boxes every paragraph and image whenever the tool is on. Only the-- // input waits while selected objects or added content own the pointer, or while page-- // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn-- // instead of vanishing until the pointer comes back.-- let others_own_pointer = on_objects || on_content;-- let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {-- let generation = doc.edit_generation();-- let images = match view.edit_images.get(&i) {-- Some((g, l)) if *g == generation => l.clone(),-- _ => {-- let l = doc.page_images(i);-- view.edit_images.insert(i, (generation, l.clone()));-- l-- }-- };-- // Editable text takes precedence over background/overlapping artwork. Both-- // inventories are painted every frame, even when text owns the pointer.-- let text_used =-- crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);-- let image_used = crate::edit_text_ui::image_input(-- ui,-- &resp,-- &xf,-- &ptr,-- i,-- info,-- &images,-- view,-- &mut image_action,-- !others_own_pointer && (image_owns_pointer || !text_used),-- );-- !others_own_pointer && (text_used || image_used)-- };-- let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);-- if tool == QuickTool::Select-- && resp.secondary_clicked()-- && can_modify-- && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))-- && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))-- {-- view.links.context = Some((i, l.index));-- }-- let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);---- let preview_target =-- (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();-- view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);-- view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());---- // Any press on the page ends Select All of the document: text read or not, any tool,-- // on a link too.-- // A press that lands on something drawn over the page (a menu, a dialog) is not one.-- if view.all_text && pressed_page == Some(i) {-- view.all_text = false;-- }-- // Text layer: find matches, selection, I-beam and drag-to-select.-- let to_screen = |g: [f32; 4]| xf.view_rect(g);-- if let Some(text) = view.texts.get(&i).cloned() {-- if let Some(f) = &view.find {-- for (k, (mp, range)) in f.matches.iter().enumerate() {-- if *mp != i {-- continue;-- }-- let current = f.current == Some(k);-- for lr in text.line_rects(range.clone()) {-- let fill = if current {-- Color32::from_rgba_unmultiplied(255, 140, 0, 110)-- } else {-- Color32::from_rgba_unmultiplied(255, 214, 0, 90)-- };-- painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);-- }-- }-- }-- if view.all_text {-- for lr in text.line_rects(0..text.glyphs.len()) {-- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));-- }-- }-- if let Some(sel) = view.selection.filter(|s| s.page == i) {-- for lr in sel.rects(&text) {-- painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));-- }-- // The rectangle being drawn, as Acrobat shows it while column-selecting.-- if let Span::Column { rect } = sel.span-- && resp.dragged()-- {-- let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));-- painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);-- }-- }-- if selects_text-- && !consumed-- && let Some(p) = pointer.filter(|p| r.contains(*p))-- {-- let (vx, vy) = xf.screen_to_view(p);-- let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);-- let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));-- // Column select (#740): the Column select tool, or Alt (Option on macOS) held-- // while a drag starts, as in Acrobat.-- let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);-- // A link or a form field under the pointer keeps its own cursor: a check box-- // drawn with a glyph, or set on printed text, shows the hand, not the I-beam.-- // So do the mode bar and side panels over a page scrolled under them (#2755),-- // unless a selection is being dragged there.-- let cursor_free = !over_link && !over_field && (resp.contains_pointer() || resp.dragged());-- if column && cursor_free {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);-- } else if over_text && cursor_free {-- ui.ctx().set_cursor_icon(egui::CursorIcon::Text);-- }-- // The pages' press, kept when its release came in the same frame (#2100): it-- // still starts multi-click selection.-- let press_here = ptr.origin.is_some_and(|o| r.contains(o));-- let pressed = ptr.pressed().is_some();-- if pressed && press_here && !over_link {-- let now = ui.input(|inp| inp.time);-- // The same limits egui uses to count clicks on release.-- let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));-- let is_consecutive =-- now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);-- view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };-- view.last_press_time = now;-- view.last_press_pos = Some(p);---- // Multi-click highlights immediately on pointer press instead of release (#1024).-- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };-- if clicks >= 2 && over_text {-- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));-- if let Some((first, last)) = span {-- view.selection = Some(Selection::run(i, first, last));-- }-- }-- }-- if resp.drag_started() && press_here && !over_link {-- // A drag replaces the selection without passing through none, so a-- // re-drag over text whose bar Copy closed would keep the bar hidden.-- view.actions_dismissed = None;-- view.selection_drag = true;-- let origin = ptr.origin.unwrap_or(p);-- let (ox, oy) = xf.screen_to_view(origin);-- if view.clicks < 2 {-- view.selection = if column {-- Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })-- } else {-- text.nearest(ox, oy).map(|a| Selection::run(i, a, a))-- };-- }-- }-- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };-- if resp.dragged()-- && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)-- {-- match &mut sel.span {-- // After a multi-click the drag extends by its unit (#1685), as in-- // Acrobat and browsers: whole words or lines, always keeping the one-- // clicked, which holds the anchor whichever way the drag went.-- Span::Run { anchor, head } if clicks >= 2 => {-- if let Some(h) = text.nearest(vx, vy)-- && let Some((first, last)) = click_unit(&text, clicks, *anchor)-- {-- let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));-- (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };-- }-- }-- Span::Run { head, .. } => {-- if let Some(h) = text.nearest(vx, vy) {-- *head = h;-- }-- }-- Span::Column { rect } => {-- rect[2] = vx;-- rect[3] = vy;-- }-- }-- }-- // A rectangle around no text selects nothing.-- if resp.drag_stopped()-- && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())-- {-- view.selection = None;-- }-- // Quick clicks widen the selection: two a word, three the line, four the page.-- // Release-based fallback for platforms or synthetic events that report double_clicked.-- let release_clicks = if resp.triple_clicked() {-- view.clicks.max(2).saturating_add(1)-- } else if resp.double_clicked() {-- view.clicks.max(2)-- } else {-- 0-- };-- if release_clicks > 0 {-- view.clicks = release_clicks;-- }-- let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };-- // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and-- // acting on every frame re-selected the word as soon as a selection was cleared-- // (a highlight made by the double-click left its word selected).-- if release_clicks > 0 && clicks >= 2 && over_text {-- if view.selection.is_none() {-- let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));-- if let Some((first, last)) = span {-- view.selection = Some(Selection::run(i, first, last));-- }-- }-- } else if resp.clicked() && view.clicks < 2 && !over_link {-- // ⇧-click extends a selection on this page to the click, keeping its-- // anchor (#527). Otherwise (no shift, no selection on this page, or a-- // column selection, which has no anchor glyph; a selection cannot yet-- // span pages) a click clears the selection.-- let shift = ui.input(|inp| inp.modifiers.shift);-- match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {-- (Some(Span::Run { head, .. }), Some(h)) => *head = h,-- _ => view.selection = None,-- }-- }-- }-- }---- if tool == QuickTool::Select && !consumed {-- crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);-- }-- crate::image_pick::drop_stale(doc, view);-- crate::image_pick::paint(painter, &xf, i, info, view);-- comments::page_after_text(&resp, &pcx, view);-- if tool == QuickTool::Redact && can_modify {-- crate::redact_ui::after_text(&resp, i, info, view);-- }-- if area_tool {-- crate::redact_ui::paint(painter, i, view, pointer);-- }-- comments::paint_page(ui, painter, &pcx, view);-- if editing_content {-- crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);-- }-- if tool == QuickTool::EditText {-- crate::object_ui::paint(painter, &xf, i, info, &view.objects);-- }-- if tool == QuickTool::EnhanceCamera {-- crate::camera_ui::paint(painter, &xf, i, view);-- }-- if tool == QuickTool::Link {-- crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);-- }-- if preparing {-- crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);-- if let Some(preview) = &table_preview {-- crate::field_table_ui::paint_preview(painter, &xf, i, preview);-- }-- if calc_order {-- let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());-- if let Some(name) =-- crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)-- {-- calc_hover = Some(name);-- }-- }-- } else {-- crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);-- }---- // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a-- // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as-- // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a-- // radio button's own) is left as it is drawn.-- if view.highlight_fields {-- for f in form.iter() {-- let required = f.has(pdfcraft_engine::field_flags::REQUIRED);-- for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {-- let r = w.rect;-- let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);-- let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);-- let (width, color) =-- if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };-- if w.round {-- let radius = sr.width().min(sr.height()) / 2.0;-- painter.circle_filled(sr.center(), radius, tint);-- painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));-- } else {-- painter.rect_filled(sr, CornerRadius::same(1), tint);-- painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);-- }-- }-- }-- }-- // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips-- // draw above the palette, so none shows while it is open, even beside it.-- if !matches!(tool, QuickTool::Fill(_))-- && unobstructed-- && let Some(p) = pointer-- {-- for l in info.links.iter().filter(|l| l.page == i) {-- let sr = xf.user_rect(info, i, l.rect);-- if sr.contains(p) {-- ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);-- let label = match &l.target {-- LinkTarget::Page(n, _) => {-- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])-- }-- LinkTarget::Uri(u) => u.clone(),-- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),-- LinkTarget::RemoteGoTo { file, .. } => file.clone(),-- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),-- };-- hover_text = Some((p, label));-- if resp.clicked() && tool == QuickTool::Select && !consumed {-- clicked_link = Some(l.target.clone());-- }-- }-- }-- // Annotation hover shows the comment, as Acrobat's popups do; not while drawing-- // freehand, where it would cover the next stroke (#429).-- let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));-- let gesturing = view.comments.gesture.is_some() || freehand;-- // Inspection sorts annotations spatially, but the renderer paints in /Annots-- // order. Keep the shared list intact and choose the last eligible raw index.-- if hover_text.is_none()-- && !gesturing-- && let Some((_, text)) = info-- .annotations-- .iter()-- .filter(|a| a.page == i)-- .filter(|a| {-- !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty))-- })-- .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))-- .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))-- .max_by_key(|(index, _)| *index)-- {-- hover_text = Some((p, text));-- }-- }-- for (mp, mr, mc) in &view.compare_marks {-- if *mp == i {-- let sr = xf.user_rect(info, i, *mr).expand(1.5);-- painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));-- }-- }-- if let Some((fp, fr, t0)) = view.flash-- && fp == i-- {-- let now = ui.input(|inp| inp.time);-- let t0 = if t0 == 0.0 { now } else { t0 };-- view.flash = Some((fp, fr, t0));-- let age = (now - t0) as f32;-- if age < 1.6 {-- let a = ((1.6 - age) / 1.6 * 255.0) as u8;-- let sr = xf.user_rect(info, i, fr).expand(4.0);-- painter.rect_stroke(-- sr,-- CornerRadius::same(3),-- Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),-- egui::StrokeKind::Outside,-- );-- ui.ctx().request_repaint();-- } else {-- view.flash = None;-- }-- }-- // Validation is viewer chrome over the signer's original artwork, which-- // may still say "Signature Not Verified". These badges never enter document-- // streams, image/text exports, vector printing or Print as Image.-- for badge in signature_badges(&doc.signatures, i) {-- let [x0, y0, x1, y1] = badge.rect;-- let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);-- let (icon, color) = crate::sign_ui::signature_status_style(badge.status);-- painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);-- // A widget too small for the mark keeps its outline: the verdict still shows.-- if sr.width() < 4.0 || sr.height() < 4.0 {-- continue;-- }-- // Big enough to read at a glance, small enough to leave the signer's own-- // text visible around it.-- let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);-- let mark = Rect::from_center_size(sr.center(), vec2(side, side));-- icons::paint(ui, mark, icon, side * 0.64, color);-- if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {-- badge_hover = Some((p, badge.summary.to_string()));-- }-- }-- // Overlapping widgets paint in order, so the topmost badge owns the hover; an-- // earlier link or annotation hover still wins over any badge.-- if hover_text.is_none() {-- hover_text = badge_hover.take();-- }-- }-- if calc_order {-- view.calc_order.set_hover_page(calc_hover);-- let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());-- crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);-- }-- // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag-- // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the-- // pointer leaves the selection's page for the gap or the next page; over the whole-- // document area, like #759. Combine direct and smoothed motion in one request so mixed-- // Point and Line events retain their full contribution.-- if selection_wheel {-- let smooth =-- if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };-- let delta = precise_scroll + boost_extra + smooth;-- if delta != Vec2::ZERO && delta.is_finite() {-- ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());-- }-- }-- // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view-- // so it can reach text off screen (#1670); the selection follows the pointer on its page.-- if view.selection_drag-- && navigation_enabled-- && unobstructed-- && !single_paging-- && let Some(p) = ptr.pos-- {-- let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));-- if dy != 0.0 {-- view.end_find_following();-- ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());-- // Keep scrolling while the pointer rests there and sends no events.-- ui.ctx().request_repaint();-- }-- }-- // The page navigated to stays current while no page shows more of itself, so the next-- // page step starts from it rather than from a page further down the screen (#188).-- // It also stays current while it is wholly on screen: a short page (a cheque) gone to-- // from the Pages panel shows less of itself than the tall page below it, and must not-- // hand the highlight to that page.-- if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {-- current = view.current;-- }-- if let Some(p) = pressed_page {-- current = p;-- }-- if view.continuous {-- view.current = current;-- }-- resp.context_menu(|ui| {-- // Preparing a form: the selected field's menu.-- if preparing && let Some((name, wi)) = view.prepare.selected.clone() {-- // Several fields: Align, Center, Distribute, Set Fields to Same Size.-- if !view.prepare.also.is_empty() {-- use crate::prepare::Arrange as A;-- let others = view.prepare.also.clone();-- let anchor = (name.clone(), wi);-- let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {-- if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {-- view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);-- ui.close();-- }-- };-- ui.menu_button(tl!("Align"), |ui| {-- pick(ui, A::AlignLeft, "Left");-- pick(ui, A::AlignRight, "Right");-- pick(ui, A::AlignTop, "Top");-- pick(ui, A::AlignBottom, "Bottom");-- pick(ui, A::AlignCenterV, "Center vertically");-- pick(ui, A::AlignCenterH, "Center horizontally");-- });-- ui.menu_button(tl!("Distribute"), |ui| {-- pick(ui, A::DistributeH, "Horizontally");-- pick(ui, A::DistributeV, "Vertically");-- });-- ui.menu_button(tl!("Set Fields to Same Size"), |ui| {-- pick(ui, A::SameHeight, "Height");-- pick(ui, A::SameWidth, "Width");-- pick(ui, A::SameSize, "Both");-- });-- ui.separator();-- }-- if ui.button(tl!("Properties…")).clicked() {-- field_menu = Some(FieldMenu::Properties);-- ui.close();-- }-- if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {-- field_menu = Some(FieldMenu::Duplicate(name.clone()));-- ui.close();-- }-- ui.separator();-- let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };-- if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {-- view.pending_edit = crate::prepare::delete_selected(view);-- ui.close();-- }-- return;-- }-- if let Some((page, index)) = view.links.context {-- if ui.button(tl!("Properties…")).clicked() {-- view.links.open_existing = Some((page, index));-- ui.close();-- }-- if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {-- view.pending_edit = Some(Edit::DeleteLink { page, index });-- view.links.selected = None;-- view.links.context = None;-- ui.close();-- }-- ui.separator();-- if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {-- view.pending_edit = Some(Edit::RemoveLinks { pages: None });-- view.links.selected = None;-- view.links.context = None;-- ui.close();-- }- return;- }- let is_image_menu = tool == QuickTool::EditText- && (ui.ctx().data_mut(|d| d.get_persisted::<bool>(crate::edit_text_ui::image_menu_id())).unwrap_or(false)- || view.image_selection.as_ref().is_some_and(|sel| {- let pointer_pos = ptr.pos;- let Some(p) = pointer_pos else { return false };- let Some((_, xf)) = view.screen_xforms.iter().find(|(page_idx, _)| *page_idx == sel.page) else { return false };- let images = doc.page_images(sel.page);- let Some(img) = images.get(sel.index) else { return false };- let obb = ImageObb::from_image(img, xf, info, sel.page);- let b = image_screen_rect(img, xf, info, sel.page);- (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p)- }));- if is_image_menu && let Some(sel) = view.image_selection.clone() {- let images = doc.page_images(sel.page);- let at = view.comments.context_at.map(|(_, at)| at);- crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action, at);-- return;-- }- if view.comments.selected.is_some() {- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify);- return;- if view.comments.selected.is_none() {- let selected = view.selected_text().is_some_and(|t| !t.is_empty());- let key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY);- if ui.add_enabled(can_copy && selected, egui::Button::new(tl!("Copy")).shortcut_text(key)).clicked() {- copy_selected = true;- ui.close();- }- ui.separator();-- }-- // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.-- let mut copy_image = None;- if let Some((page, at)) = view.comments.context_at {- if view.comments.selected.is_none()- && let Some((page, at)) = view.comments.context_at- {-- // The page's content is parsed once per right-click, not on every frame the menu is open.-- let key = egui::Id::unique("copy-image-under-menu");-- let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);-- let hit = match cached {-- Some(c) => c.2,-- None => {-- let hit = doc.page_image_at(page, at);-- ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));-- hit-- }-- };-- if let Some(image) = hit {-- if ui.button(tl!("Copy Image")).clicked() {-- copy_image = Some(comments::CanvasAction::CopyImage(page, image));-- ui.close();-- }-- if ui.button(tl!("Copy Image in Original Format")).clicked() {-- copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));-- ui.close();-- }-- ui.separator();-- }- }- let has_copy_image = copy_image.is_some();- if copy_image.is_some() {- canvas_action = copy_image;-- }- let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0]));- let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || has_copy_image);- let can_paste = can_paste_image && can_modify;- let perms = PageMenuPerms {- can_modify,- can_assemble: doc.allows_assembly(),- can_annotate: allowed,- can_print: doc.allows_printing(),- can_copy: can_copy_items,- can_paste,- has_annotations: !info.annotations.is_empty(),- };- default_page_context_menu(ui, page, at, perms, &mut page_action);- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);-- });- if !resp.context_menu_opened() {- ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), false));- }-- (wanted, visible_now)-- });-- view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {-- // At the top once the page's top edge shows where going to a page puts it (a gap-- // below the window's top). Within a point, as for wheel paging, so layout rounding-- // can't hide an edge.-- let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);-- (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)-- });---- view.viewport_screen = out.inner_rect;-- view.auto_scroll.paint(ui, avail);-- if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {-- copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);-- }---- // Collect all main-page demand, including cached surfaces, for byte admission later.-- // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding-- // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched-- // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that-- // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;-- // pages with nothing on screen yet still queue.-- let scroll_offset = out.state.clamped_offset();-- // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas-- // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag-- // background. The output gives us the area id, and egui's pinned ScrollArea registers those-- // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.-- // Ask for their exact responses instead of treating any held drag as scrolling: a text-- // selection, a panel splitter or another widget's drag must not excuse the programmatic jump-- // a search flash makes, while a track click (which moves the offset with no pointer motion)-- // must still count as the reader scrolling.-- let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());-- let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));-- if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {-- view.end_find_following();-- }-- let now_settle = ui.input(|i| i.time);-- if (scroll_offset - view.last_scroll).length() > 2.0 {-- view.pan_hold_until = now_settle + 0.25;-- ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));-- }-- if glide != Vec2::ZERO {-- view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);-- }-- view.last_scroll = scroll_offset;-- let pan_held = now_settle < view.pan_hold_until;-- let (mut wanted, visible_now) = out.inner;-- // Single-page and two-page views draw only the current row, so the next one was first asked-- // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,-- // as continuous scrolling does for the pages just off screen.-- if !view.continuous-- && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())-- {-- let n = if view.layout == PageLayout::Single { 1 } else { 2 };-- let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;-- for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {-- let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };-- // As drawn: the whole page at this scale, or the backdrop of a tiled page.-- let side = p.width.max(p.height).max(1.0);-- wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {-- let bs = BASE_SIDE.min(max_side) / side;-- (i, bs, scale_tag(bs), None)-- } else {-- (i, scale, tag, None)-- });-- }-- }-- let cur = view.current;-- wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));-- // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page-- // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below-- // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it-- // was a cold miss and the page re-blurred through the backdrop while every tile was-- // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale-- // first, and admission keeps them inside `TILE_BYTES`.-- let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();-- let on_screen: HashSet<usize> = visible_now.iter().copied().collect();-- view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));-- let mut older: Vec<(f32, (usize, u64, u32, u32))> =-- view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();-- // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a-- // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of-- // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which-- // makes that reachable in ordinary zooming, so the byte bound has to be here too.-- older.sort_by(|a, b| a.0.total_cmp(&b.0));-- let mut kept = 0usize;-- let mut kept_bytes = 0usize;-- let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();-- for (_dist, key) in older {-- let bytes = view.tiles.get(&key).map_or(0, texture_bytes);-- if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {-- drop.push(key);-- } else {-- kept = kept.saturating_add(1);-- kept_bytes = kept_bytes.saturating_add(bytes);-- }-- }-- for key in drop {-- view.tiles.remove(&key);-- }-- let mut queue: Vec<RenderRequest> = wanted-- .iter()-- .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {-- page,-- kind: RequestKind::Pixels,-- tile,-- scale: wanted_scale,-- tag: wanted_tag,-- // The low-res backdrop under tiles is a preview: tiny images are skipped for it.-- // It is the whole-page request whose scale is not the current one; sharp tiles-- // and whole-page finals always draw everything.-- preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),-- })-- .collect();-- // While the zoom or pan is settling, hold back sharp re-renders of pages that already-- // show something (a stale whole-page raster or older tiles, drawn stretched): each new-- // scale would cancel the running full-page interpret and restart it from scratch, and-- // each pan frame would queue a storm of full-page tile interprets.-- // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.-- if sharp_held || pan_held {-- let main_tag = tag;-- queue.retain(|req| {-- // Fast pages render straight through: the hold only protects heavy pages-- // whose full-page interpret costs seconds.-- if !view.slow_pages.contains(&req.page) {-- return true;-- }-- if req.tile.is_some() {-- let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);-- if has_current_tile {-- return false;-- }-- let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);-- !has_any_surface-- } else if req.tag != main_tag {-- // The low-res backdrop under tiles is zoom-independent: let it through,-- // it is the stretched surface the hold relies on.-- true-- } else {-- // The stale raster stays stretched until the zoom or pan settles; a page with-- // nothing on screen yet still renders.-- !view.pages.contains_key(&req.page)-- }-- });-- }-- // Text layers: visible pages for selection, every page while a search is active. (Select All-- // of the document needs no more: shown pages highlight as their text comes, and Copy reads-- // the rest, as text far away is let go to bound memory.)-- let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);-- let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };-- if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {-- let n = info.pages.len();-- let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();-- text_pages.extend(rest);-- }-- queue.extend(text_pages.into_iter().map(|page| RenderRequest {-- page,-- kind: RequestKind::Text,-- tile: None,-- scale: 1.0,-- tag: TEXT_TAG,-- preview: false,-- }));-- view.frame_queue = queue;-- view.frame_visible = visible_now.iter().copied().collect();---- if let Some((pos, text)) = hover_text {-- // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.-- let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);-- tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {-- egui::Frame::popup(ui.style()).show(ui, |ui| {-- ui.set_max_width(320.0);-- ui.label(text);-- });-- });-- }-- find_bar(view, info.pages.len(), avail, ui, &t);-- page_size_hint(view, info, units, avail, unobstructed, ui, &t);-- if tool == QuickTool::EnhanceCamera {-- crate::camera_ui::bar(ui.ctx(), view, avail, &t, can_modify);-- }-- if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {-- view.pending_edit = Some(e);-- }-- if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {-- view.pending_edit = Some(e);-- }-- let text_box = crate::forms_ui::text_box(doc, view, &form);-- if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, text_box.as_ref(), today) {-- view.pending_edit = Some(e);-- }-- if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, &author) {-- view.pending_edit = Some(e);-- }-- let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, &added);-- if typed.is_some() {-- view.pending_edit = typed;-- }-- if let Some(why) = view.objects.notice.take() {-- refused = Some(why);-- }-- let form_notice = view.forms.notice.take();-- // One crop, then back to selecting (as Acrobat does).-- let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));-- let mut tool = app.quick_tool;-- comments::keys(ui.ctx(), view, &mut tool, allowed);-- if preparing {-- crate::prepare::keys(ui.ctx(), view);-- }-- if editing_content {-- crate::content_ui::keys(ui.ctx(), view);-- }-- if tool == QuickTool::Link {-- crate::link_ui::keys(ui.ctx(), view);-- } else {-- view.links.selected = None;- }- if tool != QuickTool::EditText {- view.image_selection = None;-- }-- if stamp_placed {-- tool = QuickTool::Select;-- }-- // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.-- if text_done && tool == QuickTool::AddText {-- tool = QuickTool::Select;-- }-- // One field, then back to selecting (Acrobat's default without "Keep tools pinned").-- if field_placed {-- tool = QuickTool::Select;-- }-- if matches!(field_menu, Some(FieldMenu::Properties)) {-- field_props = true;-- }-- let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();-- match canvas_action {-- Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),-- // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.-- Some(comments::CanvasAction::OpenComments) => {-- app.right = Some(RightPanel::Comments);-- app.comments_panel_closed = false;-- }-- Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),-- Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),-- Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),-- None => {}-- }-- // Full screen: the click turns the page unless it did something else first. It waits out the-- // double-click time: turning on the first click's release sent a double-click's second click,-- // meant to select a word, to the next page (review on #2070). A selection cancels it, and so-- // do a link followed meanwhile and leaving full screen; a double-click elsewhere still turns-- // once.-- let now = ui.input(|i| i.time);-- if present_click && clicked_link.is_none() && view.selection.is_none() && view.clicks < 2 {-- let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);-- view.present_turn = Some((now + delay, !present_back));-- }-- if let Some((due, forward)) = view.present_turn {-- if clicked_link.is_some() || view.selection.is_some() || view.presentation.is_none() {-- view.present_turn = None;-- } else if now >= due {-- view.present_turn = None;-- view.step_page(forward);-- } else {-- ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));-- }-- }-- match clicked_link {-- Some(LinkTarget::Page(p, dest)) => view.go_to_dest(p, dest, info),-- Some(LinkTarget::Uri(u)) => app.request_document_url(&u, crate::LinkOrigin::Link),-- Some(LinkTarget::SetLayers { changes, preserve_rb }) => set_layers(app, index, &changes, preserve_rb),-- Some(LinkTarget::RemoteGoTo { file, destination, .. }) => remote_open = Some((view.id, file, destination)),-- Some(LinkTarget::Other(s)) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),-- None => {}-- }-- if tool == QuickTool::Crop && cropped {-- tool = QuickTool::Select;-- }-- if let Some(done) = app.views[index].marquee_done.take() {-- app.finish_marquee(index, done);-- }-- // A signature rectangle was drawn, or an empty signature field clicked.-- let drawn = app.views[index].sign.drawn.take();-- if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {-- tool = QuickTool::Select;-- app.quick_tool = tool;-- app.start_signing(page, Some(rect), None, certify.then_some(2));-- }-- if let Some(field) = app.views[index].sign.field.take() {-- let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));-- if signed {-- app.right = Some(RightPanel::Signatures);-- if !app.sig_expanded.contains(&field) {-- app.sig_expanded.push(field);-- }-- } else {-- let page = app.views[index].current;-- app.start_signing(page, None, Some(field), None);-- }-- }-- app.quick_tool = tool;-- if let Some((page, at)) = app.views[index].comments.attach_at.take() {-- app.attach_file_comment(page, at);-- }-- if let Some((p, i)) = open_props {-- app.open_comment_props(p, i);-- }-- if let Some((p, i)) = app.views[index].comments.default_request.take() {-- app.make_comment_default(p, i);-- }-- if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {-- let doc = app.views[index].id;-- app.comment_attachment_action(doc, p, i, open);-- }-- if let Some((name, w)) = field_props {-- app.open_field_props(&name, w);-- }-- if let Some(FieldMenu::Duplicate(name)) = field_menu {-- let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());-- app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });-- app.dialog = Some(crate::Dialog::DuplicateField);-- }-- if let Some((page, rect)) = app.views[index].links.open_new.take() {-- app.open_link_props(page, Some(rect), None);-- }-- if let Some((page, i)) = app.views[index].links.open_existing.take() {-- app.open_link_props(page, None, Some(i));-- }-- if let Some((page, quads)) = app.views[index].pending_redaction.take() {-- let author = app.comment_prefs.author.clone();-- app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {-- // An area highlight: a highlight over the box.-- let style = app.comment_prefs.style(comments::CommentTool::Highlight);-- pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {-- page,-- shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },-- style,-- contents: String::new(),-- author,-- })-- } else {-- app.redact_prefs.mark(page, quads, &author)-- });-- }-- match image_action {-- Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),-- Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),-- Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {-- app.copy_page_image(page, index);-- }-- Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),-- Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {-- app.views[index].image_selection = None;-- app.cut_page_image(page, image);- }- Some(crate::edit_text_ui::ImageAction::Paste(page, at)) => {- if let Some(pt) = at {- app.paste_image_at(page, pt);- } else {- app.paste_image(page, None);- }- }- Some(crate::edit_text_ui::ImageAction::DrawFreehand) => {- app.quick_tool = crate::QuickTool::Comment(crate::comments::CommentTool::Ink);-- }-- Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),-- Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),-- Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),- Some(crate::edit_text_ui::ImageAction::AddComment(page, i)) => {- if let Some(d) = app.session.get(app.views[index].id) {- let images = d.page_images(page);- if let Some(img) = images.get(i) {- let r = img.visible_rect.unwrap_or(img.rect);- let center = [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0];- app.views[index].comments.context_at = Some((page, center));- app.views[index].comments.composer = Some(crate::comments::Composer {- page,- at: center,- kind: crate::comments::ComposerKind::Note,- text: String::new(),- focus: true,- });- }- }- }- Some(crate::edit_text_ui::ImageAction::Crop) => {- let doc_id = app.views[index].id;- if let Some(s) = app.views[index].image_selection.as_mut()- && let Some(d) = app.session.get(doc_id)- {- let images = d.page_images(s.page);- if let Some(im) = images.get(s.index) {- s.crop = Some(crate::edit_text_ui::CropMode::new(im.visible_rect.unwrap_or(im.rect)));- s.crop_mode = true;- s.crop_rect = None;- }- }- }- None => {}- }- match page_action {- Some(PageMenuAction::Copy) => {- if let Some(sel) = app.views[index].image_selection.clone() {- app.copy_page_image(sel.page, sel.index);- } else if app.views[index].selected_text().is_some() {- app.execute("edit.copy");- } else if let Some((page, at)) = app.views[index].comments.context_at- && let Some(doc) = app.session.get(app.views[index].id)- && let Some(image) = doc.page_image_at(page, at)- {- app.copy_page_image(page, image);- }- }- Some(PageMenuAction::Paste(page, at)) => {- app.paste_image_at(page, at);- }- Some(PageMenuAction::RotateCCW(page)) => {- let _ = page;- app.views[index].rotate_view(false);- }- Some(PageMenuAction::RotateCW(page)) => {- let _ = page;- app.views[index].rotate_view(true);- }- Some(PageMenuAction::Print) => {- app.open_print();- }- Some(PageMenuAction::SelectTool) => {- app.quick_tool = QuickTool::Select;- }- Some(PageMenuAction::HandTool) => {- app.quick_tool = QuickTool::Hand;- }- Some(PageMenuAction::MarqueeZoom) => {- app.quick_tool = QuickTool::MarqueeZoom;- }- Some(PageMenuAction::AddComment(page, at)) => {- app.views[index].comments.composer =- Some(crate::comments::Composer { page, at, kind: crate::comments::ComposerKind::Note, text: String::new(), focus: true });- }- Some(PageMenuAction::FlattenComments) => {- app.views[index].comments.selected = None;- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false });- }- Some(PageMenuAction::AddBookmark(_page)) => {- app.bookmark_action(crate::panels::BmAction::New);- }- Some(PageMenuAction::TakeSnapshot) => {- app.quick_tool = QuickTool::Snapshot;- }- Some(PageMenuAction::EditPdf) => {- app.quick_tool = QuickTool::EditText;- }- Some(PageMenuAction::AddText) => {- app.quick_tool = QuickTool::AddText;- }- Some(PageMenuAction::AddImage) => {- app.add_image_dialog();- }- Some(PageMenuAction::DeletePage(page)) => {- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] });- }- Some(PageMenuAction::ExportPdf) => {- app.select_tool("export");- }- Some(PageMenuAction::Find) => {- app.views[index].open_find();- }- Some(PageMenuAction::DocProperties) => {- app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Description));- }-- None => {}-- }-- if let Some(why) = refused {-- app.notify_error(why);-- }-- if open_signature || open_initials {-- app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);-- app.dialog = Some(crate::Dialog::Signature);-- }-- if open_boxes {-- app.boxes_draft.range = crate::pageboxes::Range::Current;-- app.boxes_draft.seeded = None;-- app.dialog = Some(crate::Dialog::PageBoxes);-- }-- if let Some((page, rect)) = open_table {-- app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));-- app.dialog = Some(crate::Dialog::FieldTable);-- // The window lasts while the form is prepared. Drawn with the tool picked but its panel-- // closed, the tool goes back to Select above, so the panel opens to keep it prepared.-- app.left = crate::LeftPanel::Tool("form");-- app.reveal_tools();-- }-- if let Some(n) = form_notice {-- match n {-- crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),-- crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),-- crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),-- }-- }-- if let Some((name, action)) = app.views[index].forms.button.take() {-- run_button(app, index, &name, action);-- }-- if copy_selected {-- app.execute("edit.copy");-- }-- // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);-- // the quick tools come back with the window.-- if app.mode != crate::Mode::Read && !app.full_screen {-- quick_bar(app, avail, ui);-- }-- if let Some((source, file, destination)) = remote_open {-- app.open_remote_link(source, file, destination);- }- }-- #[derive(Clone, Copy)]- enum SelectionAction {- Note,- Markup(comments::CommentTool),- Replace,- Copy,- }-- /// Actions on an existing text selection, next to the selected words.- fn selection_actions(- ui: &mut egui::Ui,- viewport: Rect,- view: &mut DocView,- info: &DocInfo,- prefs: &comments::CommentPrefs,- can_comment: bool,- can_copy: bool,- ) -> bool {- if ui.input(|input| input.pointer.is_decidedly_dragging()) {- return false;- }- let Some(selection) = view.selection else {- view.actions_dismissed = None;- return false;- };- if view.actions_dismissed == Some(selection) {- return false;- }- let Some(text) = view.texts.get(&selection.page) else { return false };- let Some(xf) = view.page_xform(selection.page) else { return false };- let Some(last) = selection.rects(text).last().copied() else { return false };- let selected = selection.text(text);- if selected.is_empty() {- return false;- }- let rect = xf.view_rect(last);- if !viewport.intersects(rect) {- return false;- }- let menu_width = 184.0;- let ideal_x = rect.right() - 24.0;- let max_x = (viewport.right() - menu_width - 8.0).max(viewport.left() + 8.0);- let x = ideal_x.clamp(viewport.left() + 8.0, max_x);- let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };- let mut chosen = None;- egui::Area::new(egui::Id::unique(("text-selection-actions", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(- ui.ctx(),- |ui| {- egui::Frame::popup(ui.style()).corner_radius(CornerRadius::same(12)).show(ui, |ui| {- ui.spacing_mut().item_spacing.x = 2.0;- ui.horizontal(|ui| {- ui.add_enabled_ui(can_comment, |ui| {- for (icon, tooltip, action) in [- ("message-square-plus", tl!("Add comment"), SelectionAction::Note),- ("highlighter", tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),- ("underline", tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),- ("strikethrough", tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),- ("replace", tl!("Replace text"), SelectionAction::Replace),- ] {- if icons::button(ui, icon, 26.0, false, tooltip).clicked() {- chosen = Some(action);- }- }- });- if ui.add_enabled_ui(can_copy, |ui| icons::button(ui, "copy", 26.0, false, tl!("Copy"))).inner.clicked() {- chosen = Some(SelectionAction::Copy);- }- });- });- },- );- let Some(action) = chosen else { return false };- if let SelectionAction::Copy = action {- // Copying closes the bar but keeps the words selected, for ⌘C or a second action.- view.actions_dismissed = Some(selection);- return true;- }- let Some((page, quads)) = view.selection_quads(info) else { return false };- let last = quads.last().copied().unwrap_or_default();- let at = [last[2].max(last[6]), last[1].max(last[3])];- view.clear_selection();- match action {- SelectionAction::Note | SelectionAction::Replace => {- if matches!(action, SelectionAction::Replace) {- view.comments.replace = Some(quads);- }- view.comments.composer = Some(comments::Composer {- page,- at,- kind: if matches!(action, SelectionAction::Replace) { comments::ComposerKind::Replace } else { comments::ComposerKind::Note },- text: String::new(),- focus: true,- });- }- SelectionAction::Markup(tool) => {- // Every markup button carries a markup tool; anything else adds nothing.- let Some(kind) = tool.markup() else { return false };- view.pending_edit = Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {- page,- shape: pdfcraft_engine::Shape::TextMarkup { kind, quads },- style: prefs.style(tool),- contents: String::new(),- author: prefs.author.clone(),- }));- }- // Copy is dispatched through the app after the view borrow ends.- SelectionAction::Copy => {}- }- false- }-- /// Run a push button's action (the ones that need no JavaScript engine).- fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_engine::form_scripts::ButtonAction) {- use pdfcraft_engine::form_scripts::ButtonAction as B;- let pages = app.session.get(app.views[index].id).map_or(0, |d| d.info.pages.len());- match action {- B::Reset { fields, exclude } => {- let all: Vec<String> = app.session.get(app.views[index].id).map(|d| d.form.iter().map(|f| f.name.clone()).collect()).unwrap_or_default();- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- let names = match (fields.is_empty(), exclude) {- (true, _) => None,- (false, false) => Some(all.iter().filter(|n| listed(n)).cloned().collect()),- (false, true) => Some(all.iter().filter(|n| !listed(n)).cloned().collect()),- };- app.views[index].forms.focus = None;- app.views[index].pending_edit = Some(pdfcraft_engine::Edit::ResetForm { names });- }- B::Named(n) => match n.as_str() {- "Print" => app.open_print(),- // What PdfCraft's XFA buttons use, and what a script's `execMenuItem("Save")`- // does too: the Save As dialog, so a click never overwrites the file unasked.- "SaveAs" => app.run_command("file.save_as"),- "NextPage" => app.views[index].step_page(true),- "PrevPage" => app.views[index].step_page(false),- "FirstPage" => app.views[index].go_to_page(0),- "LastPage" => app.views[index].go_to_page(pages.saturating_sub(1)),- other => app.notify_fmt("{name}: the {other} action isn't supported yet", &[("name", name), ("other", other)]),- },- B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),- B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),- B::ShowHide { fields, hide } => {- let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));- // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.- let changes: Vec<pdfcraft_engine::FieldChange> = app- .session- .get(app.views[index].id)- .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())- .unwrap_or_default()- .into_iter()- .map(|name| pdfcraft_engine::FieldChange {- name,- value: None,- read_only: None,- required: None,- display: Some(if hide { 1 } else { 0 }),- })- .collect();- if !changes.is_empty() {- let label = if hide { "Hide a field" } else { "Show a field" };- app.views[index].pending_edit =- Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });- }- }- B::SetLayers { changes, preserve_rb } => {- use pdfcraft_engine::form_scripts::LayerOp as Op;- let changes: Vec<(LayerOp, (u32, u16))> = changes- .into_iter()- .map(|(op, ocg)| {- let op = match op {- Op::On => LayerOp::On,- Op::Off => LayerOp::Off,- Op::Toggle => LayerOp::Toggle,- };- (op, ocg)- })- .collect();- set_layers(app, index, &changes, preserve_rb);- }- B::Alert(m) => app.notify(m),- B::Submit(url) => app.notify_fmt(- "{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries.",- &[("name", name), ("url", &url)],- ),- B::ImportIcon => app.choose_field_image(name),- B::Script(js) => {- let id = app.views[index].id;- app.run_button_script(id, name, &js);- }- }- }-- /// Run a set-layer-visibility action from a button or link. It changes what is shown, as the- /// Layers panel does (which follows), not the document.- fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerOp, (u32, u16))], preserve_rb: bool) {- let id = app.views[index].id;- if app.session.set_layer_state(id, changes, preserve_rb) {- app.views[index].invalidate_content();- }- }-- /// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not- /// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found- /// the view under the pointer.- fn zoom_anchor(ui: &egui::Ui) -> Option<Pos2> {- ui.input(|i| i.pointer.hover_pos())- }-- /// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is- /// read before the pages' widget exists, and the pointer may be past the view's edge.- fn drawing_edge_pointer(ui: &egui::Ui) -> (Option<Pos2>, f32) {- ui.input(|i| (i.pointer.latest_pos(), i.stable_dt))- }-- /// A press anywhere, or a key, stops the touchpad's glide (#531).- fn glide_interrupted(ui: &egui::Ui) -> bool {- ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })))- }-- /// Full screen's click on the document, which turns the page: a primary click this frame with the- /// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and- /// the turn waits until the pages have had the click.- fn presentation_click(ui: &egui::Ui, area: Rect) -> bool {- ui.rect_contains_pointer(area) && ui.input(|i| i.pointer.primary_clicked())- }-- /// Whether `p` lies in the bottom-left quadrant of `area`, where the page size shows (#1855).- fn in_size_hint_zone(area: Rect, p: Pos2) -> bool {- p.x >= area.min.x && p.x < area.center().x && p.y > area.center().y && p.y <= area.max.y- }-- /// The current page's size, floating at the bottom-left of the document area while the pointer is- /// in that quadrant, as Acrobat does. Same formatter and unit as Document Properties.- fn page_size_hint(view: &DocView, info: &DocInfo, units: crate::units::Unit, area: Rect, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let Some(page) = info.pages.get(view.current) else { return };- let inside = unobstructed && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| in_size_hint_zone(area, p));- if !inside {- return;- }- let text = units.size(f64::from(page.width), f64::from(page.height));- egui::Area::new(egui::Id::unique("page-size-hint"))- .order(egui::Order::Foreground)- .interactable(false)- .pivot(egui::Align2::LEFT_BOTTOM)- .fixed_pos(area.left_bottom() + vec2(14.0, -14.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(6))- .inner_margin(egui::Margin::symmetric(8, 4))- .show(ui, |ui| {- ui.add(egui::Label::new(egui::RichText::new(text).color(t.text)).selectable(false));- });- });- }-- /// Acrobat-style floating find bar at the top-right of the document area.- fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {- let Some(find) = view.find.as_mut() else { return };- // The Search panel shows this search.- if find.in_panel {- return;- }- let mut close = false;- let mut step: Option<bool> = None;- let searched = view.texts.len() + view.text_failed.len();- egui::Area::new(egui::Id::unique("find-bar"))- .order(egui::Order::Middle)- .pivot(Align2::RIGHT_TOP)- .fixed_pos(area.right_top() + vec2(-18.0, 12.0))- .show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(10))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) })- .inner_margin(egui::Margin::symmetric(10, 6))- .show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("search", 16.0, t.text_muted));- let edit = egui::TextEdit::singleline(&mut find.query)- .id(egui::Id::unique("find-input"))- .hint_text(tl!("Find text"))- .desired_width(220.0)- .frame(egui::Frame::NONE);- let r = ui.add(edit).accessible_name(tl!("Find text"));- if find.focus {- r.request_focus();- find.focus = false;- }- if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {- step = Some(!ui.input(|i| i.modifiers.shift));- r.request_focus();- }- if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {- close = true;- }- let status = if find.query.trim().is_empty() {- String::new()- } else if find.matches.is_empty() {- if searched < pages {- crate::i18n::fmt(tl!("Searching… {s}/{p}"), &[("s", &searched.to_string()), ("p", &pages.to_string())])- } else {- tl!("No matches").to_string()- }- } else {- let more = if searched < pages { "+" } else { "" };- crate::i18n::fmt(- tl!("{c} of {n}{more}"),- &[- ("c", &find.current.map(|c| c + 1).unwrap_or(0).to_string()),- ("n", &find.matches.len().to_string()),- ("more", more),- ],- )- };- ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted));- let tip = crate::commands::key_tip(ui.ctx(), tl!("Previous ({key})"), crate::commands::FIND_PREV);- if icons::button(ui, "chevron-up", 26.0, false, &tip).clicked() {- step = Some(false);- }- let tip = crate::commands::key_tip(ui.ctx(), tl!("Next ({key})"), crate::commands::FIND_NEXT);- if icons::button(ui, "chevron-down", 26.0, false, &tip).clicked() {- step = Some(true);- }- let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, tl!("Find options"));- egui::Popup::menu(&opts).show(|ui| {- let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed();- let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed();- if a || b {- // Search again with the new options.- find.case_query.clear();- }- });- if icons::button(ui, "x", 26.0, false, tl!("Close (Esc)")).clicked() {- close = true;- }- });- });- });- if close {- view.find = None;- return;- }- if find.query != find.case_query {- view.rerun_find();- }- if let Some(forward) = step {- view.find_step(forward);-- }--}----/// The prepare-mode field menu's choices.--enum FieldMenu {-- Properties,-- Duplicate(String),- }-- /// What the notice bar's buttons ask for.- enum Notice {- /// Reload the file that changed on disk, dropping unsaved changes.- Reload,- Security,- Signatures,- Repairs,- /// Highlight fields was turned on or off.- FieldHighlights(bool),- /// Open the JavaScript console (the form's scripts were turned off; the error is there).- Console,- /// Unlock… (enter the permissions password).- Unlock,- /// Close this historical snapshot tab (View signed version / View revision).- Close,- /// Stop showing the secured-document notice, in every document (#4035).- HideSecured,- }-- /// The notice bar above the pages: a file changed on disk first, then what a historical- /// snapshot is, then the signature status bar, a form's scripts having been turned- /// off, security, forms and warnings.- fn notices(- view: &mut DocView,- doc: &pdfcraft_engine::Document,- secured: bool,- repaired: bool,- signed: Option<(&str, Color32, &str, String)>,- ui: &mut egui::Ui,- t: &Tokens,- ) -> Option<Notice> {- let info = &doc.info;- let xfa = doc.xfa.as_ref();- // The file changed on disk while this document has unsaved changes (#431): ask before- // replacing it, ahead of every other notice.- if view.disk_changed {- let mut reload = false;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(icons::image("rotate-cw", 16.0, t.accent_text));- ui.label(- egui::RichText::new(tl!(- "This file changed on disk. Reload shows the new version and drops your unsaved changes; Save replaces it with this version."- ))- .color(t.text),- );- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.disk_changed = false;- }- reload = crate::widgets::pill_button(ui, tl!("Reload"), false).clicked();- });- });- });- return reload.then_some(Notice::Reload);- }- // A historical snapshot (View signed version / View revision): what it is, above the- // signature and security bars, so the tab is never mistaken for the live document.- if let Some(snap) = view.snapshot.as_ref() {- let mut close = false;- let text = if snap.kind == SnapshotKind::SignedVersion {- crate::i18n::fmt(- tl!("You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original."),- &[("from", &snap.from), ("rev", &snap.revision.to_string())],- )- } else {- crate::i18n::fmt(- tl!("You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original."),- &[("rev", &snap.revision.to_string()), ("from", &snap.from)],- )- };- notice_bar(ui, t, "clock", t.accent_text, text, |ui| {- if crate::widgets::pill_button(ui, tl!("Close"), true).clicked() {- close = true;- }- });- if close {- return Some(Notice::Close);- }- }- if let Some((icon, color, template, arg)) = signed {- let mut open = false;- notice_bar(ui, t, icon, color, crate::i18n::fmt(tl!(template), &[("by", &arg)]), |ui| {- if crate::widgets::pill_button(ui, tl!("Signature panel"), false).clicked() {- open = true;- }- });- return open.then_some(Notice::Signatures);- }- if view.notice_dismissed {- return None;- }- let mut open_security = false;- let mut unlock = false;- let mut hide_secured = false;- let mut open_repairs = false;- let mut open_console = false;- let mut toggled = None;- // A form whose scripts were turned off no longer calculates or answers its buttons: that- // comes before what else there is to say about the document.- let scripts_off = doc.xfa_scripts_off();- // What the document is as a form, if it is one: what the bar says first, secured or not.- let form = if let Some(x) = xfa {- let lang = crate::i18n::current();- let pages = crate::i18n::trn(lang, x.pages as u64, "{n} page", "{n} pages");- let fields = crate::i18n::trn(lang, x.fields as u64, "{n} field", "{n} fields");- let mut text =- crate::i18n::fmt(tl!("Dynamic XFA form laid out from its template: {pages}, {fields}."), &[("pages", &pages), ("fields", &fields)]);- if !x.warnings.is_empty() {- // The notes are clauses ("a picture is left out"); the first starts a sentence here.- let notes = x.warnings.join("; ");- let mut chars = notes.chars();- text.push(' ');- text.extend(chars.next().into_iter().flat_map(char::to_uppercase));- text.push_str(chars.as_str());- text.push('.');- }- Some(("text-cursor-input", text, true))- } else if info.xfa == Some(pdfcraft_render::Xfa::Dynamic) {- Some((- "triangle-alert",- tl!("This is a dynamic XFA form, which PdfCraft can't display yet. What you see is the file's placeholder page.").to_string(),- false,- ))- } else if info.xfa == Some(pdfcraft_render::Xfa::Static) {- Some((- "text-cursor-input",- tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(),- true,- ))- } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) {- // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in.- Some((- "text-cursor-input",- crate::i18n::fmt(tl!("This document contains {n} interactive form fields."), &[("n", &info.fields.len().to_string())]),- true,- ))- } else {- None- };- let msg = if scripts_off {- Some(("triangle-alert", crate::js_ui::scripts_off_notice(), true))- } else if secured {- // A secured form still says what it is, and keeps Highlight fields: the security- // sentence follows the form's.- let security = tl!("This document is secured. Some changes are restricted by its security settings.");- Some(match form {- Some((icon, text, fields)) => (icon, format!("{text} {security}"), fields),- None => ("lock", security.to_string(), false),- })- } else if form.is_some() {- form- } else if repaired {- Some(("bandage", tl!("This file was damaged and has been repaired. Saving keeps the repaired version.").to_string(), false))- } else if !info.warnings.is_empty() {- Some(("triangle-alert", info.warnings[0].clone(), false))- } else {- None- };- let (icon, text, fields) = msg?;- notice_bar(ui, t, icon, t.accent_text, text, |ui| {- if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {- view.notice_dismissed = true;- }- if fields {- let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") };- if crate::widgets::pill_button(ui, label, view.highlight_fields).clicked() {- view.highlight_fields = !view.highlight_fields;- toggled = Some(Notice::FieldHighlights(view.highlight_fields));- }- }- if scripts_off && crate::widgets::pill_button(ui, tl!("JavaScript Console"), false).clicked() {- open_console = true;- }- if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {- open_security = true;- }- if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {- unlock = true;- }- // Only when the bar shows the security message: a form's stopped scripts come first.- if secured && !scripts_off && crate::widgets::pill_button(ui, tl!("Don't show again"), false).clicked() {- hide_secured = true;- }- if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {- open_repairs = true;- }- });- if open_repairs {- return Some(Notice::Repairs);- }- if open_console {- return Some(Notice::Console);- }- if unlock {- return Some(Notice::Unlock);- }- if hide_secured {- return Some(Notice::HideSecured);- }- open_security.then_some(Notice::Security).or(toggled)- }-- /// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the- /// right. The buttons are laid out first, so the message only gets the width they leave: it- /// wraps there (or, when very little is left, is cut short with the full text on hover) instead- /// of running under the buttons and past the document area into the side panel (#785). The- /// buttons are centred on a row of button height, and the message's first line is centred on- /// the same row; a wrapped message grows the bar downwards.- fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, text: String, buttons: impl FnOnce(&mut egui::Ui)) {- const ROW: f32 = 28.0;- const ICON: f32 = 16.0;- egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {- let width = ui.available_width();- ui.allocate_ui_with_layout(vec2(width, ROW), egui::Layout::right_to_left(egui::Align::Center), |ui| {- ui.set_min_height(ROW);- buttons(ui);- let rest = ui.available_width().max(0.0);- ui.allocate_ui_with_layout(vec2(rest, ROW), egui::Layout::top_down(egui::Align::Min), |ui| {- let font = egui::TextStyle::Body.resolve(ui.style());- let line = ui.fonts_mut(|f| f.row_height(&font)).max(ICON);- ui.add_space(((ROW - line) / 2.0).max(0.0));- ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {- let (slot, _) = ui.allocate_exact_size(vec2(ICON, line), Sense::hover());- icons::paint(ui, Rect::from_center_size(slot.center(), vec2(ICON, ICON)), icon, ICON, icon_color);- let label = egui::Label::new(egui::RichText::new(text).color(t.text));- // Wrapping into a sliver would stack the message a few letters per line.- ui.add(if ui.available_width() >= 120.0 { label.wrap() } else { label.truncate() });- });- });- });- });- }-- /// The floating quick-action bar at the left edge of the document area.- fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- let pos = area.left_top() + vec2(14.0, 14.0);- egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {- egui::Frame::NONE- .fill(t.card)- .stroke(Stroke::new(1.0, t.border))- .corner_radius(CornerRadius::same(12))- .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) })- .inner_margin(egui::Margin::same(6))- .show(ui, |ui| {- ui.spacing_mut().item_spacing.y = 2.0;- ui.vertical(|ui| {- if icons::button(ui, "mouse-pointer-2", 32.0, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() {- app.quick_tool = QuickTool::Select;- }- if icons::button(ui, "hand", 32.0, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() {- app.quick_tool = QuickTool::Hand;- }- // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a- // group selects its last-used tool; clicking it again opens the flyout.- for g in 0..comments::GROUPS.len() {- let current = app.comment_prefs.group_tool[g];- let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g);- let resp = icons::button(ui, current.icon(), 32.0, active, tl!(current.label()));- // A small corner triangle marks the flyout.- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE));- let open = (resp.clicked() && active) || resp.secondary_clicked();- if resp.clicked() && !active {- app.execute(current.command());- }- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in comments::GROUPS[g] {- let on = app.quick_tool == QuickTool::Comment(*tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- });- }- // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar)- // or the tool is in use.- if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText {- let on = app.quick_tool == QuickTool::EditText;- if icons::button(ui, "text-cursor-input", 32.0, on, tl!("Edit text & images")).clicked() {- if on {- app.put_down_edit_text();- } else {- app.quick_tool = QuickTool::EditText;- }- }- }- // Fill & Sign ▸ (text, marks, date, signature).- let current_fill = match app.quick_tool {- QuickTool::Fill(f) => Some(f),- _ => None,- };- let shown = current_fill.unwrap_or(crate::fill_sign::FillTool::Text);- let resp = icons::button(- ui,- if current_fill.is_some() { shown.icon() } else { "pen-line" },- 32.0,- current_fill.is_some(),- tl!("Fill & Sign"),- );- let r = resp.rect;- let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];- ui.painter().add(egui::Shape::convex_polygon(- tri.to_vec(),- if current_fill.is_some() { t.accent } else { t.text_faint },- Stroke::NONE,- ));- if resp.clicked() && current_fill.is_none() {- app.execute(shown.command());- }- let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked();- egui::Popup::menu(&resp)- .open_memory(open.then_some(egui::SetOpenCommand::Toggle))- .align(egui::RectAlign::RIGHT_START)- .gap(6.0)- .show(|ui| {- for tool in crate::fill_sign::FILL_TOOLS {- if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) {- continue;- }- let on = current_fill == Some(tool);- let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());- let press = theme::Press::track(ui, &click);- press.wash(ui, row, 4, on);- let body = row.translate(press.offset());- icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);- let reserve = if on { 28.0 } else { 8.0 };- crate::widgets::paint_left(- ui,- body.left_center() + vec2(34.0, 0.0),- tl!(tool.label()),- theme::regular(13.0),- t.text,- (row.width() - 34.0 - reserve).max(0.0),- );- if on {- icons::paint(- ui,- Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),- "check",- 14.0,- t.accent,- );- }- let click = theme::hand(click);- let info = tl!(tool.label()).to_string();- click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));- if click.clicked() {- app.execute(tool.command());- ui.close();- }- }- ui.separator();- if let Some(command) = crate::fill_sign::signature_entries(ui, app, &t) {- app.execute(command);- ui.close();- }- });- if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {- ui.label(tl!("Font size:"));- let size = ui.add(- egui::DragValue::new(&mut app.fill_text_size)- .range(crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE)- .speed(0.25)- .suffix(" pt"),- );- // #1274: the size also applies to the Fill & Sign text that is selected,- // once per change (a typed value, or the end of a drag), so a drag adds- // one undo step and not one per frame.- if ((size.changed() && !size.dragged()) || size.drag_stopped())- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && a.fill_sign && a.subtype == "FreeText" && !a.locked)- })- {- app.apply_edit(Edit::FontSizeAnnotation { page, index: annotation, size: app.fill_text_size });- }- }- if let QuickTool::Comment(tool) = app.quick_tool {- let (r, _) = ui.allocate_exact_size(vec2(32.0, 9.0), Sense::hover());- ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider));- if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs)- && let Some((index, id)) = app.active_ids()- && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)- && app.session.get(id).is_some_and(|doc| {- doc.allows_annotation()- && doc- .info- .annotations- .iter()- .any(|a| a.page == page && a.index == annotation && !a.is_reply() && comments::made_by(a, tool))- })- {- app.apply_edit(Edit::StyleAnnotation {- page,- index: annotation,- color: Some(color),- opacity: None,- width: None,- endings: None,- });- }- }- });- });- });- }-- /// Where a page of `page` size (points, as shown: after its rotation) is drawn in the grid cell- /// `cell`: as large as the picture area allows and centred in it, so a landscape or rotated page- /// fills the cell's width in its middle, as Acrobat draws it, instead of a small strip at the top.- /// The picture area leaves room for the page number and actions below. Its sides narrow only when- /// a picture that wide would reach the selection checkbox in the cell's corner.- pub(crate) fn grid_page_rect(cell: Rect, page: Vec2) -> Rect {- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- // A page size from a damaged file can be zero, NaN or infinite; draw such a page square.- let side = |v: f32| if v.is_finite() { v.max(1.0) } else { 1.0 };- let (w, h) = (side(page.x), side(page.y));- let fit = |margin: f32| {- let s = ((area.width() - 2.0 * margin).max(1.0) / w).min(area.height().max(1.0) / h);- Rect::from_center_size(area.center(), vec2(w * s, h * s))- };- let wide = fit(16.0);- // The checkbox sits at (8, 8)-(28, 28) from the cell's corner; keep 4 px clear of it.- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0)).expand(4.0);- if wide.intersects(checkbox) { fit(30.0) } else { wide }- }-- /// The organize toolbar: page operations on the selection (Acrobat's Organize Pages bar).- fn organize_toolbar(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let targets = view.target_pages();- let n = info.pages.len();- let (first, last) = (targets.first().copied().unwrap_or(0), targets.last().copied().unwrap_or(0));- egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(16, 8)).show(ui, |ui| {- ui.horizontal(|ui| {- ui.spacing_mut().item_spacing.x = 4.0;- let label = match view.selected.len() {- 0 => crate::i18n::fmt(tl!("Page {p} of {n}"), &[("p", &(view.current + 1).to_string()), ("n", &n.to_string())]),- 1 => tl!("1 page selected").to_string(),- k => crate::i18n::fmt(tl!("{n} pages selected"), &[("n", &k.to_string())]),- };- // Fixed width so the buttons never shift as the selection text changes.- ui.add_sized([150.0, 30.0], egui::Label::new(egui::RichText::new(label).font(theme::medium(13.0)).color(t.text_muted)).truncate());- ui.add_enabled_ui(editable, |ui| {- ui.add_space(8.0);- if ui.add_enabled_ui(first > 0, |ui| icons::button(ui, "chevron-left", 30.0, false, tl!("Move earlier"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first - 1 });- }- if ui.add_enabled_ui(last + 1 < n, |ui| icons::button(ui, "chevron-right", 30.0, false, tl!("Move later"))).inner.clicked() {- view.pending_edit = Some(Edit::MovePages { pages: targets.clone(), to: first + 1 });- }- });- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if widgets::ghost_button(ui, "x", tl!("Close")).on_hover_text(tl!("Back to the document")).clicked() {- view.organize = false;- }- // What the grid shows is what is saved.- let save = ui.add_enabled_ui(dirty, |ui| widgets::pill_button(ui, tl!("Save pages"), true)).inner;- if save.on_hover_text(tl!("Save these pages as one PDF")).on_disabled_hover_text(tl!("No changes to save")).clicked() {- view.pending_action = Some(ViewAction::Save);- }- ui.add_space(8.0);- // Page size in the grid (right to left: in, the percentage, out).- let zoom = view.grid_zoom;- if ui- .add_enabled_ui(zoom < *GRID_ZOOM_RANGE.end(), |ui| icons::button(ui, "zoom-in", 30.0, false, tl!("Larger pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom * GRID_ZOOM_STEP);- }- let percent = egui::Button::new(egui::RichText::new(format!("{:.0}%", zoom * 100.0)).font(theme::medium(12.0)).color(t.text_muted))- .frame(false);- let percent = ui.add_sized([44.0, 30.0], percent);- percent.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Reset page size")));- if percent.on_hover_text(tl!("Reset page size")).clicked() {- view.grid_zoom_request = Some(1.0);- }- if ui- .add_enabled_ui(zoom > *GRID_ZOOM_RANGE.start(), |ui| icons::button(ui, "zoom-out", 30.0, false, tl!("Smaller pages")))- .inner- .clicked()- {- view.grid_zoom_request = Some(zoom / GRID_ZOOM_STEP);- }- });- });- });- // Keys act on the selection unless a text field or a dialog has them (Delete under- // Preferences deleted the selected pages).- if editable && unobstructed && !ui.ctx().egui_wants_keyboard_input() {- use egui::{Key, Modifiers};- let (del, esc) = ui.input_mut(|i| {- (- i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace),- i.consume_key(Modifiers::NONE, Key::Escape),- )- });- // ⌘C / ⌘X / ⌘V copy, cut and paste pages (egui delivers them as clipboard events).- let (copy, cut, paste) = ui.input(|i| {- let any = |f: &dyn Fn(&egui::Event) -> bool| i.events.iter().any(f);- (any(&|e| matches!(e, egui::Event::Copy)), any(&|e| matches!(e, egui::Event::Cut)), any(&|e| matches!(e, egui::Event::Paste(_))))- });- if copy || cut {- view.pending_action = Some(ViewAction::CopyPages { cut });- }- if paste {- view.pending_action = Some(ViewAction::PastePages);- }- if del && targets.len() < n {- view.pending_edit = Some(Edit::DeletePages { pages: targets });- }- if esc {- view.selected.clear();- }- }- }-- /// Organize pages: a thumbnail grid (Acrobat's Organize Pages view). Click selects, ⌘-click- /// toggles, ⇧-click extends; double-click opens the page.- /// The gap (0 = before the first page, n = after the last) the pointer points at in the grid.- pub(crate) fn drop_gap(cells: &[(usize, Rect)], p: Pos2) -> Option<usize> {- let (i, r) = cells.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(p).total_cmp(&b.distance_sq_to_pos(p)))?;- Some(if p.x < r.center().x { *i } else { i + 1 })- }-- /// Ctrl (Option on macOS) held when a page drag drops copies the dragged pages into the gap- /// instead of moving them, as Acrobat's Organize Pages does.- ///- /// The OS comes from the context, not `cfg!`: the wasm build runs on macOS too, where- /// `cfg!(target_os = "macos")` is false, so Option has to copy there as well (#3092 review).- fn copy_modifier(ctx: &egui::Context, m: &egui::Modifiers) -> bool {- if crate::commands::mac_shortcuts(ctx) { m.alt } else { m.ctrl }- }-- /// A "+" on a gap of the page grid: insert files there. Returns whether it was clicked.- fn gap_button(ui: &mut egui::Ui, gap: usize, at: Pos2, height: f32, label: String, t: &Tokens) -> bool {- let resp = ui.interact(Rect::from_center_size(at, Vec2::splat(22.0)), ui.scope_id().with(("org-gap", gap)), Sense::click());- resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label.clone()));- let hot = resp.hovered();- if hot {- ui.painter().line_segment([pos2(at.x, at.y - height / 2.0), pos2(at.x, at.y + height / 2.0)], Stroke::new(3.0, t.accent));- }- ui.painter().circle(at, 9.0, if hot { t.accent } else { t.chrome }, Stroke::new(1.0, if hot { t.accent } else { t.border }));- let ink = Stroke::new(1.5, if hot { Color32::WHITE } else { t.text_muted });- ui.painter().line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], ink);- resp.on_hover_text(label).clicked()- }-- fn organize_grid(view: &mut DocView, info: &DocInfo, editable: bool, dirty: bool, unobstructed: bool, ui: &mut egui::Ui, t: &Tokens) {- let ppp = ui.ctx().pixels_per_point();- // The page image scales with the zoom; the padding and the page number don't.- let cell = vec2(146.0 * view.grid_zoom + 44.0, 194.0 * view.grid_zoom + 88.0);- let anchor = view.grid_anchor.take();- let reveal = view.grid_reveal.take();- let mut open_page = None;- organize_toolbar(view, info, editable, dirty, unobstructed, ui, t);- let viewport = ui.available_rect_before_wrap();- view.viewport_screen = viewport;- let auto_delta = if unobstructed {- view.auto_scroll.update(ui, viewport, true)- } else {- view.auto_scroll.cancel();- Vec2::ZERO- };- let middle_gesture = view.auto_scroll.blocks_input();- let mut cells: Vec<(usize, Rect)> = Vec::new();- // The pages in view that are drawn larger than their thumbnails, and those of them that- // need a sharper render than they have. The width is the size drawn, in device pixels.- let (mut in_view, mut sharper): (Vec<(usize, f32)>, Vec<RenderRequest>) = (Vec::new(), Vec::new());- // The source cell can scroll out of the virtualized rows during a drag.- let mut drop = view.org_drag.is_some() && ui.input(|i| i.pointer.primary_released());- egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, clip| {- if middle_gesture {- let opacity = ui.opacity();- ui.disable();- ui.set_opacity(opacity);- }- if auto_delta != Vec2::ZERO {- ui.scroll_with_delta_animation(auto_delta, egui::style::ScrollAnimation::none());- }- ui.add_space(20.0);- let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;- let rows = info.pages.len().div_ceil(cols);- let left = (ui.available_width() - cols as f32 * cell.x) / 2.0;- let (grid, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * cell.y), Sense::hover());- // The page Organize opened on may lie in a row the virtualized grid has not laid out,- // so its cell is computed rather than found.- if let Some(page) = reveal.filter(|p| *p < info.pages.len()) {- let row = page / cols;- let col = page % cols;- let c = Rect::from_min_size(pos2(grid.left() + left + col as f32 * cell.x, grid.top() + row as f32 * cell.y), cell);- ui.scroll_to_rect_animation(c, Some(egui::Align::Center), egui::style::ScrollAnimation::none());- }- for row in thumbnail_rows(clip.top() - 20.0, clip.bottom() - 20.0, cell.y, rows) {- let row_rect = Rect::from_min_size(grid.min + vec2(0.0, row as f32 * cell.y), vec2(grid.width(), cell.y));- for col in 0..cols {- let i = row * cols + col;- let Some(p) = info.pages.get(i) else { break };- let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);- view.need_thumbnail(i, c.intersects(ui.clip_rect()));- let resp = ui.interact(c, ui.scope_id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });- cells.push((i, c));- if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {- ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());- }- // Drag pages to move them (the selection, or the page grabbed).- if resp.drag_started() {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.select_anchor = Some(i);- }- let mut pages: Vec<usize> = view.selected.iter().copied().collect();- pages.sort_unstable();- view.org_drag = Some(pages);- }- if resp.drag_stopped() {- drop = true;- }- let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);- resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, view.selected.contains(&i), page_label.clone()));- let pr = grid_page_rect(c, vec2(p.width, p.height));- let size = pr.size();- let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);- if selected || resp.hovered() {- ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });- }- if view.selected.contains(&i) {- ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);- }- ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);- ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);- // A page drawn larger than its thumbnail gets a render at the size drawn, while- // it is in view; until that arrives the thumbnail stands in.- let want = size.x * ppp;- let thumb = view.thumbs.get(&i).map(|t| &t.tex);- let thumb_ok = thumb.is_some_and(|t| t.size()[0] as f32 >= want * GRID_SHARP.start());- let sharp = view.grid_pages.get(&i).filter(|_| !thumb_ok);- if !thumb_ok && ui.is_rect_visible(c) {- in_view.push((i, want));- if !sharp.is_some_and(|(w, _)| sharp_enough(*w, want)) && !view.errors.contains_key(&i) {- sharper.push(RenderRequest {- page: i,- kind: RequestKind::Pixels,- tile: None,- scale: want / p.width.max(1.0),- tag: GRID_TAG,- // Grid cells are previews: tiny images are skipped for them.- preview: true,- });- }- }- if let Some(tex) = sharp.map(|(_, t)| t).or(thumb) {- ui.painter().image(tex.id(), pr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);- }- ui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);- let label_font = theme::medium(12.0);- let label_w = (c.width() - 12.0).max(0.0);- let page_label = crate::widgets::fit_line(&p.label, label_w, |s| crate::widgets::text_width(ui, s, &label_font));- let label_pos = pos2(c.center().x, c.bottom() - 48.0);- ui.painter().with_clip_rect(Rect::from_center_size(label_pos, vec2(label_w, 18.0))).text(- label_pos,- Align2::CENTER_CENTER,- page_label,- label_font,- t.text_muted,- );- // The checkbox toggles just this page without requiring a modifier. Keep it- // outside the page image, including on very tall or wide pages.- let mut checked = view.selected.contains(&i);- let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;- let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);- check.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, checked, label.clone()));- if check.on_hover_text(label).changed() {- view.click_page(i, egui::Modifiers::COMMAND, false);- // The document shows the page picked here when the grid closes, as after a- // Pages-panel click, so reopening the grid keeps the pick (issue #1910).- view.go_to_page(i);- }- // Local actions always target the labelled page. The toolbar above the grid- // remains the place for actions on the whole selection.- if selected || resp.contains_pointer() || resp.has_focus() {- let actions = Rect::from_center_size(pos2(c.center().x, c.bottom() - 24.0), vec2(84.0, 26.0));- ui.scope_builder(- egui::UiBuilder::new().id_salt(("org-actions", i)).max_rect(actions).layout(egui::Layout::left_to_right(egui::Align::Center)),- |ui| {- ui.spacing_mut().item_spacing.x = 3.0;- ui.add_enabled_ui(editable, |ui| {- for (icon, degrees, key) in- [("rotate-ccw", -90, "Rotate page {label} counterclockwise"), ("rotate-cw", 90, "Rotate page {label} clockwise")]- {- let label = crate::i18n::fmt(tl!(key), &[("label", &p.label)]);- if icons::button(ui, icon, 26.0, false, &label).clicked() {- view.pending_edit = Some(Edit::RotatePages { pages: vec![i], degrees });- }- }- let label = crate::i18n::fmt(tl!("Delete page {label}"), &[("label", &p.label)]);- if ui.add_enabled_ui(info.pages.len() > 1, |ui| icons::button(ui, "trash-2", 26.0, false, &label)).inner.clicked() {- view.pending_edit = Some(Edit::DeletePages { pages: vec![i] });- }- });- },- );- }- if resp.clicked() {- let m = ui.input(|i| i.modifiers);- view.click_page(i, m, false);- view.go_to_page(i);- }- if resp.double_clicked() {- open_page = Some(i);- }- // Right-click: Extract, Replace, Cut, Copy, Paste (on the selection, or this page).- resp.context_menu(|ui| {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.go_to_page(i);- }- if ui.button(tl!("Extract pages")).clicked() {- view.pending_action = Some(ViewAction::Extract);- ui.close();- }- if ui.button(tl!("Split document…")).clicked() {- view.pending_action = Some(ViewAction::SplitBeforeSelected);- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Replace pages…"))).clicked() {- view.pending_action = Some(ViewAction::ReplacePages);- ui.close();- }- ui.separator();- if ui.add_enabled(editable, egui::Button::new(tl!("Cut"))).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: true });- ui.close();- }- if ui.button(tl!("Copy")).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: false });- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Paste after"))).clicked() {- view.pending_action = Some(ViewAction::PastePages);- ui.close();- }- });- }- }- // Between pages (and at both ends): insert files right there.- if editable && !middle_gesture && view.org_drag.is_none() {- let mid = |r: &Rect| r.top() + 16.0 + (cell.y - 88.0) / 2.0;- for (i, c) in &cells {- let label = info- .pages- .get(*i)- .map(|p| crate::i18n::fmt(tl!("Insert a file before page {label}"), &[("label", &p.label)]))- .unwrap_or_default();- if gap_button(ui, *i, pos2(c.left(), mid(c)), cell.y - 88.0, label, t) {- view.pending_action = Some(ViewAction::InsertFromFileAt(*i));- }- }- if let Some((i, c)) = cells.last()- && i + 1 == info.pages.len()- && gap_button(ui, i + 1, pos2(c.right(), mid(c)), cell.y - 88.0, tl!("Insert a file at the end").to_string(), t)- {- view.pending_action = Some(ViewAction::InsertFromFileAt(i + 1));- }- }- // While dragging: the gap the pages would go to, drawn as a bar.- if let (Some(pages), Some(p)) = (view.org_drag.clone(), ui.input(|i| i.pointer.hover_pos())) {- // Ctrl (Option on macOS) held over the drop copies the pages; see #2997.- let copying = copy_modifier(ui.ctx(), &ui.input(|i| i.modifiers));- if let Some(gap) = drop_gap(&cells, p) {- let x = match cells.iter().find(|(i, _)| *i == gap) {- Some((_, r)) => r.left() + 3.0,- None => cells.last().map_or(0.0, |(_, r)| r.right() - 3.0),- };- let row = cells.iter().find(|(i, _)| *i == gap).or(cells.last()).map(|(_, r)| r.y_range()).unwrap_or(egui::Rangef::new(0.0, 0.0));- ui.painter().line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- let mut text_at = p + vec2(14.0, 14.0);- if copying {- // A "+" by the pointer: this drop copies the pages, it doesn't move them.- let badge = p + vec2(12.0, 12.0);- ui.painter().circle(badge, 9.0, t.accent, Stroke::new(1.0, t.accent));- let ink = Stroke::new(1.5, Color32::WHITE);- ui.painter().line_segment([badge - vec2(4.0, 0.0), badge + vec2(4.0, 0.0)], ink);- ui.painter().line_segment([badge - vec2(0.0, 4.0), badge + vec2(0.0, 4.0)], ink);- text_at.x += 18.0;- }- ui.painter().text(- text_at,- Align2::LEFT_TOP,- if pages.len() == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &pages.len().to_string())]) },- theme::medium(12.0),- t.accent_text,- );- }- if drop {- view.org_drag = None;- if let Some(gap) = drop_gap(&cells, p) {- if copying {- // The copies land at the gap as it is: nothing leaves its place.- view.pending_edit = Some(Edit::DuplicatePages { pages: pages.clone(), at: Some(gap) });- view.selected = (gap..gap + pages.len()).collect();- } else {- // `to` counts positions without the moving pages.- let to = gap - pages.iter().filter(|x| **x < gap).count();- let first = pages[0];- let contiguous = pages.windows(2).all(|w| w[1] == w[0] + 1);- if !(contiguous && to == first) {- view.pending_edit = Some(Edit::MovePages { pages: pages.clone(), to });- view.selected = (to..to + pages.len()).collect();- }- }- }- }- } else if drop {- view.org_drag = None;- }- });- // Files dragged in from outside go to the gap under the pointer. Some platforms don't say- // where the pointer is until the files are dropped; then the whole grid is the target.- let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| viewport.contains(*p));- view.grid_gap = pointer.filter(|_| editable && view.org_drag.is_none()).and_then(|p| drop_gap(&cells, p));- if editable && ui.input(|i| !i.raw.hovered_files.is_empty()) {- let painter = ui.painter().with_clip_rect(viewport);- painter.rect_stroke(viewport.shrink(2.0), CornerRadius::same(6), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);- if let Some(gap) = view.grid_gap {- let at = cells.iter().find(|(i, _)| *i == gap).map(|(_, r)| (r.left() + 3.0, r.y_range()));- if let Some((x, row)) = at.or(cells.last().map(|(_, r)| (r.right() - 3.0, r.y_range()))) {- painter.line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- }- }- // A "+" that follows the pointer.- if let Some(p) = pointer {- let at = p + vec2(16.0, 16.0);- painter.circle_filled(at, 9.0, t.accent);- painter.line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], Stroke::new(1.5, Color32::WHITE));- painter.line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], Stroke::new(1.5, Color32::WHITE));- }- }- view.auto_scroll.paint(ui, viewport);- // Pinch, or Ctrl/⌘ with the wheel, zooms the grid about the page under the pointer.- let pinch = crate::motion::zoom_delta(ui.ctx());- if (pinch - 1.0).abs() > 0.001 && pointer.is_some() && !middle_gesture {- view.grid_zoom_request = Some(view.grid_zoom * pinch);- }- if let Some(zoom) = view.grid_zoom_request.take() {- let before = view.grid_zoom;- view.set_grid_zoom(zoom);- if view.grid_zoom != before {- // Keep the page under the pointer (or else the first one in view) where it is.- let under = pointer.and_then(|p| cells.iter().find(|(_, r)| r.contains(p)));- let anchor = under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top()));- view.grid_anchor = anchor.map(|(i, r)| (*i, r.top() - viewport.top()));- ui.ctx().request_repaint();- }- }- // When this frame's thumbnail will cover the cell, drop the sharp render without waiting- // for that texture to arrive.- let density = thumbnail_density(view.thumb_demand.len(), ppp);- in_view.retain(|&(page, want)| {- info.pages.get(page).is_none_or(|p| (device_pixels(p.width, thumbnail_scale(p.width, p.height, density)) as f32) < want * GRID_SHARP.start())- });- sharper.retain(|req| in_view.iter().any(|(page, _)| *page == req.page));- view.grid_pages.retain(|page, _| in_view.iter().any(|(kept, _)| kept == page));- // Sharp renders of the pages in view join this frame's demand ahead of the thumbnails.- view.frame_queue.extend(sharper);- if let Some(p) = open_page {- view.organize = false;- view.go_to_page(p);- }- }-- /// 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 {- match bytemuck::allocation::try_cast_vec::<u32, Color32>(pixels.into_words()) {- Ok(px) if px.len() == size[0].saturating_mul(size[1]) => egui::ColorImage::new(size, px),- Ok(px) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&px)),- Err((_, words)) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&words)),- }- }-- /// A luminance preview for a monochrome print. `Color32` stores premultiplied pixels, so a- /// non-opaque colour's alpha is restored after multiplying the unmultiplied RGB by its- /// luminance. This uses the display gamma-space weights users expect in editors/print dialogs,- /// not the linear-light coefficients of a colour-managed render.- fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage {- for c in img.pixels.iter_mut() {- let a = c.a();- let luminance = f32::from(c.r()) * 0.299_f32 + f32::from(c.g()) * 0.587_f32 + f32::from(c.b()) * 0.114_f32;- let gray = if a == 0 || a == 255 {- luminance.round() as u8- } else {- // Unmultiply first, so translucent content keeps its paper-relative luminance.- let f = f32::from(a) / 255.0;- let un = [f32::from(c.r()) / f, f32::from(c.g()) / f, f32::from(c.b()) / f];- let l = un[0] * 0.299_f32 + un[1] * 0.587_f32 + un[2] * 0.114_f32;- (f * l).round() as u8- };- *c = Color32::from_rgba_premultiplied(gray, gray, gray, a);- }- img--}-- pub use crate::image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};----#[cfg(test)]- mod tests {- #[test]- fn zoom_anchor_scroll_stays_within_the_content() {- let (content, viewport) = (vec2(1000.0, 2000.0), vec2(800.0, 600.0));- // Past the end: clamped to the maximum (200, 1400), not left for egui to snap back.- assert_eq!(anchored_scroll(pos2(900.0, 1900.0), vec2(0.0, 0.0), content, viewport), vec2(200.0, 1400.0));- // Before the start.- assert_eq!(anchored_scroll(pos2(10.0, 10.0), vec2(300.0, 300.0), content, viewport), Vec2::ZERO);- // Inside: unchanged.- assert_eq!(anchored_scroll(pos2(150.0, 800.0), vec2(100.0, 100.0), content, viewport), vec2(50.0, 700.0));- // Content smaller than the viewport: no scrolling.- assert_eq!(anchored_scroll(pos2(400.0, 400.0), Vec2::ZERO, vec2(500.0, 500.0), viewport), vec2(0.0, 0.0));- }-- #[test]- fn page_size_hint_zone_is_the_bottom_left_quadrant() {- let area = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 450.0));- assert!(in_size_hint_zone(area, pos2(110.0, 440.0)));- assert!(!in_size_hint_zone(area, pos2(110.0, 100.0)), "top-left");- assert!(!in_size_hint_zone(area, pos2(400.0, 440.0)), "bottom-right");- assert!(!in_size_hint_zone(area, pos2(50.0, 440.0)), "outside");- assert!(!in_size_hint_zone(area, pos2(f32::NAN, 440.0)));- }-- use super::*;-- #[test]- fn typed_zoom_percentages_parse() {- for (typed, zoom) in [("150", 1.5), ("150%", 1.5), (" 62.5 % ", 0.625), ("6400%", 64.0)] {- assert_eq!(DocView::parse_zoom_percent(typed), Some(zoom), "{typed}");- }- for typed in ["", "%", "abc", "0", "-50", "NaN", "inf", "1e40", "150%%x", "%150"] {- assert_eq!(DocView::parse_zoom_percent(typed), None, "{typed}");- }- }-- /// A rotated (landscape) page is drawn as wide as the cell allows and centred in the picture- /// area, as Acrobat draws it, not as a small strip pinned to the top; a portrait page still- /// fills the area's height; neither covers the checkbox corner or the label below.- #[test]- fn grid_pages_are_centred_and_as_large_as_the_cell_allows() {- let cell = Rect::from_min_size(pos2(100.0, 50.0), vec2(190.0, 282.0));- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let landscape = grid_page_rect(cell, vec2(842.0, 595.0));- assert!((landscape.center().y - area.center().y).abs() < 0.01, "centred vertically: {landscape:?}");- assert!((landscape.center().x - cell.center().x).abs() < 0.01);- assert!((landscape.width() - (cell.width() - 32.0)).abs() < 0.01, "as wide as the cell allows: {landscape:?}");- assert!(!landscape.intersects(checkbox));- let portrait = grid_page_rect(cell, vec2(595.0, 842.0));- assert!(area.contains_rect(portrait), "inside the picture area: {portrait:?}");- assert!((portrait.center().y - area.center().y).abs() < 0.01);- assert!(portrait.left() >= checkbox.right(), "clear of the checkbox: {portrait:?}");- // Degenerate sizes still give a finite rectangle inside the cell.- for page in [vec2(0.0, 0.0), vec2(1e9, 1.0), vec2(1.0, 1e9), vec2(f32::NAN, 10.0), vec2(f32::INFINITY, 10.0)] {- let r = grid_page_rect(cell, page);- assert!(r.is_finite() && cell.contains_rect(r), "{page:?} -> {r:?}");- }- }-- fn annotation(fill_sign: bool) -> pdfcraft_render::Annotation {- pdfcraft_render::Annotation {- page: 0,- subtype: "FreeText".into(),- author: None,- contents: Some("Hello".into()),- modified: None,- name: None,- in_reply_to: None,- parent: None,- grouped: false,- rect: [0.0; 4],- color: None,- index: 0,- state: None,- quads: Vec::new(),- locked: false,- intent: None,- fill_sign,- no_rotate: false,- points: Vec::new(),- }- }-- #[test]- fn hover_popup_skips_fill_and_sign_marks() {- assert_eq!(annotation_hover_text(&annotation(false)).as_deref(), Some("FreeText\nHello"));- assert_eq!(annotation_hover_text(&annotation(true)), None);- }-- fn signature(signed: bool, visible: bool, page: Option<usize>, rect: Option<[f64; 4]>) -> pdfcraft_engine::SignatureInfo {- pdfcraft_engine::SignatureInfo {- field: "Signature1".into(),- signed,- page,- rect,- visible,- signer: None,- certificate: None,- chain: Vec::new(),- date: None,- signing_time: None,- reason: None,- location: None,- contact: None,- sub_filter: None,- doc_timestamp: false,- certify: None,- revision: 1,- signed_len: 0,- digest: None,- algorithm: None,- timestamp: false,- timestamp_time: None,- status: pdfcraft_engine::SignatureStatus::Valid,- modification: pdfcraft_engine::sign::Modification::None,- details: Vec::new(),- }- }-- #[test]- fn signature_badges_keep_signed_visible_widgets_on_the_page() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures =- vec![signature(true, true, Some(0), Some(rect)), signature(true, true, Some(1), Some(rect)), signature(true, true, Some(0), Some(rect))];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 2);- assert_eq!(badges[0].rect, rect);- }-- #[test]- fn signature_badges_skip_unsigned_invisible_and_unplaced_fields() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures = vec![- signature(false, true, Some(0), Some(rect)),- signature(true, false, Some(0), Some(rect)),- signature(true, true, Some(0), None),- signature(true, true, Some(0), Some(rect)),- ];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);- assert_eq!(badges[0].rect, rect);- }-- #[test]- fn signature_badges_skip_rectangles_that_cannot_reach_the_screen() {- let hostile = vec![- [f64::NAN, 10.0, 100.0, 50.0],- [10.0, f64::INFINITY, 100.0, 50.0],- [10.0, 10.0, f64::NEG_INFINITY, 50.0],- [10.0, 10.0, 1e300, 50.0],- [10.0, 10.0, 100.0, 50.0],- ];- let signatures: Vec<_> = hostile.into_iter().map(|rect| signature(true, true, Some(0), Some(rect))).collect();- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);- }-- #[test]- fn page_zoom_reads_the_side_the_page_width_is_on() {- // A 200 x 100 pt page at 2 pixels per point: 400 x 200 on screen, or 200 x 400 turned.- let xf = |rot: u16, size: Vec2| PageXform { rect: Rect::from_min_size(Pos2::ZERO, size), rot, pw: 200.0, ph: 100.0 };- for rot in [0, 180] {- assert_eq!(xf(rot, vec2(400.0, 200.0)).zoom(), 2.0, "{rot}");- }- for rot in [90, 270] {- assert_eq!(xf(rot, vec2(200.0, 400.0)).zoom(), 2.0, "{rot}: the width runs down the screen");- }- }-- #[test]- fn snapshot_tabs_read_like_their_source_plus_the_suffix() {- let snap = Snapshot { kind: SnapshotKind::SignedVersion, revision: 1, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &snap), "Report (signed version)");- let rev = Snapshot { kind: SnapshotKind::Revision, revision: 2, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &rev), "Report (revision 2)");- assert_eq!(snapshot_tab_name("report.pdf", "report.pdf", &snap), "report.pdf");- assert_eq!(snapshot_tab_name("report (revision 2).pdf", "report (revision 2).pdf", &rev), "report (revision 2).pdf");- }-- #[test]- fn grayscale_converts_colours_to_their_luminance() {- let img = egui::ColorImage::new([2, 1], vec![Color32::from_rgb(255, 0, 0), Color32::from_rgba_premultiplied(0, 51, 102, 128)]);- let gray = grayscale(img);- let opaque = gray.pixels[0];- assert_eq!(opaque.to_array(), [76, 76, 76, 255]);- // Unmultiply RGB first, so a translucent colour keeps its paper-relative luminance.- let translucent = gray.pixels[1];- assert_eq!(translucent.to_array(), [42, 42, 42, 128]);- }-- #[test]- fn black_white_and_transparents_are_preserved_by_grayscale() {- let img = egui::ColorImage::new([3, 1], vec![Color32::BLACK, Color32::WHITE, Color32::TRANSPARENT]);- let gray = grayscale(img);- assert_eq!(gray.pixels[0].to_array(), [0, 0, 0, 255]);- assert_eq!(gray.pixels[1].to_array(), [255, 255, 255, 255]);- assert_eq!(gray.pixels[2].to_array(), [0, 0, 0, 0]);- }-- #[test]- fn rendered_rasters_become_texture_images_without_a_copy() {- let pdf = b"%PDF-1.4- 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj- 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj- 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 50] /Contents 4 0 R >> endobj- 4 0 obj << /Length 35 >> stream- 0 0 1 rg 10 10 30 20 re f- endstream endobj- trailer << /Root 1 0 R >>- %%EOF";- let mut r = pdfcraft_render::PageRenderer::new(Arc::new(pdf.to_vec()), Default::default());- let out = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.5, tag: 0, preview: false });- assert!(out.error.is_none(), "{:?}", out.error);- let size = [out.width as usize, out.height as usize];- let copied = egui::ColorImage::from_rgba_premultiplied(size, &out.rgba);- let at = out.rgba.as_ptr();- let img = texture_image(size, out.rgba);- assert_eq!(img, copied);- assert_eq!(img.pixels.as_ptr().cast::<u8>(), at, "the renderer's own buffer");- }-- #[test]- fn tiles_stay_granular_up_close_and_cover_giant_sheets_in_a_handful() {- // Ordinary zooms keep 1024 px tiles; degenerate scales fall back to it, never zero.- assert_eq!(tile_side(1.0, 2000), TILE);- assert_eq!(tile_side(4.0, 2000), TILE);- assert_eq!(tile_side(f32::NAN, 2000), TILE);- assert_eq!(tile_side(f32::INFINITY, 2000), TILE);- assert_eq!(tile_side(0.0, 2000), TILE);- // Zoomed viewports need a few large tiles instead of many small ones.- assert_eq!(tile_side(12.0, 2000), 2048);- assert_eq!(tile_side(20.0, 2000), 3413);- assert_eq!(tile_side(100.0, 2000), 4096);- // A giant sheet at fit width (6740 px long side) is covered four tiles a side.- assert_eq!(tile_side(96.0 / 72.0, 6740), 1685);- // The backend clamps tile sides at 4096.- assert_eq!(tile_side(20.0, 100_000), 4096);- }-- #[test]- fn grid_zoom_is_clamped_and_sharp_renders_tolerate_a_pinch() {- assert!(sharp_enough(900, 876.0) && sharp_enough(800, 876.0) && sharp_enough(1300, 876.0));- assert!(!sharp_enough(264, 876.0), "a thumbnail stretched over a zoomed page");- assert!(!sharp_enough(876, 200.0), "far larger than drawn: wasteful");- assert!(!sharp_enough(100, 0.0) && !sharp_enough(100, f32::NAN));- let mut v = view(3, PageLayout::Single, true);- for odd in [f32::NAN, f32::INFINITY] {- v.set_grid_zoom(odd);- assert_eq!(v.grid_zoom(), 1.0);- }- v.set_grid_zoom(99.0);- assert_eq!(v.grid_zoom(), 3.0);- v.set_grid_zoom(-4.0);- assert_eq!(v.grid_zoom(), 0.5);- }-- fn view(pages: usize, layout: PageLayout, continuous: bool) -> DocView {- let info = pdfcraft_render::DocInfo {- pages: (0..pages)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- DocView::new(DocId(1), &info, ViewDefaults { layout, continuous, ..Default::default() })- }-- fn history_search_view() -> DocView {- let mut v = view(5, PageLayout::Single, true);- v.texts.insert(- 3,- pdfcraft_render::PageText {- glyphs: vec![pdfcraft_render::TextGlyph {- text: "match".into(),- rect: [20.0, 260.0, 60.0, 280.0],- quad: [[20.0, 260.0], [60.0, 260.0], [60.0, 280.0], [20.0, 280.0]],- direction: [1.0, 0.0],- }],- line_of: vec![0],- space_before: vec![false],- }- .into(),- );- v.find = Some(Find { matches: vec![(3, 0..1), (3, 0..1), (1, 0..1)], current: Some(2), ..Default::default() });- v- }-- #[test]- fn explicit_search_jumps_record_history_and_keep_match_destination() {- for step in [None, Some(true), Some(false)] {- let mut v = history_search_view();- v.page_input = "draft in progress".into();- v.goto_point = Some((3, Some(0.8), Some(0.9), Vec2::ZERO));- if let Some(forward) = step {- v.find_step(forward);- } else {- v.go_to_match(0);- }- assert_eq!(v.back, vec![0], "explicit search jump must remember its origin");- assert_eq!(v.goto, Some((3, 0.5)), "keep the match offset instead of the page top");- assert_eq!(v.current, 3);- assert_eq!(v.current_page_label(None), "4");- // Chrome refreshes the idle page box; navigation must not overwrite a draft- // that may still be focused. DocView does not own the editor's focus state.- assert_eq!(v.page_input, "draft in progress");- assert!(v.goto_point.is_none(), "an earlier link destination cannot override the search offset");- v.go_to_match(1);- assert_eq!(v.back, vec![0], "same-page matches do not duplicate history");- assert!(v.view_history(false));- assert_eq!(v.current, 0);- assert!(v.view_history(true));- assert_eq!(v.current, 3);- assert!(v.view_history(false));- v.go_to_match(2);- assert!(v.forward.is_empty(), "a new explicit jump discards Forward");- assert_eq!(v.back, vec![0]);- }- }-- #[test]- fn automatic_search_updates_do_not_record_history_or_discard_forward() {- let mut v = history_search_view();- v.forward = vec![4];- v.find = Some(Find { query: "match".into(), ..Default::default() });- v.rerun_find();- assert_eq!(v.current, 3);- assert_eq!(v.goto, Some((3, 0.5)));- assert!(v.back.is_empty());- assert_eq!(v.forward, vec![4]);- v.find.as_mut().unwrap().current = None;- v.texts.insert(1, Arc::new(find_test_text("match")));- v.refresh_find_page(1);- assert_eq!(v.current, 1, "an automatic late match still follows its anchor");- assert!(v.back.is_empty(), "automatic search updates do not record history");- assert_eq!(v.forward, vec![4]);- }-- /// One glyph per character on one line, for the search-order tests below.- fn find_test_text(s: &str) -> PageText {- PageText {- glyphs: s- .chars()- .map(|c| pdfcraft_render::TextGlyph { text: c.into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] })- .collect(),- line_of: s.chars().map(|_| 0).collect(),- space_before: s.chars().map(|_| false).collect(),- }- }-- /// A text-layer result for `page`, for the search tests below.- fn find_text_result(page: usize, text: &str) -> pdfcraft_render::RenderedPage {- pdfcraft_render::RenderedPage {- request: RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() },- width: 0,- height: 0,- rgba: Default::default(),- error: None,- text: Some(Arc::new(find_test_text(text))),- warnings: Vec::new(),- millis: 0,- }- }-- /// Text layers arrive in whatever order the workers finish, not in page order. A search- /// started on page 1 must settle on page 1's match even when page 2's text arrives first,- /// instead of keeping the later match picked only because page 1 had not been read yet.- #[test]- fn automatic_search_match_follows_the_viewed_page_when_text_arrives_out_of_order() {- let mut v = view(2, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!(v.find.as_ref().unwrap().current, None, "no text yet, so no match");-- let ctx = egui::Context::default();- let request = |page| RenderRequest { page, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- let result = |page, text: &str| pdfcraft_render::RenderedPage {- request: request(page),- width: 0,- height: 0,- rgba: Default::default(),- error: None,- text: Some(Arc::new(find_test_text(text))),- warnings: Vec::new(),- millis: 0,- };- v.last_queue = vec![request(1), request(0)];- // Page 2's text finishes first, as it can when the workers race.- v.receive_result(&ctx, result(1, "Second page sample text"));- assert_eq!(v.find.as_ref().unwrap().current, Some(0), "the only known match is picked while page 1 is pending");-- v.receive_result(&ctx, result(0, "Panel sample draft notes"));- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);- assert_eq!(f.current, Some(0), "page 1's match takes over once its text arrives");- assert_eq!(v.current, 0, "the view follows the first match at or after the page being viewed");- }-- /// A match the user picked (a click in the Search panel, or ⌘G) is not moved by a text- /// layer that arrives later: only automatic choices follow the viewed page.- #[test]- fn a_user_picked_search_match_stays_put_when_earlier_text_arrives() {- let mut v = view(2, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- v.texts.insert(1, Arc::new(find_test_text("Second page sample text")));- v.refresh_find_page(1);- v.go_to_match(0);- assert_eq!(v.find.as_ref().unwrap().auto_from, None, "an explicit choice is not automatic");-- v.texts.insert(0, Arc::new(find_test_text("Panel sample draft notes")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![0, 1]);- assert_eq!(f.current, Some(1), "the picked match keeps its identity after page 1 is inserted");- assert_eq!(v.current, 1, "the user's page does not change under them");- }-- /// The automatic choice may move the view only while the reader has left it where that- /// choice put it. Navigating by the page box/Pages panel/outline or by view history is the- /// reader's decision: a text layer arriving afterwards must not pull them back to an- /// anchor-derived match. (The harness covers same-page wheel and pointer scrolling.)- #[test]- fn a_late_automatic_match_does_not_override_the_readers_navigation() {- enum Nav {- Page,- History,- }- for nav in [Nav::Page, Nav::History] {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(2, Arc::new(find_test_text("Second page sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (2, Some(2)), "the automatic match was shown");- match nav {- // The page box, the Pages panel and outline destinations all end here.- Nav::Page => v.go_to_page(1),- // View ▸ Page navigation ▸ Previous view writes `current` directly.- Nav::History => {- v.back = vec![1];- assert!(v.view_history(false));- }- }- assert_eq!(v.current, 1);- v.texts.insert(0, Arc::new(find_test_text("First page sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, None, "the reader's navigation ends automatic following");- assert_eq!(f.auto_page, None);- assert_eq!(v.current, 1, "a late match cannot pull the reader back");- }- }-- /// Typing on while the results arrive must not re-anchor the search on a page the automatic- /// flash picked. The anchor stays the page the reader was on when they started searching.- #[test]- fn refining_the_query_keeps_the_page_the_search_started_from() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(2, Arc::new(find_test_text("Second page sample text")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (2, Some(0)), "the first query's match scrolled the view");-- // Page 1 has a match for the refined query, and so has page 3. Anchored on the page the- // automatic flash reached, the search would pick page 3; the starting page picks page 1.- v.texts.insert(0, Arc::new(find_test_text("Panel draft text")));- v.find.as_mut().unwrap().query = "text".into();- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader searched from");- assert_eq!(f.matches.first().map(|(p, _)| *p), Some(0));- assert_eq!(f.current, Some(0));- assert_eq!(v.current, 0);- }-- /// ⌘G / Ctrl+G goes through `find_step`, an explicit choice like a Search-panel click: a- /// text layer arriving later must not undo it.- #[test]- fn keyboard_find_step_is_explicit_and_a_late_text_layer_cannot_undo_it() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.texts.insert(2, Arc::new(find_test_text("second sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_from), (1, Some(0)));-- let ctx = egui::Context::default();- ctx.input_mut(|i| {- i.events.push(egui::Event::Key {- key: egui::Key::G,- physical_key: None,- pressed: true,- repeat: false,- modifiers: egui::Modifiers::COMMAND,- });- });- shortcuts(&mut v, &ctx, Default::default());-- assert_eq!(v.current, 2, "the keyboard step chose the next match");- assert_eq!(v.find.as_ref().unwrap().auto_from, None, "the keyboard step is the user's choice");- assert_eq!(v.back, vec![1], "an explicit search jump records its origin");-- v.texts.insert(0, Arc::new(find_test_text("intro sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, 2, "the chosen match keeps the view");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(2));- }-- /// A page whose text extraction failed keeps the automatic anchor: the failure selects the- /// next match without moving the view, and a later text layer can still follow the anchor.- #[test]- fn a_failed_text_layer_keeps_the_automatic_anchor_without_jitter() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.texts.insert(2, Arc::new(find_test_text("second sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)));-- let goto = v.goto;- let ctx = egui::Context::default();- let request = RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- let f = v.find.as_ref().unwrap();- assert_eq!(f.matches.iter().map(|(p, _)| *p).collect::<Vec<_>>(), vec![2]);- assert_eq!(f.current, Some(0), "the remaining match is selected");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)), "a failure does not end automatic following");- assert_eq!(v.current, 1, "a failure never moves the view");- assert_eq!(v.goto, goto, "a failure never flashes the match");-- // The search still follows its original page when that page's text arrives.- v.last_queue = vec![RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() }];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- assert_eq!(v.current, 0, "the anchor's earlier match takes over");- let f = v.find.as_ref().unwrap();- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0));- }-- /// A reader who navigated before a page's text failed is not pulled back by a later- /// matching layer: the failure path must preserve the same `Ended` state as a successful- /// one, and the result list may select the late match without revealing it.- #[test]- fn a_failed_text_layer_after_navigation_does_not_reveal_a_late_match() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- v.go_to_page(2);- let moved = v.goto;- assert!(v.find.as_ref().unwrap().follow_ended, "the reader navigated before any match arrived");-- let ctx = egui::Context::default();- let failed = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![failed];- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request: failed,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended, "a failure after navigation does not restart following");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 2, "a failure never moves the view");- assert_eq!(v.goto, moved);-- let arrived = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![arrived];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 2, "the late matching layer does not pull the reader back");- assert_eq!(v.goto, moved, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");- }-- /// The reader can navigate before any text layer has supplied a match. That navigation- /// still ends automatic following, so the first late match is listed but not revealed by- /// a flash that would pull the reader back.- #[test]- fn navigation_before_the_first_match_is_not_overridden_by_a_late_text_layer() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.current, None, "no text layer has arrived yet");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));-- v.go_to_page(2);- assert_eq!(v.goto, Some((2, 0.0)), "the reader moved to page 3");- assert!(v.find.as_ref().unwrap().follow_ended, "moving the view ends automatic following");-- let ctx = egui::Context::default();- let request = RenderRequest { page: 1, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(1, "late sample"));- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, 2, "the late first match does not pull the reader back");- assert_eq!(v.goto, Some((2, 0.0)), "no flash was issued");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the result list still selects the match");- }-- /// A page-box jump to the page already shown is still the reader's navigation: automatic- /// following must end, so a late earlier match is listed without moving the view. (The- /// harness covers wheel, scrollbar and pointer scrolling through the production paint path.)- #[test]- fn a_same_page_page_box_jump_ends_automatic_following() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");-- // Choosing the page already shown still ends following; it stays on page 2 at its top.- v.go_to_page(1);- let shown = v.goto;- assert_eq!(shown, Some((1, 0.0)));-- v.texts.insert(0, Arc::new(find_test_text("intro sample")));- v.refresh_find_page(0);- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 1, "the late earlier match does not move the reader within the page");- assert_eq!(v.goto, shown, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(1), "the page-2 match stays selected");- }-- /// A document-wide invalidation (a layer toggle, an edit, undo/redo) clears results for- /// re-extraction but is not the reader navigating. Automatic following keeps its anchor so- /// the re-extracted layers still reveal the automatic choice; a reader who already took- /// over stays in control. If `document_changed` clamps the view away from that anchor, the- /// next layer ends following instead of revealing a match from the stale page.- #[test]- fn content_invalidation_keeps_the_following_state() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.texts.insert(1, Arc::new(find_test_text("first sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (1, Some(1)), "the automatic choice is on page 2");-- v.invalidate_content();- let f = v.find.as_ref().unwrap();- assert!(f.matches.is_empty() && f.current.is_none(), "results wait for the re-extracted text");- assert!(!f.follow_ended, "a content change is not reader navigation");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(1)));-- // Re-extracted text still follows the page the search started from.- let ctx = egui::Context::default();- let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- assert_eq!(v.current, 0, "the re-extracted match is revealed by the still-active search");- let f = v.find.as_ref().unwrap();- assert!(!f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(0)));-- // A reader who navigated first keeps the view they chose across the invalidation.- v.go_to_page(2);- let moved = v.goto;- assert!(v.find.as_ref().unwrap().follow_ended);- v.invalidate_content();- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended);- assert_eq!((f.auto_from, f.auto_page), (None, None));- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "late sample"));- assert_eq!(v.current, 2, "no delayed reveal after the reader navigated");- assert_eq!(v.goto, moved, "no flash was issued");- let f = v.find.as_ref().unwrap();- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the late match");- }-- /// A document edit can shrink the page count. `document_changed` clamps `current` but leaves- /// the automatic anchor's page index alone; a re-extracted layer must then end following- /// rather than reveal a match by scrolling from a page that no longer exists.- #[test]- fn a_page_count_shrink_ends_following_before_a_late_reveal() {- let mut v = view(5, PageLayout::Single, true);- v.current = 0;- v.texts.insert(4, Arc::new(find_test_text("last sample")));- v.find = Some(Find { query: "sample".into(), ..Default::default() });- v.rerun_find();- assert_eq!((v.current, v.find.as_ref().unwrap().auto_page), (4, Some(4)), "the automatic choice is on the last page");-- let info = pdfcraft_render::DocInfo {- pages: (0..2)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- v.document_changed(&info);- assert_eq!(v.current, 1, "the view clamps to the last remaining page");- let f = v.find.as_ref().unwrap();- assert!(!f.follow_ended, "the content change itself keeps the automatic state");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(4)), "the anchor still names the removed page");- let goto = v.goto;-- let ctx = egui::Context::default();- let request = RenderRequest { page: 0, kind: RequestKind::Text, tag: TEXT_TAG, ..Default::default() };- v.last_queue = vec![request];- v.receive_result(&ctx, find_text_result(0, "intro sample"));- let f = v.find.as_ref().unwrap();- assert!(f.follow_ended, "a layer for the remaining pages ends the stale follow");- assert_eq!((f.auto_from, f.auto_page), (None, None));- assert_eq!(v.current, 1, "the late layer cannot pull the view back");- assert_eq!(v.goto, goto, "no flash was issued");- assert_eq!(f.current.and_then(|i| f.matches.get(i)).map(|(p, _)| *p), Some(0), "the result list still selects the match");- }-- /// Typing refinements while text layers keep arriving must keep the page the search began- /// on, not re-anchor on whichever page an earlier automatic flash happened to show.- #[test]- fn rapid_query_edits_interleaved_with_text_results_keep_the_start_anchor() {- let mut v = view(3, PageLayout::Single, true);- v.current = 0;- v.find = Some(Find { query: "sam".into(), ..Default::default() });- v.rerun_find();- assert!(v.find.as_ref().unwrap().current.is_none());-- let edits = [("samp", 2, "Page three sample", 2), ("sampl", 1, "Page two sample", 1), ("sample", 0, "Page one sample", 0)];- for (query, page, text, shown) in edits {- v.find.as_mut().unwrap().query = query.into();- v.rerun_find();- let f = v.find.as_ref().unwrap();- assert_eq!(f.auto_from, Some(0), "refinement keeps the page the reader started from");- assert!(!f.follow_ended);- v.texts.insert(page, Arc::new(find_test_text(text)));- v.refresh_find_page(page);- let f = v.find.as_ref().unwrap();- assert_eq!(v.current, shown, "the late page follows the automatic anchor {shown}");- assert_eq!((f.auto_from, f.auto_page), (Some(0), Some(shown)));- assert!(!f.follow_ended, "the automatic flash itself does not end following");- }- assert!(v.back.is_empty(), "automatic search updates do not record history");- }-- #[test]- fn text_layers_evict_far_pages_but_keep_visible_and_matches() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50, 51]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.text_failed.insert(0);- v.text_failed.insert(99);- v.find = Some(Find { matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert!(v.texts.contains_key(&50) && v.texts.contains_key(&51), "visible pages stay");- assert!(v.texts.contains_key(&0), "matched pages stay");- assert!(v.texts.contains_key(&49), "nearest prefetch window stays");- assert!(!v.texts.contains_key(&99), "far pages go");- assert_eq!(v.texts.len(), 2 + 1 + MAX_CACHED_TEXT_PAGES, "visible + matched + prefetch window");- assert!(v.text_failed.contains(&0) && v.text_failed.contains(&99), "failures are bytes-free: never evict");- }-- /// A PDF of one line of text on each page, `lines[i]` on page `i`.- fn text_pages_pdf(lines: &[&str]) -> Vec<u8> {- let n = lines.len();- // 1 catalog, 2 pages, 3 font, then a page and its content stream for each line.- let mut objects = vec![- "<< /Type /Catalog /Pages 2 0 R >>".to_string(),- format!("<< /Type /Pages /Count {n} /Kids [{}] >>", (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect::<Vec<_>>().join(" ")),- "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),- ];- for (i, line) in lines.iter().enumerate() {- let content = format!("BT /F1 18 Tf 72 700 Td ({line}) Tj ET");- objects.push(format!(- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents {} 0 R >>",- 5 + 2 * i- ));- objects.push(format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()));- }- let mut out = b"%PDF-1.7\n".to_vec();- let mut offsets = Vec::new();- for (i, o) in objects.iter().enumerate() {- offsets.push(out.len());- out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());- }- let xref = out.len();- out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());- for o in offsets {- out.extend(format!("{o:010} 00000 n \n").bytes());- }- out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());- out- }-- /// #2639: scrolling continuously, Select All takes every page's text, and Copy gets all of it- /// in page order, reading the pages whose text wasn't read for display.- #[test]- fn select_all_copies_the_whole_document_while_scrolling_continuously() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- let v = &mut app.views[0];- assert!(v.continuous, "continuous scrolling is the default");- assert!(v.texts.is_empty(), "no page's text read yet");- // Nothing shown is selected yet (false, as for a page whose text isn't read), but the whole- // document is: Copy reads every page.- assert!(!v.select_all());- assert!(v.all_text && v.selection.is_none());- assert_eq!(v.pages_without_text(), vec![0, 1, 2]);- // Copy reads the pages off the UI thread; the clipboard gets the text once they're read.- let ctx = egui::Context::default();- assert!(app.copy_selected_text(0, &ctx), "the copy starts");- assert!(app.document_copy.is_some(), "reading the pages, not on this thread");- let mut text = None;- for _ in 0..500 {- let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.finish_document_copy(ui.ctx()));- out.textures_delta.clear();- text = out.platform_output.commands.iter().find_map(|c| match c {- egui::OutputCommand::CopyText(t) => Some(t.clone()),- _ => None,- });- if text.is_some() {- break;- }- std::thread::sleep(std::time::Duration::from_millis(10));- }- let text = text.expect("the copied text arrives");- assert!(app.document_copy.is_none(), "done");- let at = |w: &str| text.find(w).unwrap_or_else(|| panic!("{w:?} missing from {text:?}"));- assert!(at("Alpha") < at("Bravo") && at("Bravo") < at("Charlie"), "page order: {text:?}");- assert_eq!(text.lines().count(), 3, "a line per page: {text:?}");- // A new scope ends it: one page at a time, Select All is the page's again.- app.views[0].set_continuous(false);- assert!(!app.views[0].all_text, "not after switching to one page at a time");- // So do a page selection and a change of the document's content (an edit, undo).- app.views[0].set_continuous(true);- app.views[0].select_all();- app.views[0].select_text(0, 0, 0);- assert!(!app.views[0].all_text, "a page selection replaces it");- app.views[0].select_all();- app.views[0].invalidate_content();- assert!(!app.views[0].all_text, "not past an edit of the document");- }-- /// A whole-document copy reads the pages without text, keeps those already read and skips- /// those that failed before.- #[test]- fn a_document_copy_reads_only_the_pages_it_needs() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- app.views[0].text_failed.insert(2);- let job = crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());- let kinds: Vec<_> = job.pages.iter().map(|p| matches!(p, crate::CopyPage::ToRead)).collect();- assert_eq!(kinds, vec![true, true, false], "pages 1 and 2 to read, page 3 failed before");- assert!(matches!(job.pages[2], crate::CopyPage::Skip));- }-- /// A later copy wins: a whole-document copy still reading its pages never replaces what was- /// copied after it started, from the page or anywhere else (a text field, a comment).- #[test]- fn a_later_copy_cancels_a_document_copy_still_reading() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- let ctx = egui::Context::default();- // Another copy in the same frame (here a text field's) drops it.- app.views[0].select_all();- assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some());- let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {- ui.ctx().copy_text("a word".to_owned());- app.finish_document_copy(ui.ctx());- });- out.textures_delta.clear();- assert!(app.document_copy.is_none(), "cancelled");- let copies: Vec<_> = out.platform_output.commands.iter().filter(|c| matches!(c, egui::OutputCommand::CopyText(_))).collect();- assert_eq!(copies, vec![&egui::OutputCommand::CopyText("a word".to_owned())], "the later copy stays");- // So does copying a page selection.- app.views[0].select_all();- assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some());- app.views[0].select_text(0, 0, 5);- app.copy_selected_text(0, &ctx);- assert!(app.document_copy.is_none(), "a page selection's copy cancels it");- }-- /// A press anywhere on a page ends Select All of the document, whatever the tool (here the- /// Hand, which selects no text) and whether the page's text is read yet.- #[test]- fn a_press_on_a_page_ends_select_all_of_the_document() {- let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- app- });- let mut on_screen = None;- for _ in 0..600 {- h.run_steps(2);- on_screen = h.state().views[0].page_screen_rect(0);- if on_screen.is_some() {- break;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- let r = on_screen.expect("the first page is on screen");- h.state_mut().quick_tool = crate::QuickTool::Hand;- h.state_mut().views[0].select_all();- assert!(h.state().views[0].all_text);- let at = r.center();- h.event(egui::Event::PointerMoved(at));- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });- h.run_steps(1);- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });- h.run_steps(2);- assert!(!h.state().views[0].all_text, "a press on the page ends it");-- // A press while a dialog is up lands on the dialog, not the page: the selection stays.- h.state_mut().views[0].select_all();- h.state_mut().dialog = Some(crate::Dialog::JsConsole);- h.run_steps(2);- h.event(egui::Event::PointerMoved(at));- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });- h.run_steps(1);- h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });- h.run_steps(2);- assert!(h.state().views[0].all_text, "a press beneath a dialog doesn't end it");- }-- /// The pages of a whole-document copy come out in order whatever was read before, and a- /// cancelled copy gives nothing (a new copy or a closed document cancels the old one).- #[test]- fn a_document_copy_reads_in_page_order_and_stops_when_cancelled() {- let mut app = PdfCraftApp::new();- app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap();- // The middle page's text read for display already; the others read by the copy.- let doc = app.session.get(app.views[0].id).unwrap();- let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());- let middle = r.render(RenderRequest { page: 1, kind: RequestKind::Text, ..Default::default() }).text.unwrap();- app.views[0].texts.insert(1, middle);- let job = || crate::DocumentCopyJob::of(&app.views[0], app.session.get(app.views[0].id).unwrap());- let text = job().text(&std::sync::atomic::AtomicBool::new(false)).unwrap();- assert!(text.find("Alpha").unwrap() < text.find("Bravo").unwrap() && text.find("Bravo").unwrap() < text.find("Charlie").unwrap(), "{text:?}");- assert_eq!(job().text(&std::sync::atomic::AtomicBool::new(true)), None, "cancelled");- }-- /// Select All keeps to the page shown one page at a time, and in a document of one page; of- /// the document, it reads the text already read and doesn't ask again for failed pages.- #[test]- fn select_all_of_the_document_only_while_scrolling_through_several_pages() {- let info = thumbnail_info(3);- let one_line = |s: &str| PageText {- glyphs: s- .chars()- .map(|c| pdfcraft_render::TextGlyph { text: c.into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] })- .collect(),- line_of: s.chars().map(|_| 0).collect(),- space_before: s.chars().map(|_| false).collect(),- };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- for p in 0..3 {- v.texts.insert(p, Arc::new(one_line("abc")));- }- v.continuous = false;- v.current = 1;- assert!(v.select_all());- assert!(!v.all_text && v.selection.is_some_and(|s| s.page == 1), "one page at a time: the page shown");- let single = thumbnail_info(1);- let mut w = DocView::new(DocId(2), &single, ViewDefaults::default());- w.texts.insert(0, Arc::new(one_line("abc")));- assert!(w.select_all());- assert!(!w.all_text && w.selection.is_some(), "a one-page document: that page");- // Text read for display is used; pages that failed aren't asked for again.- let mut d = DocView::new(DocId(3), &info, ViewDefaults::default());- d.texts.insert(1, Arc::new(one_line("abc")));- d.text_failed.insert(2);- assert!(d.select_all() && d.all_text);- assert_eq!(d.pages_without_text(), vec![0]);- }-- #[test]- fn text_layers_keep_the_selection_page() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let text = PageText {- glyphs: vec![pdfcraft_render::TextGlyph { text: "x".into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }],- line_of: vec![0],- space_before: vec![false],- };- for p in 0..100 {- v.texts.insert(p, Arc::new(text.clone()));- }- v.select_text(0, 0, 0);- v.current = 90;- v.frame_visible = HashSet::from([90, 91]);- let _ = v.prepare_render_queue(&info, 1.0);- assert_eq!(v.selected_text().as_deref(), Some("x"), "stale selections still copy");- }-- #[test]- fn text_layers_stay_while_a_search_is_active() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.find = Some(Find { query: "dup".into(), case_query: "dup".into(), matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert_eq!(v.texts.len(), 100, "evicting mid-search would churn the workers");- }-- fn thumbnail_info(count: usize) -> DocInfo {- DocInfo {- pages: (0..count)- .map(|i| {- let (width, height) = match i % 3 {- 0 => (612.0, 792.0),- 1 => (200.0, 4000.0),- _ => (4000.0, 200.0),- };- pdfcraft_render::PageInfo { width, height, label: (i + 1).to_string(), crop: [0.0, 0.0, width, height], rotation: 0 }- })- .collect(),- ..Default::default()- }- }-- #[test]- fn ten_thousand_pages_only_demand_viewport_and_prefetch_at_both_densities() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let cols = 4;- let rows = info.pages.len().div_ceil(cols);- for ppp in [1.0, 2.0] {- for row in [0, 1234, rows - 1] {- v.begin_render_frame();- let range = thumbnail_rows(row as f32 * 250.0, row as f32 * 250.0 + 750.0, 250.0, rows);- for p in range.start * cols..(range.end * cols).min(info.pages.len()) {- v.need_thumbnail(p, p / cols == row);- }- let queue = v.prepare_render_queue(&info, ppp);- assert!(queue.len() <= 5 * cols, "only three visible rows and two prefetch rows");- assert_eq!(queue.first().unwrap().page / cols, row, "visible cells precede prefetch");- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- let (w, h) = (device_pixels(p.width, r.scale), device_pixels(p.height, r.scale));- assert!(w <= (THUMB_W * ppp).ceil() as u32);- assert!(h <= (THUMB_H * ppp).ceil() as u32);- rgba_bytes(w as usize, h as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- assert_eq!(queue, v.prepare_render_queue(&info, ppp), "unchanged demand reconstructs the same work");- }- }- }-- #[test]- fn oversized_thumbnail_viewport_scales_all_admitted_cells_to_one_budget() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- for page in 0..MAX_THUMB_DEMAND {- v.need_thumbnail(page, true);- }- let queue = v.prepare_render_queue(&info, 2.0);- assert_eq!(queue.len(), MAX_THUMB_DEMAND);- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- rgba_bytes(device_pixels(p.width, r.scale) as usize, device_pixels(p.height, r.scale) as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- }-- fn solid_result(request: RenderRequest, w: u32, h: u32) -> pdfcraft_render::RenderedPage {- pdfcraft_render::RenderedPage {- request,- width: w,- height: h,- rgba: pdfcraft_render::Pixels::from(vec![u32::MAX; rgba_bytes(w as usize, h as usize) / 4]),- text: None,- error: None,- warnings: Vec::new(),- millis: 0,- }- }-- /// #3149: the replacement dialog commits after the canvas collected this frame's demand.- #[test]- fn replacing_a_page_after_layout_never_uploads_an_oversized_texture() {- let ctx = egui::Context::default();- ctx.input_mut(|i| i.max_texture_side = 2048);- let mut app = PdfCraftApp::new();- let original = app.session.create_blank(200.0, 300.0, 1).unwrap();- let replacement = app.session.create_blank(400.0, 500.0, 1).unwrap();- app.open_bytes("original.pdf", None, original.as_ref().clone()).unwrap();- let request = RenderRequest { scale: 4.7, tag: scale_tag(4.7), ..Default::default() };- app.views[0].frame_queue = vec![request];- app.views[0].frame_visible.insert(0);- assert!(app.apply_edit(Edit::ReplacePages { pages: vec![0], name: "replacement.pdf".into(), bytes: replacement, src_pages: vec![0] }));- let doc = app.session.get(app.views[0].id).unwrap();- assert_eq!((doc.info.pages[0].width, doc.info.pages[0].height), (400.0, 500.0));- let edited_bytes = doc.bytes.clone();- let pool = RenderPool::new_inline(doc.display.clone(), Default::default());- app.views[0].finish_render_frame(&ctx, &doc.info, &pool);- assert!(app.views[0].last_queue.is_empty(), "old geometry must not reach the replacement renderer");-- // The next layout can render a bounded backdrop and sharp tiles at the same zoom.- let backdrop = RenderRequest { scale: 2048.0 / 500.0, tag: scale_tag(2048.0 / 500.0), ..request };- let tile = RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..request };- for _ in 0..2 {- let view = &mut app.views[0];- view.begin_render_frame();- view.frame_visible.insert(0);- view.frame_queue = vec![backdrop, tile];- view.finish_render_frame(&ctx, &doc.info, &pool);- }- let view = &app.views[0];- assert_eq!(view.pages.get(&0).unwrap().tex.size(), [1639, 2048]);- assert_eq!(view.tiles.get(&(0, tile.tag, 0, 0)).unwrap().size(), [1024, 1024]);- assert!(view.errors.is_empty());- assert_eq!(doc.bytes, edited_bytes, "rendering preserves the unsaved edit");- assert!(doc.dirty);- assert_eq!(doc.can_undo(), Some("Replace page"));- }-- #[test]- fn oversized_raster_results_do_not_replace_cached_textures() {- let ctx = egui::Context::default();- ctx.input_mut(|i| i.max_texture_side = 64);- for request in [- RenderRequest::default(),- RenderRequest { tag: THUMB_TAG, ..Default::default() },- RenderRequest { tag: GRID_TAG, ..Default::default() },- RenderRequest { tag: PRINT_TAG, ..Default::default() },- RenderRequest { tile: Some(Tile { x: 0, y: 0, w: 64, h: 32 }), ..Default::default() },- ] {- let mut view = DocView::new(DocId(1), &thumbnail_info(1), ViewDefaults::default());- view.last_queue = vec![request];- let texture = |v: &DocView| {- v.pages- .values()- .map(|p| &p.tex)- .chain(v.thumbs.values().map(|p| &p.tex))- .chain(v.grid_pages.values().map(|(_, t)| t))- .chain(v.print_pages.values().map(|(_, t)| t))- .chain(v.tiles.values())- .map(|t| (t.id(), t.size()))- .collect::<Vec<_>>()- };- assert_eq!(view.receive_result(&ctx, solid_result(request, 64, 32)), 64 * 32 * 4);- let cached = texture(&view);- assert_eq!(cached.len(), 1);- for (w, h) in [(65, 32), (32, 65), (65, 65), (0, 32), (32, 0)] {- assert_eq!(view.receive_result(&ctx, solid_result(request, w, h)), 0, "{request:?}: {w}x{h}");- assert_eq!(texture(&view), cached, "an invalid result must keep the previous raster");- }- assert_eq!(view.receive_result(&ctx, solid_result(request, 32, 64)), 32 * 64 * 4);- assert_eq!(texture(&view)[0].1, [32, 64], "valid results still make progress");- }- }-- /// A print preview carries the renderer's print bit; the bit that asks for luminance is- /// its own, so a colour preview is not converted to monochrome and the two modes are told- /// apart by their tags.- #[test]- fn print_preview_tag_distinguishes_grayscale_from_colour() {- let mut v = view(1, PageLayout::Single, true);- v.set_print_grayscale(false);- v.queue_print_previews(&[(0, 1.0)]);- let colour = v.frame_queue.last().expect("a print preview was queued").tag;- assert_ne!(colour & PRINT_TAG, 0, "a print preview carries the renderer's print bit");- assert_eq!(colour & GRAYSCALE_TAG, 0, "a colour print preview must not ask for luminance");-- v.set_print_grayscale(true);- v.queue_print_previews(&[(0, 1.0)]);- let gray = v.frame_queue.last().expect("a grayscale print preview was queued").tag;- assert_ne!(gray & GRAYSCALE_TAG, 0, "a grayscale print preview asks for luminance");- assert_ne!(gray, colour, "the two print preview modes must not share a tag");- }-- #[test]- fn thumbnails_release_on_scroll_panel_close_and_request_again_after_eviction() {- let ctx = egui::Context::default();- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0);- v.last_queue = first.clone();- assert_eq!(v.receive_result(&ctx, solid_result(first[0], 132, 171)), 132 * 171 * 4);- assert!(v.prepare_render_queue(&info, 1.0).is_empty());- v.begin_render_frame();- v.need_thumbnail(9999, true);- v.prepare_render_queue(&info, 1.0);- assert!(v.thumbs.is_empty(), "jump releases old handles");- v.begin_render_frame();- v.need_thumbnail(0, true);- assert_eq!(v.prepare_render_queue(&info, 1.0), first, "an evicted result must be requested again");- v.begin_render_frame();- assert!(v.prepare_render_queue(&info, 1.0).is_empty(), "closing consumers cancels thumbnail work");- }-- #[test]- fn stale_results_are_rejected_before_conversion_after_dpi_invalidation_and_suspend() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0)[0];- v.last_queue = v.prepare_render_queue(&info, 2.0);- // Valid pixels: only the request gate can keep these out (a size check can't).- let obsolete = || solid_result(first, 132, 171);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "a result for the old DPI is not uploaded");- // The same result is uploaded while its request is current.- v.last_queue = vec![first];- assert_eq!(v.receive_result(&ctx, obsolete()), 132 * 171 * 4);- v.thumbs.clear();- v.invalidate_content();- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the content changed");- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- v.last_queue = vec![first];- v.suspend_rendering(&pool);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the tab was suspended");- }-- #[test]- fn editing_after_layout_preserves_stale_page_until_replacement() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };- v.last_queue = vec![req];- v.receive_result(&ctx, solid_result(req, 10, 10));- v.frame_queue = vec![req];- v.page_changed(0);- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req]);- assert_eq!(v.pages.get(&0).unwrap().tag, STALE_TAG);- }-- /// #1858: a released drawing stays painted from its points until a raster that has it- /// arrives. A page raster that lands before the drawing's edit is applied (in full screen the- /// edit waits for the next frame, and a render already under way can finish first) is of the- /// document without it, and must not end the preview.- #[test]- fn a_raster_from_before_a_drawing_is_committed_keeps_it_drawn() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };- v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);- v.last_queue = vec![req];- assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0, "the raster is taken");- assert_eq!(v.comments.settling_len(), 1, "a raster from before the commit doesn't have the stroke");- v.comments.drawings_committed();- v.last_queue = vec![req];- assert!(v.receive_result(&ctx, solid_result(req, 10, 10)) > 0);- assert_eq!(v.comments.settling_len(), 0, "a raster after the commit draws it");- // An edit that fails leaves nothing to wait for.- v.comments.settle(0.0, 0, crate::comments::CommentTool::Ink, &[[10.0, 10.0], [40.0, 30.0]]);- v.comments.drawings_refused();- assert_eq!(v.comments.settling_len(), 0, "a refused drawing isn't left painted");- }-- #[test]- fn page_and_tile_admission_accounts_for_bytes_before_count_limits() {- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 4000.0;- p.height = 4000.0;- }- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue.len(), 2, "128 MiB admits two 4000-square pages, not 24");- v.frame_queue = (0..40)- .map(|page| RenderRequest { page, scale: 1.0, tag: 1000, tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 32);- assert!(!v.admit_texture(RenderRequest::default(), PAGE_BYTES + 1));- }-- #[test]- fn on_screen_pages_and_tiles_are_admitted_beyond_the_prefetch_allowance() {- let ctx = egui::Context::default();- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 2000.0;- p.height = 2000.0;- }- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- // Ten 16 MB pages on screen (a zoomed-out HiDPI view) exceed the 128 MiB allowance.- v.frame_visible = (0..10).collect();- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- let pages: Vec<usize> = queue.iter().map(|r| r.page).collect();- assert_eq!(pages, (0..10).collect::<Vec<_>>(), "every on-screen page, and no prefetch past the allowance");- v.last_queue = queue.clone();- for req in &queue {- assert!(v.receive_result(&ctx, solid_result(*req, 2000, 2000)) > 0, "on-screen page {} uploaded", req.page);- }- assert_eq!(v.pages.len(), 10, "none evicted another on-screen page");- // A 5K viewport needs more 1024-pixel tiles than the tile allowance holds.- v.frame_queue = (0..40)- .map(|x| RenderRequest { page: 0, scale: 1.0, tag: 1000, tile: Some(Tile { x: x * TILE, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 40);- }-- #[test]- fn a_page_turned_back_to_is_still_cached() {- let ctx = egui::Context::default();- let info = thumbnail_info(10);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = |page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() };- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- v.last_queue = v.prepare_render_queue(&info, 1.0);- v.receive_result(&ctx, solid_result(req(0), 100, 130));- // Single-page view moves on to page 1: page 0 is no longer demanded.- v.begin_render_frame();- v.current = 1;- v.frame_visible = [1].into();- v.frame_queue = vec![req(1)];- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req(1)]);- assert!(v.pages.contains_key(&0), "kept while the allowance has room");- // And back: nothing to render.- v.begin_render_frame();- v.current = 0;- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- assert!(v.prepare_render_queue(&info, 1.0).is_empty());- }-- #[test]- fn visible_pages_render_before_thumbnails_and_text() {- let ctx = egui::Context::default();- let info = thumbnail_info(4);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let main = RenderRequest { page: 0, scale: 1.0, tag: 1000, ..Default::default() };- let text = RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, tag: TEXT_TAG, ..Default::default() };- // Opening page 0 queues its pixels and text alongside Pages-panel thumbnails.- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue, vec![main], "visible pixels first: no thumbnails or text yet");- // Once the visible raster arrives, background work is admitted.- v.last_queue = queue;- assert!(v.receive_result(&ctx, solid_result(main, 100, 130)) > 0);- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted after pixels");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails admitted after pixels");- assert!(!queue.iter().any(|r| r.kind == RequestKind::Pixels && r.tag & THUMB_TAG == 0), "no main pixels re-requested");- // An errored visible page never holds background work back.- v.errors.insert(0, "gone".to_string());- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted despite the error");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails still admitted");- }-- #[test]- fn thumbnail_tags_do_not_change_as_a_row_scrolls_in_or_out() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let tags = |v: &mut DocView, cells: usize| {- v.begin_render_frame();- for page in 0..cells {- v.need_thumbnail(page, true);- }- v.thumbnail_requests(&info, 2.0).into_iter().map(|r| (r.page, r.tag)).collect::<HashMap<_, _>>()- };- // 2x on a large screen: about 70 cells, give or take a row of six.- let (a, b) = (tags(&mut v, 70), tags(&mut v, 76));- assert!((0..70).all(|p| a[&p] == b[&p]), "a row more or less re-renders nothing");- }-- #[test]- fn many_open_documents_share_one_raster_allowance_and_close_releases_handles() {- let ctx = egui::Context::default();- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 1).unwrap();- let mut expected = Vec::new();- for index in 0..6 {- app.open_bytes(&format!("synthetic-{index}.pdf"), None, bytes.as_ref().clone()).unwrap();- let info = app.session.get(app.views.last().unwrap().id).unwrap().info.clone();- let view = app.views.last_mut().unwrap();- view.begin_render_frame();- view.need_thumbnail(0, true);- let request = view.thumbnail_requests(&info, ctx.pixels_per_point()).into_iter().next().unwrap();- let page = info.pages.get(request.page).unwrap();- let dimensions = (device_pixels(page.width, request.scale), device_pixels(page.height, request.scale));- view.last_queue = vec![request];- assert_eq!(- view.receive_result(&ctx, solid_result(request, dimensions.0, dimensions.1)),- rgba_bytes(dimensions.0 as usize, dimensions.1 as usize)- );- assert_eq!(view.thumbs.get(&0).unwrap().tag, request.tag);- assert_eq!(view.thumbs.get(&0).unwrap().tex.size(), [dimensions.0 as usize, dimensions.1 as usize]);-- view.begin_render_frame();- view.need_thumbnail(0, true);- let queue = view.prepare_render_queue(&info, ctx.pixels_per_point());- assert!(queue.is_empty(), "the synthetic thumbnail satisfies current demand");- view.last_queue = queue;- expected.push((request, dimensions));- }- assert_eq!(app.views.len(), 6, "all six documents were opened");- assert_eq!(app.active_ids().map(|(index, _)| index), Some(5));- assert!(app.views.iter().zip(&expected).all(|(view, (request, dimensions))| {- view.thumbs.len() == 1- && view- .thumbs- .get(&0)- .is_some_and(|thumb| thumb.tag == request.tag && thumb.tex.size() == [dimensions.0 as usize, dimensions.1 as usize])- }));-- app.finish_render_frame(&ctx);- let total: usize = app.views.iter().map(|v| v.thumbs.values().map(|p| texture_bytes(&p.tex)).sum::<usize>()).sum();- let (active_request, active_dimensions) = expected.last().unwrap();- let active_bytes = rgba_bytes(active_dimensions.0 as usize, active_dimensions.1 as usize);- assert_eq!(total, active_bytes, "only the active view retains a thumbnail");- assert!(total <= THUMB_BYTES, "retained thumbnails stay within the existing allowance");- assert!(app.views.iter().take(5).all(|v| v.thumbs.is_empty() && v.last_queue.is_empty()));- let active = app.views.last().unwrap();- assert_eq!(active.thumbs.len(), 1);- assert_eq!(active.thumbs.get(&0).unwrap().tag, active_request.tag);- assert!(active.last_queue.is_empty(), "the current thumbnail is already cached");- for view in &app.views {- let doc = app.session.get(view.id).unwrap();- assert_eq!(doc.renderer.stats().render_requests, 0, "the fixture must not launch a native render");- }-- app.close_tab(5);- assert_eq!(app.views.len(), 5, "closing the active tab drops its owning view");- assert!(app.views.iter().all(|v| v.thumbs.is_empty()));- }-- #[test]- fn suspended_signature_preview_releases_layers_and_rebuilds_without_editing() {- let ctx = egui::Context::default();- let mut png = std::io::Cursor::new(Vec::new());- image::RgbaImage::from_pixel(12, 4, image::Rgba([20, 30, 40, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();- let image = pdfcraft_engine::SignatureImage::from_bytes(png.get_ref()).unwrap();- let mut session = pdfcraft_engine::Session::new();- let blank = session.create_blank(300.0, 400.0, 1).unwrap();- let id = session.open_new("signature-preview.pdf", blank).unwrap();- let info = session.get(id).unwrap().info.pages[0].clone();- session.apply(id, image.edit(0, &info, [20.0, 100.0], false, "Test").unwrap()).unwrap();- let doc = session.get(id).unwrap();- let bytes = doc.bytes.clone();- let generation = doc.edit_generation();- let mut v = DocView::new(id, &doc.info, ViewDefaults::default());- v.comments.selected = Some((0, 0));- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0));-- v.suspend_rendering(&doc.renderer);- assert!(!v.signature_drag.contains(0, 0), "inactive tabs release the preview pool and textures");- assert_eq!(v.comments.selected, Some((0, 0)), "the user's selection survives suspension");- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0), "reactivating the view rebuilds the selected image's preview");- assert!(Arc::ptr_eq(&bytes, &doc.bytes));- assert_eq!(doc.edit_generation(), generation);- assert_eq!(doc.can_undo(), Some("Add signature"));- assert!(doc.dirty);- }-- #[test]- fn suspending_a_view_releases_owned_raster_textures_and_queue_state() {- let ctx = egui::Context::default();- let mut view = view(2, PageLayout::Single, true);- let texture = |name| ctx.load_texture(name, egui::ColorImage::filled([1, 1], Color32::WHITE), TextureOptions::LINEAR);- let request = RenderRequest { page: 0, scale: 1.0, tag: 1, ..Default::default() };- view.pages.insert(0, PageTex { tag: request.tag, tex: texture("suspended-page") });- view.thumbs.insert(1, PageTex { tag: THUMB_TAG, tex: texture("suspended-thumbnail") });- view.tiles.insert((0, request.tag, 0, 0), texture("suspended-tile"));- view.grid_pages.insert(1, (1, texture("suspended-grid-page")));- view.print_pages.insert(1, (PRINT_TAG, texture("suspended-print-page")));- view.stale_thumbs.insert(1);- view.waiting_since.insert(0, 1.0);- view.last_queue = vec![request];- view.frame_queue = vec![request];- view.frame_visible.insert(0);- view.need_thumbnail(1, true);-- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- view.suspend_rendering(&pool);-- assert!(view.pages.is_empty(), "page handles are released");- assert!(view.thumbs.is_empty(), "thumbnail handles are released");- assert!(view.tiles.is_empty(), "tile handles are released");- assert!(view.grid_pages.is_empty(), "organize-grid handles are released");- assert!(view.print_pages.is_empty(), "print-preview handles are released");- assert!(view.stale_thumbs.is_empty(), "stale thumbnail bookkeeping is cleared");- assert!(view.waiting_since.is_empty(), "waiting bookkeeping is cleared");- assert!(view.last_queue.is_empty() && !view.render_pending(), "queued demand is retired");- assert!(view.frame_queue.is_empty() && view.frame_visible.is_empty() && view.thumb_demand.is_empty());- }-- /// Edit text & images keeps its boxes while page input is blocked (the window unfocused, a- /// dialog or the palette open): the page's paragraphs are still measured for the latest edit- /// and drawn, instead of vanishing until the pointer comes back.- #[test]- fn edit_text_boxes_stay_drawn_while_page_input_is_blocked() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 1).unwrap();- app.open_bytes("blank.pdf", None, bytes.as_ref().clone()).unwrap();- app.quick_tool = QuickTool::EditText;- app- });- h.run_steps(3);- // Block page input the way the window losing focus does.- h.state_mut().palette_open = true;- h.run_steps(2);- assert!(h.state_mut().apply_edit(Edit::RotatePages { pages: vec![0], degrees: 90 }));- h.run_steps(3);- let app = h.state();- let generation = app.session.get(app.views[0].id).unwrap().edit_generation();- assert_eq!(app.views[0].edit_lines.get(&0).map(|(g, _)| *g), Some(generation), "the boxes follow the edit while input is blocked");- }-- #[test]- fn virtualized_organizer_keeps_insert_gaps_at_document_positions() {- use egui_kittest::kittest::Queryable;-- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 100).unwrap();- app.open_bytes("organize-gaps.pdf", None, bytes.as_ref().clone()).unwrap();- app.views[0].organize = true;- app- });- h.run_steps(4);- assert!(h.state().views[0].thumb_demand.len() < 50);- assert_eq!(h.query_all_by_label("Insert a file at the end").count(), 0, "the last virtualized cell is not the final page");- let center = h.state().views[0].viewport_rect().center();- h.hover_at(center);- h.event(egui::Event::MouseWheel {- unit: egui::MouseWheelUnit::Point,- delta: vec2(0.0, -100_000.0),- phase: egui::TouchPhase::Move,- modifiers: egui::Modifiers::NONE,- source: egui::MouseWheelSource::Unknown,- });- // Well past egui's longest scroll animation (about 0.3 s).- h.run_steps(40);- h.get_by_label("Insert a file at the end");- let before_last = h.get_by_label("Insert a file before page 100").rect().center();- h.hover_at(before_last);- h.run_steps(2);- assert_eq!(h.state().views[0].grid_gap, Some(99), "external drops use the document index after virtualized scrolling");- assert!(h.state().views[0].thumb_demand.len() < 50);- }-- #[test]- fn real_shell_pages_organizer_and_print_only_collect_current_thumbnail_consumers() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 10_000).unwrap();- app.open_bytes("synthetic-ten-thousand.pdf", None, bytes.as_ref().clone()).unwrap();- app.right = Some(RightPanel::Pages);- app- });- h.run_steps(4);- assert!((1..20).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().right = None;- h.state_mut().views[0].organize = true;- h.run_steps(2);- assert!((1..50).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().views[0].organize = false;- h.state_mut().dialog = Some(crate::Dialog::Print);- h.state_mut().print_draft.sheet = 9999;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.keys().copied().collect::<Vec<_>>(), vec![9999]);- h.state_mut().print_draft.handling = crate::PrintHandling::Booklet;- h.state_mut().print_draft.sheet = 0;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.len(), 2, "booklet only needs its two placed pages");- h.state_mut().dialog = None;- h.run_steps(2);- assert!(h.state().views[0].thumb_demand.is_empty());- assert!(h.state().views[0].thumbs.is_empty());- }-- /// One mouse-wheel notch (a line) at `at` seconds.- fn notch(v: &mut DocView, dy: f32, at: f64) -> bool {- v.single_page_wheel(egui::MouseWheelUnit::Line, dy, egui::TouchPhase::Move, at, true)- }-- #[test]- fn thumbnails_cover_the_panel_on_a_high_dpi_screen() {- // Pages panel slot is at most 150 logical points. At 2 px/pt a letter page's thumbnail- // must be at least that wide, so the panel samples it down instead of stretching it.- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let queue = v.prepare_render_queue(&info, 2.0);- let scale = queue.first().expect("one thumbnail").scale;- assert!(612.0 * scale >= 150.0 * 2.0, "{scale}");- }-- #[test]- fn notches_turn_pages_and_stop_at_the_ends() {- let mut v = view(3, PageLayout::Single, false);- assert!(notch(&mut v, -1.0, 1.0) && notch(&mut v, -1.0, 1.05));- assert_eq!(v.current, 2);- assert!(!notch(&mut v, -1.0, 1.1), "nothing turns past the last page");- assert!(notch(&mut v, 1.0, 1.2));- assert_eq!(v.current, 1);- }-- #[test]- fn notches_turn_two_page_spreads() {- // Two-page view, shown one spread at a time (not continuous): a notch turns a whole- // spread at once, not a single page (#752).- let mut v = view(4, PageLayout::TwoUp, false);- assert!(notch(&mut v, -1.0, 1.0));- assert_eq!(v.current, 2, "a notch turns from the first spread to the second");- assert!(notch(&mut v, 1.0, 1.1));- assert_eq!(v.current, 0, "a notch back turns to the previous spread");- }-- #[test]- fn continuous_views_ignore_the_wheel_for_paging() {- // Scrolling views let the ScrollArea handle the wheel; it never turns pages.- for layout in [PageLayout::Single, PageLayout::TwoUp] {- let mut v = view(3, layout, true);- assert!(!notch(&mut v, -1.0, 1.0), "{layout:?} continuous ignores the wheel");- assert_eq!(v.current, 0);- }- }-- #[test]- fn navigation_drops_partial_wheel_motion() {- use egui::{MouseWheelUnit::Point, TouchPhase::Move, TouchPhase::Start};- let mut v = view(3, PageLayout::Single, false);- assert!(!v.single_page_wheel(Point, 0.0, Start, 1.0, true));- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.02, true));- v.go_to_page(1);- // The same touch has to move a full notch's worth again before it turns.- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.04, true));- assert!(v.single_page_wheel(Point, -30.0, Move, 1.06, true));- assert_eq!(v.current, 2);- }-- #[test]- fn reselecting_the_layout_does_not_scroll_to_top() {- let mut v = view(3, PageLayout::Single, true);- v.goto = None;- v.set_layout(PageLayout::Single);- assert!(v.goto.is_none(), "re-selecting the current layout is a no-op");- v.set_continuous(true);- assert!(v.goto.is_none(), "re-selecting the current continuity is a no-op");- v.set_layout(PageLayout::TwoUp);- assert_eq!(v.goto, Some((0, 0.0)), "switching the base layout aligns the current page");- v.goto = None;- v.set_continuous(false);- assert_eq!(v.goto, Some((0, 0.0)), "toggling continuous scrolling aligns the current page");- }-- #[test]- fn fit_page_and_height_hold_still_while_mixed_page_sizes_scroll_past() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0)], ..Default::default() };- for fit in [Fit::Page, Fit::Height] {- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (fit, 1000.0, 800.0);- v.fit_zoom(&info);- let zoom = v.zoom;- v.current = 1;- v.fit_zoom(&info);- assert_eq!(v.zoom, zoom, "{fit:?}: scrolling onto a bigger page keeps the zoom");- // A single page shown on its own (not scrolling) fits each one.- (v.layout, v.continuous) = (PageLayout::Single, false);- v.fit_zoom(&info);- let big = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert!(v.zoom > big, "{fit:?}: single-page view fits the page it shows");- }- }-- /// Review on #2070: full screen in two-page view fits the spread it shows, the cover page- /// on its own included; two-page view in the window keeps one zoom for the document.- #[test]- fn full_screen_two_page_view_fits_the_spread_it_shows() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- // Spreads [0, 1] small, [2, 3] large; with a cover page [0], [1, 2] mixed, [3].- let info = DocInfo { pages: vec![page(300.0, 400.0), page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.layout, v.continuous, v.viewport_w, v.viewport_h) = (PageLayout::TwoUp, false, 1000.0, 800.0);- v.fit = Fit::Page;- v.fit_zoom(&info);- let windowed = v.zoom;- v.enter_presentation();- v.fit_zoom(&info);- let small = v.zoom;- assert!(small > windowed * 1.9, "the small spread fills the screen: {small} vs {windowed}");- v.current = 3;- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "the large spread fits as before");- v.current = 1;- v.fit_zoom(&info);- assert_eq!(v.zoom, small, "page 2 is in the first spread");- // With a cover page: [0] alone, then [1, 2] (the large page decides), then [3].- v.cover = true;- v.current = 0;- v.fit_zoom(&info);- assert_eq!(v.zoom, small, "the cover page alone");- v.current = 1;- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "page 2 shares a spread with the large page 3");- // Scrolling while in full screen fits the document, as scrolling does in the window.- (v.continuous, v.current) = (true, 0);- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "continuous full screen keeps one zoom");- v.continuous = false;- // The cover page is a spread of its own even when the next page is larger.- let mixed = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0), page(600.0, 800.0)], ..Default::default() };- v.current = 0;- v.fit_zoom(&mixed);- assert_eq!(v.zoom, small, "the small cover alone, not with page 2");- // Leaving full screen brings the document-wide fit back.- v.leave_presentation();- (v.fit, v.current) = (Fit::Page, 0);- (v.layout, v.continuous) = (PageLayout::TwoUp, false);- v.fit_zoom(&info);- assert!((v.zoom - windowed).abs() < 1e-4, "in the window, one zoom for the document");- }-- #[test]- fn fit_width_fits_the_shown_page_in_single_page_view_only() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 400.0)], ..Default::default() };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (Fit::Width, 1000.0, 800.0);- v.layout = PageLayout::Single;- v.continuous = false;- v.fit_zoom(&info);- let narrow = v.zoom;- // The shown page fills the width between the side gutters, not centred for the wide page.- let shown = v.layout(&info, v.content_width(&info, 1000.0), 1.0)[0];- assert!((shown.left() - SIDE).abs() < 1e-2 && (shown.width() - 860.0).abs() < 1e-2, "{shown:?}");- v.current = 1;- v.fit_zoom(&info);- assert!((narrow / v.zoom - 2.0).abs() < 1e-3, "the narrow page gets twice the zoom of the wide one");- // Scrolling views keep one zoom for the whole document.- v.continuous = true;- v.fit_zoom(&info);- let wide = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert_eq!(v.zoom, wide, "continuous fit width holds still across page sizes");- }-- #[test]- fn layouts_match_their_commands_and_names() {- for l in PageLayout::ORDER {- let spec = pdfcraft_engine::commands::command(l.command()).expect("registered");- assert_eq!((l.label(), l.icon()), (spec.label, spec.icon), "{l:?}");- assert_eq!(PageLayout::from_command(l.command()), Some(l));- assert_eq!(PageLayout::try_parse(l.as_str()), Some(l));- }- assert_eq!(PageLayout::try_parse(" Two-Up "), Some(PageLayout::TwoUp));- assert_eq!(PageLayout::try_parse("facing"), None);- }-- #[test]- fn a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page() {- // CAD exports link each cross-reference as `/XYZ null null 0`. Acrobat keeps the- // point at the window's top-left (and the zoom) when following one to another sheet.- let info = pdfcraft_render::DocInfo {- pages: (0..3)- .map(|_| pdfcraft_render::PageInfo { width: 842.0, height: 595.0, label: String::new(), crop: [0.0, 0.0, 842.0, 595.0], rotation: 0 })- .collect(),- ..Default::default()- };- // Page 1 at 400 %, scrolled so its point 200 pt across and 125 pt down is at the corner- // where /XYZ puts its point.- let zoomed = |rot: u16, size: Vec2| {- let mut v = view(3, PageLayout::Single, true);- v.rotation = rot;- v.viewport_screen = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 600.0));- v.screen_xforms = vec![(0, PageXform { rect: Rect::from_min_size(pos2(SIDE - 800.0, -500.0), size), rot, pw: 842.0, ph: 595.0 })];- v- };- let near = |a: Option<f32>, b: f32| a.is_some_and(|a| (a - b).abs() < 1e-4);- let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- let (page, fx, fy, rel) = v.goto_point.expect("the place is kept");- assert_eq!((v.current, page, rel), (1, 1, vec2(SIDE, 0.0)));- assert!(near(fx, 200.0 / 842.0) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");- // A coordinate the destination gives wins; only the null one is kept.- let mut v = zoomed(0, vec2(4.0 * 842.0, 4.0 * 595.0));- v.go_to_dest(2, DestView::Xyz { left: Some(421.0), top: None, zoom: Some(4.0) }, &info);- let (_, fx, fy, _) = v.goto_point.expect("the place is kept");- assert!(near(fx, 0.5) && near(fy, 125.0 / 595.0), "{fx:?} {fy:?}");- // With the view turned a quarter, the point under the corner is still the one kept.- let mut v = zoomed(90, vec2(4.0 * 595.0, 4.0 * 842.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- let (_, fx, fy, _) = v.goto_point.expect("the place is kept");- assert!(near(fx, 800.0 / (4.0 * 595.0)) && near(fy, 500.0 / (4.0 * 842.0)), "{fx:?} {fy:?}");- // A page that fits the window keeps the layout's placement: no point, as before.- let mut v = zoomed(0, vec2(800.0, 565.0));- v.go_to_dest(1, DestView::Xyz { left: None, top: None, zoom: None }, &info);- assert_eq!((v.current, v.goto, v.goto_point), (1, Some((1, 0.0)), None));- }-- #[test]- fn destinations_set_the_zoom_mode_and_the_point_to_show() {- let info = pdfcraft_render::DocInfo {- pages: (0..3)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- let mut v = view(3, PageLayout::Single, true);- v.fit = Fit::Width;- // No position (or a malformed one): the top of the page, zoom as it was.- v.go_to_dest(1, DestView::Top, &info);- assert_eq!((v.current, v.goto, v.goto_point, v.fit), (1, Some((1, 0.0)), None, Fit::Width));- // /XYZ with a null zoom keeps the zoom mode; its point is a quarter down page 3.- v.go_to_dest(2, DestView::Xyz { left: None, top: Some(300.0), zoom: None }, &info);- assert_eq!((v.current, v.fit, v.goto_point), (2, Fit::Width, Some((2, None, Some(0.25), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::Xyz { left: Some(150.0), top: None, zoom: Some(2.5) }, &info);- assert_eq!((v.fit, v.zoom, v.goto_point), (Fit::None, 2.5, Some((0, Some(0.5), None, vec2(SIDE, 0.0)))));- // A zoom beyond the view's range is clamped to it.- v.go_to_dest(0, DestView::Xyz { left: None, top: None, zoom: Some(1e30) }, &info);- assert_eq!((v.zoom, v.goto_point), (64.0, None));- v.go_to_dest(0, DestView::Fit, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Page, None));- v.go_to_dest(0, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Width, Some((0, None, Some(0.75), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::FitV { left: Some(75.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Height, Some((0, Some(0.25), None, vec2(SIDE, 0.0)))));- // /FitR: the zoom that fits a 100×50 pt rectangle in an 800×600 window, centred.- (v.viewport_w, v.viewport_h) = (800.0, 600.0);- v.go_to_dest(0, DestView::FitR { rect: [0.0, 300.0, 100.0, 350.0] }, &info);- assert_eq!(v.fit, Fit::None);- assert!((v.zoom - 8.0 / PT).abs() < 1e-4, "{}", v.zoom);- let (page, fx, fy, rel) = v.goto_point.expect("a point to show");- assert_eq!((page, rel), (0, vec2(400.0, 300.0)));- assert!((fx.unwrap_or(-1.0) - 50.0 / 300.0).abs() < 1e-4 && (fy.unwrap_or(-1.0) - 75.0 / 400.0).abs() < 1e-4, "{fx:?} {fy:?}");- // A page past the end goes to the last page; a page the document info lacks, to its top.- v.go_to_dest(usize::MAX, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.current, v.goto_point.map(|g| g.0)), (2, Some(2)));- let empty = pdfcraft_render::DocInfo::default();- v.go_to_dest(1, DestView::FitH { top: Some(100.0) }, &empty);- assert_eq!((v.current, v.goto_point), (1, None));- }-- #[test]- fn page_text_failure_preserves_valid_search_match_without_jitter() {- let mut v = view(3, PageLayout::Single, true);- v.current = 1;- v.find = Some(Find {- query: "test".into(),- case_query: "test".into(),- matches: vec![(0, 0..4), (1, 5..9)],- current: Some(0),- ..Default::default()- });- let req = RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() };- v.last_queue = vec![req];- let ctx = egui::Context::default();- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request: req,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- // Active match was on page 0 which failed: current should fall back to match on page 1 without jitter- assert_eq!(v.find.as_ref().unwrap().current, Some(0));- assert_eq!(v.find.as_ref().unwrap().matches, vec![(1, 5..9)]);- assert!(v.goto.is_none());- }-- /// A page whose picture moved can get its whole-page raster back before its last stale tile.- /// From then on the raster has the picture where it went: it is drawn from there, not from- /// where it was (which the raster now shows empty), and another drag starts from there too.- #[test]- fn a_moved_picture_is_drawn_from_the_fresh_raster_while_a_tile_is_still_stale() {- let content = b"q 60 0 0 60 40 260 cm /Im0 Do Q";- let objs: Vec<Vec<u8>> = vec![- b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),- b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(),- b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(),- [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content.as_slice(), b"\nendstream"].concat(),- [- b"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceRGB /Length 3 >>\nstream\n".as_slice(),- &[200, 30, 30],- b"\nendstream",- ]- .concat(),- ];- let mut bytes = b"%PDF-1.7\n".to_vec();- let mut offsets = Vec::new();- for (i, o) in objs.iter().enumerate() {- offsets.push(bytes.len());- bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());- bytes.extend_from_slice(o);- bytes.extend_from_slice(b"\nendobj\n");- }- let xref = bytes.len();- bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());- for o in offsets {- bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());- }- bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1100.0)).build_eframe(move |_cc| {- let mut app = PdfCraftApp::new();- app.set_option("language", "en").unwrap();- app.open_bytes("picture.pdf", None, bytes.clone()).unwrap();- app.set_option("zoom", "100").unwrap();- app.quick_tool = QuickTool::EditText;- app- });- let settle = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>| {- for _ in 0..400 {- h.step();- if !h.state().render_pending() {- return;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- };- h.run_steps(4);- settle(&mut h);- let page = h.state().views[0].page_screen_rect(0).unwrap();- let at = |x: f32, y: f32| egui::pos2(page.left() + x / 300.0 * page.width(), page.top() + (400.0 - y) / 400.0 * page.height());- let red = |pixels: &image::RgbaImage, r: Rect| {- let (w, hh) = (pixels.width(), pixels.height());- (r.top().max(0.0) as u32..(r.bottom() as u32).min(hh))- .flat_map(|y| (r.left().max(0.0) as u32..(r.right() as u32).min(w)).map(move |x| (x, y)))- .filter(|(x, y)| matches!(pixels.get_pixel(*x, *y).0, [r, g, b, _] if r > 150 && g < 90 && b < 90))- .count()- };- let (old, new) = (Rect::from_two_pos(at(42.0, 262.0), at(98.0, 318.0)), Rect::from_two_pos(at(182.0, 82.0), at(238.0, 138.0)));- // Select the picture and drag it, without overlap, from (40, 260) to (180, 80).- let drag = |h: &mut egui_kittest::Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2, release: bool| {- h.hover_at(from);- h.run_steps(1);- h.drag_at(from);- h.run_steps(1);- for k in 1..=4 {- h.hover_at(from + (to - from) * (k as f32 / 4.0));- h.run_steps(1);- }- if release {- h.drop_at(to);- h.step();- }- };- let (grab, put) = (at(70.0, 290.0), at(210.0, 110.0));- h.hover_at(grab);- h.run_steps(1);- h.drag_at(grab);- h.run_steps(1);- h.drop_at(grab);- h.run_steps(3);- assert!(h.state().views[0].image_selection.is_some(), "the picture is selected");- h.state_mut().views[0].hold_rasters = true;- drag(&mut h, grab, put, true);- // One tile stays stale, as a tile result arriving after the whole-page raster would; then- // the whole-page raster is let through.- let tile = h.ctx.load_texture("stale-tile", egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), TextureOptions::LINEAR);- h.state_mut().views[0].tiles.insert((0, 1, 0, 0), tile);- h.state_mut().views[0].stale_tiles.insert((0, 1, 0, 0));- h.state_mut().views[0].hold_rasters = false;- for _ in 0..400 {- h.step();- if !h.state().views[0].page_raster_out_of_date(0) {- break;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- assert!(!h.state().views[0].page_raster_out_of_date(0), "the whole-page raster is fresh");- assert!(h.state().views[0].page_out_of_date(0), "a tile is still stale");- h.run_steps(2);- let pixels = h.render().unwrap();- assert!(red(&pixels, new) > 100, "the picture shows where it went");- assert_eq!(red(&pixels, old), 0, "and not where it was");- // Another drag in that interval takes its pixels from where the raster has them.- let further = at(210.0, 200.0);- drag(&mut h, put, further, false);- let pixels = h.render().unwrap();- let moving = Rect::from_two_pos(at(182.0, 172.0), at(238.0, 228.0));- assert!(red(&pixels, moving) > 100, "the dragged picture is drawn from the fresh raster");- assert_eq!(red(&pixels, old), 0, "nothing shows where it first was");- h.state_mut().views[0].stale_tiles.clear();- h.state_mut().views[0].tiles.clear();- }- }-mod tests;++//! The document area: page layout, zoom, render scheduling, overlays (links, annotation hovers,++//! form-field highlights), and the organize-pages grid.++//!++//! Page images come from the engine's render pool as whole-page rasters at the current zoom;++//! stale rasters are shown stretched until the sharp one arrives (tiling comes in M3.3).++++use std::collections::{BTreeSet, HashMap, HashSet};++use std::ops::Range;++use std::sync::Arc;++++use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, Vec2, pos2, vec2};++use pdfcraft_engine::{DocId, Edit};++use pdfcraft_render::{DestView, DocInfo, LayerOp, LinkTarget, PRINT_TAG, PageText, RenderPool, RenderRequest, RequestKind, Tile, device_pixels};++++use crate::page_pointer::PagePointer;++use crate::theme::{self, Tokens};++use crate::{PdfCraftApp, QuickTool, RightPanel, comments, icons, widgets};++++mod area;++pub(super) mod autoscroll;++mod bars;++mod cache;++pub(super) mod crop;++mod find;++pub(super) mod fling;++pub(super) mod image_pick;++mod navigation;++mod organize;++pub(super) mod page_pointer;++pub mod scroll_speed;++mod selection;++pub(super) mod signature_drag;++pub(super) mod wheel_boost;++pub(super) mod wheel_pager;++mod xform;++mod zoom;++pub(super) mod zoom_snap;++++pub(crate) use area::signature_badges;++use area::{++ SUPPRESS_SECS, SUPPRESS_TAIL_SECS, annotation_hover_text, drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button,++ set_layers, zoom_anchor,++};++#[cfg(test)]++use bars::in_size_hint_zone;++use bars::{Notice, notices, page_size_hint, quick_bar};++pub use cache::RasterMemory;++pub(crate) use cache::{BASE_SIDE, TILE_THRESHOLD, texture_image, thumbnail_rows};++#[cfg(test)]++use cache::{++ GRAYSCALE_TAG, GRID_TAG, MAX_CACHED_TEXT_PAGES, MAX_THUMB_DEMAND, PAGE_BYTES, THUMB_BYTES, THUMB_H, THUMB_TAG, THUMB_W, TILE, grayscale,++ rgba_bytes,++};++use cache::{OLD_TILES, PageTex, STALE_TAG, TEXT_TAG, TILE_BYTES, scale_tag, tag_scale, texture_bytes, tile_side};++pub use find::Find;++use find::find_bar;++pub use navigation::shortcuts;++pub(crate) use organize::drop_gap;++#[cfg(test)]++pub(crate) use organize::grid_page_rect;++use organize::organize_grid;++#[cfg(test)]++use organize::sharp_enough;++use selection::{Selection, Span, click_unit, selection_actions};++pub use xform::PageXform;++use xform::snap_to_pixels;++use zoom::anchored_scroll;++pub use zoom::{GRID_ZOOM_RANGE, THUMBNAIL_ZOOM_RANGE};++++/// Logical pixels per PDF point at 100% (96 dpi, like browsers).++pub const PT: f32 = 96.0 / 72.0;++const GAP: f32 = 14.0;++const MARGIN: f32 = 28.0;++/// Horizontal gutter that keeps pages clear of the floating quick-action bar.++const SIDE: f32 = 70.0;++use crate::edit_text_ui::ImageHandle;++++/// Extension trait on `egui::Painter` to draw polygons.++pub trait PainterExt {++ fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx;++}++++impl PainterExt for egui::Painter {++ fn polygon(&self, points: Vec<Pos2>, fill: Color32, stroke: Stroke) -> egui::layers::ShapeIdx {++ self.add(egui::Shape::convex_polygon(points, fill, stroke))++ }++}++++/// User-space selectable bounding box for an image object.++/// If the image object has an active clipping path applied to it (the crop box),++/// this is the mathematical intersection of the full CTM-derived rect and the clipping path's rect.++pub fn image_selectable_bounds(im: &pdfcraft_engine::PageImage) -> [f64; 4] {++ if let Some(clip) = im.clip_rect {++ let r = [im.rect[0].max(clip[0]), im.rect[1].max(clip[1]), im.rect[2].min(clip[2]), im.rect[3].min(clip[3])];++ if r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1] {++ return r;++ }++ }++ im.visible_rect.unwrap_or(im.rect)++}++++/// Screen-space selectable bounding box for an image object.++/// If the image object has an active clipping path applied to it (the crop box),++/// the final selectable `egui::Rect` is the mathematical intersection of the image's++/// full CTM-derived rect and the clipping path's rect.++pub fn image_screen_rect(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Rect {++ let full = xf.user_rect_f64(info, page, im.rect);++ if let Some(clip) = im.clip_rect {++ let clip_r = xf.user_rect_f64(info, page, clip);++ let inter = full.intersect(clip_r);++ if inter.is_positive() {++ return inter;++ }++ }++ if let Some(vr) = im.visible_rect {++ let r = xf.user_rect_f64(info, page, vr);++ if r.is_positive() {++ return r;++ }++ }++ full++}++++/// An Oriented Bounding Box (OBB) representing a rotated rectangle in screen space,++/// with 8 resize handles and rotated local axes.++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct ImageObb {++ pub s00: Pos2,++ pub s10: Pos2,++ pub s11: Pos2,++ pub s01: Pos2,++ pub s_bc: Pos2,++ pub s_rc: Pos2,++ pub s_tc: Pos2,++ pub s_lc: Pos2,++ pub s_rot: Pos2,++ pub screen_center: Pos2,++ pub width: f32,++ pub height: f32,++ pub theta: f32,++ pub u_axis: (f64, f64),++ pub v_axis: (f64, f64),++ pub is_rotated: bool,++}++++impl ImageObb {++ /// Calculates the 4 rotated corners manually using center, width, height, and rotation angle (θ).++ /// Local axes: `u_axis = (cos θ, sin θ)` and `v_axis = (-sin θ, cos θ)`.++ /// Places the 8 resize handles exactly at these rotated vertices and midpoints.++ pub fn from_center_size_angle(center: Pos2, width: f32, height: f32, theta: f32) -> Self {++ let cos_t = theta.cos();++ let sin_t = theta.sin();++ let u_axis = (cos_t as f64, sin_t as f64);++ let v_axis = (-sin_t as f64, cos_t as f64);++ let u_vec = vec2(cos_t, sin_t);++ let v_vec = vec2(-sin_t, cos_t);++ let hw = width * 0.5;++ let hh = height * 0.5;++++ let s00 = center - u_vec * hw - v_vec * hh;++ let s10 = center + u_vec * hw - v_vec * hh;++ let s11 = center + u_vec * hw + v_vec * hh;++ let s01 = center - u_vec * hw + v_vec * hh;++++ let s_bc = center - v_vec * hh;++ let s_rc = center + u_vec * hw;++ let s_tc = center + v_vec * hh;++ let s_lc = center - u_vec * hw;++++ let s_rot = s_tc + v_vec * 24.0;++ let is_rotated = theta.abs() > 1e-4;++++ Self { s00, s10, s11, s01, s_bc, s_rc, s_tc, s_lc, s_rot, screen_center: center, width, height, theta, u_axis, v_axis, is_rotated }++ }++++ pub fn new(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {++ Self::from_matrix(matrix, xf, info, page)++ }++++ pub fn from_matrix(matrix: [f64; 6], xf: &PageXform, info: &DocInfo, page: usize) -> Self {++ let m = crate::edit_text_ui::Matrix(matrix);++ let p00 = m.apply(0.0, 0.0);++ let p10 = m.apply(1.0, 0.0);++ let p11 = m.apply(1.0, 1.0);++ let p01 = m.apply(0.0, 1.0);++++ let s00 = crate::edit_text_ui::user_to_screen(xf, info, page, p00.0, p00.1);++ let s10 = crate::edit_text_ui::user_to_screen(xf, info, page, p10.0, p10.1);++ let s11 = crate::edit_text_ui::user_to_screen(xf, info, page, p11.0, p11.1);++ let s01 = crate::edit_text_ui::user_to_screen(xf, info, page, p01.0, p01.1);++++ let s_bc = Pos2::new((s00.x + s10.x) * 0.5, (s00.y + s10.y) * 0.5);++ let s_rc = Pos2::new((s10.x + s11.x) * 0.5, (s10.y + s11.y) * 0.5);++ let s_tc = Pos2::new((s01.x + s11.x) * 0.5, (s01.y + s11.y) * 0.5);++ let s_lc = Pos2::new((s00.x + s01.x) * 0.5, (s00.y + s01.y) * 0.5);++++ let screen_center = Pos2::new((s00.x + s10.x + s11.x + s01.x) * 0.25, (s00.y + s10.y + s11.y + s01.y) * 0.25);++ let out_dir = s_tc - screen_center;++ let out_len = out_dir.length().max(1e-4);++ let out_norm = out_dir / out_len;++ let s_rot = s_tc + out_norm * 24.0;++++ let [a, b, c, d, ..] = matrix;++ let w_u = (a * a + b * b).sqrt().max(1e-6);++ let h_v = (c * c + d * d).sqrt().max(1e-6);++ let u_axis = (a / w_u, b / w_u);++ let v_axis = (c / h_v, d / h_v);++ let theta = (b).atan2(a) as f32;++ let is_rotated = b.abs() > 1e-4 || c.abs() > 1e-4;++++ Self {++ s00,++ s10,++ s11,++ s01,++ s_bc,++ s_rc,++ s_tc,++ s_lc,++ s_rot,++ screen_center,++ width: (s10 - s00).length(),++ height: (s01 - s00).length(),++ theta,++ u_axis,++ v_axis,++ is_rotated,++ }++ }++++ pub fn from_image(im: &pdfcraft_engine::PageImage, xf: &PageXform, info: &DocInfo, page: usize) -> Self {++ let [_, b, c, ..] = im.matrix;++ let is_rot = b.abs() > 1e-4 || c.abs() > 1e-4;++ let bounds = image_selectable_bounds(im);++ let matrix = if !is_rot && bounds[2] > bounds[0] && bounds[3] > bounds[1] {++ [bounds[2] - bounds[0], 0.0, 0.0, bounds[3] - bounds[1], bounds[0], bounds[1]]++ } else {++ im.matrix++ };++ Self::from_matrix(matrix, xf, info, page)++ }++++ pub fn handles(&self) -> [(ImageHandle, Pos2); 8] {++ [++ (ImageHandle::TopLeft, self.s01),++ (ImageHandle::TopCenter, self.s_tc),++ (ImageHandle::TopRight, self.s11),++ (ImageHandle::RightCenter, self.s_rc),++ (ImageHandle::BottomRight, self.s10),++ (ImageHandle::BottomCenter, self.s_bc),++ (ImageHandle::BottomLeft, self.s00),++ (ImageHandle::LeftCenter, self.s_lc),++ ]++ }++++ pub fn handle_pos(&self, handle: ImageHandle) -> Pos2 {++ match handle {++ ImageHandle::TopLeft => self.s01,++ ImageHandle::TopCenter => self.s_tc,++ ImageHandle::TopRight => self.s11,++ ImageHandle::RightCenter => self.s_rc,++ ImageHandle::BottomRight => self.s10,++ ImageHandle::BottomCenter => self.s_bc,++ ImageHandle::BottomLeft => self.s00,++ ImageHandle::LeftCenter => self.s_lc,++ }++ }++++ pub fn handle_id(&self, base_id: egui::Id, handle: ImageHandle) -> egui::Id {++ base_id.with(match handle {++ ImageHandle::TopLeft => "handle_tl",++ ImageHandle::TopCenter => "handle_tc",++ ImageHandle::TopRight => "handle_tr",++ ImageHandle::RightCenter => "handle_rc",++ ImageHandle::BottomRight => "handle_br",++ ImageHandle::BottomCenter => "handle_bc",++ ImageHandle::BottomLeft => "handle_bl",++ ImageHandle::LeftCenter => "handle_lc",++ })++ }++++ pub fn handles_with_ids(&self, base_id: egui::Id) -> [(ImageHandle, Pos2, egui::Id); 8] {++ [++ (ImageHandle::TopLeft, self.s01, self.handle_id(base_id, ImageHandle::TopLeft)),++ (ImageHandle::TopCenter, self.s_tc, self.handle_id(base_id, ImageHandle::TopCenter)),++ (ImageHandle::TopRight, self.s11, self.handle_id(base_id, ImageHandle::TopRight)),++ (ImageHandle::RightCenter, self.s_rc, self.handle_id(base_id, ImageHandle::RightCenter)),++ (ImageHandle::BottomRight, self.s10, self.handle_id(base_id, ImageHandle::BottomRight)),++ (ImageHandle::BottomCenter, self.s_bc, self.handle_id(base_id, ImageHandle::BottomCenter)),++ (ImageHandle::BottomLeft, self.s00, self.handle_id(base_id, ImageHandle::BottomLeft)),++ (ImageHandle::LeftCenter, self.s_lc, self.handle_id(base_id, ImageHandle::LeftCenter)),++ ]++ }++++ pub fn corners(&self) -> [Pos2; 4] {++ [self.s00, self.s10, self.s11, self.s01]++ }++++ /// Resizes the OBB proportionally along its local axes using projected mouse delta,++ /// locking the diagonally opposite corner as the fixed anchor point.++ pub fn scale_proportional(&self, handle: ImageHandle, delta: Vec2, min_size: f32) -> Self {++ let u_vec = vec2(self.u_axis.0 as f32, self.u_axis.1 as f32);++ let v_vec = vec2(self.v_axis.0 as f32, self.v_axis.1 as f32);++ let delta_u = delta.dot(u_vec);++ let delta_v = delta.dot(v_vec);++ let min_s = min_size.max(5.0);++++ match handle {++ ImageHandle::TopRight => {++ let anchor = self.s00;++ let s_u = (self.width + delta_u) / self.width.max(1e-4);++ let s_v = (self.height + delta_v) / self.height.max(1e-4);++ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };++ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));++ let nw = self.width * s;++ let nh = self.height * s;++ let new_center = anchor + u_vec * (nw * 0.5) + v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, nw, nh, self.theta)++ }++ ImageHandle::TopLeft => {++ let anchor = self.s10;++ let s_u = (self.width - delta_u) / self.width.max(1e-4);++ let s_v = (self.height + delta_v) / self.height.max(1e-4);++ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };++ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));++ let nw = self.width * s;++ let nh = self.height * s;++ let new_center = anchor - u_vec * (nw * 0.5) + v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, nw, nh, self.theta)++ }++ ImageHandle::BottomLeft => {++ let anchor = self.s11;++ let s_u = (self.width - delta_u) / self.width.max(1e-4);++ let s_v = (self.height - delta_v) / self.height.max(1e-4);++ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };++ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));++ let nw = self.width * s;++ let nh = self.height * s;++ let new_center = anchor - u_vec * (nw * 0.5) - v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, nw, nh, self.theta)++ }++ ImageHandle::BottomRight => {++ let anchor = self.s01;++ let s_u = (self.width + delta_u) / self.width.max(1e-4);++ let s_v = (self.height - delta_v) / self.height.max(1e-4);++ let s = if (s_u - 1.0).abs() >= (s_v - 1.0).abs() { s_u } else { s_v };++ let s = s.max(min_s / self.width.max(1e-4)).max(min_s / self.height.max(1e-4));++ let nw = self.width * s;++ let nh = self.height * s;++ let new_center = anchor + u_vec * (nw * 0.5) - v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, nw, nh, self.theta)++ }++ ImageHandle::RightCenter => {++ let anchor = self.s_lc;++ let nw = (self.width + delta_u).max(min_s);++ let new_center = anchor + u_vec * (nw * 0.5);++ Self::from_center_size_angle(new_center, nw, self.height, self.theta)++ }++ ImageHandle::LeftCenter => {++ let anchor = self.s_rc;++ let nw = (self.width - delta_u).max(min_s);++ let new_center = anchor - u_vec * (nw * 0.5);++ Self::from_center_size_angle(new_center, nw, self.height, self.theta)++ }++ ImageHandle::TopCenter => {++ let anchor = self.s_bc;++ let nh = (self.height + delta_v).max(min_s);++ let new_center = anchor + v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, self.width, nh, self.theta)++ }++ ImageHandle::BottomCenter => {++ let anchor = self.s_tc;++ let nh = (self.height - delta_v).max(min_s);++ let new_center = anchor - v_vec * (nh * 0.5);++ Self::from_center_size_angle(new_center, self.width, nh, self.theta)++ }++ }++ }++}++++/// Projects mouse delta onto local unit axes `u_axis` and `v_axis` using the dot product.++pub fn project_delta(delta: Vec2, u_axis: (f64, f64), v_axis: (f64, f64)) -> (f64, f64) {++ let dx = delta.x as f64;++ let dy = delta.y as f64;++ (dx * u_axis.0 + dy * u_axis.1, dx * v_axis.0 + dy * v_axis.1)++}++++/// Visible grid rows, plus one adjacent row in either direction. Work is independent of++/// document length, including after a large scroll jump.++++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum Fit {++ Width,++ Page,++ Height,++ None,++}++++/// The page display as it was before full screen, put back on leaving it++/// ([`DocView::enter_presentation`]).++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct SavedDisplay {++ pub layout: PageLayout,++ pub continuous: bool,++ pub cover: bool,++ pub fit: Fit,++ pub zoom: f32,++}++++/// The base page display: one page across, or a two-page spread. Whether it scrolls continuously++/// is a separate flag (`continuous`), as in Acrobat, so every combination is reachable (#752).++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum PageLayout {++ Single,++ TwoUp,++}++++impl PageLayout {++ /// The base page displays, in the order the View menu, the rail's Page display button and++ /// Preferences list them.++ pub const ORDER: [Self; 2] = [Self::Single, Self::TwoUp];++++ /// The name settings and view options use for the base layout: `single` or `two-up`.++ pub fn as_str(self) -> &'static str {++ match self {++ Self::Single => "single",++ Self::TwoUp => "two-up",++ }++ }++++ /// The base layout an [`as_str`](Self::as_str) name stands for, in any case. `None` for++ /// anything else, so callers can reject a typo rather than switch layouts silently.++ pub fn try_parse(value: &str) -> Option<Self> {++ Self::ORDER.into_iter().find(|l| l.as_str().eq_ignore_ascii_case(value.trim()))++ }++++ /// Rail icon for this layout.++ pub fn icon(self) -> &'static str {++ match self {++ Self::Single => "file-text",++ Self::TwoUp => "columns-2",++ }++ }++++ /// Registry command that switches to this base layout (`PdfCraftApp::execute`).++ pub fn command(self) -> &'static str {++ match self {++ Self::Single => "view.layout.single",++ Self::TwoUp => "view.layout.two_up",++ }++ }++++ /// The base layout a [`command`](Self::command) id switches to.++ pub fn from_command(id: &str) -> Option<Self> {++ Self::ORDER.into_iter().find(|l| l.command() == id)++ }++++ /// Menu label: the label of [`command`](Self::command), which the catalogs translate.++ pub fn label(self) -> &'static str {++ match self {++ Self::Single => "Single page",++ Self::TwoUp => "Two-page view",++ }++ }++}++++/// The single page-display token settings and the control channel use, combining the base layout++/// with continuous scrolling. `single` and `two-page` show one page or one spread at a time;++/// `continuous` (Single, scrolling) and `two-up` (Two-page, scrolling) keep their earlier names++/// for back-compat.++pub fn display_token(layout: PageLayout, continuous: bool) -> &'static str {++ match (layout, continuous) {++ (PageLayout::Single, false) => "single",++ (PageLayout::Single, true) => "continuous",++ (PageLayout::TwoUp, true) => "two-up",++ (PageLayout::TwoUp, false) => "two-page",++ }++}++++/// The base layout and continuous flag a [`display_token`] names, in any case. `None` for a typo.++pub fn parse_display_token(value: &str) -> Option<(PageLayout, bool)> {++ match value.trim().to_ascii_lowercase().as_str() {++ "single" => Some((PageLayout::Single, false)),++ "continuous" => Some((PageLayout::Single, true)),++ "two-up" => Some((PageLayout::TwoUp, true)),++ "two-page" | "two-up-single" => Some((PageLayout::TwoUp, false)),++ _ => None,++ }++}++++/// How a newly opened document is shown (Preferences ▸ Documents and view). A PDF that asks++/// for its own layout or zoom gets that instead.++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct ViewDefaults {++ pub layout: PageLayout,++ /// Whether the base layout scrolls continuously.++ pub continuous: bool,++ /// Separate pages with a gutter and shadow; off joins adjacent page edges.++ pub show_page_gaps: bool,++ /// [`Fit::Width`] or [`Fit::Page`], or [`Fit::None`] for a fixed `zoom`.++ pub fit: Fit,++ /// The zoom with [`Fit::None`] (1.0 = 100%).++ pub zoom: f32,++ /// Highlight existing fields: a preference in Acrobat, so it carries over to the next++ /// document and the next session. On for new settings; a stored choice wins.++ pub highlight_fields: bool,++}++++impl Default for ViewDefaults {++ fn default() -> Self {++ // Single page, scrolling continuously at fit width: the earlier "continuous" default.++ Self { layout: PageLayout::Single, continuous: true, show_page_gaps: true, fit: Fit::Width, zoom: 1.0, highlight_fields: true }++ }++}++++impl ViewDefaults {++ /// The zoom as settings and view options name it: `fit-width`, `fit-page` or a percentage.++ pub fn zoom_name(&self) -> String {++ match self.fit {++ Fit::Page => "fit-page".into(),++ Fit::None => format!("{}%", (self.zoom * 100.0).round()),++ Fit::Width | Fit::Height => "fit-width".into(),++ }++ }++++ /// These defaults with the zoom a [`zoom_name`](Self::zoom_name) names, in any case. `None`++ /// for anything else, including a percentage outside the 8–6400% the view can show.++ pub fn with_zoom(self, name: &str) -> Option<Self> {++ let name = name.trim();++ let (fit, zoom) = if name.eq_ignore_ascii_case("fit-width") {++ (Fit::Width, self.zoom)++ } else if name.eq_ignore_ascii_case("fit-page") {++ (Fit::Page, self.zoom)++ } else {++ let percent = name.strip_suffix('%').unwrap_or(name).trim().parse::<f32>().ok().filter(|p| (8.0..=6400.0).contains(p))?;++ (Fit::None, percent / 100.0)++ };++ Some(Self { fit, zoom, ..self })++ }++}++++/// A historical snapshot opened from another document: View signed version opens the bytes++/// a signature covers, View revision an earlier incremental revision. Repeats reuse the tab,++/// and the tab and notice bar name what it is, instead of piling up identical tabs.++/// What a historical snapshot shows: the bytes a signature covers, or an earlier++/// incremental revision.++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum SnapshotKind {++ SignedVersion,++ Revision,++}++++#[derive(Clone, Debug)]++pub struct Snapshot {++ pub kind: SnapshotKind,++ /// The 1-based revision shown.++ pub revision: usize,++ /// The name of the document it was opened from.++ pub from: String,++}++++/// The name shown for a document tab, the window title and the Combine picker.++/// A snapshot reads like its source document, plus the snapshot suffix that tells++/// the tabs apart. Without a title the file name (which already carries the suffix)++/// is enough.++pub(crate) fn tab_label(app: &PdfCraftApp, index: usize) -> Option<String> {++ let view = app.views.get(index)?;++ let doc = app.session.get(view.id)?;++ let Some(snap) = view.snapshot.as_ref() else { return Some(doc.display_name()) };++ Some(snapshot_tab_name(&doc.display_name(), &doc.name, snap))++}++++/// A snapshot's tab name from its source title, file name and marker. Pure so the++/// tab strip, window title and picker cannot disagree with each other.++pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapshot) -> String {++ if title == file_name {++ return file_name.into();++ }++ if snapshot.kind == SnapshotKind::SignedVersion {++ format!("{title} (signed version)")++ } else {++ format!("{title} (revision {})", snapshot.revision)++ }++}++++pub struct DocView {++ pub id: DocId,++ pub zoom: f32,++ pub fit: Fit,++ pub layout: PageLayout,++ /// Whether the base layout scrolls continuously (independent of `layout`, as in Acrobat).++ pub continuous: bool,++ pub show_page_gaps: bool,++ /// View rotation in degrees clockwise (0, 90, 180, 270); display only, never saved.++ pub rotation: u16,++ pub current: usize,++ pub organize: bool,++ pub highlight_fields: bool,++ pub page_input: String,++ /// Select the replacement page label once if its editor remains focused.++ pub(crate) page_input_reselect: bool,++ pub notice_dismissed: bool,++ /// The user has been told that the form's scripts were turned off (it is said once).++ pub scripts_off_noted: bool,++ /// The file changed on disk while this document had unsaved changes: the notice bar asks++ /// before replacing it (#431).++ pub disk_changed: bool,++ /// The snapshot notice bar's Close was clicked: the tab closes at the top of the next++ /// frame, where no document borrow is held (the bar itself can't close it).++ pub close_requested: bool,++ /// A historical snapshot of another document (see [`Snapshot`]): `None` for real documents.++ pub snapshot: Option<Snapshot>,++ /// Two-page view: show the first page alone, as a cover (View ▸ Page display).++ pub cover: bool,++ /// Previous view / Next view: pages visited before (and after, once going back).++ pub back: Vec<usize>,++ pub forward: Vec<usize>,++ /// Pending navigation: page and fraction down the page to align with the viewport top.++ pub goto: Option<(usize, f32)>,++ /// Pending position within that page from a destination ([`Self::go_to_dest`]): the point++ /// (fractions of the displayed page; `None` leaves that axis to `goto`) to put `rel` points++ /// from the viewport's top-left corner.++ goto_point: Option<(usize, Option<f32>, Option<f32>, Vec2)>,++ /// Pending keyboard scrolling, in points down (negative: up): ↓ / ↑, and Page Down /++ /// Page Up where the pages scroll.++ pub key_scroll: f32,++ /// Single-page view, as last drawn: the page shown and whether the view was at its top and++ /// at its bottom, so ↑ / ↓ turn the page there instead of doing nothing (#273).++ single_edges: Option<(usize, bool, bool)>,++ /// Briefly outline an annotation after navigating to it from a panel.++ pub flash: Option<(usize, [f32; 4], f64)>,++ /// Compare files: differences shaded on this document's pages (page, user-space box, colour).++ pub compare_marks: Vec<(usize, [f32; 4], Color32)>,++ /// Full screen (Acrobat's Full Screen Mode): the display saved on entering it, while the view++ /// shows one page or spread at a time, fitted to the screen. `None` outside full screen.++ presentation: Option<SavedDisplay>,++ pages: HashMap<usize, PageTex>,++ /// Pages the renderer could not draw, with the reason (never re-requested).++ errors: HashMap<usize, String>,++ /// When each still-missing page was first shown, to flag unusually slow renders.++ waiting_since: HashMap<usize, f64>,++ thumbs: HashMap<usize, PageTex>,++ /// This frame's consumers, with visible cells ahead of prefetch.++ thumb_demand: HashMap<usize, bool>,++ frame_queue: Vec<RenderRequest>,++ /// A page-list edit after layout invalidates this frame's scales and page indexes.++ frame_geometry_changed: bool,++ /// Pages on screen this frame. Their rasters and tiles are always admitted: the viewport++ /// bounds them, and the byte and count limits apply to prefetch only.++ frame_visible: HashSet<usize>,++ /// Thumbnails that are out of date (still shown until their replacement arrives).++ stale_thumbs: HashSet<usize>,++ /// Tiles that are out of date (still shown until their replacement arrives).++ stale_tiles: HashSet<(usize, u64, u32, u32)>,++ /// Scale tag of the current zoom level, as last drawn.++ current_scale_tag: u64,++ /// Print dialog: the current sheet's pages at the preview pane's device resolution.++ print_pages: HashMap<usize, (u64, TextureHandle)>,++ /// Print dialog: preview rasters become luminance when Print ▸ Print in grayscale is on.++ grayscale: bool,++ /// Sharp tiles of large pages: (page, scale tag, tile x, tile y) → texture. Tiles of an++ /// earlier zoom stay, drawn stretched, until those of the current one cover the page.++ tiles: HashMap<(usize, u64, u32, u32), TextureHandle>,++ /// Text layers, extracted in the background on demand (selection, find, copy).++ pub(crate) texts: HashMap<usize, Arc<PageText>>,++ pub(crate) text_failed: HashSet<usize>,++ pub find: Option<Find>,++ selection: Option<Selection>,++ /// Select All while scrolling continuously (#2639): the text of every page of the document,++ /// highlighted on each page as its text arrives and copied whole ([`DocView::whole_text`]).++ pub(crate) all_text: bool,++ /// The selection whose action bar was closed by its Copy button: the bar stays hidden++ /// until the selection changes, as it does once a markup button consumes the selection.++ actions_dismissed: Option<Selection>,++ /// The drag in progress started a text selection: the wheel scrolls the page during it++ /// (#721), which egui's scroll area refuses while anything is dragged.++ selection_drag: bool,++ /// Clicks in the current run on the text layer: two select a word, three the line, four the page.++ clicks: u32,++ last_press_time: f64,++ last_press_pos: Option<Pos2>,++ /// Full screen: a click's page turn, when it falls due (input time) and which way. It waits++ /// out the double-click time, as the click may be the first of a double-click selecting a word.++ present_turn: Option<(f64, bool)>,++ last_queue: Vec<RenderRequest>,++ /// Finished renders wait in the pool instead of reaching the view (tests): what the view++ /// shows before a raster arrives can be looked at however fast the renderer is.++ pub hold_rasters: bool,++ viewport_w: f32,++ viewport_h: f32,++ page_count: usize,++ /// Page heights in points (view space), for mapping text positions to scroll offsets.++ page_heights: Vec<f32>,++ /// Screen rects of the pages drawn last frame (hit-testing, tests, automation).++ screen_rects: Vec<(usize, Rect)>,++ screen_xforms: Vec<(usize, PageXform)>,++ /// The scroll viewport on screen last frame.++ viewport_screen: Rect,++ /// Pending zoom anchor: page, fractional position (also in gutters), and viewport offset.++ zoom_anchor: Option<(usize, f32, f32, Vec2)>,++ /// The page view has been shown, so its scroll offset in egui's memory is this document's.++ shown: bool,++ /// Pages that Edit already tried to turn into editable text (once each, so Undo sticks).++ pub(crate) auto_ocr_tried: std::collections::HashSet<usize>,++ /// Pages Edit looked at and found not to be a scan, with the document's edit generation then:++ /// they are looked at again only after the document changes (an image added, say).++ pub(crate) auto_ocr_skipped: std::collections::HashMap<usize, u64>,++ /// Turns wheel input into page turns in single-page view.++ wheel: crate::wheel_pager::WheelPager,++ /// Until this time, apply precise (touchpad) wheel input 1:1 and suppress egui's eased copy.++ /// A precision touchpad sends pixel-precise `MouseWheel` events; on Windows they arrive with++ /// no `TouchPhase::Start`, so egui eases deltas of 8 px or more and the page lags the finger++ /// (#759). The window outlasts a single frame so egui's internal easing tail is suppressed as++ /// it decays, instead of adding on top of the 1:1 motion.++ precise_scroll_until: f64,++ /// Per-axis line-wheel state; horizontal input cannot extend a vertical burst.++ wheel_boost_x: crate::wheel_boost::WheelBoost,++ wheel_boost_y: crate::wheel_boost::WheelBoost,++ /// Touchpad momentum after the fingers lift (#531).++ fling: crate::fling::Fling,++ pub(crate) auto_scroll: crate::autoscroll::AutoScroll,++ /// Pages selected in the organize grid or the Pages panel (0-based). Empty means "the current page".++ pub selected: BTreeSet<usize>,++ pub(crate) organize_range: crate::page_selection_ui::PageSelectionInput,++ /// Anchor for ⇧-click range selection in the organize grid.++ select_anchor: Option<usize>,++ /// An edit requested by the view (organize toolbar, keys), applied by the app this frame.++ pub pending_edit: Option<Edit>,++ /// Edit text: the lines per page (with the document generation they were read at), and the++ /// line being edited.++ pub(crate) edit_lines: HashMap<usize, (u64, Vec<pdfcraft_engine::TextBlock>)>,++ pub line_editor: Option<crate::edit_text_ui::LineEditor>,++ /// The paragraph editor whose edit was just queued. It opens again with its typing if the++ /// edit fails, as a refused form field does.++ pub(crate) applied_editor: Option<crate::edit_text_ui::LineEditor>,++ /// The box a click switched to while another paragraph was being edited: it opens once the++ /// queued edit has applied, so its index and geometry come from the document it now is (#2022).++ /// It is held as the paragraph's text and box, not an index: the edit can regroup the page.++ pub(crate) pending_text_open: Option<(usize, pdfcraft_engine::BlockKey)>,++ pub(crate) text_background: crate::edit_text_ui::TextBackground,++ pub(crate) move_background: crate::content_ui::MoveBackground,++ /// Edit text & images: the images per page (by document generation), and the selected one.++ pub(crate) edit_images: HashMap<usize, (u64, Vec<pdfcraft_engine::PageImage>)>,++ pub(crate) objects: crate::object_ui::ObjectSelection,++ pub image_selection: Option<crate::edit_text_ui::ImageSelection>,++ /// Select tool: the picture clicked, to copy in its original format.++ pub picked_image: Option<crate::image_pick::PickedImage>,++ /// A paragraph box being dragged (moved, or resized from its right edge) in Edit text.++ pub block_drag: Option<crate::edit_text_ui::BlockDrag>,++ /// Commenting state: selected comment, gestures, composer.++ pub comments: crate::comments::CommentView,++ pub measure: crate::measure_ui::MeasureView,++ /// Form filling state: the focused field.++ pub forms: crate::forms_ui::FormView,++ /// Prepare a form: the selected field and the gesture in progress.++ pub prepare: crate::prepare::PrepareView,++ /// Prepare a form ▸ Calculation order.++ pub(crate) calc_order: crate::calc_order_ui::CalcOrderView,++ /// Edit a PDF: the selected added item, the text being typed.++ pub content: crate::content_ui::ContentView,++ /// Edit a PDF ▸ Link tool state.++ pub links: crate::link_ui::LinkView,++ /// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.++ pub redact_drag: crate::redact_ui::AreaDrag,++ pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,++ /// A crop rectangle being dragged (Crop tool).++ pub crop_drag: crate::crop::CropDrag,++ /// Enhance ▸ Camera image: the quadrilateral being placed.++ pub camera: Option<crate::camera_ui::CameraQuad>,++ /// Enhance ▸ Camera image: the page just enhanced, while the bar offers rotate, crop and++ /// organize.++ pub camera_done: Option<crate::camera_ui::CameraDone>,++ /// Use a certificate: a signature rectangle being drawn, or an empty signature field clicked.++ pub sign: crate::sign_ui::SignView,++ /// Organize: the pages being dragged to a new place.++ pub org_drag: Option<Vec<usize>>,++ /// Pages panel: the pages being dragged to a new place.++ pub panel_drag: Option<Vec<usize>>,++ /// Marquee Zoom / Snapshot: the rectangle being dragged (page, start), and a finished one.++ pub marquee: Option<(usize, Pos2)>,++ pub marquee_done: Option<crate::zoom_snap::Marquee>,++ /// Fill & Sign text being typed.++ pub fill_text: Option<crate::fill_sign::TypeBox>,++ /// A queued Fill & Sign signature: select it after its edit succeeds, then leave placement.++ pub(crate) fill_signature_page: Option<usize>,++ pub(crate) signature_drag: crate::signature_drag::SignatureDrag,++ /// A non-edit action requested by the organize toolbar, handled by the app.++ pub pending_action: Option<ViewAction>,++ /// The grid gap the next inserted files go to (set by a "+" between pages); otherwise they++ /// go after the selection.++ pub insert_at: Option<usize>,++ /// The page-grid gap under the pointer this frame (where dropped files go), when it can++ /// take pages.++ pub grid_gap: Option<usize>,++ /// The visible part of the Pages panel as last drawn, when it can take dropped files++ /// (cleared each frame before the panels draw).++ pub pages_panel: Option<Rect>,++ /// The Pages-panel gap under the pointer (where dropped files go), when it can take pages.++ pub panel_gap: Option<usize>,++ /// The current page the Pages panel last followed: it scrolls to the current page's++ /// thumbnail only when the page changes.++ pub(crate) panel_followed: Option<usize>,++ /// Scale of the thumbnails in the Pages inspector, independent of document and grid zoom.++ thumbnail_zoom: f32,++ /// How large the page grid draws its pages (1.0 = the usual thumbnails).++ grid_zoom: f32,++ /// A zoom asked for this frame (toolbar, pinch, keys); the grid applies it once it has laid++ /// out, so it can keep the same pages in view.++ grid_zoom_request: Option<f32>,++ /// The page to keep in place after a grid zoom, and how far below the top of the grid its++ /// cell was.++ grid_anchor: Option<(usize, f32)>,++ /// The page the grid scrolls into view on its next frame (Organize just opened on it).++ grid_reveal: Option<usize>,++ /// Sharp renders of the pages the grid shows larger than a thumbnail: only those in view,++ /// at the size drawn (device pixels wide).++ grid_pages: HashMap<usize, (u32, TextureHandle)>,++ /// Zoom-settle debounce for heavy pages: the last requested device scale, and the egui++ /// time until which sharp whole-page/tile re-renders are held back. While the zoom is++ /// still moving, every frame would otherwise cancel the in-flight full-page interpret++ /// (seconds on image-heavy CAD plots) and start it over, so a sharp raster never++ /// arrives. The stale raster stays on screen stretched meanwhile.++ last_scale: f32,++ sharp_hold_until: f64,++ /// Pan-settle debounce for tiled pages: the scroll offset last frame, and the egui time++ /// until which sharp tile re-renders are held back. Each tile costs a full page++ /// interpret, so a drag would otherwise queue a storm of them (one per frame) while the++ /// in-flight ones cannot be cancelled mid-operator. Older tiles and the backdrop stay++ /// stretched meanwhile; fresh tiles go out once the pan settles.++ pub(crate) last_scroll: Vec2,++ /// Side-by-side compare: scroll to here this frame, following the other half.++ pub(crate) sync_scroll: Option<Vec2>,++ /// The page widget's id, by which the Hand tool finds its drag before the pages are laid out.++ page_widget: Option<egui::Id>,++ pan_hold_until: f64,++ /// Pages whose raster proved slow (see `SLOW_MILLIS`): only these get the zoom/pan++ /// settle holds. Fast pages render straight through, with no added latency.++ slow_pages: HashSet<usize>,++}++++/// Organize-toolbar actions that need the app (file pickers, new tabs, dialogs).++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum ViewAction {++ InsertFromFile,++ /// Insert files at a gap of the page grid (0 = before the first page).++ InsertFromFileAt(usize),++ /// Replace the selected pages with pages from another file.++ ReplacePages,++ /// Save the document as the grid shows it.++ Save,++ Extract,++ Split,++ /// Split before each selected page: opens Split on that mode.++ SplitBeforeSelected,++ /// Copy the selected pages (Cut also deletes them).++ CopyPages {++ cut: bool,++ },++ /// Paste copied pages after the selection.++ PastePages,++ /// Enhance ▸ Camera image: straighten what the corners enclose.++ EnhanceCamera,++ /// Leave Enhance ▸ Camera image (Cancel before Enhance page, Done after it).++ CancelCamera,++ /// After Enhance page: turn the enhanced page a quarter.++ CameraRotate {++ clockwise: bool,++ },++ /// After Enhance page: enhance again at the slider's clean-up level.++ CameraLevel,++ /// After Enhance page: leave the tool for this command (Crop pages, Organize pages).++ CameraNext(&'static str),++}++++/// Default page right-click menu actions.++#[derive(Clone, Debug, PartialEq)]++pub(crate) enum PageMenuAction {++ RotateCCW(usize),++ RotateCW(usize),++ Print,++ SelectTool,++ HandTool,++ MarqueeZoom,++ Copy,++ Paste(usize, [f64; 2]),++ AddComment(usize, [f64; 2]),++ AddBookmark(usize),++ TakeSnapshot,++ EditPdf,++ AddText,++ AddImage,++ DeletePage(usize),++ ExportPdf,++ Find,++ DocProperties,++ FlattenComments,++}++++pub(crate) struct PageMenuPerms {++ pub can_modify: bool,++ pub can_assemble: bool,++ pub can_annotate: bool,++ pub can_print: bool,++ pub can_copy: bool,++ pub can_paste: bool,++ pub has_annotations: bool,++}++++pub(crate) fn default_page_context_menu(ui: &mut egui::Ui, page: usize, at: [f64; 2], perms: PageMenuPerms, action: &mut Option<PageMenuAction>) {++ // Top horizontal icon bar: Rotate CCW, Print, Select tool, Hand tool, Marquee Zoom++ ui.horizontal(|ui| {++ ui.spacing_mut().item_spacing.x = 4.0;++ if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate view counterclockwise")).clicked() {++ *action = Some(PageMenuAction::RotateCCW(page));++ ui.close();++ }++ ui.add_enabled_ui(perms.can_print, |ui| {++ if crate::icons::button(ui, "printer", 24.0, false, tl!("Print")).clicked() {++ *action = Some(PageMenuAction::Print);++ ui.close();++ }++ });++ if crate::icons::button(ui, "mouse-pointer-2", 24.0, false, tl!("Select Tool")).clicked() {++ *action = Some(PageMenuAction::SelectTool);++ ui.close();++ }++ if crate::icons::button(ui, "hand", 24.0, false, tl!("Hand Tool")).clicked() {++ *action = Some(PageMenuAction::HandTool);++ ui.close();++ }++ if crate::icons::button(ui, "zoom-in", 24.0, false, tl!("Marquee Zoom")).clicked() {++ *action = Some(PageMenuAction::MarqueeZoom);++ ui.close();++ }++ });++++ ui.separator();++++ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Copy")).shortcut_text("Ctrl+C")).clicked() {++ *action = Some(PageMenuAction::Copy);++ ui.close();++ }++ if ui.add_enabled(perms.can_paste, egui::Button::new(tl!("Paste")).shortcut_text("Ctrl+V")).clicked() {++ *action = Some(PageMenuAction::Paste(page, at));++ ui.close();++ }++++ ui.separator();++++ if ui.add_enabled(perms.can_annotate, egui::Button::new(tl!("Add comment"))).clicked() {++ *action = Some(PageMenuAction::AddComment(page, at));++ ui.close();++ }++ if perms.has_annotations && ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Flatten comments"))).clicked() {++ *action = Some(PageMenuAction::FlattenComments);++ ui.close();++ }++ if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Add bookmark"))).clicked() {++ *action = Some(PageMenuAction::AddBookmark(page));++ ui.close();++ }++ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Take a snapshot"))).clicked() {++ *action = Some(PageMenuAction::TakeSnapshot);++ ui.close();++ }++++ ui.separator();++++ if ui.add_enabled(perms.can_modify, egui::Button::new(egui::RichText::new(tl!("Edit this PDF")).strong())).clicked() {++ *action = Some(PageMenuAction::EditPdf);++ ui.close();++ }++ if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add text"))).clicked() {++ *action = Some(PageMenuAction::AddText);++ ui.close();++ }++ if ui.add_enabled(perms.can_modify, egui::Button::new(tl!("Add image"))).clicked() {++ *action = Some(PageMenuAction::AddImage);++ ui.close();++ }++ if ui.add_enabled(perms.can_assemble, egui::Button::new(tl!("Delete page"))).clicked() {++ *action = Some(PageMenuAction::DeletePage(page));++ ui.close();++ }++ if ui.add_enabled(perms.can_copy, egui::Button::new(tl!("Export this PDF"))).clicked() {++ *action = Some(PageMenuAction::ExportPdf);++ ui.close();++ }++++ ui.separator();++++ if ui.button(tl!("Find text or tools")).clicked() {++ *action = Some(PageMenuAction::Find);++ ui.close();++ }++ if ui.button(tl!("Rotate view clockwise")).clicked() {++ *action = Some(PageMenuAction::RotateCW(page));++ ui.close();++ }++ if ui.button(tl!("Document properties…")).clicked() {++ *action = Some(PageMenuAction::DocProperties);++ ui.close();++ }++}++++impl DocView {++ /// Whether a middle-button scrolling gesture is active (tests and automation).++ pub fn auto_scrolling(&self) -> bool {++ self.auto_scroll.active()++ }++++ /// Whether a held middle-button pan is active, outside Linux (tests and automation).++ pub fn middle_panning(&self) -> bool {++ self.auto_scroll.panning()++ }++++ /// Abandon only pointer previews: clearing egui's held button must not commit an app-owned++ /// grab through a tool's `!primary_down` fallback. Keep selections, text drafts and edits++ /// that were already completed before cancellation.++ pub(crate) fn cancel_pointer_gestures(&mut self) {++ self.marquee = None;++ self.marquee_done = None;++ self.comments.gesture = None;++ self.links.drag = None;++ self.sign.drag = None;++ self.redact_drag = None;++ self.crop_drag = None;++ self.block_drag = None;++ self.org_drag = None;++ self.panel_drag = None;++ self.selection_drag = false;++ self.auto_scroll.cancel();++ self.prepare.cancel_pointer_gesture();++ self.content.cancel_pointer_gesture();++ self.objects.cancel_pointer_gesture();++ if let Some(image) = &mut self.image_selection {++ image.cancel_pointer_gesture();++ }++ }++++ /// A view of a newly opened document, shown as `defaults` say. Opening a file then applies++ /// any layout or zoom the PDF itself asks for.++ pub fn new(id: DocId, info: &DocInfo, defaults: ViewDefaults) -> Self {++ Self {++ id,++ zoom: defaults.zoom,++ fit: defaults.fit,++ layout: defaults.layout,++ continuous: defaults.continuous,++ show_page_gaps: defaults.show_page_gaps,++ rotation: 0,++ current: 0,++ organize: false,++ highlight_fields: defaults.highlight_fields,++ page_input: "1".into(),++ page_input_reselect: false,++ notice_dismissed: false,++ scripts_off_noted: false,++ disk_changed: false,++ close_requested: false,++ snapshot: None,++ cover: false,++ back: Vec::new(),++ forward: Vec::new(),++ goto: None,++ goto_point: None,++ key_scroll: 0.0,++ single_edges: None,++ flash: None,++ compare_marks: Vec::new(),++ presentation: None,++ pages: HashMap::new(),++ errors: HashMap::new(),++ waiting_since: HashMap::new(),++ thumbs: HashMap::new(),++ thumb_demand: HashMap::new(),++ frame_queue: Vec::new(),++ frame_geometry_changed: false,++ frame_visible: HashSet::new(),++ stale_thumbs: HashSet::new(),++ stale_tiles: HashSet::new(),++ current_scale_tag: 0,++ print_pages: HashMap::new(),++ grayscale: false,++ tiles: HashMap::new(),++ texts: HashMap::new(),++ text_failed: HashSet::new(),++ find: None,++ selection: None,++ all_text: false,++ actions_dismissed: None,++ selection_drag: false,++ clicks: 0,++ last_press_time: 0.0,++ last_press_pos: None,++ present_turn: None,++ last_queue: Vec::new(),++ hold_rasters: false,++ viewport_w: 800.0,++ viewport_h: 600.0,++ page_count: info.pages.len(),++ page_heights: info.pages.iter().map(|p| p.height).collect(),++ screen_rects: Vec::new(),++ screen_xforms: Vec::new(),++ viewport_screen: Rect::NOTHING,++ zoom_anchor: None,++ shown: false,++ auto_ocr_tried: Default::default(),++ auto_ocr_skipped: Default::default(),++ wheel: Default::default(),++ precise_scroll_until: 0.0,++ wheel_boost_x: Default::default(),++ wheel_boost_y: Default::default(),++ fling: Default::default(),++ auto_scroll: Default::default(),++ selected: BTreeSet::new(),++ select_anchor: None,++ organize_range: Default::default(),++ pending_edit: None,++ edit_lines: HashMap::new(),++ line_editor: None,++ applied_editor: None,++ pending_text_open: None,++ text_background: Default::default(),++ move_background: Default::default(),++ edit_images: HashMap::new(),++ objects: Default::default(),++ image_selection: None,++ picked_image: None,++ block_drag: None,++ pending_action: None,++ insert_at: None,++ grid_gap: None,++ pages_panel: None,++ panel_gap: None,++ panel_followed: None,++ thumbnail_zoom: 1.0,++ grid_zoom: 1.0,++ grid_zoom_request: None,++ grid_anchor: None,++ grid_reveal: None,++ grid_pages: HashMap::new(),++ last_scale: 0.0,++ sharp_hold_until: 0.0,++ last_scroll: Vec2::ZERO,++ sync_scroll: None,++ page_widget: None,++ pan_hold_until: 0.0,++ slow_pages: HashSet::new(),++ comments: Default::default(),++ measure: Default::default(),++ forms: Default::default(),++ prepare: Default::default(),++ calc_order: Default::default(),++ content: Default::default(),++ links: Default::default(),++ redact_drag: None,++ pending_redaction: None,++ crop_drag: None,++ camera: None,++ camera_done: None,++ sign: Default::default(),++ org_drag: None,++ panel_drag: None,++ marquee: None,++ marquee_done: None,++ fill_text: None,++ fill_signature_page: None,++ signature_drag: Default::default(),++ }++ }++++ /// The document's content or page list changed (an edit, undo or redo): drop caches and++ /// adopt the new page geometry, keeping the reader's place where possible.++ pub fn document_changed(&mut self, info: &DocInfo) {++ self.invalidate_content();++ self.frame_geometry_changed = true;++ self.page_count = info.pages.len();++ self.page_heights = info.pages.iter().map(|p| p.height).collect();++ let last = self.page_count.saturating_sub(1);++ self.current = self.current.min(last);++ self.selected.retain(|p| *p <= last);++ // Text being typed on a page that no longer exists goes with the page.++ if self.content.draft.as_ref().is_some_and(|d| d.page > last || self.page_count == 0) {++ self.content.draft = None;++ }++ if self.select_anchor.is_some_and(|a| a > last) {++ self.select_anchor = None;++ }++ self.goto = None;++ self.goto_point = None;++ self.zoom_anchor = None;++ self.flash = None;++ // Thumbnail drags hold page indexes from before the change.++ self.panel_drag = None;++ self.org_drag = None;++ self.reset_coarse_state();++ }++++ /// The document was replaced by a newer version of its file (#431). The reader's place++ /// stays: zoom, layout, rotation, page, scroll, full screen, view history and the find bar,++ /// the snapshot marker and its pending close, and the page images on screen until their++ /// replacements are drawn, so nothing flashes. Everything that pointed into the old version (a selected++ /// comment, a field being typed in, text being edited, a drag, page selection) starts++ /// afresh, so no stale index reaches the new one.++ pub fn document_replaced(&mut self, info: &DocInfo) {++ let mut fresh = Self::new(self.id, info, ViewDefaults::default());++ fresh.zoom = self.zoom;++ fresh.fit = self.fit;++ fresh.layout = self.layout;++ fresh.continuous = self.continuous;++ fresh.show_page_gaps = self.show_page_gaps;++ fresh.rotation = self.rotation;++ fresh.current = self.current;++ fresh.organize = self.organize;++ fresh.grid_zoom = self.grid_zoom;++ fresh.thumbnail_zoom = self.thumbnail_zoom;++ // Same document id, so the scroll offset egui keeps for it is still this document's.++ fresh.shown = self.shown;++ fresh.highlight_fields = self.highlight_fields;++ fresh.notice_dismissed = self.notice_dismissed;++ fresh.snapshot = self.snapshot.clone();++ fresh.close_requested = self.close_requested;++ fresh.cover = self.cover;++ // Still presenting, with the display to go back to on leaving.++ fresh.presentation = self.presentation.take();++ fresh.back = std::mem::take(&mut self.back);++ fresh.forward = std::mem::take(&mut self.forward);++ fresh.find = self.find.take();++ fresh.pages = std::mem::take(&mut self.pages);++ fresh.thumbs = std::mem::take(&mut self.thumbs);++ fresh.viewport_w = self.viewport_w;++ fresh.viewport_h = self.viewport_h;++ fresh.viewport_screen = self.viewport_screen;++ *self = fresh;++ // Marks the kept images out of date and clamps the page to the new page count.++ self.document_changed(info);++ self.page_input = self.current_page_label(info.pages.get(self.current).map(|page| page.label.as_str()));++ self.page_input_reselect = true;++ }++++ /// Select pages in the organize grid (tests, automation). Empty clears the selection.++ pub(crate) fn page_count(&self) -> usize {++ self.page_count++ }++++ /// Drops wheel state after a discontinuous jump so the destination cannot++ /// inherit momentum from the previous viewport.++ fn reset_coarse_state(&mut self) {++ self.wheel.clear_motion();++ self.wheel_boost_x.reset();++ self.wheel_boost_y.reset();++ }++}++++/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a++/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.++#[allow(clippy::too_many_arguments)]++fn paint_image_suppressed(++ xf: &PageXform,++ painter: &egui::Painter,++ tex: egui::TextureId,++ u0: f32,++ v0: f32,++ u1: f32,++ v1: f32,++ suppress: Option<[f32; 4]>,++ is_full_page_tex: bool,++) {++ let Some([su0, sv0, su1, sv1]) = suppress else {++ if is_full_page_tex {++ xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1);++ } else {++ xf.paint_image(painter, tex, u0, v0, u1, v1);++ }++ return;++ };++ let iu0 = u0.max(su0);++ let iu1 = u1.min(su1);++ let iv0 = v0.max(sv0);++ let iv1 = v1.min(sv1);++ if iu0 >= iu1 || iv0 >= iv1 {++ if is_full_page_tex {++ xf.paint_page_texture_rect(painter, tex, u0, v0, u1, v1);++ } else {++ xf.paint_image(painter, tex, u0, v0, u1, v1);++ }++ return;++ }++ let map_uv = |pu: f32, pv: f32| -> (f32, f32) {++ if is_full_page_tex {++ (pu, pv)++ } else {++ let du = (u1 - u0).max(1e-6);++ let dv = (v1 - v0).max(1e-6);++ ((pu - u0) / du, (pv - v0) / dv)++ }++ };++ let draw_strip = |pu0: f32, pv0: f32, pu1: f32, pv1: f32| {++ if pu1 <= pu0 || pv1 <= pv0 {++ return;++ }++ let (tu0, tv0) = map_uv(pu0, pv0);++ let (tu1, tv1) = map_uv(pu1, pv1);++ xf.paint_image_region(painter, tex, pu0, pv0, pu1, pv1, tu0, tv0, tu1, tv1);++ };++++ if iv0 > v0 {++ draw_strip(u0, v0, u1, iv0);++ }++ if v1 > iv1 {++ draw_strip(u0, iv1, u1, v1);++ }++ if iu0 > u0 {++ draw_strip(u0, iv0, iu0, iv1);++ }++ if u1 > iu1 {++ draw_strip(iu1, iv0, u1, iv1);++ }++}++++pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {++ let t = Tokens::get(ui.ctx());++ // Keyboard scrolling applies to this frame's page view only, never later.++ let key_scroll = std::mem::take(&mut app.views[index].key_scroll);++ if key_scroll != 0.0 {++ app.views[index].end_find_following();++ }++ // The Search panel closed: its search moves to the find bar.++ let search_open = app.right == Some(crate::RightPanel::Search);++ if let Some(f) = app.views[index].find.as_mut()++ && f.in_panel++ && !search_open++ {++ f.in_panel = false;++ }++ // The snapshot notice bar's Close was clicked: close here, where no document borrow is++ // held. The tab is looked up by id: indices may have shifted since the click, and the++ // flag rides its own view, so a stale flag can never close the wrong tab.++ let pending = app.views.get(index).filter(|v| v.close_requested).map(|v| v.id).and_then(|id| app.views.iter().position(|v| v.id == id));++ if let Some(i) = pending {++ app.views[i].close_requested = false;++ if app.has_unsaved_work(i) {++ app.close_request = Some(crate::CloseRequest::Tab(app.views[i].id));++ } else {++ app.close_tab(i);++ }++ return;++ }++ let Some(doc) = app.session.get(app.views[index].id) else { return };++ let info = &doc.info;++ let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {++ let [r, g, b] = p.background;++ Color32::from_rgb(r, g, b)++ });++ if info.pages.is_empty() {++ app.views[index].auto_scroll.cancel();++ ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));++ return;++ }++ // The print dialog queues its own rasters later in the frame. Closing it drops them.++ if app.dialog != Some(crate::Dialog::Print) {++ app.views[index].print_pages.clear();++ }++ // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.++ let preparing = app.is_preparing();++ // Prepare a form ▸ Calculation order: the order's steps and links on the page.++ let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;++ // Edit a PDF: added text and images can be selected, moved and edited.++ let editing_content =++ (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);++ let text_style = app.text_style.clone();++ let show_secured_notice = app.show_secured_notice;++ // Asking means opening the system clipboard (and decoding any image on it), so it's asked++ // once when a right-click opens a menu, not on every frame.++ let can_paste_key = egui::Id::unique("can-paste-image");++ let can_paste_image = if ui.input(|i| i.pointer.secondary_pressed()) {++ let can = app.can_paste_image();++ ui.data_mut(|d| d.insert_temp(can_paste_key, can));++ can++ } else {++ ui.data(|d| d.get_temp(can_paste_key)).unwrap_or(false)++ };++ let view = &mut app.views[index];++ // Opened without the owner password and something is restricted. The notice says so unless++ // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸++ // Security, stay as they are.++ let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));++ let repaired = !doc.repair_log().is_empty();++ match notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t) {++ #[cfg(not(target_arch = "wasm32"))]++ Some(Notice::Reload) => app.watch.reload_request = Some(view.id),++ #[cfg(target_arch = "wasm32")]++ Some(Notice::Reload) => {}++ Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),++ Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),++ Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),++ // Flags the view: the tab closes at the top of the next frame, where no document++ // borrow is held.++ Some(Notice::Close) => {++ if let Some(view) = app.views.get_mut(index) {++ view.close_requested = true;++ }++ }++ Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),++ Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,++ Some(Notice::Console) => app.dialog = Some(crate::Dialog::JsConsole),++ // Back on in Preferences ▸ General.++ Some(Notice::HideSecured) => app.show_secured_notice = false,++ None => {}++ }++ // No dialog, close prompt or palette over the page: only then does page input count.++ let modal = app.modal_open();++ let unobstructed = !modal && !app.palette_open;++ let organize_zoom = app.organize_zoom;++ let view = &mut app.views[index];++ if view.organize {++ // One remembered grid size for every document, kept in the settings.++ view.set_grid_zoom(organize_zoom);++ organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);++ app.organize_zoom = view.grid_zoom();++ return;++ }++++ let avail = ui.available_rect_before_wrap();++ view.viewport_w = avail.width();++ view.viewport_h = avail.height();++ let old_zoom = view.zoom;++ view.fit_zoom(info);++ if view.shown && view.zoom_anchor.is_none() && view.goto.is_none() && view.goto_point.is_none() && (view.zoom - old_zoom).abs() > 1e-4 {++ let prev_viewport = view.viewport_screen;++ let top_y = prev_viewport.min.y;++ let anchor = view++ .screen_rects++ .iter()++ .find(|(_, r)| r.min.y <= top_y && r.max.y > top_y)++ .map(|(p, r)| {++ let fy = if r.height() > 0.0 { ((top_y - r.min.y) / r.height()).clamp(0.0, 1.0) } else { 0.0 };++ (*p, fy, 0.0f32)++ })++ .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0))))++ .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0))));++ if let Some((page, fy, rel_y)) = anchor {++ view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y)));++ } else {++ view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN)));++ }++ }++++ // Pinch / ctrl+scroll zoom, anchored on the current page.++ let zoom_delta = crate::motion::zoom_delta(ui.ctx());++ // Exclude the previous frame's scrollbar tracks from gesture activation.++ let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };++ let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);++ // Full screen: a click on the document goes forward a page and a shift-click back, as in++ // Acrobat, unless the click did something else (a link, a word selected). Decided below,++ // once the pages have had the click.++ let present_click =++ view.presentation.is_some() && navigation_enabled && presentation_click(ui, navigation_rect) && app.quick_tool == QuickTool::Select;++ // Shift as held now, or as the click's own event carried it (a synthetic click).++ let present_back = present_click++ && ui.input(|i| {++ i.modifiers.shift++ || i.events.iter().any(|e| {++ matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } if modifiers.shift)++ })++ });++ if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) {++ let z = view.zoom * zoom_delta;++ match zoom_anchor(ui) {++ Some(p) => view.zoom_at(z, p),++ None => view.set_zoom(z),++ }++ }++ view.viewport_screen = avail;++ let auto_delta = if unobstructed {++ view.auto_scroll.update(ui, avail, false)++ } else {++ view.auto_scroll.cancel();++ Vec2::ZERO++ };++++ // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view++ // that way, so a point beyond what is shown can be reached without letting go of the tool.++ let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {++ let (pointer, dt) = drawing_edge_pointer(ui);++ crate::autoscroll::edge_scroll(pointer, avail, dt)++ } else {++ Vec2::ZERO++ };++ if edge_delta != Vec2::ZERO {++ ui.ctx().request_repaint();++ }++++ let content_w = view.content_width(info, avail.width());++ let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());++ // When not scrolling continuously, only one row is shown at a time: the current page, or the++ // current two-page spread (with the cover rule). These indices drive paging, which pages are++ // drawn, and the content height (#752). Empty for a document with no pages.++ let shown_row = |view: &DocView| -> Vec<usize> {++ if rects.is_empty() {++ return Vec::new();++ }++ let last = rects.len() - 1;++ let cur = view.current.min(last);++ match view.layout {++ PageLayout::Single => vec![cur],++ PageLayout::TwoUp if view.cover && cur == 0 => vec![0],++ PageLayout::TwoUp => {++ let first = if view.cover { cur - (cur + 1) % 2 } else { cur - cur % 2 };++ if first < last { vec![first, first + 1] } else { vec![first] }++ }++ }++ };++ let row = shown_row(view);++ let middle_gesture = view.auto_scroll.blocks_input();++ // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns++ // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on++ // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with++ // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow++ // keys. Runs before `visible_pages` so the frame that turns the page draws it.++ let mut single_paging = false;++ let mut edge_turned = false;++ if !view.continuous {++ // The row's bounding box on screen (one page, or a two-page spread).++ let row_rect = row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union);++ // Within a point, so layout rounding can't stop a fitting page from turning.++ let fits = row_rect.is_some_and(|r| r.height() + 2.0 * MARGIN <= avail.height() + 1.0);++ let can_turn = !middle_gesture && unobstructed && ui.rect_contains_pointer(avail);++ single_paging = can_turn && fits;++ // Every wheel event goes to the pager, so it follows each trackpad touch to its end++ // even while the page can't turn.++ ui.input(|i| {++ for e in &i.events {++ if let egui::Event::MouseWheel { unit, delta, phase, modifiers, .. } = e {++ // Zooming (⌘ or Ctrl) and sideways scrolling (Shift) never turn pages.++ let dy = if modifiers.command || modifiers.ctrl || modifiers.shift { 0.0 } else { delta.y };++ if fits {++ view.single_page_wheel(*unit, dy, *phase, i.time, can_turn);++ } else {++ edge_turned |= view.single_page_wheel_edge(*unit, dy, *phase, i.time, can_turn);++ }++ }++ }++ });++ if single_paging {++ // Paging owns vertical wheel motion here. A diagonal gesture keeps its sideways++ // part, as `ScrollArea` itself handles each axis.++ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);++ }++ }++ // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,++ // smoothed base and adds only the accelerated surplus. While point suppression is active,++ // reconstruct line and page input here so current coarse events survive without exposing an++ // older eased tail.++ let now = ui.input(|i| i.time);++ let input = if ui.rect_contains_pointer(avail) {++ // Match the line distance used by egui's other scroll areas.++ let live = ui.ctx().options(|o| o.input_options.line_scroll_speed);++ let line_points = if live.is_finite() && live > 0.0 { live } else { crate::scroll_speed::EGUI_LINE_POINTS };++ ui.input(|i| crate::wheel_boost::accumulate(&i.events, line_points, single_paging))++ } else {++ crate::wheel_boost::FrameInput::default()++ };++ let mut precise_scroll = input.precise;++ let mut line_base = input.line;++ let mut boost_extra = crate::wheel_boost::boost_extra(input, &mut view.wheel_boost_x, &mut view.wheel_boost_y, now);++ let has_page = input.page != Vec2::ZERO;++ if now.is_finite() && precise_scroll != Vec2::ZERO && !has_page {++ view.precise_scroll_until = now + SUPPRESS_SECS;++ }++ if edge_turned {++ // The turn leaves egui's eased copy of the notch to decay for a few frames; it must not++ // scroll the page just shown away from its top (or bottom).++ view.precise_scroll_until = now + 0.25;++ view.fling.stop();++ }++ let paging_owns_vertical = single_paging || (!view.continuous && view.wheel.gesture_turned());++ if paging_owns_vertical {++ precise_scroll.y = 0.0;++ line_base.y = 0.0;++ boost_extra.y = 0.0;++ }++ // egui smooths a Point event that moved at least 8 points, keeping part of it for later++ // passes. Suppression must outlive that whole action: once it expired after a fixed 0.25 s,++ // the last few eased points leaked through the ScrollArea after a precise 1:1 scroll (held++ // point input measured 33 points for a 30-point event). Keep hiding the eased copy until++ // egui says the action is over, then forget the suppression.++ let scrolling = ui.input(|i| i.is_scrolling());++ if now < view.precise_scroll_until || (view.precise_scroll_until != 0.0 && scrolling) {++ if scrolling {++ // Keep hiding egui's unprocessed copy until it has drained. The short rolling grace++ // avoids a delayed duplicate without prolonging suppression after the tail is gone.++ view.precise_scroll_until = view.precise_scroll_until.max(now + SUPPRESS_TAIL_SECS);++ }++ ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);++ // The point path suppresses every eased wheel delta. Restore the line base through the++ // same un-eased path as its surplus; paging-owned axes were cleared above.++ boost_extra = crate::wheel_boost::cap_frame(boost_extra + line_base);++ if has_page {++ // Page units normally stay on egui's viewport-sized path. During suppression only,++ // reproduce the current event directly so an older hidden tail stays hidden.++ let page_scale = ui.input(|i| i.viewport_rect().height());++ let mut page_delta =++ if page_scale.is_finite() && page_scale > 0.0 { crate::wheel_boost::cap_frame(input.page * page_scale) } else { Vec2::ZERO };++ if paging_owns_vertical {++ page_delta.y = 0.0;++ }++ boost_extra = crate::wheel_boost::cap_frame(boost_extra + page_delta);++ }++ } else {++ precise_scroll = Vec2::ZERO;++ // Selection handling below uses zero to distinguish an inactive window. Clearing a past++ // deadline also keeps a later line/page action from being mistaken for the old tail.++ view.precise_scroll_until = 0.0;++ }++ if has_page && paging_owns_vertical {++ // Page input belongs to egui on the free axis; the pager still owns vertical motion.++ ui.input_mut(|i| i.smooth_scroll_delta.y = 0.0);++ }++ // Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a++ // stop, through the same un-eased path. Never while the pager owns the wheel, a gesture or++ // dialog has the input, or animations are off; any click, key, zoom or other scrolling ends it.++ // Asked of the preference, not of egui's animation time, which test harnesses zero.++ let animates = app.animation_effects.animates(app.motion.reduced);++ let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;++ let over_page = ui.rect_contains_pointer(avail);++ ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));++ let interrupted = glide_interrupted(ui);++ if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {++ view.fling.stop();++ }++ let glide = view.fling.step(now);++ if view.fling.gliding() {++ ui.ctx().request_repaint();++ }++ // Any reader-owned motion ends automatic search following, even when it stays on the same++ // page: the wheel, keyboard, middle-button auto-scroll, a drawing's edge scroll, or the++ // momentum left by a touchpad swipe. The automatic flash uses `goto`, not these deltas, so++ // its programmatic scroll is never mistaken for a reader action.++ let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;++ if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {++ view.end_find_following();++ }++ // The wheel may have turned the page above: draw the row it turned to. Measured from the old++ // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.++ let row = shown_row(view);++ let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };++ let (y_shift, content_h) = if view.continuous {++ (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))++ } else {++ // Only the current row scrolls into view; the content is its bounding box plus margins.++ match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {++ Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),++ None => (0.0, 0.0),++ }++ };++++ let mut scroll = egui::ScrollArea::both().auto_shrink([false, false]).scroll_source(egui::scroll_area::ScrollSource {++ drag: if middle_gesture {++ egui::scroll_area::DragScroll::Never++ } else if app.quick_tool == QuickTool::Hand {++ egui::scroll_area::DragScroll::Always++ } else {++ egui::scroll_area::DragScroll::OnTouch++ },++ ..Default::default()++ });++ // Each document keeps its own scroll position when switching tabs (#189).++ scroll = scroll.id_salt(("page-view", view.id));++ // When a page jump or programmatic reposition occurs, or in non-continuous page display++ // where single-page wheel turns jump to the page edge, disable animation so egui's++ // queued target does not overwrite or ease the jump. For continuous page scrolling,++ // animate if motion effects are enabled.++ let has_jump = !view.shown++ || edge_turned++ || view.goto.is_some()++ || view.goto_point.is_some()++ || view.zoom_anchor.is_some()++ || view.sync_scroll.is_some()++ || (app.quick_tool == QuickTool::Hand && !middle_gesture && view.page_widget.is_some_and(|id| ui.ctx().is_being_dragged(id)));++ scroll = scroll.animated(view.continuous && animates && !has_jump);++ // A newly opened document starts at the top. eframe saves egui's memory with the settings++ // and document ids start again at 1 every launch, so the offset stored under this id can be++ // where an earlier session left another document.++ if !std::mem::replace(&mut view.shown, true) {++ scroll = scroll.scroll_offset(Vec2::ZERO);++ }++ // The Hand tool pans here, before the pages are laid out, so the page moves with the pointer++ // in the frame the pointer moves (#924). Scrolling by the drag from inside the area moved the++ // page only after that frame was drawn, a frame behind. The frame egui tells the drag from a++ // click, the page catches up with all the pointer has moved since the press. A jump asked for++ // below still wins.++ if app.quick_tool == QuickTool::Hand++ && !middle_gesture++ && let Some(id) = view.page_widget.filter(|id| ui.ctx().is_being_dragged(*id))++ {++ let moved = if ui.ctx().drag_started_id() == Some(id) {++ ui.input(|i| i.pointer.total_drag_delta()).unwrap_or(Vec2::ZERO)++ } else {++ ui.input(|i| i.pointer.delta())++ };++ if moved != Vec2::ZERO {++ view.end_find_following();++ }++ // Within the content, as egui keeps it: past an end the page would show there for a++ // frame and spring back. `max` is never NaN or below zero, so the clamp can't panic.++ let max = vec2((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));++ scroll = scroll.scroll_offset((view.last_scroll - moved).clamp(Vec2::ZERO, max));++ }++ if let Some(v) = view.sync_scroll.take() {++ scroll = scroll.scroll_offset(v);++ }++ if let Some((page, fx, fy, rel)) = view.zoom_anchor.take() {++ let r = rects[page.min(rects.len() - 1)];++ let point = pos2(r.left() + fx * r.width(), r.top() - y_shift + fy * r.height());++ scroll = scroll.scroll_offset(anchored_scroll(point, rel, vec2(content_w, content_h), avail.size()));++ } else if let Some((page, frac)) = view.goto.take() {++ let page = page.min(rects.len() - 1);++ let r = rects[page];++ // Clamped here: egui clamps only after drawing, so a page that fits was drawn MARGIN - page_gap()++ // too high for a frame and then hopped into place. (`avail` is the viewport, as the++ // scroll bars float.)++ let max_y = (content_h - avail.height()).max(0.0);++ scroll = scroll.vertical_scroll_offset((r.top() - y_shift - view.page_gap() + frac * r.height()).max(0.0).min(max_y));++ // Horizontally too, as Acrobat does (#2665): beside a much wider page the others sit off++ // to one side. A page already shown whole, or one filling the window's width, keeps the++ // scroll, so paging through a zoomed-in document stays on the same column. Otherwise a++ // page that fits is centred, and a wider one scrolled just far enough to fill the window.++ // The page counts with its side gutters, which keep its edge clear of the floating++ // quick-action bar as the layout does.++ let (x, w) = (view.last_scroll.x, avail.width());++ let (left, right) = (r.left() - SIDE, r.right() + SIDE);++ let target = if right - left <= w { if left >= x && right <= x + w { x } else { r.center().x - w / 2.0 } } else { x.clamp(left, right - w) };++ if (target - x).abs() > 0.5 {++ scroll = scroll.horizontal_scroll_offset(target.clamp(0.0, (content_w - w).max(0.0)));++ }++ }++ let ppp = ui.ctx().pixels_per_point();++ let scale = view.render_scale(ppp);++ let tag = scale_tag(scale);++ // Hold sharp re-renders while the zoom is still moving: a new scale every frame would++ // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD++ // plot with ~1000 images renders for seconds) the sharp raster never arrives and the++ // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the++ // sharp request goes out once the zoom settles.++ let now_scale = ui.input(|i| i.time);++ if (scale - view.last_scale).abs() > f32::EPSILON {++ view.last_scale = scale;++ view.sharp_hold_until = now_scale + 0.35;++ ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));++ }++ let sharp_held = now_scale < view.sharp_hold_until;++ view.current_scale_tag = tag;++ let hand = app.quick_tool == QuickTool::Hand;++ let tool = app.quick_tool;++ // Text selection runs for the Select tool and for the markup tools (highlight…).++ let selects_text = match tool {++ QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,++ QuickTool::Select => !preparing,++ QuickTool::Redact | QuickTool::ColumnSelect => true,++ QuickTool::Hand++ | QuickTool::Measure(_)++ | QuickTool::Crop++ | QuickTool::EnhanceCamera++ | QuickTool::Fill(_)++ | QuickTool::Field(_)++ | QuickTool::AddText++ | QuickTool::EditText++ | QuickTool::Stamp(_)++ | QuickTool::CustomStamp(_)++ | QuickTool::Link++ | QuickTool::SignArea { .. }++ | QuickTool::MarqueeZoom++ | QuickTool::Snapshot => false,++ };++ let prefs = &app.comment_prefs;++ let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);++ let units = app.units;++ let allowed = doc.allows_annotation();++ let can_copy = doc.allows_copying();++ let mut copy_selected = false;++ let comments_hidden = doc.comments_hidden();++ let form = doc.form.clone();++ let generation = doc.edit_generation();++ let can_fill = doc.allows_form_filling();++ let can_crop = doc.allows_assembly();++ let mut open_boxes = false;++ let signature = app.signature.clone();++ let initials = app.initials.clone();++ let mut open_initials = false;++ let author = app.comment_prefs.author.clone();++ let today = app.session.today();++ // In Preferences ▸ Date format, or why it can't be stamped into the PDF.++ let date_text = crate::date_text_for_pdf(&app.session);++ let mut refused: Option<String> = None;++ let by_line = app.session.stamp_by_line(&author);++ let mut stamp_placed = false;++ let mut image_action: Option<crate::edit_text_ui::ImageAction> = None;++ let custom_stamp = match app.quick_tool {++ QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),++ _ => None,++ };++ let mut open_signature = false;++ let mut hover_text: Option<(Pos2, String)> = None;++ let mut badge_hover: Option<(Pos2, String)> = None;++ let mut clicked_link: Option<LinkTarget> = None;++ let mut remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> = None;++ let mut canvas_action: Option<comments::CanvasAction> = None;++ let mut page_action: Option<PageMenuAction> = None;++ let mut field_menu: Option<FieldMenu> = None;++ let mut open_props: Option<(usize, usize)> = None;++ let mut field_props = false;++ let mut field_placed = false;++ let mut open_table: Option<(usize, [f64; 4])> = None;++ // The table being set up in its window, shown on its own document's page.++ let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));++ let can_modify = doc.allows_modification();++ if preparing {++ crate::prepare::after_refresh(view, &form);++ } else {++ view.prepare.selected = None;++ }++ view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());++ view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);++ let added = if editing_content { doc.added().to_vec() } else { Vec::new() };++ let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };++ if editing_content {++ crate::content_ui::after_refresh(view, &added);++ } else {++ view.content.selected = None;++ }++ view.move_background.prepare(ui.ctx(), doc, &view.content, scale);++++ // A destination's position (bookmarks, links) refines `goto`: its point at the window's++ // top-left, or the centre of a /FitR rectangle at the window's centre.++ if let Some((page, fx, fy, rel)) = view.goto_point.take() {++ let r = rects[page.min(rects.len() - 1)];++ // Within the content, so an unreachable point never shows a frame scrolled past the end.++ let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));++ if let Some(fx) = fx {++ scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));++ }++ if let Some(fy) = fy {++ scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));++ }++ }++ let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);++ let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {++ // egui's drag responses accept every pointer button. Keep a wheel gesture from also++ // selecting text, drawing a mark, or panning with the Hand tool.++ if middle_gesture {++ let opacity = ui.opacity();++ ui.disable();++ // Only interactions pause; the document must keep its original colours.++ ui.set_opacity(opacity);++ }++ // Middle-button auto-scroll, the keyboard, precise touchpad input (#759) and its glide++ // (#531), accelerated wheel surplus (#1072), and a drawing's edge scroll; positive y++ // moves the content down. All scroll without easing, unlike egui's wheel default.++ // ScrollArea ignores wheel input during a widget drag. Defer the wheel contribution++ // until after the text widgets when a selection owns that drag.++ let wheel_delta = if selection_wheel { Vec2::ZERO } else { precise_scroll + boost_extra };++ let delta = auto_delta + edge_delta - vec2(0.0, key_scroll) + wheel_delta + glide;++ if delta != Vec2::ZERO && delta.is_finite() {++ let anim = if animates && key_scroll != 0.0 { ui.style().scroll_animation } else { egui::style::ScrollAnimation::none() };++ ui.scroll_with_delta_animation(delta, anim);++ }++ let (resp_rect, resp) = ui.allocate_exact_size(vec2(content_w, content_h), Sense::click_and_drag());++ view.page_widget = Some(resp.id);++ // A drag lasts only while egui reports it, so the mark can't outlive one.++ if !resp.dragged_by(egui::PointerButton::Primary) {++ view.selection_drag = false;++ }++ // The Hand tool pans by this widget's drag, before the pages are laid out (above).++ if hand {++ if resp.dragged() {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);++ } else if resp.hovered() {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);++ }++ }++ let origin = resp_rect.min - vec2(0.0, y_shift);++ let painter = ui.painter();++ let visible = viewport.translate(resp_rect.min.to_vec2());++ let mut wanted = Vec::new();++ let mut visible_now = Vec::new();++ view.screen_rects.clear();++ view.screen_xforms.clear();++ for &i in &visible_pages {++ let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);++ if r.intersects(visible) {++ view.screen_rects.push((i, r));++ view.screen_xforms++ .push((i, PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) }));++ }++ }++ // Visible heights (points) closer than this are equal: one page size can meet the++ // viewport a fraction of a point differently once the scroll offset is applied.++ const TIE: f32 = 0.5;++ let mut current = view.current;++ let mut best_overlap = -1.0f32;++ let mut current_overlap = -1.0f32;++ let mut current_height = f32::INFINITY;++ // The pointer as the pages see it: nothing over them (a dialog from the frame it opens),++ // or a press they hold. The page modules read it rather than egui's raw pointer state.++ let ptr = PagePointer::read(ui, &resp, modal);++ let pointer = ptr.pos;++ // A press on a page makes it the current one (as in Acrobat), so a page command with++ // no selection (Rotate, Delete) acts on the page the reader pointed at, not on a page++ // gone to earlier that still shows whole beside it.++ let pressed = unobstructed && ptr.pressed().is_some();++ let mut pressed_page = None;++ if resp.secondary_clicked() {++ // Set again below when the right-click lands on a link.++ view.links.context = None;++ let mut over_image = false;++ if tool == QuickTool::EditText {++ let pointer_pos = ptr.pos;++ if let Some(p) = pointer_pos {++ for (page_idx, xf) in &view.screen_xforms {++ let images = doc.page_images(*page_idx);++ for (idx, img) in images.iter().enumerate().rev() {++ let obb = ImageObb::from_image(img, xf, info, *page_idx);++ let b = image_screen_rect(img, xf, info, *page_idx);++ if (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p) {++ over_image = true;++ if view.image_selection.as_ref().is_none_or(|s| s.page != *page_idx || s.index != idx) {++ view.image_selection = Some(crate::edit_text_ui::ImageSelection {++ page: *page_idx,++ index: idx,++ drag: None,++ crop: None,++ crop_mode: false,++ crop_rect: None,++ turning: false,++ settled: None,++ });++ }++ break;++ }++ }++ if over_image {++ break;++ }++ }++ }++ }++ ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), over_image));++ }++ let mut calc_hover = None;++ for &i in &visible_pages {++ badge_hover = None;++ let r = snap_to_pixels(rects[i].translate(origin.to_vec2()), ppp);++ if !r.intersects(visible.expand(400.0)) {++ continue;++ }++ if pressed && pressed_page.is_none() && pointer.is_some_and(|p| r.contains(p)) {++ pressed_page = Some(i);++ }++ if r.intersects(visible) {++ visible_now.push(i);++ }++ let overlap = r.intersect(visible).height();++ if i == view.current {++ current_overlap = overlap;++ current_height = r.height();++ }++ // Pages shown equally (two rows wholly on screen) differ only by rounding: the++ // topmost one counts.++ if overlap > best_overlap + TIE {++ best_overlap = overlap;++ current = i;++ }++ let xf = PageXform { rect: r, rot: view.rotation, pw: info.pages[i].width.max(1.0), ph: info.pages[i].height.max(1.0) };++ // Shadows would darken the preceding page when pages touch.++ if view.show_page_gaps {++ painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));++ }++ painter.rect_filled(r, CornerRadius::ZERO, paper);++ if let Some(err) = view.errors.get(&i) {++ painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));++ icons::paint(++ ui,++ Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),++ "triangle-alert",++ 26.0,++ Color32::from_rgb(0xC8, 0x3A, 0x3A),++ );++ let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);++ let msg =++ ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));++ painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);++ } else {++ let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));++ // A GPU may take smaller textures than these (OpenGL drivers report as little as++ // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.++ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;++ let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);++ // Whole-page raster: sharp when small, a low-res backdrop when tiled.++ let (want_scale, want_tag) = if tiled {++ let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);++ (bs, scale_tag(bs))++ } else {++ (scale, tag)++ };++ // Under tiles, a whole-page raster sharper than the backdrop (from before the page++ // grew past the tiling size) is a better backdrop: keep demanding it as it is.++ match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {++ Some(p) => wanted.push((i, tag_scale(p.tag), p.tag, None)),++ None => wanted.push((i, want_scale, want_tag, None)),++ }++ let active_drag_suppress = if let Some(sel) = view.image_selection.as_ref()++ && sel.page == i++ && sel.drag.is_some()++ {++ let images = doc.page_images(i);++ if let Some(img) = images.get(sel.index) {++ let obb = ImageObb::from_image(img, &xf, info, i);++ let uvs = obb.corners().map(|c| xf.screen_to_norm(c));++ let u0 = uvs.iter().map(|(u, _)| *u).fold(1.0f32, f32::min).clamp(0.0, 1.0);++ let u1 = uvs.iter().map(|(u, _)| *u).fold(0.0f32, f32::max).clamp(0.0, 1.0);++ let v0 = uvs.iter().map(|(_, v)| *v).fold(1.0f32, f32::min).clamp(0.0, 1.0);++ let v1 = uvs.iter().map(|(_, v)| *v).fold(0.0f32, f32::max).clamp(0.0, 1.0);++ if u1 > u0 && v1 > v0 { Some([u0, v0, u1, v1]) } else { None }++ } else {++ None++ }++ } else {++ None++ };++ match view.pages.get(&i) {++ Some(p) => {++ if !tiled && p.tag == want_tag {++ paint_image_suppressed(++ &xf.texel_aligned(p.tex.size(), ppp),++ painter,++ p.tex.id(),++ 0.0,++ 0.0,++ 1.0,++ 1.0,++ active_drag_suppress,++ true,++ );++ } else {++ // A backdrop, or a raster at an older scale until the new one arrives.++ paint_image_suppressed(&xf, painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0, active_drag_suppress, true);++ }++ }++ None => {++ let now = ui.input(|inp| inp.time);++ let since = *view.waiting_since.entry(i).or_insert(now);++ let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };++ painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);++ }++ }++ if tiled && r.intersects(visible) {++ // Device-pixel geometry of the scaled page, and the visible part of it++ // (found by mapping the visible screen corners back into the page). Sides round++ // up as whole-page rasters do, so the last partial row and column get tiles.++ let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));++ // Adaptive tile side for this zoom and page, within the GPU texture limit:++ // a zoomed viewport or a giant sheet is covered by a few large tiles++ // instead of many small ones, and each tile costs one full page interpret.++ // Never zero (u32 division below).++ let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);++ let vis = r.intersect(visible);++ let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));++ let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));++ let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));++ let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);++ let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));++ // Tiles of earlier zooms first, stretched, the nearest scale last (on top):++ // until the current tiles arrive, a zoom shows them rather than the backdrop.++ let mut older: Vec<(f32, u32, u32, &TextureHandle)> = view++ .tiles++ .iter()++ .filter(|((p, t, _, _), _)| *p == i && *t != tag)++ .map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex))++ .collect();++ older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));++ for (s, ox, oy, tex) in older {++ let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);++ let [w, h] = tex.size();++ let (x, y) = (ox as f32, oy as f32);++ paint_image_suppressed(++ &xf,++ painter,++ tex.id(),++ x / ow,++ y / oh,++ (x + w as f32) / ow,++ (y + h as f32) / oh,++ active_drag_suppress,++ false,++ );++ }++ // Visible tiles, nearest the viewport centre first: each tile costs a full++ // page interpret, so the workers sharpen what is looked at before the edges.++ let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);++ let mut coords: Vec<(u32, u32)> = Vec::new();++ for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {++ for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {++ coords.push((tx, ty));++ }++ }++ coords.sort_by(|a, b| {++ let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();++ let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();++ da.total_cmp(&db)++ });++ for (tx, ty) in coords {++ let (x, y) = (tx * ts, ty * ts);++ let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));++ if w == 0 || h == 0 {++ continue;++ }++ wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));++ if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {++ let (fw, fh) = (dw as f32, dh as f32);++ paint_image_suppressed(++ &xf.texel_aligned([dw as usize, dh as usize], ppp),++ painter,++ tex.id(),++ x as f32 / fw,++ y as f32 / fh,++ (x + w) as f32 / fw,++ (y + h) as f32 / fh,++ active_drag_suppress,++ false,++ );++ }++ }++ }++ }++ view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());++ if editing_content {++ view.move_background.paint(painter, &xf, i, info, &view.content, pointer);++ }++ if view.show_page_gaps {++ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(0.5, t.border.gamma_multiply(0.8)), egui::StrokeKind::Outside);++ }++++ // Comments: tools, selection, moving and resizing come before text selection.++ let pcx = comments::PageCx { page: i, xf: &xf, ptr: &ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };++ if let QuickTool::Measure(measure_tool) = tool {++ crate::measure_ui::page_input(ui, &resp, doc, view, &pcx, measure_tool, units);++ }++++ // Form fields take clicks first with the Select tool (as Acrobat fills fields in++ // every viewing mode); then comments; then text selection.++ if let QuickTool::Stamp(kind) = tool++ && allowed++ && let Some(p) = ptr.within(xf.rect)++ {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ if resp.clicked() {++ // Centred on the click, upright as the page is shown.++ let (vx, vy) = xf.screen_to_view(p);++ let (w, h) = kind.size();++ let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];++ let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();++ let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];++ let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());++ let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };++ view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {++ page: i,++ style: pdfcraft_engine::Style::default_for(&shape),++ shape,++ contents: String::new(),++ author: author.clone(),++ }));++ stamp_placed = true;++ }++ }++ if let Some(cs) = custom_stamp.as_ref()++ && allowed++ && let Some(p) = ptr.within(xf.rect)++ {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ if resp.clicked() {++ // Centred on the click at its natural size (the engine sizes it).++ let (vx, vy) = xf.screen_to_view(p);++ let u = info.pages[i].view_to_user(vx, vy);++ let (x, y) = (u[0] as f64, u[1] as f64);++ view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {++ page: i,++ rect: [x, y, x, y],++ name: cs.name.clone(),++ file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },++ author: author.clone(),++ });++ stamp_placed = true;++ }++ }++ // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).++ if let QuickTool::Fill(ft) = tool++ && allowed++ && !comments::fill_grabs(&pcx, view)++ {++ match crate::fill_sign::page_input(++ ui,++ &resp,++ &xf,++ &ptr,++ i,++ info,++ ft,++ app.fill_text_size,++ view,++ signature.as_ref(),++ initials.as_ref(),++ &mut app.signature_preview,++ &author,++ &date_text,++ ) {++ Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),++ Some(crate::fill_sign::FillAction::Signature(e)) => {++ view.pending_edit = Some(*e);++ view.fill_signature_page = Some(i);++ }++ Some(crate::fill_sign::FillAction::CreateSignature) => open_signature = true,++ Some(crate::fill_sign::FillAction::CreateInitials) => open_initials = true,++ Some(crate::fill_sign::FillAction::Refused(why)) => refused = Some(why),++ None => {}++ }++ }++ if matches!(tool, QuickTool::SignArea { .. }) {++ crate::sign_ui::page_input(ui, &resp, &xf, &ptr, i, info, view);++ }++ if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {++ crate::zoom_snap::page_input(ui, &resp, &xf, &ptr, i, view);++ }++ if tool == QuickTool::EnhanceCamera {++ crate::camera_ui::page_input(ui, &resp, &xf, &ptr, i, view, can_modify);++ }++ if tool == QuickTool::Crop && crate::crop::page_input(ui, &resp, &xf, &ptr, i, info, view, can_crop) {++ view.current = i;++ open_boxes = true;++ }++ // `over_field`: a form field is under the pointer and has set its cursor.++ let (on_field, over_field) = if preparing {++ let field_tool = match tool {++ QuickTool::Field(f) => Some(f),++ _ => None,++ };++ // While a table is being set up, nothing else is drawn or moved.++ let allowed = can_modify && table_preview.is_none() && open_table.is_none();++ let o = crate::prepare::page_input(ui, &resp, &xf, &ptr, i, info, &form, field_tool, allowed, view);++ field_props |= o.properties;++ field_placed |= o.placed;++ open_table = open_table.or(o.table);++ (o.consumed || field_tool.is_some(), false)++ } else {++ use crate::forms_ui::FieldPointer;++ let field = if tool == QuickTool::Select++ && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, &ptr, i, info, &added, view))++ && !comments::select_grabs(&pcx, view)++ {++ crate::forms_ui::page_input(ui, &resp, &xf, &ptr, i, info, &form, can_fill, view)++ } else {++ FieldPointer::Away++ };++ (field == FieldPointer::Owned, field == FieldPointer::Over)++ };++ // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).++ let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;++ let boxing = area_tool && {++ let text = view.page_text(i);++ let over_text = |p: Pos2| {++ let (vx, vy) = xf.screen_to_view(p);++ text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))++ };++ crate::redact_ui::page_input(ui, &resp, &xf, &ptr, i, info, over_text, view)++ };++ let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, &ptr, i, info, view);++ let on_objects =++ !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, &ptr, i, doc, view);++ let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {++ let generation = doc.edit_generation();++ match view.edit_lines.get(&i) {++ Some((g, l)) if *g == generation => l.clone(),++ _ => {++ let l = doc.text_blocks(i);++ view.edit_lines.insert(i, (generation, l.clone()));++ l++ }++ }++ } else {++ Vec::new()++ };++ let over_source = tool == QuickTool::AddText++ && pointer.is_some_and(|p| {++ !crate::content_ui::hits_added(&xf, info, i, &added, p)++ && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))++ });++ let source_blocked = over_source && view.content.hold_blocked();++ if over_source && resp.clicked() && !source_blocked {++ if let Some(edit) = view.content.finish_draft(&added) {++ view.pending_edit = Some(edit);++ }++ view.content.selected = None;++ }++ let on_content = !on_objects && editing_content && can_modify && {++ source_blocked++ || crate::content_ui::page_input(++ ui,++ &resp,++ &xf,++ &ptr,++ i,++ info,++ &added,++ tool == QuickTool::AddText && !over_source,++ matches!(tool, QuickTool::AddText | QuickTool::EditText),++ &text_style,++ view,++ )++ || tool == QuickTool::AddText && !over_source++ };++ // Added content owns its gesture; its source text must not queue a second edit.++ // Edit text & images boxes every paragraph and image whenever the tool is on. Only the++ // input waits while selected objects or added content own the pointer, or while page++ // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn++ // instead of vanishing until the pointer comes back.++ let others_own_pointer = on_objects || on_content;++ let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {++ let generation = doc.edit_generation();++ let images = match view.edit_images.get(&i) {++ Some((g, l)) if *g == generation => l.clone(),++ _ => {++ let l = doc.page_images(i);++ view.edit_images.insert(i, (generation, l.clone()));++ l++ }++ };++ // Editable text takes precedence over background/overlapping artwork. Both++ // inventories are painted every frame, even when text owns the pointer.++ let text_used =++ crate::edit_text_ui::page_input(ui, &resp, &xf, &ptr, i, doc, &lines, view, !others_own_pointer && !image_owns_pointer);++ let image_used = crate::edit_text_ui::image_input(++ ui,++ &resp,++ &xf,++ &ptr,++ i,++ info,++ &images,++ view,++ &mut image_action,++ !others_own_pointer && (image_owns_pointer || !text_used),++ );++ !others_own_pointer && (text_used || image_used)++ };++ let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(ui, &resp, &xf, &ptr, i, info, &doc_links, view);++ if tool == QuickTool::Select++ && resp.secondary_clicked()++ && can_modify++ && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))++ && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))++ {++ view.links.context = Some((i, l.index));++ }++ let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, &resp, &pcx, view);++++ let preview_target =++ (matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && !comments_hidden).then_some(view.comments.selected).flatten();++ view.signature_drag.prepare(ui.ctx(), doc, preview_target, scale);++ view.signature_drag.paint(painter, &pcx, &view.comments, view.pending_edit.as_ref());++++ // Any press on the page ends Select All of the document: text read or not, any tool,++ // on a link too.++ // A press that lands on something drawn over the page (a menu, a dialog) is not one.++ if view.all_text && pressed_page == Some(i) {++ view.all_text = false;++ }++ // Text layer: find matches, selection, I-beam and drag-to-select.++ let to_screen = |g: [f32; 4]| xf.view_rect(g);++ if let Some(text) = view.texts.get(&i).cloned() {++ if let Some(f) = &view.find {++ for (k, (mp, range)) in f.matches.iter().enumerate() {++ if *mp != i {++ continue;++ }++ let current = f.current == Some(k);++ for lr in text.line_rects(range.clone()) {++ let fill = if current {++ Color32::from_rgba_unmultiplied(255, 140, 0, 110)++ } else {++ Color32::from_rgba_unmultiplied(255, 214, 0, 90)++ };++ painter.rect_filled(to_screen(lr).expand(1.0), CornerRadius::same(2), fill);++ }++ }++ }++ if view.all_text {++ for lr in text.line_rects(0..text.glyphs.len()) {++ painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));++ }++ }++ if let Some(sel) = view.selection.filter(|s| s.page == i) {++ for lr in sel.rects(&text) {++ painter.rect_filled(to_screen(lr), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70));++ }++ // The rectangle being drawn, as Acrobat shows it while column-selecting.++ if let Span::Column { rect } = sel.span++ && resp.dragged()++ {++ let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0));++ painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle);++ }++ }++ if selects_text++ && !consumed++ && let Some(p) = pointer.filter(|p| r.contains(*p))++ {++ let (vx, vy) = xf.screen_to_view(p);++ let over_text = text.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]);++ let over_link = info.links.iter().any(|l| l.page == i && xf.user_rect(info, i, l.rect).contains(p));++ // Column select (#740): the Column select tool, or Alt (Option on macOS) held++ // while a drag starts, as in Acrobat.++ let column = tool == QuickTool::ColumnSelect || ui.input(|inp| inp.modifiers.alt);++ // A link or a form field under the pointer keeps its own cursor: a check box++ // drawn with a glyph, or set on printed text, shows the hand, not the I-beam.++ // So do the mode bar and side panels over a page scrolled under them (#2755),++ // unless a selection is being dragged there.++ let cursor_free = !over_link && !over_field && (resp.contains_pointer() || resp.dragged());++ if column && cursor_free {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);++ } else if over_text && cursor_free {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Text);++ }++ // The pages' press, kept when its release came in the same frame (#2100): it++ // still starts multi-click selection.++ let press_here = ptr.origin.is_some_and(|o| r.contains(o));++ let pressed = ptr.pressed().is_some();++ if pressed && press_here && !over_link {++ let now = ui.input(|inp| inp.time);++ // The same limits egui uses to count clicks on release.++ let (max_delay, max_dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));++ let is_consecutive =++ now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(p) <= max_dist);++ view.clicks = if is_consecutive { view.clicks.saturating_add(1) } else { 1 };++ view.last_press_time = now;++ view.last_press_pos = Some(p);++++ // Multi-click highlights immediately on pointer press instead of release (#1024).++ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };++ if clicks >= 2 && over_text {++ let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));++ if let Some((first, last)) = span {++ view.selection = Some(Selection::run(i, first, last));++ }++ }++ }++ if resp.drag_started() && press_here && !over_link {++ // A drag replaces the selection without passing through none, so a++ // re-drag over text whose bar Copy closed would keep the bar hidden.++ view.actions_dismissed = None;++ view.selection_drag = true;++ let origin = ptr.origin.unwrap_or(p);++ let (ox, oy) = xf.screen_to_view(origin);++ if view.clicks < 2 {++ view.selection = if column {++ Some(Selection { page: i, span: Span::Column { rect: [ox, oy, vx, vy] } })++ } else {++ text.nearest(ox, oy).map(|a| Selection::run(i, a, a))++ };++ }++ }++ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };++ if resp.dragged()++ && let Some(sel) = view.selection.as_mut().filter(|s| s.page == i)++ {++ match &mut sel.span {++ // After a multi-click the drag extends by its unit (#1685), as in++ // Acrobat and browsers: whole words or lines, always keeping the one++ // clicked, which holds the anchor whichever way the drag went.++ Span::Run { anchor, head } if clicks >= 2 => {++ if let Some(h) = text.nearest(vx, vy)++ && let Some((first, last)) = click_unit(&text, clicks, *anchor)++ {++ let (to_first, to_last) = click_unit(&text, clicks, h).unwrap_or((h, h));++ (*anchor, *head) = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) };++ }++ }++ Span::Run { head, .. } => {++ if let Some(h) = text.nearest(vx, vy) {++ *head = h;++ }++ }++ Span::Column { rect } => {++ rect[2] = vx;++ rect[3] = vy;++ }++ }++ }++ // A rectangle around no text selects nothing.++ if resp.drag_stopped()++ && view.selection.is_some_and(|s| s.page == i && matches!(s.span, Span::Column { .. }) && s.text(&text).is_empty())++ {++ view.selection = None;++ }++ // Quick clicks widen the selection: two a word, three the line, four the page.++ // Release-based fallback for platforms or synthetic events that report double_clicked.++ let release_clicks = if resp.triple_clicked() {++ view.clicks.max(2).saturating_add(1)++ } else if resp.double_clicked() {++ view.clicks.max(2)++ } else {++ 0++ };++ if release_clicks > 0 {++ view.clicks = release_clicks;++ }++ let clicks = if view.clicks > 2 && tool != QuickTool::Select { 1 } else { view.clicks };++ // Only on the frame egui reports the multi-click: `view.clicks` outlives it, and++ // acting on every frame re-selected the word as soon as a selection was cleared++ // (a highlight made by the double-click left its word selected).++ if release_clicks > 0 && clicks >= 2 && over_text {++ if view.selection.is_none() {++ let span = text.nearest(vx, vy).and_then(|a| click_unit(&text, clicks, a));++ if let Some((first, last)) = span {++ view.selection = Some(Selection::run(i, first, last));++ }++ }++ } else if resp.clicked() && view.clicks < 2 && !over_link {++ // ⇧-click extends a selection on this page to the click, keeping its++ // anchor (#527). Otherwise (no shift, no selection on this page, or a++ // column selection, which has no anchor glyph; a selection cannot yet++ // span pages) a click clears the selection.++ let shift = ui.input(|inp| inp.modifiers.shift);++ match (view.selection.as_mut().filter(|s| shift && s.page == i).map(|s| &mut s.span), text.nearest(vx, vy)) {++ (Some(Span::Run { head, .. }), Some(h)) => *head = h,++ _ => view.selection = None,++ }++ }++ }++ }++++ if tool == QuickTool::Select && !consumed {++ crate::image_pick::page_input(&resp, &xf, i, info, doc, pointer, view);++ }++ crate::image_pick::drop_stale(doc, view);++ crate::image_pick::paint(painter, &xf, i, info, view);++ comments::page_after_text(&resp, &pcx, view);++ if tool == QuickTool::Redact && can_modify {++ crate::redact_ui::after_text(&resp, i, info, view);++ }++ if area_tool {++ crate::redact_ui::paint(painter, i, view, pointer);++ }++ comments::paint_page(ui, painter, &pcx, view);++ if editing_content {++ crate::content_ui::paint_page(painter, &xf, i, info, &added, view, pointer);++ }++ if tool == QuickTool::EditText {++ crate::object_ui::paint(painter, &xf, i, info, &view.objects);++ }++ if tool == QuickTool::EnhanceCamera {++ crate::camera_ui::paint(painter, &xf, i, view);++ }++ if tool == QuickTool::Link {++ crate::link_ui::paint(painter, &xf, i, info, &doc_links, view, pointer);++ }++ if preparing {++ crate::prepare::paint_page(ui, painter, &xf, i, info, &form, view, pointer);++ if let Some(preview) = &table_preview {++ crate::field_table_ui::paint_preview(painter, &xf, i, preview);++ }++ if calc_order {++ let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());++ if let Some(name) =++ crate::calc_order_ui::paint_page(painter, &xf, i, info, &form, &view.calc_order, generation, selected, pointer)++ {++ calc_hover = Some(name);++ }++ }++ } else {++ crate::forms_ui::paint_page(painter, &xf, i, info, &form, view, pointer);++ }++++ // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a++ // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as++ // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a++ // radio button's own) is left as it is drawn.++ if view.highlight_fields {++ for f in form.iter() {++ let required = f.has(pdfcraft_engine::field_flags::REQUIRED);++ for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden && !w.read_only) {++ let r = w.rect;++ let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);++ let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48);++ let (width, color) =++ if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) };++ if w.round {++ let radius = sr.width().min(sr.height()) / 2.0;++ painter.circle_filled(sr.center(), radius, tint);++ painter.circle_stroke(sr.center(), radius - width / 2.0, Stroke::new(width, color));++ } else {++ painter.rect_filled(sr, CornerRadius::same(1), tint);++ painter.rect_stroke(sr, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside);++ }++ }++ }++ }++ // Fill & Sign keeps its placement cursor clear of link/comment hover feedback. Tips++ // draw above the palette, so none shows while it is open, even beside it.++ if !matches!(tool, QuickTool::Fill(_))++ && unobstructed++ && let Some(p) = pointer++ {++ for l in info.links.iter().filter(|l| l.page == i) {++ let sr = xf.user_rect(info, i, l.rect);++ if sr.contains(p) {++ ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);++ let label = match &l.target {++ LinkTarget::Page(n, _) => {++ crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])++ }++ LinkTarget::Uri(u) => u.clone(),++ LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),++ LinkTarget::RemoteGoTo { file, .. } => file.clone(),++ LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),++ };++ hover_text = Some((p, label));++ if resp.clicked() && tool == QuickTool::Select && !consumed {++ clicked_link = Some(l.target.clone());++ }++ }++ }++ // Annotation hover shows the comment, as Acrobat's popups do; not while drawing++ // freehand, where it would cover the next stroke (#429).++ let freehand = matches!(tool, QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::Eraser));++ let gesturing = view.comments.gesture.is_some() || freehand;++ // Inspection sorts annotations spatially, but the renderer paints in /Annots++ // order. Keep the shared list intact and choose the last eligible raw index.++ if hover_text.is_none()++ && !gesturing++ && let Some((_, text)) = info++ .annotations++ .iter()++ .filter(|a| a.page == i)++ .filter(|a| {++ !(prefs.hide_empty_highlight_hover && a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty))++ })++ .filter(|a| pcx.screen_rects(a).any(|r| r.contains(p)))++ .filter_map(|a| annotation_hover_text(a).map(|text| (a.index, text)))++ .max_by_key(|(index, _)| *index)++ {++ hover_text = Some((p, text));++ }++ }++ for (mp, mr, mc) in &view.compare_marks {++ if *mp == i {++ let sr = xf.user_rect(info, i, *mr).expand(1.5);++ painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28));++ }++ }++ if let Some((fp, fr, t0)) = view.flash++ && fp == i++ {++ let now = ui.input(|inp| inp.time);++ let t0 = if t0 == 0.0 { now } else { t0 };++ view.flash = Some((fp, fr, t0));++ let age = (now - t0) as f32;++ if age < 1.6 {++ let a = ((1.6 - age) / 1.6 * 255.0) as u8;++ let sr = xf.user_rect(info, i, fr).expand(4.0);++ painter.rect_stroke(++ sr,++ CornerRadius::same(3),++ Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)),++ egui::StrokeKind::Outside,++ );++ ui.ctx().request_repaint();++ } else {++ view.flash = None;++ }++ }++ // Validation is viewer chrome over the signer's original artwork, which++ // may still say "Signature Not Verified". These badges never enter document++ // streams, image/text exports, vector printing or Print as Image.++ for badge in signature_badges(&doc.signatures, i) {++ let [x0, y0, x1, y1] = badge.rect;++ let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]);++ let (icon, color) = crate::sign_ui::signature_status_style(badge.status);++ painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside);++ // A widget too small for the mark keeps its outline: the verdict still shows.++ if sr.width() < 4.0 || sr.height() < 4.0 {++ continue;++ }++ // Big enough to read at a glance, small enough to leave the signer's own++ // text visible around it.++ let side = (sr.width().min(sr.height()) * 0.8).clamp(24.0, 192.0);++ let mark = Rect::from_center_size(sr.center(), vec2(side, side));++ icons::paint(ui, mark, icon, side * 0.64, color);++ if let Some(p) = pointer.filter(|p| mark.expand(2.0).contains(*p)) {++ badge_hover = Some((p, badge.summary.to_string()));++ }++ }++ // Overlapping widgets paint in order, so the topmost badge owns the hover; an++ // earlier link or annotation hover still wins over any badge.++ if hover_text.is_none() {++ hover_text = badge_hover.take();++ }++ }++ if calc_order {++ view.calc_order.set_hover_page(calc_hover);++ let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str());++ crate::calc_order_ui::paint_trace(ui, painter, visible, &view.calc_order, generation, selected);++ }++ // ScrollArea ignores the wheel while any widget is dragged, so a text-selection drag++ // scrolls the page itself (#721). After the page loop, so it keeps scrolling once the++ // pointer leaves the selection's page for the gap or the next page; over the whole++ // document area, like #759. Combine direct and smoothed motion in one request so mixed++ // Point and Line events retain their full contribution.++ if selection_wheel {++ let smooth =++ if view.precise_scroll_until == 0.0 { ui.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta)) } else { Vec2::ZERO };++ let delta = precise_scroll + boost_extra + smooth;++ if delta != Vec2::ZERO && delta.is_finite() {++ ui.scroll_with_delta_animation(delta, egui::style::ScrollAnimation::none());++ }++ }++ // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view++ // so it can reach text off screen (#1670); the selection follows the pointer on its page.++ if view.selection_drag++ && navigation_enabled++ && unobstructed++ && !single_paging++ && let Some(p) = ptr.pos++ {++ let dy = crate::autoscroll::edge_delta(p.y, avail, ui.input(|i| i.stable_dt));++ if dy != 0.0 {++ view.end_find_following();++ ui.scroll_with_delta_animation(vec2(0.0, dy), egui::style::ScrollAnimation::none());++ // Keep scrolling while the pointer rests there and sends no events.++ ui.ctx().request_repaint();++ }++ }++ // The page navigated to stays current while no page shows more of itself, so the next++ // page step starts from it rather than from a page further down the screen (#188).++ // It also stays current while it is wholly on screen: a short page (a cheque) gone to++ // from the Pages panel shows less of itself than the tall page below it, and must not++ // hand the highlight to that page.++ if current_overlap >= best_overlap - TIE || current_overlap >= current_height - TIE {++ current = view.current;++ }++ if let Some(p) = pressed_page {++ current = p;++ }++ if view.continuous {++ view.current = current;++ }++ resp.context_menu(|ui| {++ // Preparing a form: the selected field's menu.++ if preparing && let Some((name, wi)) = view.prepare.selected.clone() {++ // Several fields: Align, Center, Distribute, Set Fields to Same Size.++ if !view.prepare.also.is_empty() {++ use crate::prepare::Arrange as A;++ let others = view.prepare.also.clone();++ let anchor = (name.clone(), wi);++ let mut pick = |ui: &mut egui::Ui, op: A, label: &str| {++ if ui.add_enabled(can_modify, egui::Button::new(tl!(label))).clicked() {++ view.pending_edit = crate::prepare::arrange(&form, &anchor, &others, op);++ ui.close();++ }++ };++ ui.menu_button(tl!("Align"), |ui| {++ pick(ui, A::AlignLeft, "Left");++ pick(ui, A::AlignRight, "Right");++ pick(ui, A::AlignTop, "Top");++ pick(ui, A::AlignBottom, "Bottom");++ pick(ui, A::AlignCenterV, "Center vertically");++ pick(ui, A::AlignCenterH, "Center horizontally");++ });++ ui.menu_button(tl!("Distribute"), |ui| {++ pick(ui, A::DistributeH, "Horizontally");++ pick(ui, A::DistributeV, "Vertically");++ });++ ui.menu_button(tl!("Set Fields to Same Size"), |ui| {++ pick(ui, A::SameHeight, "Height");++ pick(ui, A::SameWidth, "Width");++ pick(ui, A::SameSize, "Both");++ });++ ui.separator();++ }++ if ui.button(tl!("Properties…")).clicked() {++ field_menu = Some(FieldMenu::Properties);++ ui.close();++ }++ if ui.add_enabled(can_modify, egui::Button::new(tl!("Duplicate…"))).clicked() {++ field_menu = Some(FieldMenu::Duplicate(name.clone()));++ ui.close();++ }++ ui.separator();++ let delete = if view.prepare.also.is_empty() { "Delete" } else { "Delete selected fields" };++ if ui.add_enabled(can_modify, egui::Button::new(tl!(delete))).clicked() {++ view.pending_edit = crate::prepare::delete_selected(view);++ ui.close();++ }++ return;++ }++ if let Some((page, index)) = view.links.context {++ if ui.button(tl!("Properties…")).clicked() {++ view.links.open_existing = Some((page, index));++ ui.close();++ }++ if ui.add_enabled(can_modify, egui::Button::new(tl!("Delete"))).clicked() {++ view.pending_edit = Some(Edit::DeleteLink { page, index });++ view.links.selected = None;++ view.links.context = None;++ ui.close();++ }++ ui.separator();++ if ui.add_enabled(can_modify, egui::Button::new(tl!("Remove all links"))).clicked() {++ view.pending_edit = Some(Edit::RemoveLinks { pages: None });++ view.links.selected = None;++ view.links.context = None;++ ui.close();++ }++ return;++ }++ let is_image_menu = tool == QuickTool::EditText++ && (ui.ctx().data_mut(|d| d.get_persisted::<bool>(crate::edit_text_ui::image_menu_id())).unwrap_or(false)++ || view.image_selection.as_ref().is_some_and(|sel| {++ let pointer_pos = ptr.pos;++ let Some(p) = pointer_pos else { return false };++ let Some((_, xf)) = view.screen_xforms.iter().find(|(page_idx, _)| *page_idx == sel.page) else { return false };++ let images = doc.page_images(sel.page);++ let Some(img) = images.get(sel.index) else { return false };++ let obb = ImageObb::from_image(img, xf, info, sel.page);++ let b = image_screen_rect(img, xf, info, sel.page);++ (b.is_positive() && b.contains(p)) || crate::edit_text_ui::quad_contains(obb.corners(), p)++ }));++ if is_image_menu && let Some(sel) = view.image_selection.clone() {++ let images = doc.page_images(sel.page);++ let at = view.comments.context_at.map(|(_, at)| at);++ crate::edit_text_ui::image_context_menu(ui, view, &images, sel.page, sel.index, can_paste_image, &mut image_action, at);++ return;++ }++ if view.comments.selected.is_some() {++ canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify);++ return;++ }++ // Over a picture (and no comment): Copy Image, as in Acrobat's page menu.++ let mut copy_image = None;++ if let Some((page, at)) = view.comments.context_at {++ // The page's content is parsed once per right-click, not on every frame the menu is open.++ let key = egui::Id::unique("copy-image-under-menu");++ let cached = ui.data(|d| d.get_temp::<(usize, [f64; 2], Option<usize>)>(key)).filter(|c| c.0 == page && c.1 == at);++ let hit = match cached {++ Some(c) => c.2,++ None => {++ let hit = doc.page_image_at(page, at);++ ui.data_mut(|d| d.insert_temp(key, (page, at, hit)));++ hit++ }++ };++ if let Some(image) = hit {++ if ui.button(tl!("Copy Image")).clicked() {++ copy_image = Some(comments::CanvasAction::CopyImage(page, image));++ ui.close();++ }++ if ui.button(tl!("Copy Image in Original Format")).clicked() {++ copy_image = Some(comments::CanvasAction::CopyImageFile(page, image));++ ui.close();++ }++ ui.separator();++ }++ }++ let has_copy_image = copy_image.is_some();++ if copy_image.is_some() {++ canvas_action = copy_image;++ }++ let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0]));++ let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || has_copy_image);++ let can_paste = can_paste_image && can_modify;++ let perms = PageMenuPerms {++ can_modify,++ can_assemble: doc.allows_assembly(),++ can_annotate: allowed,++ can_print: doc.allows_printing(),++ can_copy: can_copy_items,++ can_paste,++ has_annotations: !info.annotations.is_empty(),++ };++ default_page_context_menu(ui, page, at, perms, &mut page_action);++ });++ if !resp.context_menu_opened() {++ ui.ctx().data_mut(|d| d.insert_persisted(crate::edit_text_ui::image_menu_id(), false));++ }++ (wanted, visible_now)++ });++ view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {++ // At the top once the page's top edge shows where going to a page puts it (a gap++ // below the window's top). Within a point, as for wheel paging, so layout rounding++ // can't hide an edge.++ let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);++ (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)++ });++++ view.viewport_screen = out.inner_rect;++ view.auto_scroll.paint(ui, avail);++ if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {++ copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);++ }++++ // Collect all main-page demand, including cached surfaces, for byte admission later.++ // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding++ // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched++ // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that++ // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;++ // pages with nothing on screen yet still queue.++ let scroll_offset = out.state.clamped_offset();++ // The document ScrollArea's own scroll surfaces move the offset without the wheel deltas++ // above: its two scroll-bar tracks/handles and, for touch or the Hand tool, its drag++ // background. The output gives us the area id, and egui's pinned ScrollArea registers those++ // widgets under `id.with(0)` (horizontal), `id.with(1)` (vertical) and `id.with("area")`.++ // Ask for their exact responses instead of treating any held drag as scrolling: a text++ // selection, a panel splitter or another widget's drag must not excuse the programmatic jump++ // a search flash makes, while a track click (which moves the offset with no pointer motion)++ // must still count as the reader scrolling.++ let scroll_surface = |id: egui::Id| ui.ctx().read_response(id).is_some_and(|r| r.is_pointer_button_down_on() || r.dragged() || r.clicked());++ let pointer_scrolling = scroll_surface(out.id.with(0usize)) || scroll_surface(out.id.with(1usize)) || scroll_surface(out.id.with("area"));++ if pointer_scrolling && (scroll_offset - view.last_scroll).length() > 2.0 {++ view.end_find_following();++ }++ let now_settle = ui.input(|i| i.time);++ if (scroll_offset - view.last_scroll).length() > 2.0 {++ view.pan_hold_until = now_settle + 0.25;++ ui.ctx().request_repaint_after(std::time::Duration::from_millis(280));++ }++ if glide != Vec2::ZERO {++ view.fling.moved((scroll_offset - view.last_scroll).length() > 0.01);++ }++ view.last_scroll = scroll_offset;++ let pan_held = now_settle < view.pan_hold_until;++ let (mut wanted, visible_now) = out.inner;++ // Single-page and two-page views draw only the current row, so the next one was first asked++ // for on the turn and showed blank paper until it rendered. Prefetch the rows either side,++ // as continuous scrolling does for the pages just off screen.++ if !view.continuous++ && let (Some(&first), Some(&last)) = (visible_pages.first(), visible_pages.last())++ {++ let n = if view.layout == PageLayout::Single { 1 } else { 2 };++ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;++ for i in (last.saturating_add(1)..=last.saturating_add(n)).chain(first.saturating_sub(n)..first) {++ let Some(p) = info.pages.get(i).filter(|_| !view.errors.contains_key(&i)) else { continue };++ // As drawn: the whole page at this scale, or the backdrop of a tiled page.++ let side = p.width.max(p.height).max(1.0);++ wanted.push(if side * scale > TILE_THRESHOLD.min(max_side) {++ let bs = BASE_SIDE.min(max_side) / side;++ (i, bs, scale_tag(bs), None)++ } else {++ (i, scale, tag, None)++ });++ }++ }++ let cur = view.current;++ wanted.sort_by_key(|w| (!visible_now.contains(&w.0), w.0.abs_diff(cur), w.3.is_some()));++ // Tiles of far-away pages are useless: free them. Tiles of an earlier zoom stay for a page++ // that is on screen, whether or not the page is tiled at this zoom (#2196): a zoom out below++ // the tiling threshold used to drop the tiles of the zoom just left, so coming back to it++ // was a cold miss and the page re-blurred through the backdrop while every tile was++ // interpreted again. `OLD_TILES` still bounds how many older tiles are kept, nearest scale++ // first, and admission keeps them inside `TILE_BYTES`.++ let missing: HashSet<usize> = wanted.iter().filter(|w| w.3.is_some()).map(|w| w.0).collect();++ let on_screen: HashSet<usize> = visible_now.iter().copied().collect();++ view.tiles.retain(|(p, t, _, _), _| p.abs_diff(cur) <= 2 && (*t == tag || missing.contains(p) || on_screen.contains(p)));++ let mut older: Vec<(f32, (usize, u64, u32, u32))> =++ view.tiles.keys().filter(|k| k.1 != tag).map(|k| ((tag_scale(k.1) / scale).ln().abs(), *k)).collect();++ // Tiles of earlier zooms are kept nearest scale first, and bounded by count *and* bytes: a++ // large scan renders a tile up to 4096² (about 67 MiB), so a count alone let a few tiles of++ // a few zooms run far past the tile allowance. #2196 keeps a zoom already visited, which++ // makes that reachable in ordinary zooming, so the byte bound has to be here too.++ older.sort_by(|a, b| a.0.total_cmp(&b.0));++ let mut kept = 0usize;++ let mut kept_bytes = 0usize;++ let mut drop: Vec<(usize, u64, u32, u32)> = Vec::new();++ for (_dist, key) in older {++ let bytes = view.tiles.get(&key).map_or(0, texture_bytes);++ if kept >= OLD_TILES || kept_bytes.saturating_add(bytes) > TILE_BYTES {++ drop.push(key);++ } else {++ kept = kept.saturating_add(1);++ kept_bytes = kept_bytes.saturating_add(bytes);++ }++ }++ for key in drop {++ view.tiles.remove(&key);++ }++ let mut queue: Vec<RenderRequest> = wanted++ .iter()++ .map(|&(page, wanted_scale, wanted_tag, tile)| RenderRequest {++ page,++ kind: RequestKind::Pixels,++ tile,++ scale: wanted_scale,++ tag: wanted_tag,++ // The low-res backdrop under tiles is a preview: tiny images are skipped for it.++ // It is the whole-page request whose scale is not the current one; sharp tiles++ // and whole-page finals always draw everything.++ preview: tile.is_none() && (wanted_scale != scale || wanted_tag != tag),++ })++ .collect();++ // While the zoom or pan is settling, hold back sharp re-renders of pages that already++ // show something (a stale whole-page raster or older tiles, drawn stretched): each new++ // scale would cancel the running full-page interpret and restart it from scratch, and++ // each pan frame would queue a storm of full-page tile interprets.++ // Pages with nothing on screen yet still queue, so panning to a fresh page draws it.++ if sharp_held || pan_held {++ let main_tag = tag;++ queue.retain(|req| {++ // Fast pages render straight through: the hold only protects heavy pages++ // whose full-page interpret costs seconds.++ if !view.slow_pages.contains(&req.page) {++ return true;++ }++ if req.tile.is_some() {++ let has_current_tile = view.tiles.keys().any(|(p, t, _, _)| *p == req.page && *t == req.tag);++ if has_current_tile {++ return false;++ }++ let has_any_surface = view.pages.contains_key(&req.page) || view.tiles.keys().any(|(p, _, _, _)| *p == req.page);++ !has_any_surface++ } else if req.tag != main_tag {++ // The low-res backdrop under tiles is zoom-independent: let it through,++ // it is the stretched surface the hold relies on.++ true++ } else {++ // The stale raster stays stretched until the zoom or pan settles; a page with++ // nothing on screen yet still renders.++ !view.pages.contains_key(&req.page)++ }++ });++ }++ // Text layers: visible pages for selection, every page while a search is active. (Select All++ // of the document needs no more: shown pages highlight as their text comes, and Copy reads++ // the rest, as text far away is let go to bound memory.)++ let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p);++ let mut text_pages: Vec<usize> = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() };++ if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) {++ let n = info.pages.len();++ let rest: Vec<usize> = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect();++ text_pages.extend(rest);++ }++ queue.extend(text_pages.into_iter().map(|page| RenderRequest {++ page,++ kind: RequestKind::Text,++ tile: None,++ scale: 1.0,++ tag: TEXT_TAG,++ preview: false,++ }));++ view.frame_queue = queue;++ view.frame_visible = visible_now.iter().copied().collect();++++ if let Some((pos, text)) = hover_text {++ // Click-through, as a tooltip is: the pages lose the pointer under anything that isn't.++ let tip = egui::Area::new(egui::Id::unique("canvas-hover")).order(egui::Order::Tooltip).interactable(false);++ tip.fixed_pos(pos + vec2(14.0, 16.0)).show(ui.ctx(), |ui| {++ egui::Frame::popup(ui.style()).show(ui, |ui| {++ ui.set_max_width(320.0);++ ui.label(text);++ });++ });++ }++ find_bar(view, info.pages.len(), avail, ui, &t);++ page_size_hint(view, info, units, avail, unobstructed, ui, &t);++ if tool == QuickTool::EnhanceCamera {++ crate::camera_ui::bar(ui.ctx(), view, avail, &t, can_modify);++ }++ if let Some(e) = comments::composer(ui.ctx(), view, info, prefs) {++ view.pending_edit = Some(e);++ }++ if let Some(e) = crate::edit_text_ui::overlay(ui.ctx(), view, info) {++ view.pending_edit = Some(e);++ }++ let text_box = crate::forms_ui::text_box(doc, view, &form);++ if let Some(e) = crate::forms_ui::overlay(ui.ctx(), view, info, &form, text_box.as_ref(), today) {++ view.pending_edit = Some(e);++ }++ if let Some(e) = crate::fill_sign::type_box(ui.ctx(), view, info, &author) {++ view.pending_edit = Some(e);++ }++ let (typed, text_done) = crate::content_ui::editor(ui.ctx(), view, info, &added);++ if typed.is_some() {++ view.pending_edit = typed;++ }++ if let Some(why) = view.objects.notice.take() {++ refused = Some(why);++ }++ let form_notice = view.forms.notice.take();++ // One crop, then back to selecting (as Acrobat does).++ let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));++ let mut tool = app.quick_tool;++ comments::keys(ui.ctx(), view, &mut tool, allowed);++ if preparing {++ crate::prepare::keys(ui.ctx(), view);++ }++ if editing_content {++ crate::content_ui::keys(ui.ctx(), view);++ }++ if tool == QuickTool::Link {++ crate::link_ui::keys(ui.ctx(), view);++ } else {++ view.links.selected = None;++ }++ if tool != QuickTool::EditText {++ view.image_selection = None;++ }++ if stamp_placed {++ tool = QuickTool::Select;++ }++ // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.++ if text_done && tool == QuickTool::AddText {++ tool = QuickTool::Select;++ }++ // One field, then back to selecting (Acrobat's default without "Keep tools pinned").++ if field_placed {++ tool = QuickTool::Select;++ }++ if matches!(field_menu, Some(FieldMenu::Properties)) {++ field_props = true;++ }++ let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();++ match canvas_action {++ Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),++ // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.++ Some(comments::CanvasAction::OpenComments) => {++ app.right = Some(RightPanel::Comments);++ app.comments_panel_closed = false;++ }++ Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),++ Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),++ Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),++ None => {}++ }++ // Full screen: the click turns the page unless it did something else first. It waits out the++ // double-click time: turning on the first click's release sent a double-click's second click,++ // meant to select a word, to the next page (review on #2070). A selection cancels it, and so++ // do a link followed meanwhile and leaving full screen; a double-click elsewhere still turns++ // once.++ let now = ui.input(|i| i.time);++ if present_click && clicked_link.is_none() && view.selection.is_none() && view.clicks < 2 {++ let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay);++ view.present_turn = Some((now + delay, !present_back));++ }++ if let Some((due, forward)) = view.present_turn {++ if clicked_link.is_some() || view.selection.is_some() || view.presentation.is_none() {++ view.present_turn = None;++ } else if now >= due {++ view.present_turn = None;++ view.step_page(forward);++ } else {++ ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((due - now).max(0.0)));++ }++ }++ match clicked_link {++ Some(LinkTarget::Page(p, dest)) => view.go_to_dest(p, dest, info),++ Some(LinkTarget::Uri(u)) => app.request_document_url(&u, crate::LinkOrigin::Link),++ Some(LinkTarget::SetLayers { changes, preserve_rb }) => set_layers(app, index, &changes, preserve_rb),++ Some(LinkTarget::RemoteGoTo { file, destination, .. }) => remote_open = Some((view.id, file, destination)),++ Some(LinkTarget::Other(s)) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]),++ None => {}++ }++ if tool == QuickTool::Crop && cropped {++ tool = QuickTool::Select;++ }++ if let Some(done) = app.views[index].marquee_done.take() {++ app.finish_marquee(index, done);++ }++ // A signature rectangle was drawn, or an empty signature field clicked.++ let drawn = app.views[index].sign.drawn.take();++ if let (Some((page, rect)), QuickTool::SignArea { certify }) = (drawn, tool) {++ tool = QuickTool::Select;++ app.quick_tool = tool;++ app.start_signing(page, Some(rect), None, certify.then_some(2));++ }++ if let Some(field) = app.views[index].sign.field.take() {++ let signed = app.session.get(app.views[index].id).is_some_and(|d| d.signatures.iter().any(|s| s.field == field && s.signed));++ if signed {++ app.right = Some(RightPanel::Signatures);++ if !app.sig_expanded.contains(&field) {++ app.sig_expanded.push(field);++ }++ } else {++ let page = app.views[index].current;++ app.start_signing(page, None, Some(field), None);++ }++ }++ app.quick_tool = tool;++ if let Some((page, at)) = app.views[index].comments.attach_at.take() {++ app.attach_file_comment(page, at);++ }++ if let Some((p, i)) = open_props {++ app.open_comment_props(p, i);++ }++ if let Some((p, i)) = app.views[index].comments.default_request.take() {++ app.make_comment_default(p, i);++ }++ if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {++ let doc = app.views[index].id;++ app.comment_attachment_action(doc, p, i, open);++ }++ if let Some((name, w)) = field_props {++ app.open_field_props(&name, w);++ }++ if let Some(FieldMenu::Duplicate(name)) = field_menu {++ let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());++ app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });++ app.dialog = Some(crate::Dialog::DuplicateField);++ }++ if let Some((page, rect)) = app.views[index].links.open_new.take() {++ app.open_link_props(page, Some(rect), None);++ }++ if let Some((page, i)) = app.views[index].links.open_existing.take() {++ app.open_link_props(page, None, Some(i));++ }++ if let Some((page, quads)) = app.views[index].pending_redaction.take() {++ let author = app.comment_prefs.author.clone();++ app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {++ // An area highlight: a highlight over the box.++ let style = app.comment_prefs.style(comments::CommentTool::Highlight);++ pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {++ page,++ shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },++ style,++ contents: String::new(),++ author,++ })++ } else {++ app.redact_prefs.mark(page, quads, &author)++ });++ }++ match image_action {++ Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),++ Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),++ Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {++ app.copy_page_image(page, index);++ }++ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),++ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {++ app.views[index].image_selection = None;++ app.cut_page_image(page, image);++ }++ Some(crate::edit_text_ui::ImageAction::Paste(page, at)) => {++ if let Some(pt) = at {++ app.paste_image_at(page, pt);++ } else {++ app.paste_image(page, None);++ }++ }++ Some(crate::edit_text_ui::ImageAction::DrawFreehand) => {++ app.quick_tool = crate::QuickTool::Comment(crate::comments::CommentTool::Ink);++ }++ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),++ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),++ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),++ Some(crate::edit_text_ui::ImageAction::AddComment(page, i)) => {++ if let Some(d) = app.session.get(app.views[index].id) {++ let images = d.page_images(page);++ if let Some(img) = images.get(i) {++ let r = img.visible_rect.unwrap_or(img.rect);++ let center = [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0];++ app.views[index].comments.context_at = Some((page, center));++ app.views[index].comments.composer = Some(crate::comments::Composer {++ page,++ at: center,++ kind: crate::comments::ComposerKind::Note,++ text: String::new(),++ focus: true,++ });++ }++ }++ }++ Some(crate::edit_text_ui::ImageAction::Crop) => {++ let doc_id = app.views[index].id;++ if let Some(s) = app.views[index].image_selection.as_mut()++ && let Some(d) = app.session.get(doc_id)++ {++ let images = d.page_images(s.page);++ if let Some(im) = images.get(s.index) {++ s.crop = Some(crate::edit_text_ui::CropMode::new(im.visible_rect.unwrap_or(im.rect)));++ s.crop_mode = true;++ s.crop_rect = None;++ }++ }++ }++ None => {}++ }++ match page_action {++ Some(PageMenuAction::Copy) => {++ if let Some(sel) = app.views[index].image_selection.clone() {++ app.copy_page_image(sel.page, sel.index);++ } else if app.views[index].selected_text().is_some() {++ app.execute("edit.copy");++ } else if let Some((page, at)) = app.views[index].comments.context_at++ && let Some(doc) = app.session.get(app.views[index].id)++ && let Some(image) = doc.page_image_at(page, at)++ {++ app.copy_page_image(page, image);++ }++ }++ Some(PageMenuAction::Paste(page, at)) => {++ app.paste_image_at(page, at);++ }++ Some(PageMenuAction::RotateCCW(page)) => {++ let _ = page;++ app.views[index].rotate_view(false);++ }++ Some(PageMenuAction::RotateCW(page)) => {++ let _ = page;++ app.views[index].rotate_view(true);++ }++ Some(PageMenuAction::Print) => {++ app.open_print();++ }++ Some(PageMenuAction::SelectTool) => {++ app.quick_tool = QuickTool::Select;++ }++ Some(PageMenuAction::HandTool) => {++ app.quick_tool = QuickTool::Hand;++ }++ Some(PageMenuAction::MarqueeZoom) => {++ app.quick_tool = QuickTool::MarqueeZoom;++ }++ Some(PageMenuAction::AddComment(page, at)) => {++ app.views[index].comments.composer =++ Some(crate::comments::Composer { page, at, kind: crate::comments::ComposerKind::Note, text: String::new(), focus: true });++ }++ Some(PageMenuAction::FlattenComments) => {++ app.views[index].comments.selected = None;++ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::Flatten { comments: true, fields: false });++ }++ Some(PageMenuAction::AddBookmark(_page)) => {++ app.bookmark_action(crate::panels::BmAction::New);++ }++ Some(PageMenuAction::TakeSnapshot) => {++ app.quick_tool = QuickTool::Snapshot;++ }++ Some(PageMenuAction::EditPdf) => {++ app.quick_tool = QuickTool::EditText;++ }++ Some(PageMenuAction::AddText) => {++ app.quick_tool = QuickTool::AddText;++ }++ Some(PageMenuAction::AddImage) => {++ app.add_image_dialog();++ }++ Some(PageMenuAction::DeletePage(page)) => {++ app.views[index].pending_edit = Some(pdfcraft_engine::Edit::DeletePages { pages: vec![page] });++ }++ Some(PageMenuAction::ExportPdf) => {++ app.select_tool("export");++ }++ Some(PageMenuAction::Find) => {++ app.views[index].open_find();++ }++ Some(PageMenuAction::DocProperties) => {++ app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Description));++ }++ None => {}++ }++ if let Some(why) = refused {++ app.notify_error(why);++ }++ if open_signature || open_initials {++ app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);++ app.dialog = Some(crate::Dialog::Signature);++ }++ if open_boxes {++ app.boxes_draft.range = crate::pageboxes::Range::Current;++ app.boxes_draft.seeded = None;++ app.dialog = Some(crate::Dialog::PageBoxes);++ }++ if let Some((page, rect)) = open_table {++ app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));++ app.dialog = Some(crate::Dialog::FieldTable);++ // The window lasts while the form is prepared. Drawn with the tool picked but its panel++ // closed, the tool goes back to Select above, so the panel opens to keep it prepared.++ app.left = crate::LeftPanel::Tool("form");++ app.reveal_tools();++ }++ if let Some(n) = form_notice {++ match n {++ crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),++ crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),++ crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),++ }++ }++ if let Some((name, action)) = app.views[index].forms.button.take() {++ run_button(app, index, &name, action);++ }++ if copy_selected {++ app.execute("edit.copy");++ }++ // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);++ // the quick tools come back with the window.++ if app.mode != crate::Mode::Read && !app.full_screen {++ quick_bar(app, avail, ui);++ }++ if let Some((source, file, destination)) = remote_open {++ app.open_remote_link(source, file, destination);++ }++}++++/// The prepare-mode field menu's choices.++enum FieldMenu {++ Properties,++ Duplicate(String),++}++++pub use crate::image_engine::{apply_crop, apply_resize, apply_resize_proportional, reset_crop, HandleId, MIN_RECT_SIZE};++#[cfg(test)]++mod tests;diff --cc crates/ui-egui/src/canvas/page_pointer.rsindex 000000000,f0df1d92f..02cb2208emode 000000,100644..100644--- a/crates/ui-egui/src/canvas/page_pointer.rs+++ b/crates/ui-egui/src/canvas/page_pointer.rs@@@ -1,0 -1,116 +1,115 @@@+ //! The pointer as the pages see it, read once per frame from the page view's content widget.+ //!+ //! egui knows what is drawn over the pages (a dialog, a menu, the palette, the quick bar, the+ //! chrome over a page scrolled under it) and which widget holds a drag (a panel's tab carried+ //! over them), and keeps a press with the widget it began on until release. egui's raw pointer+ //! state knows none of that, and its hover position is gone on the frame+ //! a touch or a Windows pen lifts: egui-winit sends `PointerGone` with every touch release, and+ //! winit reports Windows pen input as touch. So page modules read [`PagePointer`], never egui's+ //! pointer positions or button states; a test below keeps it that way.+ //!+ //! Dialogs are drawn after the pages, so on the frame one opens egui has not met its layer yet:+ //! the reading also takes whether one is open.++ use egui::{Event, PointerButton, Pos2, Rect};++ /// A primary-button press or release, and where it happened.+ #[derive(Clone, Copy, Debug, PartialEq)]+ pub(crate) enum Edge {+ Press(Pos2),+ Release(Pos2),+ }++ /// How many of a frame's presses and releases are kept. A frame holds one or two (a click, a+ /// double-click in a slow frame), but one after a stall can hold any number.+ const MAX_EDGES: usize = 8;++ /// One frame's pointer, as the pages see it.+ #[derive(Clone, Debug, Default, PartialEq)]+ pub(crate) struct PagePointer {+ /// Where the pointer is, while the pages are what egui has under it and no other widget holds+ /// a drag (a panel's tab carried over them), or while they hold a press (until the frame of+ /// its release, past a page's edge included). With a dialog open only a drag the pages+ /// already have keeps it. It is egui's `interact_pos`, which still has the position on the+ /// frame a touch lifts.+ pub pos: Option<Pos2>,+ /// Where the press the pages hold began, also on the frame of its release when the press+ /// came in that same frame (egui has forgotten it by then). `None` for a press that began on+ /// something else.+ pub origin: Option<Pos2>,+ /// This frame's primary presses and releases of a press the pages hold, in order.+ pub edges: Vec<Edge>,+ /// The primary button is down, wherever it was pressed: a gesture ends once it is up.+ pub primary_down: bool,+ /// Some button is down, wherever it was pressed.+ pub any_down: bool,+ }++ impl PagePointer {+ /// The pointer for `resp`, the content widget that holds every page, allocated in `ui`, while+ /// a dialog is open over the window or not (`modal`).+ pub(crate) fn read(ui: &egui::Ui, resp: &egui::Response, modal: bool) -> Self {+ let (at, origin, edges, primary_down, any_down) =+ ui.input(|i| (i.pointer.interact_pos(), i.pointer.press_origin(), edges(&i.events), i.pointer.primary_down(), i.pointer.any_down()));+ // egui's own answer to "do the pages hold a press?": from the press on until the frame+ // of its click, release or drag stop. A drag can outlive egui's press while the+ // pointer is outside the window. With a dialog open only a drag counts, up to the frame+ // it stops: on the frame one opens egui still gives the pages a press that lands under+ // it, and its click.- let held = resp.dragged() || resp.drag_stopped() || (!modal && resp.interact_pointer_pos().is_some());- // `contains_pointer` alone also holds a few points under the edge of an Area over the- // pages (egui's interact radius), so the top layer there must be the pages' own. A- // dialog covers them from the frame it opens, before egui knows its layer.+ let layer = ui.layer_id();+ let on_top =+ |p: &Pos2| !modal && !dragged_elsewhere(ui, resp) && resp.contains_pointer() && ui.ctx().layer_id_at(*p).is_none_or(|l| l == layer);++ let press_origin = origin.or_else(|| first_press(&edges));++ let held =++ resp.dragged() || resp.drag_stopped() || (!modal && (resp.interact_pointer_pos().is_some() || press_origin.is_some_and(|p| on_top(&p))));+ let pos = at.filter(|p| held || on_top(p));+ if !held {+ return Self { pos, origin: None, edges: Vec::new(), primary_down, any_down };+ }- Self { pos, origin: origin.or_else(|| first_press(&edges)), edges, primary_down, any_down }++ Self { pos, origin: press_origin, edges, primary_down, any_down }+ }++ /// Where the pointer is, when it is inside `r`.+ pub(crate) fn within(&self, r: Rect) -> Option<Pos2> {+ self.pos.filter(|p| r.contains(*p))+ }++ /// Where this frame's first primary press was.+ pub(crate) fn pressed(&self) -> Option<Pos2> {+ first_press(&self.edges)+ }+ }++ /// Whether egui gives the drag to a widget that is not the pages' (a panel's tab, a floating panel's+ /// grip): egui hovers nothing else until it stops, though it still reports the pages under the+ /// pointer. A widget on the pages (a form field's editor) keeps them.+ fn dragged_elsewhere(ui: &egui::Ui, resp: &egui::Response) -> bool {+ let ctx = ui.ctx();+ ctx.dragged_id().is_some_and(|id| {+ id != resp.id && !ctx.read_response(id).is_some_and(|r| r.layer_id == resp.layer_id && resp.interact_rect.contains_rect(r.interact_rect))+ })+ }++ fn first_press(edges: &[Edge]) -> Option<Pos2> {+ edges.iter().find_map(|e| match e {+ Edge::Press(p) => Some(*p),+ Edge::Release(_) => None,+ })+ }++ /// The first [`MAX_EDGES`] primary presses and releases among `events`, in order.+ fn edges(events: &[Event]) -> Vec<Edge> {+ events+ .iter()+ .filter_map(|e| match e {+ Event::PointerButton { pos, button: PointerButton::Primary, pressed, .. } if pos.is_finite() => {+ Some(if *pressed { Edge::Press(*pos) } else { Edge::Release(*pos) })+ }+ _ => None,+ })+ .take(MAX_EDGES)+ .collect()+ }++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/canvas/xform.rsindex 000000000,24ff25f7d..c914233d8mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/xform.rs+++ b/crates/ui-egui/src/canvas/xform.rs@@@ -1,0 -1,151 +1,185 @@@+ use super::*;++ impl DocView {+ /// Where `page` is drawn on screen this frame (`None` when it is not on screen).+ pub fn page_screen_rect(&self, page: usize) -> Option<Rect> {+ self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| xf.rect)+ }++ /// The document area on screen.+ pub fn viewport_rect(&self) -> Rect {+ self.viewport_screen+ }++ /// Pages drawn last frame and their screen rectangles.+ pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {+ self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()+ }++ /// Where `page` is drawn this frame, with its coordinate mapping.+ pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {+ self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)+ }+ }++ /// `r` moved so its corner lies on a whole physical pixel, so that a raster drawn from there+ /// maps texel for texel onto the screen.+ pub(super) fn snap_to_pixels(r: Rect, ppp: f32) -> Rect {+ let snap = |v: f32| (v * ppp).round() / ppp;+ Rect::from_min_size(pos2(snap(r.min.x), snap(r.min.y)), r.size())+ }++ /// Maps between a page's coordinate spaces and the screen, including view rotation.+ ///+ /// *View space* is the page as rendered (points, y down, the document's own `/Rotate` applied);+ /// normalised page coordinates `(u, v)` are view space divided by the page size. The view+ /// rotation (View ▸ Rotate View) turns the page clockwise on screen by `rot` degrees.+ #[derive(Clone, Copy)]+ pub struct PageXform {+ /// The page's rectangle on screen (already rotated, so width/height may be swapped).+ pub rect: Rect,+ pub rot: u16,+ /// Page size in view space (unrotated by the view).+ pub pw: f32,+ pub ph: f32,+ }++ impl PageXform {+ /// Screen pixels per page point. The view's rotation swaps the rectangle's sides, so a page+ /// turned a quarter shows its width down the screen.+ pub(crate) fn zoom(&self) -> f32 {+ let across = if self.rot % 180 == 90 { self.rect.height() } else { self.rect.width() };+ across / self.pw.max(1.0)+ }++ /// Draw an image in the PDF user-space `rect` as a custom stamp's appearance draws it: turned+ /// back by `turn` (the page /Rotate it was placed for), so with the page's own rotation it+ /// reads upright as displayed.+ pub(crate) fn paint_user_image(+ &self,+ painter: &egui::Painter,+ tex: egui::TextureId,+ p: &pdfcraft_render::PageInfo,+ rect: [f64; 4],+ turn: i64,+ color: Color32,+ ) {+ let mut mesh = egui::Mesh::with_texture(tex);+ let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);+ let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) };+ let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect);+ for (u, v) in [(0.0_f32, 0.0_f32), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {+ // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space.+ let (dx, dy) = (f64::from(u) * shown_w, f64::from(1.0 - v) * shown_h);+ let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f);+ let q = p.user_to_view(x as f32, y as f32);+ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(q[0] / self.pw, q[1] / self.ph), uv: pos2(u, v), color });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ painter.add(egui::Shape::mesh(mesh));+ }+ pub fn norm_to_screen(&self, u: f32, v: f32) -> Pos2 {+ let (a, b) = match self.rot {+ 90 => (1.0 - v, u),+ 180 => (1.0 - u, 1.0 - v),+ 270 => (v, 1.0 - u),+ _ => (u, v),+ };+ pos2(self.rect.left() + a * self.rect.width(), self.rect.top() + b * self.rect.height())+ }++ pub fn screen_to_norm(&self, p: Pos2) -> (f32, f32) {+ let (a, b) = ((p.x - self.rect.left()) / self.rect.width().max(1e-3), (p.y - self.rect.top()) / self.rect.height().max(1e-3));+ match self.rot {+ 90 => (b, 1.0 - a),+ 180 => (1.0 - a, 1.0 - b),+ 270 => (1.0 - b, a),+ _ => (a, b),+ }+ }++ /// Screen point → view space (points).+ pub fn screen_to_view(&self, p: Pos2) -> (f32, f32) {+ let (u, v) = self.screen_to_norm(p);+ (u * self.pw, v * self.ph)+ }++ /// A view-space rect [x0, y0, x1, y1] → screen rect.+ pub fn view_rect(&self, g: [f32; 4]) -> Rect {+ Rect::from_two_pos(self.norm_to_screen(g[0] / self.pw, g[1] / self.ph), self.norm_to_screen(g[2] / self.pw, g[3] / self.ph))+ }++ /// A PDF user-space rect (crop box, document `/Rotate`) → screen rect.+ pub fn user_rect(&self, info: &DocInfo, page: usize, r: [f32; 4]) -> Rect {+ let p = &info.pages[page];+ let [cx0, cy0, cx1, cy1] = p.crop;+ let (cw, ch) = ((cx1 - cx0).max(1.0), (cy1 - cy0).max(1.0));+ let norm = |x: f32, y: f32| -> (f32, f32) {+ let (u, v) = ((x - cx0) / cw, (cy1 - y) / ch);+ match p.rotation {+ 90 => (1.0 - v, u),+ 180 => (1.0 - u, 1.0 - v),+ 270 => (v, 1.0 - u),+ _ => (u, v),+ }+ };+ let (a, b) = (norm(r[0], r[1]), norm(r[2], r[3]));+ Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))+ }+++ pub fn user_rect_f64(&self, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {++ self.user_rect(info, page, r.map(|v| v as f32))++ }+++ /// This transform resized to a raster of `px` device pixels (width, height before the view+ /// rotation), so each of its texels covers one screen pixel. The rectangle's corner must+ /// already be on a whole pixel ([`snap_to_pixels`]).+ pub(super) fn texel_aligned(&self, px: [usize; 2], ppp: f32) -> PageXform {+ let (w, h) = (px[0] as f32 / ppp, px[1] as f32 / ppp);+ let size = if self.rot % 180 == 90 { vec2(h, w) } else { vec2(w, h) };+ PageXform { rect: Rect::from_min_size(self.rect.min, size), ..*self }+ }++ /// Draw a texture covering the normalised page region, rotated with the view.+ pub fn paint_image(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {+ let mut mesh = egui::Mesh::with_texture(tex);+ let corners = [(u0, v0, 0.0, 0.0), (u1, v0, 1.0, 0.0), (u1, v1, 1.0, 1.0), (u0, v1, 0.0, 1.0)];+ for (u, v, tu, tv) in corners {+ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });+ }+ mesh.add_triangle(0, 1, 2);+ mesh.add_triangle(0, 2, 3);+ painter.add(egui::Shape::mesh(mesh));+ }++++ /// Draw a sub-rectangle of a whole-page raster texture with specific texture UVs covering the normalised page region.++ #[allow(clippy::too_many_arguments)]++ pub fn paint_image_region(++ &self,++ painter: &egui::Painter,++ tex: egui::TextureId,++ pu0: f32,++ pv0: f32,++ pu1: f32,++ pv1: f32,++ tu0: f32,++ tv0: f32,++ tu1: f32,++ tv1: f32,++ ) {++ let mut mesh = egui::Mesh::with_texture(tex);++ let corners = [(pu0, pv0, tu0, tv0), (pu1, pv0, tu1, tv0), (pu1, pv1, tu1, tv1), (pu0, pv1, tu0, tv1)];++ for (u, v, tu, tv) in corners {++ mesh.vertices.push(egui::epaint::Vertex { pos: self.norm_to_screen(u, v), uv: pos2(tu, tv), color: Color32::WHITE });++ }++ mesh.add_triangle(0, 1, 2);++ mesh.add_triangle(0, 2, 3);++ painter.add(egui::Shape::mesh(mesh));++ }++++ /// Draw a sub-rectangle of a whole-page raster texture, where UV space matches page normalized space.++ pub fn paint_page_texture_rect(&self, painter: &egui::Painter, tex: egui::TextureId, u0: f32, v0: f32, u1: f32, v1: f32) {++ self.paint_image_region(painter, tex, u0, v0, u1, v1, u0, v0, u1, v1);++ }+ }diff --cc crates/ui-egui/src/editing.rsindex c2c143520,ba2d3cbf9..f6e43f8a6--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@ -691,436 -628,8 +675,50 @@@ impl PdfCraftApp|| new_text_typed(v)|| v.line_editor.as_ref().map_or_else(|| false, |ed| ed.has_unsaved_text())}-- /// Save the active document. Returns `true` if it was written.- pub fn save_active(&mut self, target: SaveTarget) -> bool {- match self.active {- Some(i) => self.save_view(i, target),- None => false,- }- }-- /// Save the document shown in tab `index`. Returns `true` if it was written now. When it has- /// to ask where (a new document, or Save As) it returns `false` and saves on a later frame,- /// once the user has chosen.- pub fn save_view(&mut self, index: usize, target: SaveTarget) -> bool {- self.save_then(index, target, |_| {})- }-- /// [`Self::save_view`], then `after` once the document is written: now, or on a later frame- /// when the user had to choose where. `after` never runs when the save fails or is cancelled.- pub(crate) fn save_then(&mut self, index: usize, target: SaveTarget, after: impl FnOnce(&mut Self) + Send + 'static) -> bool {- // What's typed in a field is part of what's saved (#166).- if let Some(id) = self.views.get(index).map(|v| v.id)- && !self.commit_typing_in(id)- {- return false;- }- let Some(id) = self.views.get(index).map(|v| v.id) else { return false };- let Some(doc) = self.session.get(id) else { return false };- let (name, path) = (doc.name.clone(), doc.path.clone());- #[cfg(not(target_arch = "wasm32"))]- {- let doc_path = path.clone();- let destination = match (target, path, &self.save_override) {- (_, _, Some(p)) => p.clone(),- // An email attachment's temporary copy is no place to keep work: ask, as for a new- // document (`is_mail_temp_copy`).- (SaveTarget::InPlace, Some(p), _) if !is_mail_temp_copy(&p) => p,- _ => {- let name = if name.to_ascii_lowercase().ends_with(".pdf") { name } else { format!("{name}.pdf") };- let dialog = rfd::AsyncFileDialog::new().add_filter("PDF", &["pdf"]).set_file_name(name);- let dialog = in_document_folder(dialog, doc_path.as_deref());- // The bytes are taken once the user has chosen, so edits made meanwhile are saved too.- self.ask_one(crate::pickers::Ask::Save(dialog), None, move |app, dest| {- app.save_doc_to_then(id, &dest.to_string_lossy(), target, Box::new(after));- });- return false;- }- };- self.save_doc_to_then(id, &destination, target, Box::new(after))- }- #[cfg(target_arch = "wasm32")]- {- let _ = path;- if !self.flatten_fill_sign_for_save(id) {- return false;- }- let bytes = match self.session.save_bytes(id) {- Ok(b) => b,- Err(e) => {- self.notify_fmt("Couldn't save {name}: {e}", &[("name", &name), ("e", &e.to_string())]);- return false;- }- };- // An embedding page that asked for saves (`?host=parent`) gets the bytes; otherwise- // the browser downloads them.- let to_host = self.host_save.is_some();- let delivered = match &self.host_save {- Some(save) => save(&name, &bytes, matches!(target, SaveTarget::As)),- None => download(&name, &bytes),- };- match delivered {- Ok(()) => {- let _ = self.session.mark_saved(id, bytes, None);- if let Some(doc) = self.session.get(id)- && let Some(view) = self.views.get_mut(index)- {- view.document_changed(&doc.info);- }- // The host reports where the file went (and any failure) itself.- if !to_host {- self.notify_fmt("Downloaded {name}", &[("name", &name)]);- }- after(self);- true- }- Err(e) if to_host => {- self.notify_fmt("Couldn't save {name}: {e}", &[("name", &name), ("e", &e)]);- false- }- Err(e) => {- self.notify_fmt("Couldn't download {name}: {e}", &[("name", &name), ("e", &e.to_string())]);- false- }- }- }- }-- /// [`Self::save_doc_to`], then `after`. When `dest` is the document's own file and it is- /// another version on disk than the one the document came from (something else wrote it- /// since the open or the last save, #2166), it asks first: the save waits in- /// `pending_overwrite` behind [`Dialog::OverwriteChanged`](crate::Dialog::OverwriteChanged).- /// Returns `true` if written now.- #[cfg(not(target_arch = "wasm32"))]- fn save_doc_to_then(&mut self, id: pdfcraft_engine::DocId, dest: &str, target: SaveTarget, after: Box<dyn FnOnce(&mut Self) + Send>) -> bool {- let own = self.session.get(id).and_then(|d| d.path.as_deref()).is_some_and(|p| crate::same_file(p, dest));- if own && self.watch.disk_differs(id, dest, self.session.get(id).map(|d| d.saved_bytes())) {- self.pending_overwrite = Some(PendingOverwrite { id, dest: dest.to_string(), target, after });- self.dialog = Some(crate::Dialog::OverwriteChanged);- return false;- }- let saved = self.save_doc_to(id, dest, target);- if saved {- after(self);- }- saved- }-- /// The dialog's Save anyway: write over the changed file.- #[cfg(not(target_arch = "wasm32"))]- pub(crate) fn overwrite_changed_file(&mut self) {- let Some(p) = self.pending_overwrite.take() else { return };- if self.save_doc_to(p.id, &p.dest, p.target) {- (p.after)(self);- }- }-- /// The dialog's Save as…: leave the file on disk as it is and ask where to put this version.- #[cfg(not(target_arch = "wasm32"))]- pub(crate) fn save_changed_file_elsewhere(&mut self) {- let Some(p) = self.pending_overwrite.take() else { return };- if let Some(index) = self.views.iter().position(|v| v.id == p.id) {- self.save_then(index, SaveTarget::As, p.after);- }- }-- /// Write document `id` to `dest` and make it the document's file. Returns `true` if written.- #[cfg(not(target_arch = "wasm32"))]- fn save_doc_to(&mut self, id: pdfcraft_engine::DocId, dest: &str, target: SaveTarget) -> bool {- // Save As answers on a later frame: commit what was typed meanwhile, too (#166), even- // if another tab is active by then.- if !self.commit_typing_in(id) || !self.flatten_fill_sign_for_save(id) {- return false;- }- let Some((name, full)) = self.session.get(id).map(|d| {- // Save As to another file is a clean copy, without the earlier revisions that still- // hold deleted pages or replaced text (#2165). A signed document stays incremental so- // its signatures keep covering the file.- let full = target == SaveTarget::As- && !d.path.as_deref().is_some_and(|p| crate::same_file(p, dest))- && d.read_only_reason.is_none()- && !d.is_signed();- (d.name.clone(), full)- }) else {- self.notify_tr("The document was closed before it could be saved.");- return false;- };- let bytes = if full { self.session.save_full_bytes(id) } else { self.session.save_bytes(id) };- let bytes = match bytes.and_then(|b| self.session.check_save(id, &b).map(|()| b)) {- Ok(b) => b,- Err(e) => {- self.notify_fmt("Couldn't save {name}: {e}", &[("name", &name), ("e", &e.to_string())]);- return false;- }- };- if let Err(e) = write_atomically(dest, &bytes) {- self.notify_fmt("Couldn't save {name}: {e}", &[("name", dest), ("e", &e.to_string())]);- return false;- }- // Our own write is not a change on disk to reload (#431).- self.watch.known_now(id, dest);- match self.session.mark_saved(id, bytes, Some(dest.to_string())) {- Ok(()) => {- self.forget_recovery(id);- if let Some(doc) = self.session.get(id)- && let Some(view) = self.views.iter_mut().find(|v| v.id == id)- {- view.document_changed(&doc.info);- // Saving over a version that changed on disk keeps this one: nothing to ask.- view.disk_changed = false;- }- self.notify_fmt("Saved {name}", &[("name", &short_name(dest))]);- #[cfg(target_os = "macos")]- crate::macos_association::repair(std::path::Path::new(dest));- true- }- Err(e) => {- self.notify_fmt("Saved, but reopening failed: {e}", &[("e", &e.to_string())]);- false- }- }- }-- /// Close a tab, asking first if it has unsaved changes.- pub fn request_close_tab(&mut self, index: usize) {- // Text typed into a field counts as an unsaved change.- if self.has_unsaved_work(index)- && let Some(id) = self.views.get(index).map(|v| v.id)- {- self.close_request = Some(CloseRequest::Tab(id));- } else {- self.close_tab(index);- }- }-- /// File ▸ Close all: clean documents close at once; each one with unsaved changes asks.- pub fn close_all(&mut self) {- for i in (0..self.views.len()).rev() {- if !self.has_unsaved_work(i) {- self.close_tab(i);- }- }- if self.first_dirty().is_some() {- self.close_request = Some(CloseRequest::All);- }- }-- /// File ▸ Revert (after the confirmation).- pub fn revert_active(&mut self) {- let Some((_, id)) = self.active_ids() else { return };- match self.session.revert(id) {- Ok(()) => {- if let Some(i) = self.active- && let Some(d) = self.session.get(id)- {- let view = &mut self.views[i];- view.document_changed(&d.info);- // Revert discards this source's uncommitted typing as well as model edits.- // Otherwise a later Save could write a rejected draft back into the file.- view.forms.focus = None;- view.forms.committed = None;- view.forms.unbaked.clear();- view.pending_edit = None;- }- self.notify_tr("Reverted to the last saved version");- }- Err(e) => self.notify_error(e),- }- }-- /// The first tab with unsaved changes.- pub fn first_dirty(&self) -> Option<usize> {- (0..self.views.len()).find(|&i| self.has_unsaved_work(i))- }-- /// Answer the save prompt: `Some(true)` save, `Some(false)` discard, `None` cancel.- pub fn resolve_close(&mut self, ctx: &egui::Context, choice: Option<bool>) {- let Some(req) = self.close_request.take() else { return };- // The next question (another dirty document) starts on Save again.- self.save_prompt_button = Default::default();- let index = match req {- CloseRequest::Tab(id) => match self.views.iter().position(|v| v.id == id) {- Some(i) => i,- None => return, // already closed- },- CloseRequest::Quit | CloseRequest::All => match self.first_dirty() {- Some(i) => i,- None => {- if req == CloseRequest::Quit {- self.quit(ctx);- }- return;- }- },- };- // Quitting closes the unsaved tabs one by one (and brings each forward to save it):- // remember what was open, and which tab was active, before the first one goes (#442).- if req == CloseRequest::Quit {- match choice {- Some(_) => self.note_quit_session(),- None => self.forget_quit_session(),- }- }- match choice {- None => {} // cancelled: nothing closes- Some(false) => self.close_and_continue(ctx, index, req),- Some(true) => {- let Some(id) = self.views.get(index).map(|v| v.id) else { return };- // Bring the document forward: what's typed in its form is committed and saved- // with it, and a field that rejects the value is shown where the user can fix it.- self.active = Some(index);- // Close only once the save has actually been written, which may be on a later- // frame when the user has to choose where. A failed or cancelled save keeps the- // document open.- let ctx = ctx.clone();- self.save_then(index, SaveTarget::InPlace, move |app| {- if let Some(i) = app.views.iter().position(|v| v.id == id) {- app.close_and_continue(&ctx, i, req);- }- });- }- }- }-- /// Close tab `index` for a close request, then ask about the next dirty document, or quit.- fn close_and_continue(&mut self, ctx: &egui::Context, index: usize, req: CloseRequest) {- self.close_tab(index);- // A newer prompt wins: the user may have started another close while a save was pending,- // and seen its question, which keeps counting as seen.- if (req == CloseRequest::Quit || req == CloseRequest::All) && self.close_request.is_none() {- match self.first_dirty() {- Some(_) => {- // A question about the next document is a new one.- self.save_prompt_seen = false;- self.close_request = Some(req);- }- None if req == CloseRequest::Quit => self.quit(ctx),- None => {}- }- }- }-- /// Request a normal application exit, preserving every unsaved document until answered.- /// Returns false while the existing save/discard/cancel prompt needs a decision.- pub(crate) fn request_quit(&mut self, ctx: &egui::Context) -> bool {- if self.first_dirty().is_some() {- self.close_request = Some(CloseRequest::Quit);- ctx.request_repaint();- false- } else {- self.shutdown_recovery();- self.quit(ctx);- true- }- }-- fn quit(&mut self, ctx: &egui::Context) {- self.allow_quit = true;- ctx.send_viewport_cmd(egui::ViewportCommand::Close);- }-- /// Publish whether any document has unsaved work, for the browser's reload warning (#812).- pub(crate) fn sync_unsaved_flag(&self) {- self.unsaved_flag.store(self.first_dirty().is_some(), std::sync::atomic::Ordering::Relaxed);- }-- /// Intercept window close while documents have unsaved changes.- pub(crate) fn guard_quit(&mut self, ctx: &egui::Context) {- // egui's default quit shortcut ignores extra Alt/Shift, including Ctrl+Alt+Q for '@'.- ctx.options_mut(|o| o.quit_shortcuts.clear());- let shortcut = ctx.input(|i| {- i.events.iter().any(|e| {- matches!(e, egui::Event::Key { key: egui::Key::Q, pressed: true, modifiers, .. }- if modifiers.matches_exact(egui::Modifiers::COMMAND))- })- });- if shortcut {- self.request_quit(ctx);- }- self.sync_unsaved_flag();- if !ctx.input(|i| i.viewport().close_requested()) {- return;- }- // `first_dirty` counts text typed into a field as an unsaved change.- if !self.allow_quit && self.first_dirty().is_some() {- ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);- self.close_request = Some(CloseRequest::Quit);- } else {- // A clean quit: nothing is left to recover.- self.shutdown_recovery();- }- }-- /// Ask for the user's attention when the "save changes?" question opens while PdfCraft is in- /// the background (Quit in the Dock menu, logging out, or an agent quitting), and withdraw the- /// request once the user comes back or the question is answered.- ///- /// The question holds up the quit the user asked for, so the request is critical, as AppKit- /// makes it for a modal panel that an inactive app presents: the Dock icon bounces until- /// PdfCraft is active, Windows flashes the taskbar button until the window is in front, and- /// X11 sets the urgency hint, which stays until it is reset. A question that opens in front- /// asks nothing, and neither does leaving it open: the user has seen it. Each document asked- /// about when quitting is a new question, so one that opens in the background asks even after- /// a question the user saw; a request that still stands carries over to it.- pub(crate) fn attend_save_prompt(&mut self, ctx: &egui::Context) {- let open = self.close_request.is_some();- let focused = ctx.input(|i| i.focused);- if self.save_prompt_attention {- if focused || !open {- ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(egui::UserAttentionType::Reset));- self.save_prompt_attention = false;- }- } else if open && !self.save_prompt_seen && !focused {- ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(egui::UserAttentionType::Critical));- self.save_prompt_attention = true;- }- self.save_prompt_seen = open;- }}+fn rect_matches(a: [f64; 4], b: [f64; 4]) -> bool {+ a.iter().zip(b.iter()).all(|(x, y)| (x - y).abs() < 1e-3)+}++fn re_resolve_image_selection(+ view: &mut crate::DocView,+ page: usize,+ target: &pdfcraft_engine::PageImage,+ ambiguous_before: bool,+ page_images: &[pdfcraft_engine::PageImage],+) {+ let exact_matches: Vec<usize> = page_images+ .iter()+ .enumerate()+ .filter(|(_, img)| img.name == target.name && img.object == target.object && rect_matches(img.rect, target.rect))+ .map(|(idx, _)| idx)+ .collect();+ let new_idx = if !ambiguous_before && exact_matches.len() == 1 {+ exact_matches.first().copied()+ } else if !ambiguous_before && exact_matches.is_empty() {+ let name_obj_matches: Vec<usize> =+ page_images.iter().enumerate().filter(|(_, img)| img.name == target.name && img.object == target.object).map(|(idx, _)| idx).collect();+ if name_obj_matches.len() == 1 {+ name_obj_matches.first().copied()+ } else if name_obj_matches.is_empty() {+ let name_matches: Vec<usize> = page_images.iter().enumerate().filter(|(_, img)| img.name == target.name).map(|(idx, _)| idx).collect();+ if name_matches.len() == 1 { name_matches.first().copied() } else { None }+ } else {+ None+ }+ } else {+ None+ };+ if let Some(s) = view.image_selection.as_mut().filter(|s| s.page == page) {+ if let Some(idx) = new_idx {+ s.index = idx;+ } else {+ view.image_selection = None;+ }+ }+}+/// The single page a content edit changes (`None` for other edits). Like comment edits,/// these leave every other page's bytes, geometry and text alone, so their rasters stay valid.fn content_page(edit: &Edit) -> Option<usize> {diff --cc crates/ui-egui/src/i18n.rsindex 000000000,3f478b637..3ac16d622mode 000000,100644..100644--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -1,0 -1,799 +1,799 @@@+ //! UI localisation. Strings in code stay English and are the default lookup keys; a per-language+ //! catalog (`*.tsv`, see `ja.tsv` for the format) maps them to display text at render time. Command+ //! ids, document text, file names, the control channel, the CLI and MCP never see translated text,+ //! so agents and scripts are unaffected. A string without a translation is shown in English, so+ //! coverage can grow incrementally.+ //!+ //! The system is the one PhotoCraft uses (`photocraft/crates/ui-egui/src/i18n`), so catalogs and+ //! habits carry over between the two apps.+ //!+ //! # Adding a language+ //! 1. Add `xx.tsv` next to `ja.tsv` (copy its header; translate from the *meaning* of the English+ //! text, clean-room, see `ja.tsv`).+ //! 2. Add one row to [`LANGUAGES`] (code, native name, catalog, plural rule).+ //!+ //! That is all: the Preferences dropdown, the system-locale match and the catalog tests (parse,+ //! placeholders, plural forms) pick it up from the registry.+ //!+ //! # Looking strings up-//! - [`tl!`](crate::tl) / [`t`]: a plain string in the current language. [`tr`]: in a given one.++//! - `tl!` / [`t`]: a plain string in the current language. [`tr`]: in a given one.+ //! - [`tr_ctx`] (`tl_ctx!` in UI code): when one English word needs different translations.+ //! - [`tr_id`]: a command-id keyed string with the English label as fallback (menu items), so a+ //! translation survives rewording of the English text and can differ per command.+ //! - [`trn`]: plural-aware (`{n}` is filled in). [`fmt`]: fill `{name}` placeholders after [`tr`];+ //! translators may reorder placeholders freely.++ mod catalog;++ use std::cell::Cell;+ use std::sync::OnceLock;++ use catalog::Catalog;++ /// The `language` preference value that follows the system locale.+ pub const AUTO: &str = "auto";++ /// One supported UI language.+ pub struct LangInfo {+ /// BCP 47 code, lowercase (`ja`, `zh-hans`, `pt-br`). Also the `language` preference value.+ pub code: &'static str,+ /// The language's name in itself, shown in the Preferences dropdown.+ pub name: &'static str,+ /// Catalog file contents (empty for the built-in English).+ pub source: &'static str,+ /// Plural form index for a count (English: 0 = one, 1 = other; Japanese: always 0). A catalog's+ /// `@plural` entries list one form per index.+ pub plural: fn(u64) -> usize,+ /// The language is written right to left. Catalogs stay in logical order: the egui 0.37 fork+ /// owns bidi shaping/reordering (E5/E12), so preordering here would reverse Arabic twice.+ pub rtl: bool,+ catalog: OnceLock<Catalog>,+ }++ fn plural_one_other(n: u64) -> usize {+ usize::from(n != 1)+ }++ fn plural_none(_: u64) -> usize {+ 0+ }++ /// Romanian (CLDR `ro`): 1 is `one`; 0 and numbers whose last two digits are 1–19 (2, 19, 101,+ /// 119) are `few`; everything else (20, 100, 120) is `other`, the form with "de" ("20 de pagini").+ fn plural_ro(n: u64) -> usize {+ if n == 1 {+ 0+ } else if n == 0 || (1..=19).contains(&(n % 100)) {+ 1+ } else {+ 2+ }+ }++ /// Lithuanian: one (ending in 1 except 11), few (ending in 2–9 except 12–19), other otherwise.+ fn plural_lithuanian(n: u64) -> usize {+ match (n % 10, n % 100) {+ (1, 11) => 2,+ (1, _) => 0,+ (2..=9, 12..=19) => 2,+ (2..=9, _) => 1,+ _ => 2,+ }+ }++ /// Czech: 1 → one, 2–4 → few, everything else (0, 5+) → other.+ fn plural_cs(n: u64) -> usize {+ match n {+ 1 => 0,+ 2..=4 => 1,+ _ => 2,+ }+ }++ /// Portuguese: 0 and 1 take the singular, everything else the plural.+ fn plural_pt(n: u64) -> usize {+ usize::from(n > 1)+ }++ /// French (CLDR `fr`): 0 and 1 take the singular, everything else the plural.+ fn plural_fr(n: u64) -> usize {+ usize::from(n > 1)+ }++ /// Russian: 1 (but not 11) is `one`, 2–4 (but not 12–14) `few`, everything else `many`.+ fn plural_russian(n: u64) -> usize {+ match n % 100 {+ 11..=14 => 2,+ _ => match n % 10 {+ 1 => 0,+ 2..=4 => 1,+ _ => 2,+ },+ }+ }++ /// Ukrainian (CLDR `uk`, integer counts): one (1, 21), few (2–4, 22–24), many (0, 5–19).+ /// Counts ending in 11–14 always take many, regardless of the last digit.+ fn plural_ukrainian(n: u64) -> usize {+ match n % 100 {+ 11..=14 => 2,+ _ => match n % 10 {+ 1 => 0,+ 2..=4 => 1,+ _ => 2,+ },+ }+ }++ /// Arabic (CLDR `ar`, integer counts): zero (0), one (1), two (2), few (3–10, 103–110),+ /// many (11–99, 111–199), other (100–102, 200–202).+ fn plural_arabic(n: u64) -> usize {+ match (n, n % 100) {+ (0, _) => 0,+ (1, _) => 1,+ (2, _) => 2,+ (_, 3..=10) => 3,+ (_, 11..=99) => 4,+ _ => 5,+ }+ }++ /// Polish integer counts: 1 is one; endings 2–4 except 12–14 are few; the rest are many.+ fn plural_polish(n: u64) -> usize {+ match (n, n % 100, n % 10) {+ (1, _, _) => 0,+ (_, 12..=14, _) => 2,+ (_, _, 2..=4) => 1,+ _ => 2,+ }+ }++ /// Slovene (CLDR `sl`): one (1, 101, 201 ...) | two (2, 102 ...) | few (3, 4, 103 ...) | other.+ fn plural_sl(n: u64) -> usize {+ match n % 100 {+ 1 => 0,+ 2 => 1,+ 3 | 4 => 2,+ _ => 3,+ }+ }++ /// The registry. English first: it is the fallback and the source language.+ pub static LANGUAGES: [LangInfo; 35] = [+ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ LangInfo { code: "ja", name: "日本語", source: include_str!("i18n/ja.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Simplified Chinese; `zh`, `zh-CN`, `zh-SG` and `zh-Hans-*` locales resolve here (see `candidates`).+ LangInfo {+ code: "zh-hans",+ name: "简体中文",+ source: include_str!("i18n/zh-hans.tsv"),+ plural: plural_none,+ rtl: false,+ catalog: OnceLock::new(),+ },+ // Traditional Chinese in the vocabulary used in Taiwan; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant-*`+ // locales all resolve here (see `candidates`).+ LangInfo {+ code: "zh-hant",+ name: "繁體中文",+ source: include_str!("i18n/zh-hant.tsv"),+ plural: plural_none,+ rtl: false,+ catalog: OnceLock::new(),+ },+ LangInfo { code: "cs", name: "Čeština", source: include_str!("i18n/cs.tsv"), plural: plural_cs, rtl: false, catalog: OnceLock::new() },+ // Brazilian Portuguese; `pt`, `pt-BR` and `pt-PT` locales all resolve here (see `candidates`).+ LangInfo {+ code: "pt-br",+ name: "Português (Brasil)",+ source: include_str!("i18n/pt-br.tsv"),+ plural: plural_pt,+ rtl: false,+ catalog: OnceLock::new(),+ },+ // German (informal "du"); every `de-*` locale (`de-DE`, `de-AT`, `de-CH` ...) resolves here.+ LangInfo { code: "de", name: "Deutsch", source: include_str!("i18n/de.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Spanish (European vocabulary); every `es-*` locale (`es-ES`, `es-MX`, `es-419` ...) resolves here.+ LangInfo { code: "es", name: "Español", source: include_str!("i18n/es.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // French; every `fr-*` locale (`fr-FR`, `fr-CA`, `fr-BE` ...) resolves here.+ LangInfo { code: "fr", name: "Français", source: include_str!("i18n/fr.tsv"), plural: plural_fr, rtl: false, catalog: OnceLock::new() },+ // Russian; every `ru-*` locale (`ru-RU`, `ru-BY`, `ru-KZ` ...) resolves here.+ LangInfo {+ code: "ru", name: "Русский", source: include_str!("i18n/ru.tsv"), plural: plural_russian, rtl: false, catalog: OnceLock::new()+ },+ // Kazakh; every `kk-*` locale (`kk-KZ`, `kk-KZ.UTF-8`) resolves here.+ LangInfo {+ code: "kk", name: "Қазақша", source: include_str!("i18n/kk.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new()+ },+ // Bulgarian; every `bg-*` locale (`bg-BG`) resolves here.+ LangInfo {+ code: "bg", name: "Български", source: include_str!("i18n/bg.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new()+ },+ // Telugu; every `te-*` locale (`te-IN`) resolves here.+ LangInfo {+ code: "te", name: "తెలుగు", source: include_str!("i18n/te.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new()+ },+ // Hungarian; every `hu-*` locale (`hu-HU`) resolves here.+ LangInfo { code: "hu", name: "Magyar", source: include_str!("i18n/hu.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Ukrainian; every `uk-*` locale (`uk-UA`, `uk_UA.UTF-8`) resolves here.+ LangInfo {+ code: "uk", name: "Українська", source: include_str!("i18n/uk.tsv"), plural: plural_ukrainian, rtl: false, catalog: OnceLock::new()+ },+ // Italian; every `it-*` locale (`it-IT`) resolves here.+ LangInfo { code: "it", name: "Italiano", source: include_str!("i18n/it.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Arabic (Modern Standard, Western digits); every `ar-*` locale (`ar-MA`, `ar-EG`, `ar-SA` ...)+ // resolves here. Right to left: see `LangInfo::rtl`.+ LangInfo { code: "ar", name: "العربية", source: include_str!("i18n/ar.tsv"), plural: plural_arabic, rtl: true, catalog: OnceLock::new() },+ // Central Kurdish (Sorani); every `ckb-*` locale (`ckb-IQ`, `ckb-IR`) resolves here. Right to+ // left like Arabic: see `LangInfo::rtl`. CLDR `ckb` counts have two forms (one, other).+ LangInfo {+ code: "ckb",+ name: "کوردیی ناوەندی",+ source: include_str!("i18n/ckb.tsv"),+ plural: plural_one_other,+ rtl: true,+ catalog: OnceLock::new(),+ },+ // Persian (Farsi); every `fa-*` locale (`fa-IR`, `fa_IR.UTF-8`, `fa-AF` ...) resolves here. Right+ // to left like Arabic: see `LangInfo::rtl`. CLDR `fa` counts have two forms (one: i = 0 or n = 1,+ // other), which for whole counts is the French rule, so `@plural` entries list two forms.+ LangInfo { code: "fa", name: "فارسی", source: include_str!("i18n/fa.tsv"), plural: plural_fr, rtl: true, catalog: OnceLock::new() },+ // Polish; every `pl-*` locale (`pl-pl`, `pl_pl.UTF-8`) resolves here.+ LangInfo { code: "pl", name: "Polski", source: include_str!("i18n/pl.tsv"), plural: plural_polish, rtl: false, catalog: OnceLock::new() },+ // Slovene; every `sl-*` locale (`sl-SI`) resolves here. Four plural forms (one, two, few, other).+ LangInfo { code: "sl", name: "Slovenščina", source: include_str!("i18n/sl.tsv"), plural: plural_sl, rtl: false, catalog: OnceLock::new() },+ LangInfo {+ code: "el", name: "Ελληνικά", source: include_str!("i18n/el.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new()+ },+ // Turkish; every `tr-*` locale (`tr-TR`, `tr_TR.UTF-8`) resolves here.+ LangInfo { code: "tr", name: "Türkçe", source: include_str!("i18n/tr.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Lithuanian; every `lt-*` locale (`lt-LT`, `lt_LT.UTF-8`) resolves here. Three plural forms (one, few, other).+ LangInfo { code: "lt", name: "Lietuvių", source: include_str!("i18n/lt.tsv"), plural: plural_lithuanian, rtl: false, catalog: OnceLock::new() },+ // Indonesian; every `id-*` locale (`id-ID`, `id_ID.UTF-8`) resolves here. CLDR `id` counts have+ // one form ("other"), so `@plural` entries list a single form.+ LangInfo { code: "id", name: "Bahasa Indonesia", source: include_str!("i18n/id.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Vietnamese; every `vi-*` locale (`vi-VN`, `vi_VN.UTF-8`) resolves here. CLDR `vi` counts have+ // one form ("other"), so `@plural` entries list a single form.+ LangInfo { code: "vi", name: "Tiếng Việt", source: include_str!("i18n/vi.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Finnish; every `fi-*` locale (`fi-FI`, `fi_FI.UTF-8`) resolves here. Two plural forms (one, other):+ // the partitive singular follows any number but 1 (`1 sivu`, `2 sivua`).+ LangInfo { code: "fi", name: "Suomi", source: include_str!("i18n/fi.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Albanian; every `sq-*` locale (`sq-AL`, `sq_AL.UTF-8`, `sq-XK`) resolves here. One/other plural, like English.+ LangInfo { code: "sq", name: "Shqip", source: include_str!("i18n/sq.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Thai; every `th-*` locale (`th-TH`, `th_TH.UTF-8`) resolves here. No grammatical plural.+ LangInfo { code: "th", name: "ไทย", source: include_str!("i18n/th.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Catalan; every `ca-*` locale (`ca-ES`, `ca_ES.UTF-8`, `ca_ES@valencia`) resolves here.+ LangInfo { code: "ca", name: "Català", source: include_str!("i18n/ca.tsv"), plural: plural_one_other, rtl: false, catalog: OnceLock::new() },+ // Romanian; every `ro-*` locale (`ro-RO`, `ro_RO.UTF-8`, `ro-MD`) resolves here. Three plural forms (one, few, other).+ LangInfo { code: "ro", name: "Română", source: include_str!("i18n/ro.tsv"), plural: plural_ro, rtl: false, catalog: OnceLock::new() },+ // Lao; every `lo-*` locale (`lo-LA`, `lo_LA.UTF-8` ...) resolves here.+ LangInfo {+ code: "lo", name: "ພາສາລາວ", source: include_str!("i18n/lo.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new()+ },+ // Hindi; every `hi-*` locale (`hi-IN`, `hi_IN.UTF-8`) resolves here. CLDR `hi` has "one"+ // (0 and 1) and "other", but the catalog's nouns are the same in both ("{n} पृष्ठ"), so+ // `@plural` entries list a single form.+ LangInfo {+ code: "hi", name: "हिन्दी", source: include_str!("i18n/hi.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new()+ },+ // Korean; every `ko-*` locale (`ko-KR`, `ko_KR.UTF-8`) resolves here. CLDR `ko` counts have+ // one form ("other"), so `@plural` entries list a single form.+ LangInfo { code: "ko", name: "한국어", source: include_str!("i18n/ko.tsv"), plural: plural_none, rtl: false, catalog: OnceLock::new() },+ // Norwegian Bokmål; every `nb-*` locale resolves here, and so do general Norwegian (`no-*`) and+ // Nynorsk (`nn-*`), which have no catalog of their own (see `candidates`).+ LangInfo {+ code: "nb",+ name: "Norsk bokmål",+ source: include_str!("i18n/nb.tsv"),+ plural: plural_one_other,+ rtl: false,+ catalog: OnceLock::new(),+ },+ ];++ impl LangInfo {+ /// How many plural forms the language's `@plural` entries list.+ fn plural_forms(&self) -> usize {+ (0..=1000).map(self.plural).max().unwrap_or(0).saturating_add(1)+ }++ /// Return the parsed catalogue, building it on first use and warning about entries that fall back to+ /// English.+ fn catalog(&self) -> &Catalog {+ self.catalog.get_or_init(|| {+ let (catalog, errors) = Catalog::parse(self.source, self.plural_forms());+ for error in errors {+ log::warn!("{} interface catalog: {error}; that entry shows in English", self.code);+ }+ // Catalogs keep logical text: the fork shapes and reorders each run once. Accessibility+ // names, copied text and search therefore see the same logical string as the source.+ catalog+ })+ }+ }++ /// A language the UI can be shown in (a handle into [`LANGUAGES`]).+ #[derive(Clone, Copy)]+ pub struct Lang(&'static LangInfo);++ impl std::fmt::Debug for Lang {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Lang({})", self.0.code)+ }+ }++ impl PartialEq for Lang {+ fn eq(&self, other: &Self) -> bool {+ self.0.code == other.0.code+ }+ }++ impl Eq for Lang {}++ impl Lang {+ pub const EN: Lang = Lang(&LANGUAGES[0]);++ pub fn code(self) -> &'static str {+ self.0.code+ }++ /// A language by its exact code.+ pub fn from_code(code: &str) -> Option<Lang> {+ LANGUAGES.iter().find(|l| l.code.eq_ignore_ascii_case(code)).map(Lang)+ }++ /// Resolve the `language` preference: a language code, or [`AUTO`] (and anything unknown,+ /// e.g. a code from a newer version) to follow the system locale.+ pub fn from_pref(pref: &str) -> Lang {+ Lang::from_code(pref).unwrap_or_else(system_lang)+ }++ /// Every registered language.+ pub fn all() -> impl Iterator<Item = Lang> {+ LANGUAGES.iter().map(Lang)+ }++ /// Every registered language in the order a picker lists them: English first (the source+ /// language and the fallback), then the rest by their own name with accents folded, so+ /// Čeština sits under C rather than after Z. Names in other scripts follow the Latin ones in+ /// code point order: Greek, Cyrillic, Arabic, then the CJK languages.+ pub fn for_picker() -> Vec<Lang> {+ Self::for_picker_by(Lang::name)+ }++ /// [`for_picker`](Self::for_picker), ordered by the names the picker actually shows.+ ///+ /// `shown` must return each language's displayed name. Pass [`Lang::picker_name`] to keep a+ /// Latin-script fallback with the other Latin names when a script's face is missing, rather+ /// than sorting it into a block of unrenderable labels.+ pub fn for_picker_by(mut shown: impl FnMut(Lang) -> &'static str) -> Vec<Lang> {+ let mut rest: Vec<Lang> = Lang::all().filter(|l| l.code() != Lang::EN.code()).collect();+ rest.sort_by_cached_key(|l| name_sort_key(shown(*l)));+ std::iter::once(Lang::EN).chain(rest).collect()+ }++ pub fn name(self) -> &'static str {+ self.0.name+ }++ /// The language's name in English, used by [`picker_name`](Self::picker_name) when this+ /// build's fonts cannot draw [`name`](Self::name).+ pub fn english_name(self) -> &'static str {+ match self.code() {+ "en" => "English",+ "ja" => "Japanese",+ "zh-hans" => "Simplified Chinese",+ "zh-hant" => "Traditional Chinese",+ "cs" => "Czech",+ "pt-br" => "Portuguese (Brazil)",+ "de" => "German",+ "es" => "Spanish",+ "fr" => "French",+ "ru" => "Russian",+ "kk" => "Kazakh",+ "bg" => "Bulgarian",+ "te" => "Telugu",+ "hu" => "Hungarian",+ "uk" => "Ukrainian",+ "it" => "Italian",+ "ar" => "Arabic",+ "ckb" => "Central Kurdish",+ "fa" => "Persian",+ "pl" => "Polish",+ "sl" => "Slovenian",+ "el" => "Greek",+ "tr" => "Turkish",+ "lt" => "Lithuanian",+ "id" => "Indonesian",+ "vi" => "Vietnamese",+ "fi" => "Finnish",+ "nb" => "Norwegian Bokmål",+ "sq" => "Albanian",+ "th" => "Thai",+ "ca" => "Catalan",+ "ro" => "Romanian",+ "lo" => "Lao",+ "hi" => "Hindi",+ "ko" => "Korean",+ // Only reached if a language is added to `LANGUAGES` without an English name; the+ // code still tells the reader which entry it is.+ _ => self.0.code,+ }+ }++ /// The name to show in the language picker: the native name when the current fonts can draw+ /// it, otherwise the English name. With egui 0.37's default `MissingGlyphPolicy::Panic`, a+ /// native name whose script has no face (for example Hindi in a build without a Devanagari+ /// face and with installed fonts turned off) would otherwise abort while the list opens.+ pub fn picker_name(self, drawable: impl FnOnce(&str) -> bool) -> &'static str {+ if drawable(self.name()) { self.name() } else { self.english_name() }+ }++ /// Whether the language is written right to left. Lookups stay logical; the egui fork+ /// shapes and reorders each run for display (see [`LangInfo::rtl`]).+ pub fn rtl(self) -> bool {+ self.0.rtl+ }++ fn catalog(self) -> &'static Catalog {+ self.0.catalog()+ }+ }++ /// The canonical `language` preference for user input: [`AUTO`] or a registered code (any case).+ /// `None` for anything else, so callers can keep the current setting.+ pub fn normalize_pref(pref: &str) -> Option<&'static str> {+ if pref.eq_ignore_ascii_case(AUTO) {+ return Some(AUTO);+ }+ Lang::from_code(pref).map(Lang::code)+ }++ /// Candidate language codes for a locale tag, most specific first: `zh_TW.UTF-8` →+ /// `zh-tw`, `zh-hant`, `zh`.+ fn candidates(tag: &str) -> Vec<String> {+ let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-").to_ascii_lowercase();+ let parts: Vec<&str> = base.split('-').filter(|p| !p.is_empty()).collect();+ let Some(&primary) = parts.first() else { return Vec::new() };+ let mut out = Vec::new();+ for n in (1..=parts.len()).rev() {+ out.push(parts.get(..n).unwrap_or_default().join("-"));+ }+ if primary == "zh" && !parts.iter().any(|p| matches!(*p, "hans" | "hant")) {+ // Chinese by region when no script is given.+ let script = if parts.iter().any(|p| matches!(*p, "tw" | "hk" | "mo")) { "zh-hant" } else { "zh-hans" };+ out.insert(out.len().saturating_sub(1), script.to_string());+ }+ if primary == "pt" && !out.iter().any(|c| c == "pt-br") {+ // The only Portuguese catalog is Brazilian; other regions use it rather than English.+ out.insert(out.len().saturating_sub(1), "pt-br".to_string());+ }+ if matches!(primary, "no" | "nn") {+ // The only Norwegian catalog is Bokmål. `no` (Norwegian in general) and Nynorsk readers use+ // it rather than English; last, so a catalog of their own would win.+ out.push("nb".to_string());+ }+ out+ }++ /// The registered language for a locale tag such as `ja_JP.UTF-8`, `ja-JP`; `None` if the+ /// language isn't supported. `C`/`POSIX` mean English.+ pub fn lang_from_tag(tag: &str) -> Option<Lang> {+ let cands = candidates(tag);+ if matches!(cands.first().map(String::as_str), Some("c" | "posix")) {+ return Some(Lang::EN);+ }+ cands.iter().find_map(|c| Lang::from_code(c))+ }++ /// The system language (cached). English when it can't be determined.+ pub fn system_lang() -> Lang {+ // Tests drive the UI by its English labels whatever the developer's locale is. This covers+ // the unit tests; the integration tests link the library as it ships, where `cfg!(test)` is+ // off, so each of their harnesses pins the `language` option to `en` instead.+ if cfg!(test) {+ return Lang::EN;+ }+ static SYSTEM: OnceLock<Lang> = OnceLock::new();+ *SYSTEM.get_or_init(detect_system_lang)+ }++ #[cfg(not(target_arch = "wasm32"))]+ fn detect_system_lang() -> Lang {+ for var in ["LC_ALL", "LC_MESSAGES", "LANG"] {+ if let Some(l) = std::env::var(var).ok().and_then(|v| language_override(&v)) {+ return l;+ }+ }+ // Apps started from the Finder don't inherit LANG: use the macOS preferred-languages list.+ // The absolute path keeps a `defaults` earlier on PATH from running; any failure means English.+ #[cfg(target_os = "macos")]+ if let Ok(out) = std::process::Command::new("/usr/bin/defaults").args(["read", "-g", "AppleLanguages"]).output()+ && out.status.success()+ && let Some(l) = first_supported(&String::from_utf8_lossy(&out.stdout))+ {+ return l;+ }+ #[cfg(target_os = "windows")]+ if let Some(l) = windows_ui_language().as_deref().and_then(first_supported) {+ return l;+ }+ Lang::EN+ }++ /// A named locale can override the display language. On Windows, the neutral+ /// C/POSIX locale inherited from a launcher says nothing about the user's UI language.+ #[cfg(not(target_arch = "wasm32"))]+ fn language_override(tag: &str) -> Option<Lang> {+ let tag = tag.trim();+ if cfg!(target_os = "windows") && matches!(candidates(tag).first().map(String::as_str), Some("c" | "posix")) {+ return None;+ }+ lang_from_tag(tag)+ }++ /// The Windows display languages in preference order, one tag per line, queried once when Auto+ /// first resolves. `sys-locale` asks Windows directly (`GetUserPreferredUILanguages`), so no+ /// process is started.+ #[cfg(target_os = "windows")]+ fn windows_ui_language() -> Option<String> {+ let tags: Vec<String> = sys_locale::get_locales().collect();+ (!tags.is_empty()).then(|| tags.join("\n"))+ }++ /// The first supported language in a macOS `defaults read` list or Windows UI-culture output.+ #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]+ fn first_supported(list: &str) -> Option<Lang> {+ list.split(['(', ')', ',', '"', '\n']).map(str::trim).filter(|s| !s.is_empty()).find_map(lang_from_tag)+ }++ /// The first supported language among BCP 47 tags in preference order, as the browser lists them+ /// in `navigator.languages` (#2954). Only the first few tags are looked at: the list is short in+ /// practice, and a page can't make Auto walk an unbounded one.+ #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]+ fn first_supported_tag<S: AsRef<str>>(tags: impl IntoIterator<Item = S>) -> Option<Lang> {+ tags.into_iter().take(32).find_map(|tag| lang_from_tag(tag.as_ref().trim()))+ }++ /// The browser's preferred languages, as the desktop builds use the system's: `navigator.languages`+ /// in order, then `navigator.language` (kept within the 32 tags `first_supported_tag` reads).+ /// English when the browser offers none we have a catalog for.+ #[cfg(target_arch = "wasm32")]+ fn detect_system_lang() -> Lang {+ let Some(navigator) = web_sys::window().map(|w| w.navigator()) else { return Lang::EN };+ let mut tags: Vec<String> = navigator.languages().iter().take(31).filter_map(|v| v.as_string()).collect();+ tags.extend(navigator.language());+ first_supported_tag(&tags).unwrap_or(Lang::EN)+ }++ thread_local! {+ // Per thread, as in PhotoCraft: independent app and test threads (kittest harnesses run in+ // parallel) must not change each other's drawing language.+ static CURRENT: Cell<Lang> = const { Cell::new(Lang::EN) };+ }++ /// Set the UI language for drawing (the shell calls this once per frame from the preference), so+ /// widgets can translate without every call site carrying a language around.+ pub fn set_current(lang: Lang) {+ CURRENT.set(lang);+ }++ /// The language the UI is drawn in.+ /// `label` as it reads inside a sentence ("add a text box"): lowercased, except in languages+ /// that capitalise nouns (German), where lowercasing would misspell it.+ pub fn in_sentence(label: &str) -> std::borrow::Cow<'_, str> {+ match current().code() {+ "de" => std::borrow::Cow::Borrowed(label),+ "tr" => std::borrow::Cow::Owned(label.chars().flat_map(lower_turkish).collect()),+ _ => std::borrow::Cow::Owned(label.to_lowercase()),+ }+ }++ /// The translation of `english` in upper case, for section titles. Rust's case mapping knows no+ /// language, and Turkish has a dotted and a dotless i (`i` ↔ `İ`, `ı` ↔ `I`): "Gelişmiş" must+ /// become "GELİŞMİŞ", not "GELIŞMIŞ". A label without a Turkish row is still English and keeps+ /// the English rule.+ pub fn upper_label(english: &str) -> String {+ let lang = current();+ let shown = tr(lang, english);+ if lang.code() == "tr" && has(lang, english) { shown.chars().flat_map(upper_turkish).collect() } else { shown.to_uppercase() }+ }++ fn upper_turkish(c: char) -> std::char::ToUppercase {+ match c {+ 'i' => 'İ'.to_uppercase(),+ 'ı' => 'I'.to_uppercase(),+ c => c.to_uppercase(),+ }+ }++ fn lower_turkish(c: char) -> std::char::ToLowercase {+ match c {+ // `İ`.to_lowercase() is "i" plus a combining dot above.+ 'İ' => 'i'.to_lowercase(),+ 'I' => 'ı'.to_lowercase(),+ c => c.to_lowercase(),+ }+ }++ pub fn current() -> Lang {+ CURRENT.get()+ }++ /// Does `lang` have a catalog entry for this plain string? (English never does: it is the source.)+ pub fn has(lang: Lang, s: &str) -> bool {+ lang.catalog().plain(s).is_some()+ }++ /// Translate an English UI string into the current language ([`tr`] with [`current`]).+ pub fn t(s: &str) -> &str {+ tr(current(), s)+ }++ /// The name of a keyboard key, distinct from a command such as Delete. Missing key-name+ /// translations use the English key name, never a plain command translation.+ pub fn key_name(s: &str) -> &str {+ current().catalog().contextual("key", s).unwrap_or(s)+ }++ /// Translate an English UI string; unknown strings come back unchanged.+ pub fn tr(lang: Lang, s: &str) -> &str {+ lang.catalog().plain(s).unwrap_or(s)+ }++ /// How the layers below say their own sentences in the current language.+ ///+ /// The checker, the preflight profiles and the signature panel hand over a whole English wording+ /// — holes and all — and the document's own words apart from it, so this is all they need of us:+ /// `f.said(&i18n::words)` says the sentence here, and `in_english` says it in English. An unknown+ /// wording comes back as it stands, which is the English, so a catalog that is missing one is a+ /// sentence in English rather than a gap.+ pub fn words(wording: &str) -> String {+ t(wording).to_owned()+ }++ /// Like [`tr`], for an English string that needs a disambiguating `context`.+ pub fn tr_ctx<'a>(lang: Lang, context: &str, s: &'a str) -> &'a str {+ lang.catalog().contextual(context, s).unwrap_or_else(|| tr(lang, s))+ }++ /// A string keyed by its command id, falling back to the translation of the English `label`.+ pub fn tr_id<'a>(lang: Lang, id: &str, label: &'a str) -> &'a str {+ lang.catalog().id(id).unwrap_or_else(|| tr(lang, label))+ }++ /// Fill `{name}` placeholders in one pass. Unknown placeholders are left as written, and inserted+ /// values are never read as templates again, so a file name containing `{n}` stays intact.+ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {+ let mut out = String::with_capacity(template.len());+ let mut rest = template;+ while let Some((before, after_open)) = rest.split_once('{') {+ out.push_str(before);+ let Some((name, after_close)) = after_open.split_once('}') else {+ out.push('{');+ out.push_str(after_open);+ return out;+ };+ match args.iter().find(|(key, _)| *key == name) {+ Some((_, value)) => out.push_str(value),+ None => {+ out.push('{');+ out.push_str(name);+ out.push('}');+ }+ }+ rest = after_close;+ }+ out.push_str(rest);+ out+ }++ /// A generated history label (the action part of "Undo …") in the current language. Captured+ /// values (file and field names) are inserted as they are; unknown labels are looked up whole.+ pub fn action_label(text: &str) -> String {+ for (prefix, template) in [+ ("Insert pages from ", "Insert pages from {name}"),+ ("Fill in ", "Fill in {name}"),+ ("Set the image of ", "Set the image of {name}"),+ ("Edit script of ", "Edit script of {name}"),+ ("Import ", "Import {name}"),+ ] {+ if let Some(value) = text.strip_prefix(prefix) {+ return fmt(t(template), &[("name", value)]);+ }+ }+ if let Some(key) = text.strip_prefix("Change ")+ && ["Title", "Author", "Subject", "Keywords", "Creator", "Producer"].contains(&key)+ {+ return fmt(t("Change {key}"), &[("key", t(key))]);+ }+ if let Some(n) = text.strip_prefix("Delete ").and_then(|rest| rest.strip_suffix(" fields")).and_then(|n| n.parse::<u64>().ok()) {+ return trn(current(), n, "Delete {n} field", "Delete {n} fields");+ }+ t(text).to_owned()+ }++ /// A history label in the current language, out of the engine's own two parts: the wording is+ /// looked up whole and the document's own word goes into its `{}` afterwards, so a file or field+ /// name is never read as part of the wording. This is exact where [`action_label`] has to guess+ /// from the English text, and is what the engine's own labels go through.+ pub fn edit_label(label: &pdfcraft_engine::Label) -> String {+ // A batch's wording is only the hole: it carries its name as text, which from below L7 is one+ // of `BATCH_LABELS` and so is looked up too.+ if let Some(name) = label.value.as_deref().filter(|_| label.wording == "{batch}") {+ return t(name).to_owned();+ }+ label.said(t(label.wording))+ }++ /// A command label such as "Undo Insert pages from a.pdf" in the current language. A catalog+ /// whose word order doesn't put the verb first translates "Undo {action}" and "Redo {action}"+ /// as whole phrases; otherwise the translated verb goes before the action.+ pub fn command_label(text: &str) -> String {+ for (prefix, template) in [("Undo", "Undo {action}"), ("Redo", "Redo {action}")] {+ if let Some(action) = text.strip_prefix(prefix).and_then(|tail| tail.strip_prefix(' ')) {+ let action = action_label(action);+ if has(current(), template) {+ return fmt(t(template), &[("action", &action)]);+ }+ return format!("{} {action}", t(prefix));+ }+ }+ t(text).to_owned()+ }++ /// A registered command's menu label: its `@id` catalog entry if there is one, otherwise+ /// [`command_label`] of the current English label.+ pub fn menu_label(id: &str, label: &str) -> String {+ match current().catalog().id(id) {+ Some(translated) => translated.to_owned(),+ None => command_label(label),+ }+ }++ /// A plural-aware message: `one`/`other` are the English forms (with `{n}` where the count goes).+ pub fn trn(lang: Lang, n: u64, one: &str, other: &str) -> String {+ let idx = (lang.0.plural)(n);+ let text = lang.catalog().plural(one, other, idx).unwrap_or(if n == 1 { one } else { other });+ fmt(text, &[("n", &n.to_string())])+ }++ /// `name` lowercased with the Latin accents that occur in language names folded away, so a+ /// byte-wise sort reads alphabetically. Other scripts are left as they are.+ fn name_sort_key(name: &str) -> String {+ name.chars()+ .flat_map(char::to_lowercase)+ .map(|c| match c {+ 'à'..='å' | 'ā' | 'ă' | 'ą' => 'a',+ 'ç' | 'ć' | 'č' => 'c',+ 'è'..='ë' | 'ē' | 'ě' | 'ę' | 'ế' | 'ệ' => 'e',+ 'ì'..='ï' | 'ī' => 'i',+ 'ñ' | 'ń' | 'ň' => 'n',+ 'ò'..='ö' | 'ø' | 'ő' => 'o',+ 'ś' | 'š' => 's',+ 'ù'..='ü' | 'ū' | 'ů' | 'ű' => 'u',+ 'ý' | 'ÿ' => 'y',+ 'ź' | 'ż' | 'ž' => 'z',+ c => c,+ })+ .collect()+ }++ #[cfg(test)]+ mod tests;++ #[cfg(test)]+ mod picker_order_tests {+ use super::*;++ #[test]+ fn picker_lists_english_first_then_names_alphabetically() {+ let order = Lang::for_picker();+ assert_eq!(order.first().map(|l| l.code()), Some(Lang::EN.code()));+ assert_eq!(order.len(), Lang::all().count());+ let keys: Vec<String> = order[1..].iter().map(|l| name_sort_key(l.name())).collect();+ assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}");+ assert_eq!(name_sort_key("Čeština"), "cestina");+ assert_eq!(name_sort_key("Türkçe"), "turkce");+ }+ }diff --cc crates/ui-egui/src/lib.rsindex 757cef6a7,65bc7e4b1..105e8d2e5--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -31,49 -25,13 +25,15 @@@ macro_rules! tl_ctx$crate::i18n::tr_ctx($crate::i18n::current(), $context, $s)};}-- mod a11y_ui;- mod actions_ui;- mod all_tools_ui;- mod appearance;- mod calc_order_ui;pub mod canvas;mod chrome;- mod combine_grid;+pub mod image_engine;- mod image_pick;+pub use image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};- mod tags_ui;pub use combine_grid::ThumbState as CombineThumb;- mod combine_ui;pub use combine_ui::{Columns as CombineColumns, CombineView, Lock as CombineLock, SortKey};- mod camera_ui;mod commands;- mod comment_props;- pub mod comments;- mod comments_panel;- mod compare_ui;pub mod control;- mod create_multiple_ui;- mod create_ui;- mod credits;- mod crop;- mod drag_pointer;- mod export_ui;- mod js_ui;- #[cfg(target_os = "macos")]- mod macos_association;- mod marks_ui;- mod measure_ui;mod menus;- mod ocr_ui;- mod optimize_ui;- mod search_ui;- pub mod side_panels;- mod sign_ui;- mod stamps_ui;- mod standards_ui;- mod zoom_snap;/// Header & footer / watermark / background dialog types (tests and automation).pub mod marks {pub use crate::marks_ui::{MarksDraft, PageRange, Subset};@@@ -85,86 -40,17 +42,17 @@@ pub use create_ui::Clippub use link_ui::LinkDraft;pub use optimize_ui::{OptimizeDraft, OptimizeTab};pub use sign_ui::{DigitalIdEntry, SignDraft, SignGraphic, SignStep};- mod autoscroll;mod bidi;- pub mod bulk_fields;mod dialogs;- pub mod edit_text_ui;- pub mod field_table_ui;-pub use edit_text_ui::CropMode;+pub use edit_text_ui::{CropMode, DragTarget, ImageDrag, ImageHandle, ImageSelection};mod editing;- #[cfg(not(target_arch = "wasm32"))]- pub mod file_watch;- mod files;- pub mod fill_sign;- mod fling;- pub mod folders_ui;- mod format_text_ui;- pub mod forms_ui;mod home;- mod icon_data;- pub mod icons;- pub mod last_session;- pub mod last_view;- pub mod motion;- #[cfg(not(target_arch = "wasm32"))]- mod os_clipboard;- mod page_pointer;- mod page_selection_ui;- mod pageboxes;- mod palette;mod panels;- #[cfg(not(target_arch = "wasm32"))]- mod pickers;- pub mod prepare;- mod print_ui;- mod signature_drag;- pub mod units;- mod web_print;- mod word_count_ui;pub use print_ui::{Handling as PrintHandling, OptionsSource, PrintDraft, PrinterSource, Which as PrintWhich, system_printers};- mod redact_ui;pub use redact_ui::{HiddenDraft, PagesDraft as RedactPagesDraft, RedactPrefs, SearchDraft as RedactSearchDraft, SearchMode as RedactSearchMode};pub mod i18n;-- /// [`PdfCraftApp::date_text`] for callers that already borrow other parts of the app.- pub(crate) fn date_text(session: &Session, fmt: Option<&str>) -> Result<String, String> {- let lang = session.date_language().unwrap_or(i18n::current().code());- session.today_text(fmt, Some(lang))- }-- /// Today in Preferences ▸ Date format for stamping into a PDF; refused when it has characters- /// Fill & Sign can't write yet (see [`pdfcraft_engine::dates::unwritable`]).- pub(crate) fn date_text_for_pdf(session: &Session) -> Result<String, String> {- let lang = session.date_language().unwrap_or(i18n::current().code());- session.today_text_for_pdf(None, Some(lang))- }-- /// The longest author name kept (Preferences ▸ Identity, restored settings).- pub(crate) const MAX_AUTHOR_CHARS: usize = 200;-- #[cfg(not(target_arch = "wasm32"))]- mod open_worker;- mod organize_panel;- pub mod portable;- mod protect;- mod recovery;- pub mod scroll_speed;- #[cfg(not(target_arch = "wasm32"))]- mod system_fonts;- mod tab_context;pub mod theme;- pub mod ui_scale;- pub mod updates;- mod wheel_boost;- mod wheel_pager;mod widgets;- pub mod window_controls;- #[cfg(not(target_arch = "wasm32"))]- pub mod window_state;-- #[cfg(all(test, not(target_arch = "wasm32")))]- mod open_worker_tests;use pdfcraft_engine::{DocId, Session};@@@ -174,113 -60,109 +62,112 @@@ pub use files::{ExtractDraft, FilePurpopub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore};use theme::{ThemeKind, ThemePreference};- /// Top-level workspace modes (Acrobat's mode bar).- #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]- #[serde(rename_all = "lowercase")]- pub enum Mode {- #[serde(rename = "all")]- AllTools,- Read,- Edit,- Convert,- Sign,- }-- impl Mode {- fn parse(value: &str) -> Option<Self> {- match value {- "all" => Some(Self::AllTools),- "read" => Some(Self::Read),- "edit" => Some(Self::Edit),- "convert" => Some(Self::Convert),- "sign" => Some(Self::Sign),- _ => None,- }- }- }-- /// What the left panel shows.- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum LeftPanel {- AllTools,- Tool(&'static str),- /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.- CalculationOrder,- }-- /// Right-hand panels, opened from the rail.- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]- pub enum RightPanel {- Comments,- Bookmarks,- Pages,- Fields,- Layers,- Attachments,- Signatures,- /// Accessibility Checker results.- Accessibility,- /// Reachable PDF structure tags and their properties.- Tags,- /// Advanced Search results.- Search,- /// Compare files: the differences.- Compare,- }-- /// Quick-action bar tools (the vertical floating strip).- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum QuickTool {- Select,- Hand,- /// A commenting tool (Add comments).- Comment(comments::CommentTool),- Measure(measure_ui::Tool),- /// Crop pages by dragging a rectangle.- Crop,- /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.- EnhanceCamera,- /// A Fill & Sign tool.- Fill(fill_sign::FillTool),- /// A Prepare a form field tool.- Field(prepare::FieldTool),- /// Redact text and images (drag across text or draw a box).- Redact,- /// Edit a PDF ▸ Add content ▸ Text.- AddText,- /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.- EditText,- /// Add a stamp: click to place this stamp.- Stamp(pdfcraft_engine::StampKind),- /// A custom stamp from the library (its index).- CustomStamp(usize),- /// Edit a PDF ▸ Link: draw link areas, select and edit links.- Link,- /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.- SignArea {- certify: bool,- },- /// View ▸ Zoom ▸ Marquee Zoom.- MarqueeZoom,- /// Edit ▸ Take a Snapshot.- Snapshot,- /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The- /// Select tool does the same while Alt/Option is held at the start of a drag.- ColumnSelect,- }+ mod app;+ mod hooks;+ mod persist;+ mod platform;+ mod state;+ mod tools;+ mod workflows;- /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are- /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).- type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);++#[cfg(not(target_arch = "wasm32"))]++pub(crate) mod os_clipboard;+- /// Read a file dropped on a page grid (see [`GridFile`]).- fn read_grid_file((name, source): GridFile) -> Result<(String, Vec<u8>), (String, String)> {- let bytes = match source {- Ok(bytes) => bytes,- Err(path) => std::fs::read(&path).map_err(|e| (name.clone(), e.to_string()))?,- };- Ok((name, bytes))- }+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use app::same_file;+ pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused};+ use canvas::autoscroll;+ use canvas::crop;+ use canvas::fling;+ use canvas::image_pick;+ use canvas::page_pointer;+ pub use canvas::scroll_speed;+ use canvas::signature_drag;+ use canvas::wheel_boost;+ use canvas::wheel_pager;+ use canvas::zoom_snap;+ use dialogs::appearance;+ use dialogs::comment_props;+ use dialogs::credits;+ use dialogs::marks_ui;+ use dialogs::pageboxes;+ use dialogs::palette;+ use dialogs::protect;+ use dialogs::standards_ui;+ use dialogs::word_count_ui;+ pub use home::folders_ui;+ pub use hooks::{FailedInbox, HostDirtyFn, HostSaveFn, Inbox, OsEvent, OsEventsFn};+ use menus::tab_context;+ use panels::all_tools_ui;+ use panels::comments_panel;+ use panels::format_text_ui;+ use panels::organize_panel;+ use panels::page_selection_ui;+ use panels::search_ui;+ pub use panels::side_panels;+ pub use persist::last_session;+ pub use persist::last_view;+ use persist::recovery;+ pub use persist::units;+ #[cfg(not(target_arch = "wasm32"))]+ pub use persist::window_state;+ use platform::drag_pointer;+ #[cfg(not(target_arch = "wasm32"))]+ pub use platform::file_watch;+ #[cfg(target_os = "macos")]+ use platform::macos_association;+ pub use platform::motion;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::open_worker;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::pickers;+ pub use platform::portable;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::system_fonts;+ pub use platform::ui_scale;+ pub use platform::updates;+ pub use platform::window_controls;+ #[cfg(test)]+ use state::CopyPage;+ #[cfg(not(target_arch = "wasm32"))]+ use state::OpenRequest;+ pub use state::{+ CustomDraft, Dialog, DuplicateDraft, LeftPanel, LinkOrigin, Mode, NumberDraft, OpenOutcome, PageClip, PasswordPrompt, PendingLink,+ PendingRemoteLink, PropsTab, QuickTool, RecentFile, RightPanel, UnlockPrompt,+ };+ use state::{DocumentCopyJob, GridFile};+ pub use tools::bulk_fields;+ use tools::calc_order_ui;+ use tools::camera_ui;+ pub use tools::comments;+ use tools::content_ui;+ use tools::edit_text_ui;+ pub use tools::field_table_ui;+ pub use tools::fill_sign;+ pub use tools::forms_ui;+ use tools::link_ui;+ use tools::measure_ui;+ use tools::object_ui;+ pub use tools::prepare;+ use tools::redact_ui;+ use tools::sign_ui;+ use tools::stamps_ui;+ use tools::tags_ui;+ use widgets::icon_data;+ pub use widgets::icons;+ use workflows::a11y_ui;+ use workflows::actions_ui;+ use workflows::combine_grid;+ use workflows::combine_ui;+ use workflows::compare_ui;+ use workflows::create_ui;+ use workflows::export_ui;+ use workflows::files;+ use workflows::js_ui;+ use workflows::ocr_ui;+ use workflows::optimize_ui;+ use workflows::print_ui;+ use workflows::web_print;/// Files dropped on a document's page grid or its Pages panel.struct GridDrop {diff --cc crates/ui-egui/src/panels/edit.rsindex 000000000,e10d0d01e..98e89d310mode 000000,100644..100644--- a/crates/ui-egui/src/panels/edit.rs+++ b/crates/ui-egui/src/panels/edit.rs@@@ -1,0 -1,370 +1,372 @@@+ use super::tools::row_label;+ use super::*;++ /// The page operations Edit shows as a row of icon buttons, as Acrobat's Edit panel does.+ const EDIT_PAGE_BUTTONS: [&str; 4] = ["page.rotate", "page.insert", "page.delete", "page.extract"];++ /// Add content items shown before More.+ const EDIT_CONTENT_SHOWN: usize = 5;++ /// Other options: the tools Acrobat's Edit panel links to.+ const EDIT_OTHER_TOOLS: [&str; 3] = ["combine", "redact", "form"];++ /// Edit a PDF, laid out as Acrobat's Edit panel: the title with Preferences and Close; Format text+ /// while text is being edited or added; Modify page as a row of icon buttons and Organize pages;+ /// Add content with the rarer items under More; and Other options, the neighbouring tools.+ /// Edit text & images itself is on the floating toolbar, and on from the moment Edit opens.+ /// Every item comes from the catalogue, so its label, icon and availability have one source.+ pub(super) fn edit_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static ToolGroup) {+ let items = || g.sections.iter().flat_map(|s| s.items.iter());+ let item = |command: &str| items().find(|i| i.command == command);+ let mut run = None;+ let mut tool = None;+ // Back to All tools only when Edit was opened from there; the Edit tab is its own way back.+ let from_all_tools = app.mode != crate::Mode::Edit;+ ui.horizontal(|ui| {+ if from_all_tools && icons::button(ui, "chevron-left", 26.0, false, tl!("Back to all tools")).clicked() {+ app.left = LeftPanel::AllTools;+ app.enter_mode(crate::Mode::AllTools);+ }+ // "Edit" under the Edit tab, as Acrobat titles it; the tool's own name from All tools.+ let title = if from_all_tools { tl!(g.label) } else { tl!("Edit") };+ let title_width = (ui.available_width() - 2.0 * (26.0 + ui.spacing().item_spacing.x)).max(1.0);+ ui.add_sized([title_width, 26.0], egui::Label::new(egui::RichText::new(title).font(theme::semibold(15.5)).color(t.text)).truncate())+ .on_hover_text(title);+ if icons::button(ui, "settings", 26.0, false, tl!("Preferences")).clicked() {+ run = Some("app.preferences");+ }+ if icons::button(ui, "x", 26.0, false, tl!("Close panel")).clicked() {+ app.left_open = false;+ }+ });+ ui.add_space(4.0);+ ui.separator();+ ui.add_space(6.0);+ // Several objects selected: how many, and how to move them. Acrobat's panel has no idle hint.+ let count = app.active_ids().filter(|_| app.quick_tool == crate::QuickTool::EditText).map_or(0, |(i, _)| app.views[i].objects.count());+ if count > 0 {+ ui.label(crate::i18n::trn(crate::i18n::current(), count as u64, "{n} object selected", "{n} objects selected"));+ ui.label(tl!("Drag the selection to move it. Esc clears the selection."));+ ui.add_space(6.0);+ }+ // Format text at the top while text is selected or being added.+ format_section(app, ui, t);+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {+ widgets::section_title(ui, tl!("Modify page"));+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 6.0;+ for i in EDIT_PAGE_BUTTONS.iter().filter_map(|c| item(c)) {+ // Enabled as the command itself is: a document that forbids page assembly refuses these.+ let enabled = pdfcraft_engine::commands::command(i.command).is_some_and(|spec| app.command_enabled(spec));+ let resp = ui.add_enabled_ui(enabled, |ui| icons::button(ui, i.icon, 34.0, false, tl!(i.label))).inner;+ if resp.clicked() {+ run = Some(i.command);+ }+ }+ });+ ui.add_space(2.0);+ // Organize pages is a workspace of its own: its panel replaces this one, with the grid.+ if let Some(i) = item("page.organize")+ && edit_row(ui, t, i.icon, tl!(i.label), i.availability).clicked()+ {+ // With no document there is no grid to open: the command asks for a file first.+ if app.active.is_some() {+ tool = Some("organize");+ } else {+ run = Some("page.organize");+ }+ }++ widgets::section_title(ui, tl!("Add content"));+ let content: Vec<_> =+ g.sections.iter().filter(|s| s.title == "Add content").flat_map(|s| s.items.iter()).filter(|i| i.command != "edit.edit_text").collect();+ let more_id = egui::Id::unique("edit_panel_more");+ let more = ui.data(|d| d.get_temp::<bool>(more_id)).unwrap_or(false);+ let shown = if more { content.len() } else { EDIT_CONTENT_SHOWN.min(content.len()) };+ for i in content.iter().take(shown) {+ let resp = edit_row(ui, t, i.icon, tl!(i.label), i.availability);+ // Header and footer, Watermark and Background open their Add / Update / Remove menu.+ if i.actions.is_empty() {+ if resp.clicked() {+ run = Some(i.command);+ }+ } else if let Some(cmd) = actions_menu(app, ui, &resp, i, resp.rect.right_center() - vec2(14.0, 0.0), t.text) {+ run = Some(cmd);+ }+ }+ if content.len() > EDIT_CONTENT_SHOWN {+ ui.add_space(4.0);+ let label = if more { tl!("Less") } else { tl!("More") };+ let resp = ui+ .add(+ egui::Label::new(egui::RichText::new(label).color(t.accent_text).font(theme::medium(13.0)))+ .selectable(false)+ .sense(Sense::click()),+ )+ .on_hover_cursor(egui::CursorIcon::PointingHand);+ if resp.clicked() {+ ui.data_mut(|d| d.insert_temp(more_id, !more));+ }+ }++ widgets::section_title(ui, tl!("Other options"));+ for other in EDIT_OTHER_TOOLS.iter().filter_map(|id| catalog::group(id)) {+ if edit_row(ui, t, other.icon, tl!(other.label), other.availability).clicked() {+ tool = Some(other.id);+ }+ }+ });+ if let Some(id) = tool {+ app.select_tool(id);+ }+ if let Some(cmd) = run {+ app.run_command(cmd);+ }+ }++ /// A tool entry with further commands (Add / Update / Remove): a caret at `caret` says it opens a+ /// menu, and each command is enabled by its own needs. Returns the command chosen.+ pub(super) fn actions_menu(+ app: &PdfCraftApp,+ ui: &egui::Ui,+ resp: &egui::Response,+ item: &ToolItem,+ caret: egui::Pos2,+ color: Color32,+ ) -> Option<&'static str> {+ ui.painter().add(egui::Shape::convex_polygon(+ vec![caret + vec2(-3.5, -2.0), caret + vec2(3.5, -2.0), caret + vec2(0.0, 2.5)],+ color,+ egui::Stroke::NONE,+ ));+ let mut run = None;+ egui::Popup::menu(resp).show(|ui| {+ ui.set_min_width(180.0);+ for (n, id) in item.actions.iter().enumerate() {+ let Some(spec) = pdfcraft_engine::commands::command(id) else { continue };+ // Add stays usable with no document open: it asks for a file first.+ let enabled = (n == 0 && app.active.is_none()) || app.command_enabled(spec);+ let label = crate::i18n::menu_label(spec.id, spec.label);+ if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {+ run = Some(spec.id);+ ui.close();+ }+ }+ });+ run+ }++ /// One row of the Edit panel: a monochrome icon and the label, as Acrobat draws them. A planned+ /// item is muted and says when it ships when hovered.+ fn edit_row(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str, availability: Availability) -> egui::Response {+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));+ let press = theme::Press::track(ui, &resp);+ press.wash(ui, rect, 6, false);+ let body = rect.translate(press.offset());+ let ready = availability == Availability::Ready;+ let fg = if ready { t.text } else { t.text_muted };+ icons::paint(ui, Rect::from_min_size(body.min + vec2(6.0, 8.0), vec2(18.0, 18.0)), icon, 17.0, if ready { t.text } else { t.text_faint });+ row_label(ui, label, theme::regular(13.5), fg, body.left_center() + vec2(34.0, 0.0), rect.width() - 42.0);+ let resp = theme::hand(resp);+ match availability {+ Availability::Ready => resp,+ Availability::Planned(m) => resp.on_hover_text(format!("{} {m}", tl!("Planned for milestone"))),+ Availability::Provider => resp.on_hover_text(tl!("Optional: needs an AI provider you configure")),+ }+ }++ /// Add a stamp: Dynamic, Sign Here and Standard Business stamps; click one, then click on the+ /// page to place it.+ pub(super) fn stamp_palette(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {+ use pdfcraft_engine::{StampGroup, StampKind};+ ui.label(egui::RichText::new(tl!("Choose a stamp, then click on the page to place it.")).small().color(t.text_faint));+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {+ for (group, title) in [+ (StampGroup::Dynamic, tl!("Dynamic")),+ (StampGroup::SignHere, tl!("Sign Here")),+ (StampGroup::StandardBusiness, tl!("Standard Business")),+ ] {+ widgets::section_title(ui, title);+ for kind in StampKind::ALL.into_iter().filter(|k| k.group() == group) {+ let active = app.quick_tool == crate::QuickTool::Stamp(kind);+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, kind.label()));+ let press = theme::Press::track(ui, &resp);+ press.wash(ui, rect, 6, active);+ let body = rect.translate(press.offset());+ let [r, g, b] = kind.color().map(|v| (v * 255.0) as u8);+ let col = Color32::from_rgb(r, g, b);+ let chip = Rect::from_min_size(body.min + vec2(8.0, 5.0), vec2((rect.width() - 16.0).min(200.0), 28.0));+ if group == StampGroup::SignHere {+ let tip = chip.height() * 0.45;+ let pts = vec![+ chip.left_center(),+ chip.left_top() + vec2(tip, 0.0),+ chip.right_top(),+ chip.right_bottom(),+ chip.left_bottom() + vec2(tip, 0.0),+ ];+ ui.painter().add(egui::Shape::convex_polygon(pts, col, Stroke::NONE));+ let label = kind.label();+ let font = theme::semibold(11.0);+ let shown = crate::widgets::fit_line(label, (chip.width() - 10.0).max(0.0), |s| crate::widgets::text_width(ui, s, &font));+ ui.painter().with_clip_rect(chip.shrink(3.0)).text(+ chip.center() + vec2(tip / 2.0, 0.0),+ Align2::CENTER_CENTER,+ shown,+ font,+ Color32::WHITE,+ );+ } else {+ ui.painter().rect(chip, CornerRadius::same(5), col.gamma_multiply(0.1), Stroke::new(1.5, col), egui::StrokeKind::Inside);+ let y = if group == StampGroup::Dynamic { chip.center().y - 4.0 } else { chip.center().y };+ let font = theme::semibold(11.0);+ let shown = crate::widgets::fit_line(kind.label(), (chip.width() - 10.0).max(0.0), |s| crate::widgets::text_width(ui, s, &font));+ ui.painter().with_clip_rect(chip.shrink(3.0)).text(egui::pos2(chip.center().x, y), Align2::CENTER_CENTER, shown, font, col);+ if group == StampGroup::Dynamic {+ let by = "By name at time, date";+ let by_font = theme::regular(7.5);+ let by_shown = crate::widgets::fit_line(by, (chip.width() - 8.0).max(0.0), |s| crate::widgets::text_width(ui, s, &by_font));+ ui.painter().with_clip_rect(chip.shrink(2.0)).text(+ egui::pos2(chip.center().x, chip.bottom() - 6.0),+ Align2::CENTER_CENTER,+ by_shown,+ by_font,+ col,+ );+ }+ }+ if theme::hand(resp).clicked() {+ app.quick_tool = crate::QuickTool::Stamp(kind);+ }+ }+ }+ crate::stamps_ui::palette_section(app, ui, t);+ });+ }++ /// Edit a PDF ▸ Format text: for the selected added text (one undoable change), or the style+ /// new text gets.+ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {+ // Editing a paragraph of existing text: its formatting, applied as it changes.+ if let Some((i, _)) = app.active_ids()+ && let Some(ed) = app.views[i].line_editor.clone()+ {+ use crate::format_text_ui::{FontChoice, Fonts};+ let mut ed = ed;+ let sources: Vec<(String, String)> = app+ .session+ .get(app.views[i].id)+ .map(|d| d.text_editor_fonts(ed.page))+ .unwrap_or_default()+ .into_iter()+ .map(|f| (f.resource, f.face))+ .collect();- let shown = ed.font_shown(&sources);- let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown });++ let fmt = ed.selection_formatting(&sources);++ let shown = fmt.font_shown;++ let mixed_size = fmt.size.is_none();++ let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown, mixed_size });+ let mut changed = out.changed;+ match out.font {+ Some(FontChoice::KeepSource) => {+ ed.keep_source_font();+ changed = true;+ }+ Some(FontChoice::Resource(resource)) => {+ ed.font_resource = Some(resource);+ changed = true;+ }+ Some(FontChoice::Family(family)) => {+ ed.choose_family(family);+ changed = true;+ }+ Some(FontChoice::Load) => app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false),+ #[cfg(not(target_arch = "wasm32"))]+ Some(FontChoice::Installed(path)) => app.use_paths(crate::files::FilePurpose::TextFont { page: ed.page }, &[path]),+ #[cfg(target_arch = "wasm32")]+ Some(FontChoice::Installed(_)) => {}+ None => {}+ }+ if changed {+ app.apply_line_format(i, ed, Some(ui.ctx()));+ }+ return;+ }+ let image = app.active_ids().and_then(|(i, id)| {+ let (page, index) = app.views[i].content.selected?;+ let doc = app.session.get(id)?;+ match &doc.added().iter().filter(|a| a.page == page).nth(index)?.content {+ pdfcraft_engine::AddedContent::Image(img) => Some((page, index, img.clone())),+ _ => None,+ }+ });+ if let Some((page, index, img)) = image {+ match crate::content_ui::image_panel(ui, t, &img) {+ Some(crate::content_ui::ImageAction::Update(content)) => {+ app.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index, content });+ }+ Some(crate::content_ui::ImageAction::Replace) => app.replace_image_dialog(page, index),+ None => {}+ }+ ui.add_space(6.0);+ ui.separator();+ return;+ }+ let selected = app.active_ids().and_then(|(i, id)| {+ let (page, index) = app.views[i].content.selected?;+ let doc = app.session.get(id)?;+ let a = doc.added().iter().filter(|a| a.page == page).nth(index)?;+ match &a.content {+ pdfcraft_engine::AddedContent::Text(text) => Some((page, index, text.clone())),+ _ => None,+ }+ });+ match selected {+ Some((page, index, text)) => {+ let mut style = text.clone();+ added_text_format(ui, t, &mut style);+ if style != text {+ // The reusable style follows the selection only when the edit took, so a refused one adds nothing odd later.+ if app.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index, content: pdfcraft_engine::AddedContent::Text(style.clone()) }) {+ app.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], ..style };+ }+ }+ }+ None if app.quick_tool == crate::QuickTool::AddText => {+ crate::content_ui::hint(ui, t);+ let mut style = app.text_style.clone();+ added_text_format(ui, t, &mut style);+ app.text_style = style;+ }+ None => {}+ }+ }++ /// Format text for added text: the standard families, size, colour, style and alignment.+ fn added_text_format(ui: &mut egui::Ui, t: &Tokens, style: &mut pdfcraft_engine::AddedText) {+ let shown = style.family.label().to_string();- let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown });++ let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown, mixed_size: false });+ if let Some(crate::format_text_ui::FontChoice::Family(family)) = out.font {+ style.family = family;+ }+ }++ impl PdfCraftApp {+ /// Apply the open paragraph's formatting as one change; the paragraph stays open.+ pub(crate) fn apply_line_format(&mut self, index: usize, mut ed: crate::edit_text_ui::LineEditor, ctx: Option<&egui::Context>) {+ let edit = pdfcraft_engine::Edit::EditTextBlock { page: ed.page, block: ed.block, text: ed.text.clone(), style: ed.style() };+ if self.apply_edit(edit) {+ ed.applied();+ if let Some(doc) = self.session.get(self.views[index].id)+ && let Some(block) = doc.text_blocks(ed.page).get(ed.block)+ {+ ed.refresh_source(block, doc.text_lines(ed.page));+ if let Some(ctx) = ctx {+ ed.fonts = crate::edit_text_ui::install_source_fonts(ctx, doc, ed.page);+ }+ }+ }+ self.views[index].line_editor = Some(ed);+ }+ }diff --cc crates/ui-egui/src/platform/motion.rsindex 000000000,92ca469da..316f82076mode 000000,100644..100644--- a/crates/ui-egui/src/platform/motion.rs+++ b/crates/ui-egui/src/platform/motion.rs@@@ -1,0 -1,285 +1,285 @@@+ //! Animation effects, and the system's request to do without them.+ //!+ //! Windows' Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects, turned off, asks+ //! apps not to animate (other systems have a Reduce motion switch for it). The desktop app+ //! reads the setting ([`MotionSource`]), and Preferences ▸ Animation effects+ //! ([`AnimationEffects`]) follows it unless the user chose On or Off there. With animation+ //! effects off, nothing in the window eases:+ //!+ //! - A wheel notch scrolls its whole distance in the frame it arrives. egui spreads a notch+ //! over about a quarter of a second and has no switch for that, so each frame's wheel input-//! is read again here, the way egui reads it but for the easing ([`WheelReader`]), and handed++//! is read again here, the way egui reads it but for the easing (`WheelReader`), and handed+ //! to egui's scroll areas in place of its own.+ //! - ⌘/Ctrl-wheel zooms by a notch's whole step at once: egui makes its zoom factor from the-//! same eased wheel motion. Views read [`zoom_delta`] instead of egui's.++//! same eased wheel motion. Views read `zoom_delta` instead of egui's.+ //! - Scrolling to a place (a row revealed by the keys, the Hand tool's drag) takes no time.+ //! - egui's other animations (menus fading in, sections opening) take no time: its style's-//! animation time is zero, which the app's own fades and sweeps ask about too ([`animated`]).++//! animation time is zero, which the app's own fades and sweeps ask about too (`animated`).+ //!+ //! How far anything scrolls or zooms doesn't change, only how long it takes.++ use egui::style::ScrollAnimation;+ use egui::{Event, Modifiers, MouseWheelUnit, TouchPhase, Vec2, vec2};++ /// Preferences ▸ Animation effects: whether anything in the window is animated, the wheel's+ /// scrolling and zooming included.+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+ #[serde(rename_all = "lowercase")]+ pub enum AnimationEffects {+ /// Animated unless the system asks for no animations ([`Motion::reduced`]).+ #[default]+ System,+ On,+ Off,+ }++ impl AnimationEffects {+ pub const ALL: [Self; 3] = [Self::System, Self::On, Self::Off];++ pub fn label(self) -> &'static str {+ match self {+ Self::System => "Use system setting",+ Self::On => "On",+ Self::Off => "Off",+ }+ }++ /// The name in saved settings and on the control channel.+ pub fn name(self) -> &'static str {+ match self {+ Self::System => "system",+ Self::On => "on",+ Self::Off => "off",+ }+ }++ pub fn parse(value: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|choice| choice.name().eq_ignore_ascii_case(value))+ }++ /// Whether the window animates, given whether the system asks for no animations.+ pub fn animates(self, system_reduced: bool) -> bool {+ match self {+ Self::System => !system_reduced,+ Self::On => true,+ Self::Off => false,+ }+ }+ }++ /// Asks the system whether it wants no animations; `None` when it can't say, which leaves the-/// last answer standing. Asked from the UI thread every [`ASK_EVERY`] seconds while the window++/// last answer standing. Asked from the UI thread every `ASK_EVERY` seconds while the window+ /// is in use, so it must answer at once.+ pub type MotionSource = Box<dyn Fn() -> Option<bool>>;++ /// Seconds between two questions to [`MotionSource`]. Changing the setting takes longer than+ /// this away from the window, so the first frame back already follows it.+ const ASK_EVERY: f64 = 2.0;++ /// What the system says about animations, and what it takes to stop egui's.+ pub struct Motion {+ /// The system asks for no animations. The desktop app's [`Self::source`] sets it; false+ /// elsewhere, so tests and screenshots don't depend on the machine.+ pub reduced: bool,+ /// How to ask the system (the desktop app sets it).+ pub source: Option<MotionSource>,+ /// egui time of the last question.+ asked_at: f64,+ /// egui's own animation time and scroll animation, kept while they are changed here.+ egui_times: Option<(f32, ScrollAnimation)>,+ wheel: WheelReader,+ /// This frame's wheel motion, read on its first pass and reused on later passes.+ ///+ /// egui empties `RawInput` between the passes of a multi-pass frame, so reading the wheel+ /// again in a later pass sees nothing. Only the first pass is handed the motion (a scroll+ /// area keeps the offset it moved to, a view keeps the zoom it set); later passes are handed+ /// no scroll and a unit zoom, explicitly.+ frame: Option<(u64, WheelMotion)>,+ }++ impl Default for Motion {+ /// Start motion handling with animations enabled and no desktop preference sampled yet.+ fn default() -> Self {+ Self { reduced: false, source: None, asked_at: f64::NEG_INFINITY, egui_times: None, wheel: WheelReader::default(), frame: None }+ }+ }++ impl Motion {+ /// Call once at the start of every pass, before any ui reads the wheel or draws.+ pub(crate) fn begin_pass(&mut self, ctx: &egui::Context, effects: AnimationEffects) {+ let now = ctx.input(|i| i.time);+ // `>=` is false for a NaN time, which then never asks.+ if now - self.asked_at >= ASK_EVERY+ && let Some(source) = &self.source+ {+ self.asked_at = now;+ if let Some(reduced) = source() {+ self.reduced = reduced;+ }+ }+ let animate = effects.animates(self.reduced);+ self.sync_style(ctx, animate);+ if animate {+ // A gesture begun while easing is egui's to finish.+ self.wheel = WheelReader::default();+ self.frame = None;+ return;+ }+ let options = ctx.options(|o| o.input_options);+ // One frame may run several passes (`request_discard`). Only the first pass has this+ // frame's events, and only it may hand the wheel on: a scroll area applies the delta to+ // its persisted offset, and a view multiplies the zoom into its persisted zoom, so+ // replaying either would apply it twice. egui also rebuilds `smooth_scroll_delta` and+ // its zoom factor from its retained wheel state every pass, so later passes must be+ // given zero scroll and a unit zoom explicitly. A missing zoom entry would not do: it+ // would fall back to egui's rebuilt factor.+ let frame = ctx.cumulative_frame_nr();+ let first_pass = match self.frame {+ Some((read_in, _)) => read_in != frame,+ None => true,+ };+ let motion = match self.frame {+ Some((read_in, motion)) if read_in == frame => motion,+ _ => {+ let motion = ctx.input(|i| self.wheel.read(&i.events, i.viewport_rect().height(), &options));+ self.frame = Some((frame, motion));+ motion+ }+ };+ let (scroll, zoom) = if first_pass { (motion.scroll, motion.zoom) } else { (Vec2::ZERO, 1.0) };+ ctx.input_mut(|i| i.smooth_scroll_delta = scroll);+ let pass = ctx.cumulative_pass_nr();+ ctx.data_mut(|d| d.insert_temp(zoom_id(), (pass, zoom)));+ // Existing kinetic scrolling remains owned by egui; gating wheel input does not+ // suppress a scroll area's per-pass advancement of retained velocity.+ }++ /// egui's animations, and its scrolling to a place, take no time unless the window is to+ /// `animate`; then both get back the times egui had.+ fn sync_style(&mut self, ctx: &egui::Context, animate: bool) {+ if animate && self.egui_times.is_none() {+ return;+ }+ // Checked every pass, so a style replaced since can't bring the animations back.+ let style = ctx.global_style();+ let egui_times = *self.egui_times.get_or_insert((style.animation_time, style.scroll_animation));+ let wanted = if animate { egui_times } else { (0.0, ScrollAnimation::none()) };+ if (style.animation_time, style.scroll_animation) != wanted {+ ctx.all_styles_mut(|s| (s.animation_time, s.scroll_animation) = wanted);+ }+ if animate {+ self.egui_times = None;+ }+ }+ }++ /// Whether the window animates this pass. The app's own fades and sweeps, which have their own+ /// durations, ask this; egui's animations stop by themselves ([`Motion::begin_pass`]).+ pub(crate) fn animated(ctx: &egui::Context) -> bool {+ ctx.global_style().animation_time > 0.0+ }++ /// Return the stable egui id holding the last wheel-zoom input state.+ fn zoom_id() -> egui::Id {+ egui::Id::unique("pdfcraft-motion-wheel-zoom")+ }++ /// This pass's zoom factor from a pinch or ⌘/Ctrl with the wheel (1.0 for none): egui's+ /// `zoom_delta`, without the easing while animation effects are off.+ pub(crate) fn zoom_delta(ctx: &egui::Context) -> f32 {+ let read: Option<(u64, f32)> = ctx.data(|d| d.get_temp(zoom_id()));+ let pass = ctx.cumulative_pass_nr();+ ctx.input(|i| match read {+ // Only what [`Motion::begin_pass`] read in this very pass: a factor left from an earlier+ // one would zoom again every frame. Fingers on a touch screen are measured, never eased.+ Some((at, zoom)) if at == pass && i.multi_touch().is_none() => zoom,+ _ => i.zoom_delta(),+ })+ }++ /// One pass's wheel input.+ #[derive(Clone, Copy, Debug, PartialEq)]+ struct WheelMotion {+ /// Points to scroll by, as `InputState::smooth_scroll_delta` gives them (positive moves the+ /// content right and down).+ scroll: Vec2,+ /// The zoom factor from pinch events and ⌘/Ctrl with the wheel.+ zoom: f32,+ }++ /// Reads wheel events as egui's `WheelState` does (egui 0.36, `input_state/wheel_state.rs`):+ /// the same units, modifiers and touch phases, but every step lands whole in its own pass,+ /// where egui keeps part of a coarse one for later passes. Compare the two when updating egui;+ /// `tests::reading_at_once_goes_as_far_as_egui_eases` fails if they come apart.+ #[derive(Default)]+ struct WheelReader {+ /// The modifiers of the touch gesture in progress (`TouchPhase::Start` to `End`). They hold+ /// for the whole gesture, as in egui: its momentum arrives after the keys are let go.+ touch: Option<Modifiers>,+ }++ impl WheelReader {+ /// `page_height` is what one `MouseWheelUnit::Page` scrolls: the window's height in points.+ fn read(&mut self, events: &[Event], page_height: f32, options: &egui::InputOptions) -> WheelMotion {+ let mut delta = Vec2::ZERO;+ let mut zoom = 1.0_f32;+ let mut modifiers = self.touch.unwrap_or_default();+ for event in events {+ match event {+ Event::MouseWheel { unit, delta: step, phase, modifiers: latest, .. } => match phase {+ TouchPhase::Start => {+ self.touch = Some(*latest);+ modifiers = *latest;+ }+ TouchPhase::Move => {+ modifiers = match &mut self.touch {+ Some(held) => {+ *held |= *latest;+ *held+ }+ None => *latest,+ };+ let mut step = match unit {+ MouseWheelUnit::Point => *step,+ MouseWheelUnit::Line => options.line_scroll_speed * *step,+ MouseWheelUnit::Page => page_height * *step,+ };+ let horizontal = modifiers.matches_any(options.horizontal_scroll_modifier);+ let vertical = modifiers.matches_any(options.vertical_scroll_modifier);+ if horizontal && !vertical {+ step = vec2(step.x + step.y, 0.0);+ }+ if !horizontal && vertical {+ step = vec2(0.0, step.x + step.y);+ }+ // The system's numbers: one that isn't finite would end up in a scroll offset.+ if step.x.is_finite() && step.y.is_finite() {+ delta += step;+ }+ }+ // egui drops what the gesture moved earlier in the pass it ends in.+ TouchPhase::End | TouchPhase::Cancel => {+ self.touch = None;+ modifiers = Modifiers::NONE;+ delta = Vec2::ZERO;+ }+ },+ Event::Zoom(factor) => zoom *= *factor,+ _ => {}+ }+ }+ // A pass is all zoom or all scroll, by the modifiers it ends with, as in egui.+ let mut scroll = delta;+ if modifiers.matches_any(options.zoom_modifier) {+ zoom *= (options.scroll_zoom_speed * (delta.x + delta.y)).exp();+ scroll = Vec2::ZERO;+ }+ if !(zoom.is_finite() && zoom > 0.0) {+ zoom = 1.0;+ }+ WheelMotion { scroll, zoom }+ }+ }++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/state.rsindex 000000000,dd3b3e90a..e65565f2amode 000000,100644..100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@@ -1,0 -1,417 +1,419 @@@+ use super::*;++ /// Top-level workspace modes (Acrobat's mode bar).+ #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+ #[serde(rename_all = "lowercase")]+ pub enum Mode {+ #[serde(rename = "all")]+ AllTools,+ Read,+ Edit,+ Convert,+ Sign,+ }++ impl Mode {+ pub(crate) fn parse(value: &str) -> Option<Self> {+ match value {+ "all" => Some(Self::AllTools),+ "read" => Some(Self::Read),+ "edit" => Some(Self::Edit),+ "convert" => Some(Self::Convert),+ "sign" => Some(Self::Sign),+ _ => None,+ }+ }+ }++ /// What the left panel shows.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum LeftPanel {+ AllTools,+ Tool(&'static str),+ /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.+ CalculationOrder,+ }++ /// Right-hand panels, opened from the rail.+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]+ pub enum RightPanel {+ Comments,+ Bookmarks,+ Pages,+ Fields,+ Layers,+ Attachments,+ Signatures,+ /// Accessibility Checker results.+ Accessibility,+ /// Reachable PDF structure tags and their properties.+ Tags,+ /// Advanced Search results.+ Search,+ /// Compare files: the differences.+ Compare,+ }++ /// Quick-action bar tools (the vertical floating strip).+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum QuickTool {+ Select,+ Hand,+ /// A commenting tool (Add comments).+ Comment(comments::CommentTool),+ Measure(measure_ui::Tool),+ /// Crop pages by dragging a rectangle.+ Crop,+ /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.+ EnhanceCamera,+ /// A Fill & Sign tool.+ Fill(fill_sign::FillTool),+ /// A Prepare a form field tool.+ Field(prepare::FieldTool),+ /// Redact text and images (drag across text or draw a box).+ Redact,+ /// Edit a PDF ▸ Add content ▸ Text.+ AddText,+ /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.+ EditText,+ /// Add a stamp: click to place this stamp.+ Stamp(pdfcraft_engine::StampKind),+ /// A custom stamp from the library (its index).+ CustomStamp(usize),+ /// Edit a PDF ▸ Link: draw link areas, select and edit links.+ Link,+ /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.+ SignArea {+ certify: bool,+ },+ /// View ▸ Zoom ▸ Marquee Zoom.+ MarqueeZoom,+ /// Edit ▸ Take a Snapshot.+ Snapshot,+ /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The+ /// Select tool does the same while Alt/Option is held at the start of a drag.+ ColumnSelect,+ }++ /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are+ /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).+ pub(crate) type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum Dialog {+ WordCount,+ CreateImages,+ Properties(PropsTab),+ About,+ Shortcuts,+ Split,+ /// Pages ▸ Number pages… (page labels).+ NumberPages,+ /// Protect Using Password.+ Protect,+ /// Set Page Boxes (crop, trim, bleed, art, media).+ PageBoxes,+ /// Add / Update Header and Footer, Watermark, Background.+ Marks(pdfcraft_engine::MarkKind),+ /// Export a PDF ▸ Image / Text.+ Export(export_ui::ExportKind),+ /// Fill & Sign ▸ Create signature (the drawing pad).+ Signature,+ /// Comment Properties.+ CommentProps,+ /// Replace Pages (after choosing the file).+ ReplacePages,+ /// Prepare a form ▸ Field Properties.+ FieldProps,+ /// Shared properties of several selected form fields.+ BulkFieldProps,+ /// Redact a PDF ▸ Redact pages, Find text and redact, Set properties, apply confirmation.+ RedactPages,+ RedactSearch,+ RedactProps,+ RedactApply,+ /// File ▸ Print.+ Print,+ /// File ▸ Revert confirmation.+ Revert,+ /// Save over a file that changed on disk since the document came from it (#2166).+ OverwriteChanged,+ /// Link Properties.+ LinkProps,+ /// Organize ▸ Extract (options), Rotate Pages.+ Extract,+ RotatePages,+ /// Remove Hidden Information and Sanitize Document.+ RemoveHidden,+ Sanitize,+ /// Documents from a session that ended unexpectedly.+ Recovery,+ /// Comments ▸ Summarize comments (options).+ SummarizeComments,+ /// Sign with a Digital ID ▸ Configure ▸ Sign as.+ Sign,+ /// Optimize PDF ▸ Advanced optimization.+ Optimize,+ /// Prepare a form ▸ right-click a field ▸ Duplicate.+ DuplicateField,+ /// Prepare a form ▸ Text field table: a movable window rather than a modal (`field_table_ui`).+ FieldTable,+ /// Check for accessibility ▸ Accessibility Checker Options.+ AccessibilityOptions,+ /// Scan & OCR ▸ Recognize text.+ RecognizeText,+ /// The JavaScript console (⌘J).+ JsConsole,+ /// Document JavaScripts.+ DocumentJs,+ /// Preferences.+ Preferences,+ /// Compare files: choose the older version.+ CompareFiles,+ /// Action Wizard.+ ActionWizard,+ /// Standards ▸ PDF/A.+ PdfA,+ /// Custom stamps ▸ Create.+ CreateStamp,+ /// Prepare for accessibility ▸ Add alternate text.+ AltText,+ /// PDF Optimizer ▸ Audit space usage (then back to the optimizer).+ AuditSpace,+ /// Signatures ▸ Show certificate.+ CertificateViewer,++ /// Pin tools to Home: selection modal.++ PinTool,+ }++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum PropsTab {+ Description,+ InitialView,+ Security,+ Fonts,+ Custom,+ Advanced,+ SpaceAudit,+ }++ /// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order,+ /// and the Name and Value fields.+ #[derive(Clone, Debug, Default, PartialEq)]+ pub struct CustomDraft {+ pub props: Vec<(String, String)>,+ pub name: String,+ pub value: String,+ }++ /// Duplicate Field: the field and the pages (all, or a range, 1-based).+ #[derive(Clone, Debug, PartialEq)]+ pub struct DuplicateDraft {+ pub name: String,+ pub all: bool,+ pub from: usize,+ pub to: usize,+ }++ /// Copied pages: their document's name and bytes (as it was when copied) and the pages.+ #[derive(Clone, Debug)]+ pub struct PageClip {+ /// The document the pages were copied from: pasting back into it keeps field names.+ pub from: DocId,+ pub name: String,+ pub bytes: std::sync::Arc<Vec<u8>>,+ pub pages: Vec<usize>,+ }++ /// One page of a whole-document copy: its text as read for display, to read, or not to try+ /// (reading it failed before).+ pub(crate) enum CopyPage {+ Read(std::sync::Arc<pdfcraft_render::PageText>),+ ToRead,+ Skip,+ }++ /// What a whole-document copy needs, taken from the view on the UI thread: each page's text+ /// layer as far as it was read, and the document to read the others from.+ pub(crate) struct DocumentCopyJob {+ pub(crate) pages: Vec<CopyPage>,+ bytes: std::sync::Arc<Vec<u8>>,+ password: Option<std::sync::Arc<str>>,+ }++ impl DocumentCopyJob {+ pub(crate) fn of(v: &DocView, doc: &pdfcraft_engine::Document) -> DocumentCopyJob {+ let pages = (0..v.page_count())+ .map(|p| match v.texts.get(&p) {+ Some(t) => CopyPage::Read(t.clone()),+ None if v.text_failed.contains(&p) => CopyPage::Skip,+ None => CopyPage::ToRead,+ })+ .collect();+ DocumentCopyJob { pages, bytes: doc.bytes.clone(), password: doc.password.as_deref().map(std::sync::Arc::from) }+ }++ /// The document's text in page order, a page per line run. Each page read here is let go+ /// once its text is taken, so a large document never holds every page's text layer at once.+ /// `None` when `cancel` was set.+ pub(crate) fn text(self, cancel: &std::sync::atomic::AtomicBool) -> Option<String> {+ let mut renderer: Option<pdfcraft_render::PageRenderer> = None;+ let mut out = String::new();+ let mut push = |text: String| {+ if !text.is_empty() {+ if !out.is_empty() {+ out.push('\n');+ }+ out.push_str(&text);+ }+ };+ for (page, p) in self.pages.into_iter().enumerate() {+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {+ return None;+ }+ match p {+ CopyPage::Read(t) => push(t.text_of(0..t.glyphs.len())),+ CopyPage::ToRead => {+ let r = renderer.get_or_insert_with(|| {+ let config = pdfcraft_render::RenderConfig { password: self.password.clone(), ..Default::default() };+ pdfcraft_render::PageRenderer::new(self.bytes.clone(), config)+ });+ let req = pdfcraft_render::RenderRequest {+ page,+ kind: pdfcraft_render::RequestKind::Text,+ tile: None,+ scale: 1.0,+ tag: 0,+ preview: false,+ };+ if let Some(t) = r.render(req).text {+ push(t.text_of(0..t.glyphs.len()));+ }+ }+ CopyPage::Skip => {}+ }+ }+ Some(out)+ }+ }++ pub struct PasswordPrompt {+ pub name: String,+ pub path: Option<String>,+ pub bytes: std::sync::Arc<Vec<u8>>,+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) stamp: Option<file_watch::Stamp>,+ pub input: String,+ pub error: Option<String>,+ /// A late startup file must stay in the background even after it is unlocked.+ pub(crate) activate: bool,+ /// The bytes are a recovery snapshot: once the document is open it takes the snapshot's+ /// path and recovery entry. Cancelling the prompt drops the association with it (#813).+ pub(crate) recovered: Option<RecoveryMeta>,+ /// The tool that asked for this file (a tool chosen with no document open): it runs once+ /// the document is unlocked.+ pub(crate) then: Option<&'static str>,+ /// A link destination to apply after the linked PDF is unlocked.+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,+ }++ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) struct OpenRequest {+ pub(crate) name: String,+ pub(crate) path: Option<String>,+ pub(crate) stamp: Option<file_watch::Stamp>,+ pub(crate) input: open_worker::Input,+ pub(crate) password: Option<String>,+ pub(crate) activate: bool,+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,+ pub(crate) recovered: Option<RecoveryMeta>,+ pub(crate) then: Option<&'static str>,+ }++ /// Asks for the permissions password of an open document whose security restricts it, which+ /// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed.+ pub struct UnlockPrompt {+ pub doc: DocId,+ pub name: String,+ pub input: String,+ pub error: Option<String>,+ /// The command to run once unlocked (Protect using password, Remove security), if any.+ pub then: Option<&'static str>,+ }++ impl UnlockPrompt {+ pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self {+ Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then }+ }+ }++ #[derive(serde::Serialize, serde::Deserialize)]+ pub struct RecentFile {+ pub name: String,+ pub path: String,+ pub pages: usize,+ pub size: usize,+ }++ /// Where in a document a request to open an address came from.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum LinkOrigin {+ /// A link on the page.+ Link,+ /// A push button's URI action.+ Button,+ /// A script (`app.launchURL`).+ Script,+ }++ impl LinkOrigin {+ pub(crate) fn noun(self) -> &'static str {+ match self {+ Self::Link => "A link",+ Self::Button => "A button",+ Self::Script => "A script",+ }+ }+ }++ /// An address a document asked to open, waiting for the user to allow or cancel it.+ #[derive(Clone, Debug, PartialEq, Eq)]+ pub struct PendingLink {+ pub url: String,+ pub origin: LinkOrigin,+ }++ /// A resolved local target and its original source/destination, independent of the active tab.+ #[derive(Clone, Debug)]+ pub struct PendingRemoteLink {+ pub source: DocId,+ pub path: std::path::PathBuf,+ pub destination: pdfcraft_render::RemoteDestination,+ }++ /// Settings for the Number pages dialog.+ #[derive(Clone, Debug, PartialEq)]+ pub struct NumberDraft {+ pub from: usize,+ pub to: usize,+ pub style: pdfcraft_engine::LabelStyle,+ pub prefix: String,+ pub start: u32,+ }++ /// What [`PdfCraftApp::open_path`] did: opened the file in a new tab, focused the tab already+ /// showing it, handed it to the background open worker, or failed. Failures tell the user+ /// through a toast; this is the programmatic contract for callers that must know (the control+ /// channel, tools that wait for a file) (#1620).+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum OpenOutcome {+ /// The file opened in a new tab (or raised its password prompt).+ Opened,+ /// A tab already showed the file; it was focused and no tab was added.+ Focused,+ /// The file was accepted for opening in the background; its tab appears when the open+ /// completes (`ui.state.pending_opens` lists the files on the way).+ Pending,+ /// The file could not be read or opened; the user was told.+ Failed,+ }diff --cc crates/ui-egui/src/tools/edit_text_ui.rsindex 000000000,66daa6edb..b2317a7a2mode 000000,100644..100644--- a/crates/ui-egui/src/tools/edit_text_ui.rs+++ b/crates/ui-egui/src/tools/edit_text_ui.rs@@@ -1,0 -1,913 +1,1491 @@@-//! Edit a PDF ▸ Edit text & images: boxes around the paragraphs and images already on the page.-//! Click a paragraph to edit it in place (⌘Enter or clicking away applies and rewraps it to the-//! box, Esc cancels); drag it to move it, or drag the handle on its left or right edge to rewrap-//! it to a new width. Click an image to select it: drag to move, drag a corner to resize (keeping-//! its proportions), right-click for rotate, flip, replace, save and delete; Delete removes it.--use std::collections::BTreeMap;-use std::sync::Arc;--use egui::{Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Stroke};-use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};-use pdfcraft_render::DocInfo;--use crate::canvas::{DocView, PageXform};-use crate::page_pointer::PagePointer;--mod background;-mod image;-mod layout;--pub(crate) use background::TextBackground;-pub use image::{CropMode, ImageSelection};-pub(crate) use image::{ImageAction, image_input, image_owns_pointer};-#[cfg(test)]-use image::{rotate_knob, turn_degrees};-#[cfg(test)]-use layout::{DARK_EDITOR_FILL, contrast};-pub(crate) use layout::{caret_color_on, editor_fill, editor_font, install_source_fonts};-use layout::{color32, editor_galley, editor_job, look_of, luminance, unseen};--const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);--#[derive(Clone, Copy, PartialEq)]-enum TextTarget {- Block(usize),- Added(usize),-}--/// How many faint Edit-text outlines are drawn per page per frame. CAD plots can draw-/// ~1000 tiny images on one page; stroking all of them every frame (plus a hover query-/// per box) stalls the UI. Past this, only the selected and hovered boxes are outlined:-/// hit-testing still covers every image, so nothing becomes unselectable.-const MAX_OUTLINES: usize = 250;--/// A paragraph being edited.-#[derive(Clone, Debug, PartialEq)]-pub struct LineEditor {- pub selection: Option<std::ops::Range<usize>>,- pub font_resource: Option<String>,- pub page: usize,- pub block: usize,- pub text: String,- original: String,- rect: Rect,- /// The original PDF rectangle, in user space. It is converted again each frame so the editor- /// stays attached while the page is zoomed, scrolled, or rotated.- source_rect: [f32; 4],- multiline: bool,- source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,- pub(crate) fonts: BTreeMap<String, String>,- /// The draft extends outside the source container; its frame follows the live draft bounds.- pub overflow: bool,- /// The initial source container width in screen pixels.- max_width: f32,- /// Current screen-space size. Recomputed from the current page transform before painting.- size: f32,- /// Take the keyboard focus on the next frame.- pub(crate) focus: bool,- /// Whether the text box had the keyboard at the end of the editor's last frame- /// ([`lost_focus_once`]).- had_focus: bool,- /// The Format text panel's values, and what the paragraph had (to send only changes).- pub look: pdfcraft_engine::AddedText,- look0: pdfcraft_engine::AddedText,- /// A standard family was picked from the font list. The family guessed from a PDF font name- /// (Calibri reads as Helvetica) can be the one picked, so comparing `look` with `look0` alone- /// would miss the choice.- family_chosen: bool,- /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and- /// horizontal scale (%), and what they were.- pub extras: Extras,- extras0: Extras,-}--#[derive(Clone, Copy, Debug, PartialEq)]-pub struct Extras {- pub underline: bool,- pub line_spacing: f64,- pub char_spacing: f64,- pub scale: f64,-}--impl Default for Extras {- fn default() -> Self {- Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }- }-}--impl LineEditor {- /// What Format text's font list shows: the chosen page font, a standard family picked- /// instead, or the paragraph's own font (its `/BaseFont` without the subset tag).- pub(crate) fn font_shown(&self, sources: &[(String, String)]) -> String {- if let Some(face) = self.font_resource.as_ref().and_then(|r| sources.iter().find(|(res, _)| res == r)).map(|(_, face)| face) {- return face.clone();- }- if self.look.family != self.look0.family || self.family_chosen {- return self.look.family.label().to_string();- }- let base = self.source.as_ref().map(|(block, _)| block.base_font.as_str()).unwrap_or_default();- // "ABCDEF+Calibri" is a subset of Calibri.- let name = match base.split_once('+') {- Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,- _ => base,- };- if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }- }-- /// Back to the paragraph's own font: no page font chosen and the family it started with.- pub(crate) fn keep_source_font(&mut self) {- self.font_resource = None;- self.look.family = self.look0.family;- self.family_chosen = false;- }-- /// A standard family picked from the font list, replacing the paragraph's font even when it- /// is the family the paragraph's font name reads as.- pub(crate) fn choose_family(&mut self, family: pdfcraft_engine::FontFamily) {- self.font_resource = None;- self.look.family = family;- self.family_chosen = true;- }-- pub(crate) fn has_changes(&self) -> bool {- self.changes_with(&self.text)- }-- /// Whether the paragraph with `text` in it differs from what was opened.- fn changes_with(&self, text: &str) -> bool {- text != self.original || self.look != self.look0 || self.extras != self.extras0 || self.family_chosen- }-- /// Extra width permitted by the editor. Source containers now remain fixed.- pub fn growth(&self) -> Option<f32> {- (self.max_width > self.rect.width()).then_some(self.max_width)- }-- /// Whether the edited text differs from the original (unsaved changes).- pub fn has_unsaved_text(&self) -> bool {- self.text != self.original- }-- /// The formatting the panel changed.- pub fn style(&self) -> pdfcraft_engine::BlockStyle {- let (l, o) = (&self.look, &self.look0);- let mut style = pdfcraft_engine::BlockStyle {- resource: self.font_resource.clone(),- family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),- size: (l.size != o.size).then_some(l.size),- color: (l.color != o.color).then_some(l.color),- align: (l.align != o.align).then_some(l.align),- underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),- line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0)- .then_some(self.extras.line_spacing),- char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing),- scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale),- ..Default::default()- };- if let Some(range) = &self.selection- && (style.family.is_some()- || style.resource.is_some()- || style.size.is_some()- || style.color.is_some()- || style.underline.is_some()- || style.char_spacing.is_some()- || style.scale.is_some())- {- style.ranges.push(pdfcraft_engine::RangeStyle {- range: range.clone(),- family: style.family.take(),- resource: style.resource.take(),- size: style.size.take(),- color: style.color.take(),- underline: style.underline.take(),- char_spacing: style.char_spacing.take(),- scale: style.scale.take(),- });- }- style- }-- /// After applying formatting: the paragraph now has it.- pub fn applied(&mut self) {- self.selection = None;- self.font_resource = None;- self.family_chosen = false;- self.look0 = self.look.clone();- self.extras0 = self.extras;- self.original = self.text.clone();- self.focus = true;- }-- /// Adopt the rewritten paragraph's current geometry before the next overlay frame.- pub(crate) fn refresh_source(&mut self, block: &pdfcraft_engine::TextBlock, lines: Vec<pdfcraft_engine::TextLine>) {- self.source_rect = block.rect.map(|v| v as f32);- self.multiline = block.rows.len() > 1;- self.source = Some((block.clone(), lines));- self.text = block.editor_text.clone();- self.original = self.text.clone();- }-}--/// What a drag on a paragraph box takes hold of.-#[derive(Clone, Copy, Debug, PartialEq)]-enum Grip {- Move,- /// An edge (screen left or right), dragged to rewrap the paragraph.- Left,- Right,-}--/// A paragraph box being dragged: moved, or (from a handle on its left or right edge) resized.-#[derive(Clone, Copy, Debug, PartialEq)]-pub struct BlockDrag {- page: usize,- block: usize,- /// A paragraph index belongs to the document generation where the press was resolved.- generation: u64,- /// Where the drag started (screen).- start: Pos2,- grip: Grip,-}--/// How far an edge grip reaches either side of a box's edge (screen pixels).-const EDGE_REACH: f32 = 6.0;-/// How far outside an open paragraph's frame the pointer still means the frame (screen pixels).-const FRAME_REACH: f32 = 4.0;--/// The rewrap handles drawn on a paragraph box's left and right edges (screen).-fn width_handles(b: Rect) -> [Rect; 2] {- let h = (b.height() * 0.5).clamp(14.0, 28.0);- [b.left(), b.right()].map(|x| Rect::from_center_size(Pos2::new(x, b.center().y), egui::vec2(7.0, h)))-}--/// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow-/// box keeps its middle for moving.-fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {- if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {- return None;- }- let inside = EDGE_REACH.min(b.width() / 4.0);- let (dl, dr) = (p.x - b.left(), b.right() - p.x);- match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {- (true, true) if dl <= dr => Some(Grip::Left),- (_, true) => Some(Grip::Right),- (true, false) => Some(Grip::Left),- _ => None,- }-}--/// The topmost box under `p` and what it grabs there; edges only on an upright page.-fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {- boxes.iter().enumerate().rev().find_map(|(i, b)| match upright.then(|| edge_at(*b, p)).flatten() {- Some(g) => Some((i, g)),- None => b.contains(p).then_some((i, Grip::Move)),- })-}--/// A paragraph's box on screen: its text rect (user space), with a little room around it.-fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {- xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)-}--/// The width handles need the page upright (or upside down): on a quarter-turned page the-/// screen's horizontal is the paragraph's vertical.-fn has_edges(info: &DocInfo, page: usize) -> bool {- info.pages.get(page).is_some_and(|p| p.rotation % 180 == 0)-}--/// Whether a press at `p` takes hold of the width handle of one of the paragraphs `rects` (user-/// space). The handle is drawn half outside the box and grabs from a little further out still,-/// where a press is not on the box itself, so area selection must leave it to [`page_input`].-pub(crate) fn grabs_edge(xf: &PageXform, info: &DocInfo, page: usize, mut rects: impl Iterator<Item = [f64; 4]>, p: Pos2) -> bool {- has_edges(info, page) && rects.any(|r| edge_at(paragraph_box(xf, info, page, r), p).is_some())-}--fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {- let p = &info.pages[page];- let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));- let (u, v) = (p.view_to_user(a.0, a.1), p.view_to_user(b.0, b.1));- [u[0].min(v[0]) as f64, u[1].min(v[1]) as f64, u[0].max(v[0]) as f64, u[1].max(v[1]) as f64]-}--/// Open `block` on `page` in the inline editor. The box's geometry and source are read from the-/// `lines` handed in, so callers pass the document's current inventory.-#[allow(clippy::too_many_arguments)]-fn open_editor(- ui: &egui::Ui,- xf: &PageXform,- doc: &pdfcraft_engine::Document,- lines: &[pdfcraft_engine::TextBlock],- boxes: &[Rect],- page: usize,- block: usize,- view: &mut DocView,-) {- view.pending_text_open = None;- let (Some(l), Some(b)) = (lines.get(block), boxes.get(block)) else { return };- view.image_selection = None;- let source_lines = doc.text_lines(page);- let text = l.editor_text.clone();- // Screen pixels per point, from the box's width.- let scale = (b.width() - 4.0) / ((l.rect[2] - l.rect[0]).max(1.0) as f32);- // How far the editor box may grow: a single-line paragraph's rewrite grows to the- // page's right edge, a multi-line paragraph rewraps to its own width.- let right = xf.rect.right().min(view.viewport_rect().right()) - 6.0;- let max_width = if l.rows.len() == 1 { (right - b.left()).max(b.width()) } else { b.width() };- view.line_editor = Some(LineEditor {- selection: None,- font_resource: None,- page,- block,- text: text.clone(),- original: text,- rect: *b,- source_rect: l.rect.map(|v| v as f32),- multiline: l.rows.len() > 1,- source: Some((l.clone(), source_lines)),- fonts: install_source_fonts(ui.ctx(), doc, page),- overflow: false,- max_width,- size: (l.size as f32 * scale).clamp(8.0, 72.0),- focus: true,- had_focus: false,- look: look_of(l),- look0: look_of(l),- family_chosen: false,- extras: Extras::default(),- extras0: Extras::default(),- });-}--/// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns-/// `true` when the pointer was used.-#[allow(clippy::too_many_arguments)]-pub(crate) fn page_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- doc: &pdfcraft_engine::Document,- lines: &[pdfcraft_engine::TextBlock],- view: &mut DocView,- allow_interaction: bool,-) -> bool {- let info = &doc.info;- if view.block_drag.is_some_and(|d| d.generation != doc.edit_generation()) {- view.block_drag = None;- return true;- }- let boxes: Vec<Rect> = lines.iter().map(|l| paragraph_box(xf, info, page, l.rect)).collect();- // Outlines stay on their page, like its text (#3061).- let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(xf.rect.expand(1.0)));- let active = view.line_editor.as_ref().filter(|e| e.page == page).map(|e| e.block);- for (i, b) in boxes.iter().enumerate() {- if active != Some(i) {- painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);- }- }- // A box a switching click asked for opens now, once the edit queued with that click has- // applied and `lines`/`boxes` are the document's new inventory (#2022).- if allow_interaction- && active.is_none()- && let Some((open_page, key)) = view.pending_text_open.clone()- && open_page == page- {- // The edit may have regrouped the page: open the paragraph that was clicked, wherever it- // is now, and none if it was merged into another (#2516).- match key.find(lines, 0) {- Some(block) => open_editor(ui, xf, doc, lines, &boxes, page, block, view),- None => view.pending_text_open = None,- }- }- if !allow_interaction {- return false;- }- let upright = has_edges(info, page);- let draw_handles = |b: Rect| {- for h in width_handles(b) {- painter.rect(h, CornerRadius::same(2), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);- }- };- // A drag in progress: the box follows the pointer (or the grabbed edge does); releasing applies it.- if let Some(d) = view.block_drag.filter(|d| d.page == page)- && let (Some(b), Some(l)) = (boxes.get(d.block).copied(), lines.get(d.block))- {- let p = ptr.pos.unwrap_or(d.start);- let dx = p.x - d.start.x;- let preview = match d.grip {- Grip::Move => b.translate(p - d.start),- Grip::Left => Rect::from_min_max(Pos2::new((b.left() + dx).min(b.right() - 12.0), b.min.y), b.max),- Grip::Right => Rect::from_min_max(b.min, Pos2::new((b.right() + dx).max(b.left() + 12.0), b.max.y)),- };- painter.rect_stroke(preview, CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- let resizing = d.grip != Grip::Move;- if resizing {- draw_handles(preview);- }- ui.ctx().set_cursor_icon(if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });- if resp.drag_stopped() || !ptr.any_down {- view.block_drag = None;- let (from, to) = (user_box(xf, info, page, b), user_box(xf, info, page, preview));- let edit = if resizing {- // The new width in user space: the box's change, added to the paragraph's own. A- // moved left side (in user space; on an upside-down page that's the screen's right- // edge) moves the paragraph with it.- let width = (l.rect[2] - l.rect[0]) + (to[2] - to[0]) - (from[2] - from[0]);- let shift = to[0] - from[0];- let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() };- Edit::EditTextBlock { page, block: d.block, text: l.text.clone(), style }- } else {- // Translation must keep the selected source operators. Rewriting unchanged text- // would also remove unrelated paragraphs that now overlap this one (#594).- Edit::MoveObjects {- page,- objects: vec![ObjectTarget { kind: ObjectKind::Text, index: d.block }],- offset: [to[0] - from[0], to[1] - from[1]],- }- };- if preview != b {- view.pending_edit = Some(edit);- }- }- return true;- }- // Dragging a box (not while a paragraph is open for typing) moves it; from an edge, resizes it.- // What it grabs comes from where the button went down, not where the pointer is now: egui- // only calls it a drag once the pointer has moved a few pixels (or been held a moment), and a- // quick flick has left the edge by then.- if resp.drag_started()- && active.is_none()- && let Some(o) = ptr.origin- && let Some((block, grip)) = grab_at(&boxes, o, upright)- {- view.block_drag = Some(BlockDrag { page, block, generation: doc.edit_generation(), start: o, grip });- return true;- }- let Some(p) = ptr.within(xf.rect) else { return false };- let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };- if active != Some(hit) {- painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- }- let on_edge = active.is_none() && grip != Grip::Move;- if upright && active.is_none() {- draw_handles(boxes[hit]);- }- // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it- // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page- // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own- // cursor (#2755).- if resp.contains_pointer() {- ui.ctx().set_cursor_icon(if on_edge {- egui::CursorIcon::ResizeHorizontal- } else if active.is_none() {- egui::CursorIcon::Move- } else {- egui::CursorIcon::Text- });- }- if resp.clicked() {- view.image_selection = None;- // A click that moves the editor to another paragraph applies the open one first, so its- // typed text is not dropped with the switched-away editor (#2022). A click on the open- // box's own frame, which the editor's overlay does not cover, keeps it open instead.- if let Some(open) = view.line_editor.as_ref().filter(|e| e.has_changes()) {- if open.page == page && open.block == hit {- return true;- }- if let Some(old) = view.line_editor.take() {- let style = old.style();- if old.text != old.original || style != pdfcraft_engine::BlockStyle::default() {- view.applied_editor = Some(old.clone());- view.pending_edit = Some(Edit::EditTextBlock { page: old.page, block: old.block, text: old.text, style });- }- }- // The clicked box opens next frame, from the document with that edit applied.- view.pending_text_open = lines.get(hit).map(|l| (page, pdfcraft_engine::BlockKey::of(l)));- return true;- }- open_editor(ui, xf, doc, lines, &boxes, page, hit, view);- }- true-}--/// The inline editor; returns the edit once the text is applied.-pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {- // Clicks outside the document (the Format text panel) keep the paragraph open. Where the- // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.- let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));- let page = view.line_editor.as_ref()?.page;- let xf = view.page_xform(page)?;- let hold = view.objects.hold_editor;- // An OCR word is invisible text over a scan: the textless background still shows the scanned- // word, so the editor covers it, as the applied edit will.- let background_ready = view- .line_editor- .as_ref()- .is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));- // The measured extent of this paragraph's draft: a click straight from another paragraph- // opens this one after the frame's measuring, which was the other one's.- let draft_rect = view- .line_editor- .as_ref()- .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))- .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));- // The editor draws on its page only, as the page itself does: a paragraph running past the- // page's edge (a converter relying on the page clip) must not cover the next page or the- // tool bars (#3061).- let viewport = view.viewport_rect();- let page_clip = xf.rect.intersect(viewport);- let ed = view.line_editor.as_mut()?;- if hold {- ed.focus = true;- }- // Reproject the source box every frame. The page may have been zoomed, scrolled or rotated- // while the format panel was open.- // A font definition becomes active at the start of the next egui pass. Keep the source- // raster visible until then instead of flashing an unrelated interface face.- if !ctx.fonts(|f| ed.fonts.values().all(|name| f.definitions().families.contains_key(&FontFamily::Name(name.clone().into())))) {- ctx.request_repaint();- return None;- }- ed.rect = xf.user_rect(info, ed.page, ed.source_rect);- ed.max_width = ed.rect.width();- let scale = (ed.rect.width() / (ed.source_rect[2] - ed.source_rect[0]).abs().max(0.01)).max(0.01);- ed.size = (ed.look.size as f32 * scale).clamp(1.0, 300.0);- // egui draws the caret at least one row of this font tall. Each row already has its source- // row's height, so the font stays below every row (half the region's smallest size): on a- // 12 pt row under a 24 pt title the caret is as tall as the row, not the title.- let smallest =- ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));- let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));- let text_color = color32(ed.look.color);- let block = ed.block;- let mut done = None;- let mut reveal = false;- let mut look = None;- // No fade-in: while it faded, the page's own copy of the text showed through the cover.- // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or- // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as- // the page is, rather than pushed back into the window.- egui::Area::new(egui::Id::unique("edit-text-line"))- .order(egui::Order::Foreground)- .fade_in(false)- .fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))- .constrain_to(viewport)- .constrain(false)- .show(ctx, |ui| {- ui.set_clip_rect(ui.clip_rect().intersect(page_clip));- // The editor opens at the source size. Once text changes, show the real draft- // extent: single rows grow toward the page edge, paragraphs rewrap at their- // source width, and the visible frame grows/shrinks vertically with their rows.- // An OCR phrase (several stretched words on one scanned line) also grows rightwards.- let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);- let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {- let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);- let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;- natural.max(ed.size * 0.4).min((xf.rect.right() - ed.rect.left() - 36.0 * scale).max(ed.rect.width()))- } else {- ed.rect.width().max(1.0)- };- ui.set_width(width);- let measured = editor_galley(ui, ed, &ed.text, scale, width);- ed.overflow = ed.has_changes() && (measured.rect.width() > ed.rect.width() + 1.5 || measured.rect.height() > ed.rect.height() + 1.5);- let visible = Rect::from_min_size(ed.rect.min, measured.rect.size().max(egui::vec2(1.0, 1.0)));- // Unsupported source programs use an interface fallback whose glyph advances- // can differ from the PDF's. Keep every visible row inside the growing frame.- let live = draft_rect.map_or(visible, |bounds| bounds.union(visible));- ui.painter().rect_stroke(live.expand(2.0), CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- // On the frame, a press takes hold of the box (a click selects it, a drag moves it):- // the pointer says so there, and reads as text inside.- if let Some(p) = ui.input(|i| i.pointer.hover_pos())- && ui.clip_rect().contains(p)- && live.expand(2.0 + FRAME_REACH).contains(p)- && !live.expand(2.0).contains(p)- {- ui.ctx().set_cursor_icon(egui::CursorIcon::Move);- }- // White, unless the text is too pale to read on white (white text from a coloured- // banner, #913): then a dark box, with a caret that shows on it.- let fill = if background_ready { Color32::TRANSPARENT } else { editor_fill(text_color) };- // An unchanged paragraph is the page's own text: the editor draws only its frame and- // caret over it. Once it changes, the textless page goes under the editor's text or,- // until that background is ready, a cover over the entire source box, including lines- // the draft no longer occupies. Shrinking the text must never expose a copy. Both are- // decided after this frame's typing, in places kept under the editor's text.- let cover = ui.painter().add(egui::Shape::Noop);- let unchanged = !ed.has_changes();- egui::Frame::NONE.show(ui, |ui| {- // A textless PDF preview, or the page itself, keeps its real background through- // the transparent editor. The temporary opaque cover uses the shared caret-contrast rule.- ui.visuals_mut().text_cursor.stroke.color = if background_ready || unchanged {- if luminance(text_color) < 0.5 { Color32::BLACK } else { Color32::WHITE }- } else {- caret_color_on(fill)- };- let rows = 1;- let snapshot = ed.clone();- let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {- let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);- if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }- };- let output = egui::TextEdit::multiline(&mut ed.text)- .id(egui::Id::unique("edit-text-line-input"))- .font(font.clone())- .margin(egui::Margin::ZERO)- .layouter(&mut layouter)- .text_color(text_color)- .frame(egui::Frame::NONE)- .desired_width(width)- .desired_rows(rows)- .show(ui);- // The editor paints over the page with no visible label; name it for assistive tech.- output.response.response.clone().accessible_name(tl!("Text editing line"));- if ed.has_changes() {- if background_ready {- reveal = true;- } else {- ui.painter().set(cover, egui::Shape::rect_filled(ed.rect.expand(1.0).union(output.response.rect), CornerRadius::ZERO, fill));- }- }- look = Some((Arc::clone(&output.galley), output.galley_pos));- if let Some(cursor) = output.cursor_range {- let selected = cursor.as_sorted_char_range();- let byte = |index| ed.text.char_indices().nth(index).map_or(ed.text.len(), |(at, _)| at);- ed.selection = (!selected.is_empty()).then(|| byte(selected.start.into())..byte(selected.end.into()));- }- let r = output.response;- if r.changed() {- // The next pass measures the updated draft with the Apply/Save rewrite.- ctx.request_repaint();- }- if ed.focus {- r.request_focus();- ed.focus = false;- }- let lost = lost_focus_once(&r, &mut ed.had_focus);- let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));- let apply = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command);- if esc {- done = Some(false);- } else if apply || (lost && !outside && !hold) {- done = Some(true);- }- });- });- if reveal {- view.text_background.reveal();- }- if let Some((galley, pos)) = look {- view.text_background.remember(&xf, page, block, galley, pos, text_color);- }- match done {- Some(apply) => {- let ed = view.line_editor.take()?;- if !apply {- return None;- }- view.applied_editor = Some(ed.clone());- finished_edit(ed)- }- None => None,- }-}--/// The edit a closed paragraph editor applies, or `None` when nothing in it changed.-pub(crate) fn finished_edit(ed: LineEditor) -> Option<Edit> {- let style = ed.style();- (ed.text != ed.original || style != pdfcraft_engine::BlockStyle::default()).then_some(Edit::EditTextBlock {- page: ed.page,- block: ed.block,- text: ed.text,- style,- })-}--/// Whether an editor's text box `r` lost the keyboard this frame, given whether it `had` it at-/// the end of the editor's last frame (updated here). egui's `lost_focus` holds for a second-/// frame as well, and an editor that judges a click away by where the click landed must judge it-/// once, on the click's frame: on the next, a tap's position is gone (egui-winit sends-/// `PointerGone` with every touch release) and a mouse may have moved on.-pub(crate) fn lost_focus_once(r: &egui::Response, had: &mut bool) -> bool {- let has = r.has_focus();- std::mem::replace(had, has) && !has-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn the_rotate_knob_moves_below_when_there_is_no_room_above() {- let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));- let roomy = Rect::from_min_max(Pos2::new(100.0, 200.0), Pos2::new(200.0, 250.0));- assert_eq!(rotate_knob(roomy, view).0, Pos2::new(150.0, 178.0));- let at_top = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0));- let (knob, stem) = rotate_knob(at_top, view);- assert_eq!((knob, stem), (Pos2::new(150.0, 172.0), Pos2::new(150.0, 150.0)));- }-- #[test]- fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {- let c = Pos2::new(100.0, 100.0);- let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);- assert!(at(100.0, 0.0).abs() < 1e-3);- assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");- assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);- assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);- // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.- assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);- assert_eq!(at(101.0, 101.0), 0.0);- assert_eq!(at(f32::NAN, 5.0), 0.0);- }-- /// An app with one text document open, and an editor on its first paragraph.- fn preview_app() -> (crate::PdfCraftApp, LineEditor) {- let mut app = crate::PdfCraftApp::new();- let bytes = app.session.create_from_text("Preview", "Preview text").unwrap();- app.open_bytes("preview.pdf", None, bytes.as_ref().clone()).unwrap();- let doc = app.session.get(app.views[0].id).unwrap();- let block = doc.text_blocks(0).remove(0);- let ed = LineEditor {- selection: None,- font_resource: None,- page: 0,- block: 0,- text: block.text.clone(),- original: block.text.clone(),- rect: Rect::NOTHING,- source_rect: block.rect.map(|v| v as f32),- multiline: block.rows.len() > 1,- source: None,- fonts: BTreeMap::new(),- overflow: false,- max_width: 400.0,- size: block.size as f32,- focus: true,- had_focus: false,- look: look_of(&block),- look0: look_of(&block),- family_chosen: false,- extras: Extras::default(),- extras0: Extras::default(),- };- (app, ed)- }-- #[test]- fn picking_the_family_the_font_name_reads_as_still_changes_the_font() {- // A Calibri paragraph reads as Helvetica; picking Helvetica from the list used to leave- // `look` equal to what the paragraph had, so no family change was sent and Calibri stayed.- let (_app, mut ed) = preview_app();- let family = ed.look0.family;- assert_eq!(ed.style().family, None, "nothing chosen yet");- ed.choose_family(family);- assert_eq!(ed.style().family, Some((family, ed.look.bold, ed.look.italic)));- assert!(ed.has_changes());- assert_eq!(ed.font_shown(&[]), family.label());- ed.keep_source_font();- assert_eq!(ed.style().family, None, "Keep source fonts withdraws the choice");- ed.choose_family(family);- ed.applied();- assert_eq!(ed.style().family, None, "an applied choice is the paragraph's font now");- }-- #[test]- fn a_loaded_font_is_applied_to_the_paragraph_being_edited() {- // Loading a font used to only register it on the page: the paragraph kept its source- // face until the font was found again in the document-font menu (#2591).- let (mut app, ed) = preview_app();- app.views[0].line_editor = Some(ed);- let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();- app.use_files(crate::files::FilePurpose::TextFont { page: 0 }, vec![("Inter-Regular.ttf".into(), inter)]);- let doc = app.session.get(app.views[0].id).unwrap();- let lines = doc.text_lines(0);- assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "Preview text");- assert!(lines.iter().all(|l| l.base_font == "Inter-Regular"), "{:?}", lines.iter().map(|l| &l.base_font).collect::<Vec<_>>());- assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");- }-- #[test]- fn save_applies_the_paragraph_open_in_the_editor() {- // Save wrote the file without the paragraph still open in the editor (#3496).- let (mut app, mut ed) = preview_app();- ed.text = "Text preview".into();- app.views[0].line_editor = Some(ed);- let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();- app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());-- assert!(app.save_active(crate::SaveTarget::InPlace));- assert!(app.views[0].line_editor.is_none());- let doc = app.session.get(app.views[0].id).unwrap();- assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn a_refused_text_box_does_not_lose_the_open_paragraph() {- let (mut app, mut ed) = preview_app();- ed.text = "Text preview".into();- app.views[0].line_editor = Some(ed);- let draft = crate::content_ui::TextDraft {- page: 9,- index: None,- rect: [20.0, 20.0, 120.0, 40.0],- text: "Typed text".into(),- style: crate::content_ui::default_style(),- focus: true,- };- app.views[0].content.draft = Some(draft.clone());-- assert!(!app.commit_typing_in(app.views[0].id));- assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");- assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");- let doc = app.session.get(app.views[0].id).unwrap();- assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");- }-- #[test]- fn a_refused_paragraph_stays_open_with_its_text() {- let (mut app, mut ed) = preview_app();- ed.text = "Text preview".into();- ed.page = 9;- app.views[0].line_editor = Some(ed.clone());-- assert!(!app.commit_typing_in(app.views[0].id));- assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");- }-- #[test]- fn text_background_is_cached_without_editing_and_released_on_cancel() {- let (app, ed) = preview_app();- let doc = app.session.get(app.views[0].id).unwrap();- let source = doc.bytes.clone();- let generation = doc.edit_generation();- let ctx = egui::Context::default();- let mut background = TextBackground::default();- for _ in 0..100 {- background.prepare(&ctx, doc, Some(&ed), None, 1.0);- if background.ready(0, 0) {- break;- }- std::thread::sleep(std::time::Duration::from_millis(5));- }- assert!(background.ready(0, 0));- assert!(!background.pending());- let texture = background.texture.as_ref().unwrap().id();- background.prepare(&ctx, doc, Some(&ed), None, 1.0);- assert_eq!(background.texture.as_ref().unwrap().id(), texture);- assert_eq!(doc.bytes, source);- assert_eq!(doc.edit_generation(), generation);- assert!(!doc.dirty && doc.can_undo().is_none());- background.prepare(&ctx, doc, None, None, 1.0);- assert!(background.texture.is_none() && background.renderer.is_none());- }-- #[test]- fn the_editing_background_stays_sharp_on_a_zoomed_page() {- // While a paragraph is open, the page around it is drawn from this one raster: it is- // asked for at the tiling threshold, not the 2048-pixel backdrop side, which went soft- // beyond about 1.2x on a Retina display.- let (app, ed) = preview_app();- let doc = app.session.get(app.views[0].id).unwrap();- let page = &doc.info.pages[0];- let ctx = egui::Context::default();- ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });- let mut background = TextBackground::default();- background.prepare(&ctx, doc, Some(&ed), None, 8.0);- let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));- assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");- assert_eq!(background.tag, Some((expected * 1000.0) as u64));- // A GPU that can't hold such a texture caps it.- ctx.end_pass().textures_delta.clear();- ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });- let mut small = TextBackground::default();- small.prepare(&ctx, doc, Some(&ed), None, 8.0);- assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));- ctx.end_pass().textures_delta.clear();- }-- #[test]- fn pale_text_is_edited_on_a_dark_box() {- // #913: white text from a coloured banner was typed onto a white box and vanished.- for pale in [Color32::WHITE, Color32::from_rgb(0xFF, 0xFF, 0x00), Color32::from_gray(0xE0), Color32::from_rgb(0xFF, 0xA5, 0x00)] {- assert_eq!(editor_fill(pale), DARK_EDITOR_FILL, "{pale:?}");- assert!(contrast(pale, editor_fill(pale)) >= 4.5, "{pale:?} is readable");- }- // Ordinary dark or saturated text keeps the white box.- for dark in [Color32::BLACK, Color32::from_rgb(0x1F, 0x2A, 0x6B), Color32::from_rgb(0xC0, 0x00, 0x00), Color32::from_gray(0x60)] {- assert_eq!(editor_fill(dark), Color32::WHITE, "{dark:?}");- }- }-- #[test]- fn caret_contrasts_with_its_fill() {- assert_eq!(caret_color_on(Color32::WHITE), Color32::BLACK);- assert_eq!(caret_color_on(Color32::from_rgb(0xFF, 0xFF, 0xF4)), Color32::BLACK);- assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);- assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);- }-}++//! Edit a PDF ▸ Edit text & images: boxes around the paragraphs and images already on the page.++//! Click a paragraph to edit it in place (⌘Enter or clicking away applies and rewraps it to the++//! box, Esc cancels); drag it to move it, or drag the handle on its left or right edge to rewrap++//! it to a new width. Click an image to select it: drag to move, drag a corner to resize (keeping++//! its proportions), right-click for rotate, flip, replace, save and delete; Delete removes it.++++use std::collections::BTreeMap;++use std::sync::Arc;++++use egui::{Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Stroke, pos2};++use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget};++use pdfcraft_render::DocInfo;++++use crate::canvas::{DocView, PageXform};++use crate::page_pointer::PagePointer;++++mod background;++mod image;++mod layout;++++pub(crate) use background::TextBackground;++pub use image::{CropMode, DragTarget, ImageAction, ImageDrag, ImageHandle, ImageSelection, image_menu_id};++pub(crate) use image::{image_context_menu, image_input, image_owns_pointer, Matrix, quad_contains, user_to_screen};++#[cfg(test)]++use image::{rotate_knob, turn_degrees};++#[cfg(test)]++use layout::{DARK_EDITOR_FILL, contrast};++pub(crate) use layout::{caret_color_on, editor_fill, editor_font, install_source_fonts};++use layout::{color32, editor_galley, editor_job, look_of, luminance, source_look, unseen};++++const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);++++#[derive(Clone, Copy, PartialEq)]++enum TextTarget {++ Block(usize),++ Added(usize),++}++++/// How many faint Edit-text outlines are drawn per page per frame. CAD plots can draw++/// ~1000 tiny images on one page; stroking all of them every frame (plus a hover query++/// per box) stalls the UI. Past this, only the selected and hovered boxes are outlined:++/// hit-testing still covers every image, so nothing becomes unselectable.++pub(crate) const MAX_OUTLINES: usize = 250;++++pub fn is_bulleted(text: &str) -> bool {++ let mut lines = text.lines();++ let Some(first) = lines.next() else { return false };++ first.trim_start().starts_with("• ") || first.trim_start().starts_with("- ")++}++++pub fn is_numbered(text: &str) -> bool {++ let mut lines = text.lines();++ let Some(first) = lines.next() else { return false };++ let t = first.trim_start();++ let num_end = t.find('.').unwrap_or(0);++ num_end > 0 && t[..num_end].chars().all(|c| c.is_ascii_digit()) && t[num_end..].starts_with(". ")++}++++pub fn toggle_bullet_list(text: &mut String) -> bool {++ let lines: Vec<&str> = text.lines().collect();++ if lines.is_empty() {++ return false;++ }++ let all_bulleted = lines.iter().all(|l| {++ let t = l.trim_start();++ t.is_empty() || t.starts_with("• ") || t.starts_with("- ")++ });++ let mut new_text = String::with_capacity(text.len() + 16);++ for (i, line) in lines.iter().enumerate() {++ if i > 0 {++ new_text.push('\n');++ }++ let trimmed = line.trim_start();++ if all_bulleted {++ if let Some(rest) = trimmed.strip_prefix("• ").or_else(|| trimmed.strip_prefix("- ")) {++ new_text.push_str(rest);++ } else {++ new_text.push_str(line);++ }++ } else if trimmed.is_empty() || trimmed.starts_with("• ") {++ new_text.push_str(line);++ } else {++ new_text.push_str("• ");++ new_text.push_str(line);++ }++ }++ if new_text != *text {++ *text = new_text;++ true++ } else {++ false++ }++}++++pub fn toggle_numbered_list(text: &mut String) -> bool {++ let lines: Vec<&str> = text.lines().collect();++ if lines.is_empty() {++ return false;++ }++ let is_num_line = |l: &str| {++ let t = l.trim_start();++ if t.is_empty() {++ return true;++ }++ let dot_idx = t.find('.').unwrap_or(0);++ dot_idx > 0 && t[..dot_idx].chars().all(|c| c.is_ascii_digit()) && t[dot_idx..].starts_with(". ")++ };++ let all_numbered = lines.iter().all(|l| is_num_line(l));++ let mut new_text = String::with_capacity(text.len() + 16);++ let mut num = 1;++ for (i, line) in lines.iter().enumerate() {++ if i > 0 {++ new_text.push('\n');++ }++ let t = line.trim_start();++ if all_numbered {++ if let Some(dot_idx) = t.find('.')++ && dot_idx > 0++ && t[..dot_idx].chars().all(|c| c.is_ascii_digit())++ && t[dot_idx..].starts_with(". ")++ {++ new_text.push_str(t.get(dot_idx + 2..).unwrap_or(""));++ continue;++ }++ new_text.push_str(line);++ } else if t.is_empty() {++ new_text.push_str(line);++ } else {++ use std::fmt::Write as _;++ let _ = write!(new_text, "{num}. ");++ new_text.push_str(t);++ num += 1;++ }++ }++ if new_text != *text {++ *text = new_text;++ true++ } else {++ false++ }++}++++pub fn char_to_superscript(c: char) -> char {++ match c {++ '0' => '⁰',++ '1' => '¹',++ '2' => '²',++ '3' => '³',++ '4' => '⁴',++ '5' => '⁵',++ '6' => '⁶',++ '7' => '⁷',++ '8' => '⁸',++ '9' => '⁹',++ '+' => '⁺',++ '-' | '−' => '⁻',++ '=' => '⁼',++ '(' => '⁽',++ ')' => '⁾',++ 'a' => 'ᵃ',++ 'b' => 'ᵇ',++ 'c' => 'ᶜ',++ 'd' => 'ᵈ',++ 'e' => 'ᵉ',++ 'f' => 'ᶠ',++ 'g' => 'ᵍ',++ 'h' => 'ʰ',++ 'i' => 'ⁱ',++ 'j' => 'ʲ',++ 'k' => 'ᵏ',++ 'l' => 'ˡ',++ 'm' => 'ᵐ',++ 'n' => 'ⁿ',++ 'o' => 'ᵒ',++ 'p' => 'ᵖ',++ 'r' => 'ʳ',++ 's' => 'ˢ',++ 't' => 'ᵗ',++ 'u' => 'ᵘ',++ 'v' => 'ᵛ',++ 'w' => 'ʷ',++ 'x' => 'ˣ',++ 'y' => 'ʸ',++ 'z' => 'ᶻ',++ 'A' => 'ᴬ',++ 'B' => 'ᴮ',++ 'D' => 'ᴰ',++ 'E' => 'ᴱ',++ 'G' => 'ᴳ',++ 'H' => 'ᴴ',++ 'I' => 'ᴵ',++ 'J' => 'ᴶ',++ 'K' => 'ᴷ',++ 'L' => 'ᴸ',++ 'M' => 'ᴹ',++ 'N' => 'ᴺ',++ 'O' => 'ᴼ',++ 'P' => 'ᴾ',++ 'R' => 'ᴿ',++ 'T' => 'ᵀ',++ 'U' => 'ᵁ',++ 'V' => 'ⱽ',++ 'W' => 'ᵂ',++ other => other,++ }++}++++pub fn char_from_superscript(c: char) -> char {++ match c {++ '⁰' => '0',++ '¹' => '1',++ '²' => '2',++ '³' => '3',++ '⁴' => '4',++ '⁵' => '5',++ '⁶' => '6',++ '⁷' => '7',++ '⁸' => '8',++ '⁹' => '9',++ '⁺' => '+',++ '⁻' => '-',++ '⁼' => '=',++ '⁽' => '(',++ '⁾' => ')',++ 'ᵃ' => 'a',++ 'ᵇ' => 'b',++ 'ᶜ' => 'c',++ 'ᵈ' => 'd',++ 'ᵉ' => 'e',++ 'ᶠ' => 'f',++ 'ᵍ' => 'g',++ 'ʰ' => 'h',++ 'ⁱ' => 'i',++ 'ʲ' => 'j',++ 'ᵏ' => 'k',++ 'ˡ' => 'l',++ 'ᵐ' => 'm',++ 'ⁿ' => 'n',++ 'ᵒ' => 'o',++ 'ᵖ' => 'p',++ 'ʳ' => 'r',++ 'ˢ' => 's',++ 'ᵗ' => 't',++ 'ᵘ' => 'u',++ 'ᵛ' => 'v',++ 'ʷ' => 'w',++ 'ˣ' => 'x',++ 'ʸ' => 'y',++ 'ᶻ' => 'z',++ 'ᴬ' => 'A',++ 'ᴮ' => 'B',++ 'ᴰ' => 'D',++ 'ᴱ' => 'E',++ 'ᴳ' => 'G',++ 'ᴴ' => 'H',++ 'ᴵ' => 'I',++ 'ᴶ' => 'J',++ 'ᴷ' => 'K',++ 'ᴸ' => 'L',++ 'ᴹ' => 'M',++ 'ᴺ' => 'N',++ 'ᴼ' => 'O',++ 'ᴾ' => 'P',++ 'ᴿ' => 'R',++ 'ᵀ' => 'T',++ 'ᵁ' => 'U',++ 'ⱽ' => 'V',++ 'ᵂ' => 'W',++ other => other,++ }++}++++pub fn char_to_subscript(c: char) -> char {++ match c {++ '0' => '₀',++ '1' => '₁',++ '2' => '₂',++ '3' => '₃',++ '4' => '₄',++ '5' => '₅',++ '6' => '₆',++ '7' => '₇',++ '8' => '₈',++ '9' => '₉',++ '+' => '₊',++ '-' | '−' => '₋',++ '=' => '₌',++ '(' => '₍',++ ')' => '₎',++ 'a' => 'ₐ',++ 'e' => 'ₑ',++ 'h' => 'ₕ',++ 'i' => 'ᵢ',++ 'j' => 'ⱼ',++ 'k' => 'ₖ',++ 'l' => 'ₗ',++ 'm' => 'ₘ',++ 'n' => 'ₙ',++ 'o' => 'ₒ',++ 'p' => 'ₚ',++ 'r' => 'ᵣ',++ 's' => 'ₛ',++ 't' => 'ₜ',++ 'u' => 'ᵤ',++ 'v' => 'ᵥ',++ 'x' => 'ₓ',++ other => other,++ }++}++++pub fn char_from_subscript(c: char) -> char {++ match c {++ '₀' => '0',++ '₁' => '1',++ '₂' => '2',++ '₃' => '3',++ '₄' => '4',++ '₅' => '5',++ '₆' => '6',++ '₇' => '7',++ '₈' => '8',++ '₉' => '9',++ '₊' => '+',++ '₋' => '-',++ '₌' => '=',++ '₍' => '(',++ '₎' => ')',++ 'ₐ' => 'a',++ 'ₑ' => 'e',++ 'ₕ' => 'h',++ 'ᵢ' => 'i',++ 'ⱼ' => 'j',++ 'ₖ' => 'k',++ 'ₗ' => 'l',++ 'ₘ' => 'm',++ 'ₙ' => 'n',++ 'ₒ' => 'o',++ 'ₚ' => 'p',++ 'ᵣ' => 'r',++ 'ₛ' => 's',++ 'ₜ' => 't',++ 'ᵤ' => 'u',++ 'ᵥ' => 'v',++ 'ₓ' => 'x',++ other => other,++ }++}++++fn snap_char_boundaries(s: &str, start: usize, end: usize) -> (usize, usize) {++ let mut s_idx = start.min(s.len());++ while s_idx > 0 && !s.is_char_boundary(s_idx) {++ s_idx -= 1;++ }++ let mut e_idx = end.min(s.len());++ while e_idx < s.len() && !s.is_char_boundary(e_idx) {++ e_idx += 1;++ }++ (s_idx, e_idx)++}++++pub fn toggle_superscript(ed: &mut LineEditor) -> bool {++ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };++ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);++ if start >= end {++ return false;++ }++ let target = &ed.text[start..end];++ let all_sup = target.chars().all(|c| char_from_superscript(c) != c);++ let converted: String =++ if all_sup { target.chars().map(char_from_superscript).collect() } else { target.chars().map(char_to_superscript).collect() };++ if converted != target {++ let conv_len = converted.len();++ ed.text.replace_range(start..end, &converted);++ if ed.selection.is_some() {++ ed.selection = Some(start..start + conv_len);++ }++ true++ } else {++ false++ }++}++++pub fn toggle_subscript(ed: &mut LineEditor) -> bool {++ let (s_pos, e_pos) = if let Some(r) = &ed.selection { (r.start.min(ed.text.len()), r.end.min(ed.text.len())) } else { (0, ed.text.len()) };++ let (start, end) = snap_char_boundaries(&ed.text, s_pos, e_pos);++ if start >= end {++ return false;++ }++ let target = &ed.text[start..end];++ let all_sub = target.chars().all(|c| char_from_subscript(c) != c);++ let converted: String = if all_sub { target.chars().map(char_from_subscript).collect() } else { target.chars().map(char_to_subscript).collect() };++ if converted != target {++ let conv_len = converted.len();++ ed.text.replace_range(start..end, &converted);++ if ed.selection.is_some() {++ ed.selection = Some(start..start + conv_len);++ }++ true++ } else {++ false++ }++}++++/// A paragraph being edited.++#[derive(Clone, Debug, PartialEq)]++pub struct LineEditor {++ pub selection: Option<std::ops::Range<usize>>,++ pub font_resource: Option<String>,++ pub page: usize,++ pub block: usize,++ pub text: String,++ original: String,++ rect: Rect,++ /// The original PDF rectangle, in user space. It is converted again each frame so the editor++ /// stays attached while the page is zoomed, scrolled, or rotated.++ source_rect: [f32; 4],++ multiline: bool,++ source: Option<(pdfcraft_engine::TextBlock, Vec<pdfcraft_engine::TextLine>)>,++ pub(crate) fonts: BTreeMap<String, String>,++ /// The draft extends outside the source container; its frame follows the live draft bounds.++ pub overflow: bool,++ /// The initial source container width in screen pixels.++ max_width: f32,++ /// Current screen-space size. Recomputed from the current page transform before painting.++ size: f32,++ /// Take the keyboard focus on the next frame.++ pub(crate) focus: bool,++ /// Whether the text box had the keyboard at the end of the editor's last frame++ /// ([`lost_focus_once`]).++ had_focus: bool,++ /// The Format text panel's values, and what the paragraph had (to send only changes).++ pub look: pdfcraft_engine::AddedText,++ look0: pdfcraft_engine::AddedText,++ /// A standard family was picked from the font list. The family guessed from a PDF font name++ /// (Calibri reads as Helvetica) can be the one picked, so comparing `look` with `look0` alone++ /// would miss the choice.++ family_chosen: bool,++ /// Underline, line spacing (× size; 0 = the paragraph's own), character spacing (pt) and++ /// horizontal scale (%), and what they were.++ pub extras: Extras,++ extras0: Extras,++}++++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct Extras {++ pub underline: bool,++ pub line_spacing: f64,++ pub char_spacing: f64,++ pub scale: f64,++}++++impl Default for Extras {++ fn default() -> Self {++ Extras { underline: false, line_spacing: 0.0, char_spacing: 0.0, scale: 100.0 }++ }++}++++impl LineEditor {++ /// What Format text's font list shows: the chosen page font, a standard family picked++ /// instead, or the paragraph's own font (its `/BaseFont` without the subset tag).++ pub(crate) fn font_shown(&self, sources: &[(String, String)]) -> String {++ if let Some(face) = self.font_resource.as_ref().and_then(|r| sources.iter().find(|(res, _)| res == r)).map(|(_, face)| face) {++ return face.clone();++ }++ if self.look.family != self.look0.family || self.family_chosen {++ return self.look.family.label().to_string();++ }++ let base = self.source.as_ref().map(|(block, _)| block.base_font.as_str()).unwrap_or_default();++ // "ABCDEF+Calibri" is a subset of Calibri.++ let name = match base.split_once('+') {++ Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,++ _ => base,++ };++ if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }++ }++++ /// Back to the paragraph's own font: no page font chosen and the family it started with.++ pub(crate) fn keep_source_font(&mut self) {++ self.font_resource = None;++ self.look.family = self.look0.family;++ self.family_chosen = false;++ }++++ /// A standard family picked from the font list, replacing the paragraph's font even when it++ /// is the family the paragraph's font name reads as.++ pub(crate) fn choose_family(&mut self, family: pdfcraft_engine::FontFamily) {++ self.font_resource = None;++ self.look.family = family;++ self.family_chosen = true;++ }++++ pub(crate) fn has_changes(&self) -> bool {++ self.changes_with(&self.text)++ }++++ /// Whether the paragraph with `text` in it differs from what was opened.++ fn changes_with(&self, text: &str) -> bool {++ text != self.original || self.look != self.look0 || self.extras != self.extras0 || self.family_chosen++ }++++ /// Extra width permitted by the editor. Source containers now remain fixed.++ pub fn growth(&self) -> Option<f32> {++ (self.max_width > self.rect.width()).then_some(self.max_width)++ }++++ /// Whether the edited text differs from the original (unsaved changes).++ pub fn has_unsaved_text(&self) -> bool {++ self.text != self.original++ }++++ /// The formatting the panel changed.++ pub fn style(&self) -> pdfcraft_engine::BlockStyle {++ let (l, o) = (&self.look, &self.look0);++ let mut style = pdfcraft_engine::BlockStyle {++ resource: self.font_resource.clone(),++ family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),++ size: (l.size != o.size).then_some(l.size),++ color: (l.color != o.color).then_some(l.color),++ align: (l.align != o.align).then_some(l.align),++ underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),++ line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0)++ .then_some(self.extras.line_spacing),++ char_spacing: (self.extras.char_spacing != self.extras0.char_spacing).then_some(self.extras.char_spacing),++ scale: (self.extras.scale != self.extras0.scale).then_some(self.extras.scale),++ ..Default::default()++ };++ if let Some(range) = &self.selection++ && (style.family.is_some()++ || style.resource.is_some()++ || style.size.is_some()++ || style.color.is_some()++ || style.underline.is_some()++ || style.char_spacing.is_some()++ || style.scale.is_some())++ {++ style.ranges.push(pdfcraft_engine::RangeStyle {++ range: range.clone(),++ family: style.family.take(),++ resource: style.resource.take(),++ size: style.size.take(),++ color: style.color.take(),++ underline: style.underline.take(),++ char_spacing: style.char_spacing.take(),++ scale: style.scale.take(),++ });++ }++ style++ }++++ /// After applying formatting: the paragraph now has it.++ pub fn applied(&mut self) {++ self.font_resource = None;++ self.family_chosen = false;++ self.look0 = self.look.clone();++ self.extras0 = self.extras;++ self.original = self.text.clone();++ self.selection = None;++ self.focus = true;++ }++++ /// Adopt the rewritten paragraph's current geometry before the next overlay frame.++ pub(crate) fn refresh_source(&mut self, block: &pdfcraft_engine::TextBlock, lines: Vec<pdfcraft_engine::TextLine>) {++ self.source_rect = block.rect.map(|v| v as f32);++ self.multiline = block.rows.len() > 1;++ self.source = Some((block.clone(), lines));++ self.text = block.editor_text.clone();++ self.original = self.text.clone();++ }++++ pub fn selection_formatting(&self, sources: &[(String, String)]) -> SelectionFormatting {++ let Some((block, lines)) = &self.source else {++ return SelectionFormatting {++ font_shown: self.font_shown(sources),++ size: Some(self.look.size),++ family: Some(self.look.family),++ bold: Some(self.look.bold),++ italic: Some(self.look.italic),++ color: Some(self.look.color),++ };++ };++++ let spans = block.edited_spans(&self.text);++ let matching_lines: Vec<&pdfcraft_engine::TextLine> = match &self.selection {++ Some(range) if range.start < range.end => {++ spans.iter().filter(|(span, _)| span.start < range.end && span.end > range.start).filter_map(|(_, idx)| lines.get(*idx)).collect()++ }++ _ => spans.iter().filter_map(|(_, idx)| lines.get(*idx)).collect(),++ };++++ if matching_lines.is_empty() {++ return SelectionFormatting {++ font_shown: self.font_shown(sources),++ size: Some(self.look.size),++ family: Some(self.look.family),++ bold: Some(self.look.bold),++ italic: Some(self.look.italic),++ color: Some(self.look.color),++ };++ }++++ let line_font = |l: &pdfcraft_engine::TextLine| -> String {++ if let Some((_, face)) = sources.iter().find(|(res, _)| res == &l.font) {++ return face.clone();++ }++ let base = l.base_font.as_str();++ let name = match base.split_once('+') {++ Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,++ _ => base,++ };++ if let Some((_, face)) = sources.iter().find(|(_, face)| face.as_str() == name) {++ return face.clone();++ }++ let look = look_of_line(l);++ let lower = name.to_ascii_lowercase();++ if ["times", "serif", "roman", "courier", "helvetica", "arial"].iter().any(|s| lower.contains(s)) {++ return look.family.label().to_string();++ }++ if name.is_empty() { tl!("Keep source fonts").to_string() } else { name.to_string() }++ };++++ let first_font = line_font(matching_lines[0]);++ let same_font = matching_lines.iter().skip(1).all(|l| line_font(l) == first_font);++ let font_shown = if same_font {++ if self.font_resource.is_some() || self.look.family != self.look0.family || self.family_chosen {++ self.font_shown(sources)++ } else {++ first_font++ }++ } else {++ tl!("Mixed").to_string()++ };++++ let first_size = (matching_lines[0].size * 10.0).round() / 10.0;++ let same_size = matching_lines.iter().skip(1).all(|l| ((l.size * 10.0).round() / 10.0 - first_size).abs() < 0.05);++ let size = if same_size { Some(first_size) } else { None };++++ let first_look = look_of_line(matching_lines[0]);++ let same_family = matching_lines.iter().skip(1).all(|l| look_of_line(l).family == first_look.family);++ let family = if same_family { Some(first_look.family) } else { None };++ let same_bold = matching_lines.iter().skip(1).all(|l| l.bold == matching_lines[0].bold);++ let bold = if same_bold { Some(matching_lines[0].bold) } else { None };++ let same_italic = matching_lines.iter().skip(1).all(|l| l.italic == matching_lines[0].italic);++ let italic = if same_italic { Some(matching_lines[0].italic) } else { None };++ let same_color = matching_lines.iter().skip(1).all(|l| l.color == matching_lines[0].color);++ let color = if same_color { Some(matching_lines[0].color) } else { None };++++ SelectionFormatting { font_shown, size, family, bold, italic, color }++ }++++ pub(crate) fn sync_selection_look(&mut self, fmt: &SelectionFormatting) {++ if let Some(sz) = fmt.size {++ self.look.size = sz;++ self.look0.size = sz;++ } else {++ self.look.size = 0.0;++ self.look0.size = 0.0;++ }++ if let Some(f) = fmt.family {++ self.look.family = f;++ self.look0.family = f;++ }++ if let Some(b) = fmt.bold {++ self.look.bold = b;++ self.look0.bold = b;++ }++ if let Some(it) = fmt.italic {++ self.look.italic = it;++ self.look0.italic = it;++ }++ if let Some(c) = fmt.color {++ self.look.color = c;++ self.look0.color = c;++ }++ }++}++++#[derive(Clone, Debug, PartialEq)]++pub struct SelectionFormatting {++ pub font_shown: String,++ pub size: Option<f64>,++ pub family: Option<pdfcraft_engine::FontFamily>,++ pub bold: Option<bool>,++ pub italic: Option<bool>,++ pub color: Option<[f64; 3]>,++}++++fn look_of_line(l: &pdfcraft_engine::TextLine) -> pdfcraft_engine::AddedText {++ source_look(&l.base_font, l.size, l.color, l.bold, l.italic)++}++++/// What a drag on a paragraph box takes hold of.++#[derive(Clone, Copy, Debug, PartialEq)]++enum Grip {++ Move,++ /// An edge (screen left or right), dragged to rewrap the paragraph.++ Left,++ Right,++}++++/// A paragraph box being dragged: moved, or (from a handle on its left or right edge) resized.++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct BlockDrag {++ page: usize,++ block: usize,++ /// A paragraph index belongs to the document generation where the press was resolved.++ generation: u64,++ /// Where the drag started (screen).++ start: Pos2,++ grip: Grip,++}++++/// How far an edge grip reaches either side of a box's edge (screen pixels).++const EDGE_REACH: f32 = 6.0;++/// How far outside an open paragraph's frame the pointer still means the frame (screen pixels).++const FRAME_REACH: f32 = 4.0;++++/// The rewrap handles drawn on a paragraph box's left and right edges (screen).++fn width_handles(b: Rect) -> [Rect; 2] {++ let h = (b.height() * 0.5).clamp(14.0, 28.0);++ [b.left(), b.right()].map(|x| Rect::from_center_size(Pos2::new(x, b.center().y), egui::vec2(7.0, h)))++}++++/// The edge of `b` that `p` grabs: anywhere along its height, within reach of the line. A narrow++/// box keeps its middle for moving.++fn edge_at(b: Rect, p: Pos2) -> Option<Grip> {++ if p.y < b.top() - EDGE_REACH || p.y > b.bottom() + EDGE_REACH {++ return None;++ }++ let inside = EDGE_REACH.min(b.width() / 4.0);++ let (dl, dr) = (p.x - b.left(), b.right() - p.x);++ match (dl >= -EDGE_REACH && dl <= inside, dr >= -EDGE_REACH && dr <= inside) {++ (true, true) if dl <= dr => Some(Grip::Left),++ (_, true) => Some(Grip::Right),++ (true, false) => Some(Grip::Left),++ _ => None,++ }++}++++/// The topmost box under `p` and what it grabs there; edges only on an upright page.++fn grab_at(boxes: &[Rect], p: Pos2, upright: bool) -> Option<(usize, Grip)> {++ boxes.iter().enumerate().rev().find_map(|(i, b)| match upright.then(|| edge_at(*b, p)).flatten() {++ Some(g) => Some((i, g)),++ None => b.contains(p).then_some((i, Grip::Move)),++ })++}++++/// A paragraph's box on screen: its text rect (user space), with a little room around it.++fn paragraph_box(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Rect {++ xf.user_rect(info, page, rect.map(|v| v as f32)).expand(2.0)++}++++/// The width handles need the page upright (or upside down): on a quarter-turned page the++/// screen's horizontal is the paragraph's vertical.++fn has_edges(info: &DocInfo, page: usize) -> bool {++ info.pages.get(page).is_some_and(|p| p.rotation % 180 == 0)++}++++/// Whether a press at `p` takes hold of the width handle of one of the paragraphs `rects` (user++/// space). The handle is drawn half outside the box and grabs from a little further out still,++/// where a press is not on the box itself, so area selection must leave it to [`page_input`].++pub(crate) fn grabs_edge(xf: &PageXform, info: &DocInfo, page: usize, mut rects: impl Iterator<Item = [f64; 4]>, p: Pos2) -> bool {++ has_edges(info, page) && rects.any(|r| edge_at(paragraph_box(xf, info, page, r), p).is_some())++}++++pub(crate) fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {++ let p = &info.pages[page];++ let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));++ let (u, v) = (p.view_to_user(a.0, a.1), p.view_to_user(b.0, b.1));++ [u[0].min(v[0]) as f64, u[1].min(v[1]) as f64, u[0].max(v[0]) as f64, u[1].max(v[1]) as f64]++}++++/// Open `block` on `page` in the inline editor. The box's geometry and source are read from the++/// `lines` handed in, so callers pass the document's current inventory.++#[allow(clippy::too_many_arguments)]++fn open_editor(++ ui: &egui::Ui,++ xf: &PageXform,++ doc: &pdfcraft_engine::Document,++ lines: &[pdfcraft_engine::TextBlock],++ boxes: &[Rect],++ page: usize,++ block: usize,++ view: &mut DocView,++) {++ view.pending_text_open = None;++ let (Some(l), Some(b)) = (lines.get(block), boxes.get(block)) else { return };++ view.image_selection = None;++ let source_lines = doc.text_lines(page);++ let text = l.editor_text.clone();++ // Screen pixels per point, from the box's width.++ let scale = (b.width() - 4.0) / ((l.rect[2] - l.rect[0]).max(1.0) as f32);++ // How far the editor box may grow: a single-line paragraph's rewrite grows to the++ // page's right edge, a multi-line paragraph rewraps to its own width.++ let right = xf.rect.right().min(view.viewport_rect().right()) - 6.0;++ let max_width = if l.rows.len() == 1 { (right - b.left()).max(b.width()) } else { b.width() };++ view.line_editor = Some(LineEditor {++ selection: None,++ font_resource: None,++ page,++ block,++ text: text.clone(),++ original: text,++ rect: *b,++ source_rect: l.rect.map(|v| v as f32),++ multiline: l.rows.len() > 1,++ source: Some((l.clone(), source_lines)),++ fonts: install_source_fonts(ui.ctx(), doc, page),++ overflow: false,++ max_width,++ size: (l.size as f32 * scale).clamp(8.0, 72.0),++ focus: true,++ had_focus: false,++ look: look_of(l),++ look0: look_of(l),++ family_chosen: false,++ extras: Extras::default(),++ extras0: Extras::default(),++ });++}++++/// Lines and their screen boxes for a page; hover outlines, click opens the editor. Returns++/// `true` when the pointer was used.++#[allow(clippy::too_many_arguments)]++pub(crate) fn page_input(++ ui: &egui::Ui,++ resp: &egui::Response,++ xf: &PageXform,++ ptr: &PagePointer,++ page: usize,++ doc: &pdfcraft_engine::Document,++ lines: &[pdfcraft_engine::TextBlock],++ view: &mut DocView,++ allow_interaction: bool,++) -> bool {++ let info = &doc.info;++ if view.block_drag.is_some_and(|d| d.generation != doc.edit_generation()) {++ view.block_drag = None;++ return true;++ }++ let boxes: Vec<Rect> = lines.iter().map(|l| paragraph_box(xf, info, page, l.rect)).collect();++ // Outlines stay on their page, like its text (#3061).++ let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(xf.rect.expand(1.0)));++ let active = view.line_editor.as_ref().filter(|e| e.page == page).map(|e| e.block);++ for (i, b) in boxes.iter().enumerate() {++ if active != Some(i) {++ painter.rect_stroke(*b, CornerRadius::same(2), Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);++ }++ }++ // A box a switching click asked for opens now, once the edit queued with that click has++ // applied and `lines`/`boxes` are the document's new inventory (#2022).++ if allow_interaction++ && active.is_none()++ && let Some((open_page, key)) = view.pending_text_open.clone()++ && open_page == page++ {++ // The edit may have regrouped the page: open the paragraph that was clicked, wherever it++ // is now, and none if it was merged into another (#2516).++ match key.find(lines, 0) {++ Some(block) => open_editor(ui, xf, doc, lines, &boxes, page, block, view),++ None => view.pending_text_open = None,++ }++ }++ if !allow_interaction {++ return false;++ }++ let upright = has_edges(info, page);++ let draw_handles = |b: Rect| {++ for h in width_handles(b) {++ painter.rect(h, CornerRadius::same(2), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);++ }++ };++ // A drag in progress: the box follows the pointer (or the grabbed edge does); releasing applies it.++ if let Some(d) = view.block_drag.filter(|d| d.page == page)++ && let (Some(b), Some(l)) = (boxes.get(d.block).copied(), lines.get(d.block))++ {++ let p = ptr.pos.unwrap_or(d.start);++ let dx = p.x - d.start.x;++ let preview = match d.grip {++ Grip::Move => b.translate(p - d.start),++ Grip::Left => Rect::from_min_max(Pos2::new((b.left() + dx).min(b.right() - 12.0), b.min.y), b.max),++ Grip::Right => Rect::from_min_max(b.min, Pos2::new((b.right() + dx).max(b.left() + 12.0), b.max.y)),++ };++ painter.rect_stroke(preview, CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ let resizing = d.grip != Grip::Move;++ if resizing {++ draw_handles(preview);++ }++ ui.ctx().set_cursor_icon(if resizing { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::Move });++ if resp.drag_stopped() || !ptr.any_down {++ view.block_drag = None;++ let (from, to) = (user_box(xf, info, page, b), user_box(xf, info, page, preview));++ let edit = if resizing {++ // The new width in user space: the box's change, added to the paragraph's own. A++ // moved left side (in user space; on an upside-down page that's the screen's right++ // edge) moves the paragraph with it.++ let width = (l.rect[2] - l.rect[0]) + (to[2] - to[0]) - (from[2] - from[0]);++ let shift = to[0] - from[0];++ let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() };++ Edit::EditTextBlock { page, block: d.block, text: l.text.clone(), style }++ } else {++ // Translation must keep the selected source operators. Rewriting unchanged text++ // would also remove unrelated paragraphs that now overlap this one (#594).++ Edit::MoveObjects {++ page,++ objects: vec![ObjectTarget { kind: ObjectKind::Text, index: d.block }],++ offset: [to[0] - from[0], to[1] - from[1]],++ }++ };++ if preview != b {++ view.pending_edit = Some(edit);++ }++ }++ return true;++ }++ // Dragging a box (not while a paragraph is open for typing) moves it; from an edge, resizes it.++ // What it grabs comes from where the button went down, not where the pointer is now: egui++ // only calls it a drag once the pointer has moved a few pixels (or been held a moment), and a++ // quick flick has left the edge by then.++ if resp.drag_started()++ && active.is_none()++ && let Some(o) = ptr.origin++ && let Some((block, grip)) = grab_at(&boxes, o, upright)++ {++ view.block_drag = Some(BlockDrag { page, block, generation: doc.edit_generation(), start: o, grip });++ return true;++ }++ let Some(p) = ptr.within(xf.rect) else { return false };++ let Some((hit, grip)) = grab_at(&boxes, p, upright) else { return false };++ if active != Some(hit) {++ painter.rect_stroke(boxes[hit], CornerRadius::same(2), Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ }++ let on_edge = active.is_none() && grip != Grip::Move;++ if upright && active.is_none() {++ draw_handles(boxes[hit]);++ }++ // A closed paragraph moves when dragged (the four-way arrow says so; a click still opens it++ // for typing); an edge rewraps it. The open one takes the text cursor. Only where the page++ // shows, so the mode bar and side panels over a paragraph scrolled under them keep their own++ // cursor (#2755).++ if resp.contains_pointer() {++ ui.ctx().set_cursor_icon(if on_edge {++ egui::CursorIcon::ResizeHorizontal++ } else if active.is_none() {++ egui::CursorIcon::Move++ } else {++ egui::CursorIcon::Text++ });++ }++ if resp.clicked() {++ view.image_selection = None;++ // A click that moves the editor to another paragraph applies the open one first, so its++ // typed text is not dropped with the switched-away editor (#2022). A click on the open++ // box's own frame, which the editor's overlay does not cover, keeps it open instead.++ if let Some(open) = view.line_editor.as_ref().filter(|e| e.has_changes()) {++ if open.page == page && open.block == hit {++ return true;++ }++ if let Some(old) = view.line_editor.take() {++ let style = old.style();++ if old.text != old.original || style != pdfcraft_engine::BlockStyle::default() {++ view.applied_editor = Some(old.clone());++ view.pending_edit = Some(Edit::EditTextBlock { page: old.page, block: old.block, text: old.text, style });++ }++ }++ // The clicked box opens next frame, from the document with that edit applied.++ view.pending_text_open = lines.get(hit).map(|l| (page, pdfcraft_engine::BlockKey::of(l)));++ return true;++ }++ open_editor(ui, xf, doc, lines, &boxes, page, hit, view);++ }++ true++}++++/// The inline editor; returns the edit once the text is applied.++pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {++ // Clicks outside the document (the Format text panel) keep the paragraph open. Where the++ // click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.++ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));++ let page = view.line_editor.as_ref()?.page;++ let xf = view.page_xform(page)?;++ let hold = view.objects.hold_editor;++ // An OCR word is invisible text over a scan: the textless background still shows the scanned++ // word, so the editor covers it, as the applied edit will.++ let background_ready = view++ .line_editor++ .as_ref()++ .is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));++ // The measured extent of this paragraph's draft: a click straight from another paragraph++ // opens this one after the frame's measuring, which was the other one's.++ let draft_rect = view++ .line_editor++ .as_ref()++ .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))++ .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));++ // The editor draws on its page only, as the page itself does: a paragraph running past the++ // page's edge (a converter relying on the page clip) must not cover the next page or the++ // tool bars (#3061).++ let viewport = view.viewport_rect();++ let page_clip = xf.rect.intersect(viewport);++ let ed = view.line_editor.as_mut()?;++ if hold {++ ed.focus = true;++ }++ // Reproject the source box every frame. The page may have been zoomed, scrolled or rotated++ // while the format panel was open.++ // A font definition becomes active at the start of the next egui pass. Keep the source++ // raster visible until then instead of flashing an unrelated interface face.++ if !ctx.fonts(|f| ed.fonts.values().all(|name| f.definitions().families.contains_key(&FontFamily::Name(name.clone().into())))) {++ ctx.request_repaint();++ return None;++ }++ ed.rect = xf.user_rect(info, ed.page, ed.source_rect);++ ed.max_width = ed.rect.width();++ let scale = (ed.rect.width() / (ed.source_rect[2] - ed.source_rect[0]).abs().max(0.01)).max(0.01);++ ed.size = (ed.look.size as f32 * scale).clamp(1.0, 300.0);++ // egui draws the caret at least one row of this font tall. Each row already has its source++ // row's height, so the font stays below every row (half the region's smallest size): on a++ // 12 pt row under a 24 pt title the caret is as tall as the row, not the title.++ let smallest =++ ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));++ let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));++ let text_color = color32(ed.look.color);++ let block = ed.block;++ let mut done = None;++ let mut reveal = false;++ let mut look = None;++ // No fade-in: while it faded, the page's own copy of the text showed through the cover.++ // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or++ // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as++ // the page is, rather than pushed back into the window.++ egui::Area::new(egui::Id::unique("edit-text-line"))++ .order(egui::Order::Foreground)++ .fade_in(false)++ .fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))++ .constrain_to(viewport)++ .constrain(false)++ .show(ctx, |ui| {++ ui.set_clip_rect(ui.clip_rect().intersect(page_clip));++ // The editor opens at the source size. Once text changes, show the real draft++ // extent: single rows grow toward the page edge, paragraphs rewrap at their++ // source width, and the visible frame grows/shrinks vertically with their rows.++ // An OCR phrase (several stretched words on one scanned line) also grows rightwards.++ let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);++ let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {++ let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);++ let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;++ natural.max(ed.size * 0.4).min((xf.rect.right() - ed.rect.left() - 36.0 * scale).max(ed.rect.width()))++ } else {++ ed.rect.width().max(1.0)++ };++ ui.set_width(width);++ let measured = editor_galley(ui, ed, &ed.text, scale, width);++ ed.overflow = ed.has_changes() && (measured.rect.width() > ed.rect.width() + 1.5 || measured.rect.height() > ed.rect.height() + 1.5);++ let visible = Rect::from_min_size(ed.rect.min, measured.rect.size().max(egui::vec2(1.0, 1.0)));++ // Unsupported source programs use an interface fallback whose glyph advances++ // can differ from the PDF's. Keep every visible row inside the growing frame.++ let live = draft_rect.map_or(visible, |bounds| bounds.union(visible));++ ui.painter().rect_stroke(live.expand(2.0), CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ // On the frame, a press takes hold of the box (a click selects it, a drag moves it):++ // the pointer says so there, and reads as text inside.++ if let Some(p) = ui.input(|i| i.pointer.hover_pos())++ && ui.clip_rect().contains(p)++ && live.expand(2.0 + FRAME_REACH).contains(p)++ && !live.expand(2.0).contains(p)++ {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Move);++ }++ // White, unless the text is too pale to read on white (white text from a coloured++ // banner, #913): then a dark box, with a caret that shows on it.++ let fill = if background_ready { Color32::TRANSPARENT } else { editor_fill(text_color) };++ // An unchanged paragraph is the page's own text: the editor draws only its frame and++ // caret over it. Once it changes, the textless page goes under the editor's text or,++ // until that background is ready, a cover over the entire source box, including lines++ // the draft no longer occupies. Shrinking the text must never expose a copy. Both are++ // decided after this frame's typing, in places kept under the editor's text.++ let cover = ui.painter().add(egui::Shape::Noop);++ let unchanged = !ed.has_changes();++ egui::Frame::NONE.show(ui, |ui| {++ // A textless PDF preview, or the page itself, keeps its real background through++ // the transparent editor. The temporary opaque cover uses the shared caret-contrast rule.++ ui.visuals_mut().text_cursor.stroke.color = if background_ready || unchanged {++ if luminance(text_color) < 0.5 { Color32::BLACK } else { Color32::WHITE }++ } else {++ caret_color_on(fill)++ };++ let rows = 1;++ let snapshot = ed.clone();++ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {++ let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);++ if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }++ };++ let output = egui::TextEdit::multiline(&mut ed.text)++ .id(egui::Id::unique("edit-text-line-input"))++ .font(font.clone())++ .margin(egui::Margin::ZERO)++ .layouter(&mut layouter)++ .text_color(text_color)++ .frame(egui::Frame::NONE)++ .desired_width(width)++ .desired_rows(rows)++ .show(ui);++ // The editor paints over the page with no visible label; name it for assistive tech.++ output.response.response.clone().accessible_name(tl!("Text editing line"));++ if ed.has_changes() {++ if background_ready {++ reveal = true;++ } else {++ ui.painter().set(cover, egui::Shape::rect_filled(ed.rect.expand(1.0).union(output.response.rect), CornerRadius::ZERO, fill));++ }++ }++ look = Some((Arc::clone(&output.galley), output.galley_pos));++ if let Some(cursor) = output.cursor_range {++ let selected = cursor.as_sorted_char_range();++ let byte = |index| ed.text.char_indices().nth(index).map_or(ed.text.len(), |(at, _)| at);++ ed.selection = (!selected.is_empty()).then(|| byte(selected.start.into())..byte(selected.end.into()));++ }++ let r = output.response;++ if r.changed() {++ // The next pass measures the updated draft with the Apply/Save rewrite.++ ctx.request_repaint();++ }++ if ed.focus {++ r.request_focus();++ ed.focus = false;++ }++ let lost = lost_focus_once(&r, &mut ed.had_focus);++ let esc = ui.input(|i| i.key_pressed(egui::Key::Escape));++ let apply = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.command);++ if esc {++ done = Some(false);++ } else if apply || (lost && !outside && !hold) {++ done = Some(true);++ }++ });++ });++ if reveal {++ view.text_background.reveal();++ }++ if let Some((galley, pos)) = look {++ view.text_background.remember(&xf, page, block, galley, pos, text_color);++ }++ match done {++ Some(apply) => {++ let ed = view.line_editor.take()?;++ if !apply {++ return None;++ }++ view.applied_editor = Some(ed.clone());++ finished_edit(ed)++ }++ None => None,++ }++}++++/// The edit a closed paragraph editor applies, or `None` when nothing in it changed.++pub(crate) fn finished_edit(ed: LineEditor) -> Option<Edit> {++ let style = ed.style();++ (ed.text != ed.original || style != pdfcraft_engine::BlockStyle::default()).then_some(Edit::EditTextBlock {++ page: ed.page,++ block: ed.block,++ text: ed.text,++ style,++ })++}++++/// Whether an editor's text box `r` lost the keyboard this frame, given whether it `had` it at++/// the end of the editor's last frame (updated here). egui's `lost_focus` holds for a second++/// frame as well, and an editor that judges a click away by where the click landed must judge it++/// once, on the click's frame: on the next, a tap's position is gone (egui-winit sends++/// `PointerGone` with every touch release) and a mouse may have moved on.++pub(crate) fn lost_focus_once(r: &egui::Response, had: &mut bool) -> bool {++ let has = r.has_focus();++ std::mem::replace(had, has) && !has++}++++#[cfg(test)]++mod tests {++ use super::*;++++ #[test]++ fn the_rotate_knob_moves_below_when_there_is_no_room_above() {++ let view = Rect::from_min_max(Pos2::new(0.0, 100.0), Pos2::new(500.0, 500.0));++ let roomy = Rect::from_min_max(Pos2::new(100.0, 200.0), Pos2::new(200.0, 250.0));++ assert_eq!(rotate_knob(roomy, view).0, Pos2::new(150.0, 178.0));++ let at_top = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0));++ let (knob, stem) = rotate_knob(at_top, view);++ assert_eq!((knob, stem), (Pos2::new(150.0, 172.0), Pos2::new(150.0, 150.0)));++ }++++ #[test]++ fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {++ let c = Pos2::new(100.0, 100.0);++ let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);++ assert!(at(100.0, 0.0).abs() < 1e-3);++ assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");++ assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);++ assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);++ // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.++ assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);++ assert_eq!(at(101.0, 101.0), 0.0);++ assert_eq!(at(f32::NAN, 5.0), 0.0);++ }++++ /// An app with one text document open, and an editor on its first paragraph.++ fn preview_app() -> (crate::PdfCraftApp, LineEditor) {++ let mut app = crate::PdfCraftApp::new();++ let bytes = app.session.create_from_text("Preview", "Preview text").unwrap();++ app.open_bytes("preview.pdf", None, bytes.as_ref().clone()).unwrap();++ let doc = app.session.get(app.views[0].id).unwrap();++ let block = doc.text_blocks(0).remove(0);++ let ed = LineEditor {++ selection: None,++ font_resource: None,++ page: 0,++ block: 0,++ text: block.text.clone(),++ original: block.text.clone(),++ rect: Rect::NOTHING,++ source_rect: block.rect.map(|v| v as f32),++ multiline: block.rows.len() > 1,++ source: None,++ fonts: BTreeMap::new(),++ overflow: false,++ max_width: 400.0,++ size: block.size as f32,++ focus: true,++ had_focus: false,++ look: look_of(&block),++ look0: look_of(&block),++ family_chosen: false,++ extras: Extras::default(),++ extras0: Extras::default(),++ };++ (app, ed)++ }++++ #[test]++ fn picking_the_family_the_font_name_reads_as_still_changes_the_font() {++ // A Calibri paragraph reads as Helvetica; picking Helvetica from the list used to leave++ // `look` equal to what the paragraph had, so no family change was sent and Calibri stayed.++ let (_app, mut ed) = preview_app();++ let family = ed.look0.family;++ assert_eq!(ed.style().family, None, "nothing chosen yet");++ ed.choose_family(family);++ assert_eq!(ed.style().family, Some((family, ed.look.bold, ed.look.italic)));++ assert!(ed.has_changes());++ assert_eq!(ed.font_shown(&[]), family.label());++ ed.keep_source_font();++ assert_eq!(ed.style().family, None, "Keep source fonts withdraws the choice");++ ed.choose_family(family);++ ed.applied();++ assert_eq!(ed.style().family, None, "an applied choice is the paragraph's font now");++ }++++ #[test]++ fn a_loaded_font_is_applied_to_the_paragraph_being_edited() {++ // Loading a font used to only register it on the page: the paragraph kept its source++ // face until the font was found again in the document-font menu (#2591).++ let (mut app, ed) = preview_app();++ app.views[0].line_editor = Some(ed);++ let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();++ app.use_files(crate::files::FilePurpose::TextFont { page: 0 }, vec![("Inter-Regular.ttf".into(), inter)]);++ let doc = app.session.get(app.views[0].id).unwrap();++ let lines = doc.text_lines(0);++ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "Preview text");++ assert!(lines.iter().all(|l| l.base_font == "Inter-Regular"), "{:?}", lines.iter().map(|l| &l.base_font).collect::<Vec<_>>());++ assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");++ }++++ #[test]++ fn save_applies_the_paragraph_open_in_the_editor() {++ // Save wrote the file without the paragraph still open in the editor (#3496).++ let (mut app, mut ed) = preview_app();++ ed.text = "Text preview".into();++ app.views[0].line_editor = Some(ed);++ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));++ let _ = std::fs::remove_dir_all(&dir);++ std::fs::create_dir_all(&dir).unwrap();++ app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());++++ assert!(app.save_active(crate::SaveTarget::InPlace));++ assert!(app.views[0].line_editor.is_none());++ let doc = app.session.get(app.views[0].id).unwrap();++ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");++ let _ = std::fs::remove_dir_all(&dir);++ }++++ #[test]++ fn a_refused_text_box_does_not_lose_the_open_paragraph() {++ let (mut app, mut ed) = preview_app();++ ed.text = "Text preview".into();++ app.views[0].line_editor = Some(ed);++ let draft = crate::content_ui::TextDraft {++ page: 9,++ index: None,++ rect: [20.0, 20.0, 120.0, 40.0],++ text: "Typed text".into(),++ style: crate::content_ui::default_style(),++ focus: true,++ };++ app.views[0].content.draft = Some(draft.clone());++++ assert!(!app.commit_typing_in(app.views[0].id));++ assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");++ assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");++ let doc = app.session.get(app.views[0].id).unwrap();++ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");++ }++++ #[test]++ fn a_refused_paragraph_stays_open_with_its_text() {++ let (mut app, mut ed) = preview_app();++ ed.text = "Text preview".into();++ ed.page = 9;++ app.views[0].line_editor = Some(ed.clone());++++ assert!(!app.commit_typing_in(app.views[0].id));++ assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");++ }++++ #[test]++ fn text_background_is_cached_without_editing_and_released_on_cancel() {++ let (app, ed) = preview_app();++ let doc = app.session.get(app.views[0].id).unwrap();++ let source = doc.bytes.clone();++ let generation = doc.edit_generation();++ let ctx = egui::Context::default();++ let mut background = TextBackground::default();++ for _ in 0..100 {++ background.prepare(&ctx, doc, Some(&ed), None, 1.0);++ if background.ready(0, 0) {++ break;++ }++ std::thread::sleep(std::time::Duration::from_millis(5));++ }++ assert!(background.ready(0, 0));++ assert!(!background.pending());++ let texture = background.texture.as_ref().unwrap().id();++ background.prepare(&ctx, doc, Some(&ed), None, 1.0);++ assert_eq!(background.texture.as_ref().unwrap().id(), texture);++ assert_eq!(doc.bytes, source);++ assert_eq!(doc.edit_generation(), generation);++ assert!(!doc.dirty && doc.can_undo().is_none());++ background.prepare(&ctx, doc, None, None, 1.0);++ assert!(background.texture.is_none() && background.renderer.is_none());++ }++++ #[test]++ fn the_editing_background_stays_sharp_on_a_zoomed_page() {++ // While a paragraph is open, the page around it is drawn from this one raster: it is++ // asked for at the tiling threshold, not the 2048-pixel backdrop side, which went soft++ // beyond about 1.2x on a Retina display.++ let (app, ed) = preview_app();++ let doc = app.session.get(app.views[0].id).unwrap();++ let page = &doc.info.pages[0];++ let ctx = egui::Context::default();++ ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });++ let mut background = TextBackground::default();++ background.prepare(&ctx, doc, Some(&ed), None, 8.0);++ let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));++ assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");++ assert_eq!(background.tag, Some((expected * 1000.0) as u64));++ // A GPU that can't hold such a texture caps it.++ ctx.end_pass().textures_delta.clear();++ ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });++ let mut small = TextBackground::default();++ small.prepare(&ctx, doc, Some(&ed), None, 8.0);++ assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));++ ctx.end_pass().textures_delta.clear();++ }++++ #[test]++ fn pale_text_is_edited_on_a_dark_box() {++ // #913: white text from a coloured banner was typed onto a white box and vanished.++ for pale in [Color32::WHITE, Color32::from_rgb(0xFF, 0xFF, 0x00), Color32::from_gray(0xE0), Color32::from_rgb(0xFF, 0xA5, 0x00)] {++ assert_eq!(editor_fill(pale), DARK_EDITOR_FILL, "{pale:?}");++ assert!(contrast(pale, editor_fill(pale)) >= 4.5, "{pale:?} is readable");++ }++ // Ordinary dark or saturated text keeps the white box.++ for dark in [Color32::BLACK, Color32::from_rgb(0x1F, 0x2A, 0x6B), Color32::from_rgb(0xC0, 0x00, 0x00), Color32::from_gray(0x60)] {++ assert_eq!(editor_fill(dark), Color32::WHITE, "{dark:?}");++ }++ }++++ #[test]++ fn caret_contrasts_with_its_fill() {++ assert_eq!(caret_color_on(Color32::WHITE), Color32::BLACK);++ assert_eq!(caret_color_on(Color32::from_rgb(0xFF, 0xFF, 0xF4)), Color32::BLACK);++ assert_eq!(caret_color_on(Color32::BLACK), Color32::WHITE);++ assert_eq!(caret_color_on(DARK_EDITOR_FILL), Color32::WHITE);++ }++++ #[test]++ fn bullet_list_toggles_and_preserves_content() {++ let mut text = "First line\nSecond line\n\nThird line".to_string();++ assert!(!is_bulleted(&text));++ assert!(toggle_bullet_list(&mut text));++ assert!(is_bulleted(&text));++ assert_eq!(text, "• First line\n• Second line\n\n• Third line");++++ // Toggling again removes bullets++ assert!(toggle_bullet_list(&mut text));++ assert!(!is_bulleted(&text));++ assert_eq!(text, "First line\nSecond line\n\nThird line");++ }++++ #[test]++ fn numbered_list_toggles_and_preserves_content() {++ let mut text = "Item A\nItem B\n\nItem C".to_string();++ assert!(!is_numbered(&text));++ assert!(toggle_numbered_list(&mut text));++ assert!(is_numbered(&text));++ assert_eq!(text, "1. Item A\n2. Item B\n\n3. Item C");++++ // Toggling again removes numbering++ assert!(toggle_numbered_list(&mut text));++ assert!(!is_numbered(&text));++ assert_eq!(text, "Item A\nItem B\n\nItem C");++ }++++ #[test]++ fn superscript_and_subscript_conversion() {++ let mut ed = LineEditor {++ page: 0,++ block: 0,++ text: "E = mc2".to_string(),++ original: "E = mc2".to_string(),++ rect: egui::Rect::ZERO,++ source_rect: [0.0; 4],++ max_width: 100.0,++ overflow: false,++ selection: Some(6..7), // selecting '2'++ font_resource: None,++ fonts: std::collections::BTreeMap::new(),++ source: None,++ multiline: false,++ size: 12.0,++ family_chosen: false,++ focus: true,++ had_focus: false,++ look: pdfcraft_engine::AddedText::default(),++ look0: pdfcraft_engine::AddedText::default(),++ extras: Extras::default(),++ extras0: Extras::default(),++ };++++ assert!(toggle_superscript(&mut ed));++ assert_eq!(ed.text, "E = mc²");++ // Toggling superscript again returns to normal '2'++ assert!(toggle_superscript(&mut ed));++ assert_eq!(ed.text, "E = mc2");++++ // Test subscript on H2O++ ed.text = "H2O".to_string();++ ed.selection = Some(1..2); // selecting '2'++ assert!(toggle_subscript(&mut ed));++ assert_eq!(ed.text, "H₂O");++ assert!(toggle_subscript(&mut ed));++ assert_eq!(ed.text, "H2O");++ }++++ #[test]++ fn value_based_line_spacing_in_style() {++ let ed = LineEditor {++ page: 0,++ block: 0,++ text: "Paragraph text".to_string(),++ original: "Paragraph text".to_string(),++ rect: egui::Rect::ZERO,++ source_rect: [0.0; 4],++ max_width: 100.0,++ overflow: false,++ selection: None,++ font_resource: None,++ fonts: std::collections::BTreeMap::new(),++ source: None,++ multiline: false,++ size: 12.0,++ family_chosen: false,++ focus: true,++ had_focus: false,++ look: pdfcraft_engine::AddedText::default(),++ look0: pdfcraft_engine::AddedText::default(),++ extras: Extras { line_spacing: 1.33, underline: true, ..Default::default() },++ extras0: Extras::default(),++ };++ let style = ed.style();++ assert_eq!(style.line_spacing, Some(1.33));++ assert_eq!(style.underline, Some(true));++ }++}diff --cc crates/ui-egui/src/tools/edit_text_ui/image.rsindex 000000000,9f55a7d5e..53a9116bamode 000000,100644..100644--- a/crates/ui-egui/src/tools/edit_text_ui/image.rs+++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs@@@ -1,0 -1,637 +1,1203 @@@-use super::*;--/// A selected page image, and what the pointer is doing to it.-#[derive(Clone, Debug, PartialEq)]-pub struct ImageSelection {- pub page: usize,- pub index: usize,- /// Dragging: the start point and, for a corner, the opposite corner (screen).- drag: Option<(Pos2, Option<Pos2>)>,- /// Crop mode (Acrobat's crop handles): the box kept so far.- pub crop: Option<CropMode>,- /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).- turning: bool,- /// A move or resize applied on release: the frame it had and the one it got, in the page's- /// 0..1 coordinates, while the page raster still has the picture where it was.- settled: Option<(Rect, Rect)>,-}--impl ImageSelection {- /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.- pub(crate) fn cancel_pointer_gesture(&mut self) {- self.drag = None;- self.turning = false;- if let Some(crop) = &mut self.crop- && let Some((_, _, before)) = crop.drag.take()- {- crop.keep = before;- }- }-}--/// Cropping a page image: the handles trim instead of resizing, the part that will go is-/// dimmed, Enter or Done applies and Esc or Cancel leaves it.-#[derive(Clone, Debug, PartialEq)]-pub struct CropMode {- /// The box to keep (user space).- pub keep: [f64; 4],- /// A drag in progress: the grip (0–3 corners, 4–7 edges, 8 the inside), where it started- /// and the box then.- drag: Option<(usize, Pos2, [f64; 4])>,-}--impl CropMode {- pub fn new(keep: [f64; 4]) -> Self {- Self { keep, drag: None }- }-}--/// The screen boxes of the crop's eight handles: corners, then the top, right, bottom and left-/// edge midpoints.-fn crop_handles(k: Rect) -> [Pos2; 8] {- [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]-}--/// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`-/// (the pointer and keys are the crop's while it lasts).-#[allow(clippy::too_many_arguments)]-fn crop_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- info: &DocInfo,- view: &mut DocView,- i: usize,- b: Rect,- allow_interaction: bool,-) -> bool {- let painter = ui.painter();- let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false };- let hover_pos = ptr.pos;- let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);- // A drag in progress moves a grip; the box stays inside the picture and at least 6 px.- if allow_interaction- && resp.drag_started()- && let Some(o) = ptr.origin- {- let k = keep_screen(mode.keep);- let grip = crop_handles(k).iter().position(|h| h.distance(o) < 8.0).or_else(|| k.contains(o).then_some(8));- if let Some(g) = grip {- mode.drag = Some((g, o, mode.keep));- }- }- if let Some((grip, start, at_start)) = mode.drag- && let Some(p) = hover_pos- {- let d = p - start;- let k0 = keep_screen(at_start);- let (mut min, mut max) = (k0.min, k0.max);- match grip {- 0 => {- min.x += d.x;- min.y += d.y;- }- 1 => {- max.x += d.x;- min.y += d.y;- }- 2 => {- min.x += d.x;- max.y += d.y;- }- 3 => {- max.x += d.x;- max.y += d.y;- }- 4 => min.y += d.y,- 5 => max.x += d.x,- 6 => max.y += d.y,- 7 => min.x += d.x,- _ => {- let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));- min += shift;- max += shift;- }- }- let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));- min.x = min.x.clamp(b.min.x, b.max.x - min_w);- min.y = min.y.clamp(b.min.y, b.max.y - min_h);- max.x = max.x.clamp(min.x + min_w, b.max.x);- max.y = max.y.clamp(min.y + min_h, b.max.y);- mode.keep = user_box(xf, info, page, Rect::from_min_max(min, max));- if resp.drag_stopped() || !ptr.primary_down {- mode.drag = None;- }- }- let k = keep_screen(mode.keep);- // What goes is dimmed; what stays keeps its frame and handles.- let dim = Color32::from_black_alpha(96);- for r in [- Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)),- Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max),- Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)),- Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)),- ] {- if r.is_positive() {- painter.rect_filled(r.intersect(xf.rect), CornerRadius::ZERO, dim);- }- }- painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- for h in crop_handles(k) {- painter.rect(- Rect::from_center_size(h, egui::vec2(8.0, 8.0)),- CornerRadius::ZERO,- Color32::WHITE,- Stroke::new(1.0, ACCENT),- egui::StrokeKind::Middle,- );- }- // Done and Cancel, painted under the box (above it near the bottom of the view).- let font = egui::FontId::proportional(12.5);- let pill = |label: &str, right: f32, y: f32| -> Rect {- let w = painter.layout_no_wrap(label.to_string(), font.clone(), Color32::WHITE).size().x + 20.0;- Rect::from_min_size(Pos2::new(right - w, y), egui::vec2(w, 22.0))- };- let y = if k.max.y + 30.0 < xf.rect.max.y { k.max.y + 6.0 } else { k.min.y - 28.0 };- let done = pill(tl!("Done"), k.max.x, y);- let cancel = pill(tl!("Cancel"), done.min.x - 6.0, y);- let t = crate::theme::Tokens::get(ui.ctx());- painter.rect_filled(done, CornerRadius::same(11), ACCENT);- painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);- painter.rect(cancel, CornerRadius::same(11), t.panel, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);- painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font, t.text);- if let Some(p) = hover_pos {- let icon = if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {- match g {- 0 | 3 => egui::CursorIcon::ResizeNwSe,- 1 | 2 => egui::CursorIcon::ResizeNeSw,- 4 | 6 => egui::CursorIcon::ResizeVertical,- _ => egui::CursorIcon::ResizeHorizontal,- }- } else if done.contains(p) || cancel.contains(p) {- egui::CursorIcon::PointingHand- } else if k.contains(p) {- egui::CursorIcon::Move- } else {- egui::CursorIcon::Default- };- ui.ctx().set_cursor_icon(icon);- }- let clicked = |r: Rect| allow_interaction && resp.clicked() && hover_pos.is_some_and(|p| r.contains(p));- let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();- if clicked(done) || keys(egui::Key::Enter) {- let keep = mode.keep;- if let Some(s) = view.image_selection.as_mut() {- s.crop = None;- }- if keep_screen(keep) != b {- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });- }- } else if (clicked(cancel) || keys(egui::Key::Escape))- && let Some(s) = view.image_selection.as_mut()- {- s.crop = None;- }- true-}--impl ImageSelection {- pub(crate) fn dragging(&self) -> bool {- self.drag.is_some()- }-}--/// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where-/// the screen may still show the picture).-fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {- let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));- for r in blank {- clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);- }- let mut mesh = egui::Mesh::with_texture(tex);- for (a, b) in [- (from.left_top(), to.left_top()),- (from.right_top(), to.right_top()),- (from.right_bottom(), to.right_bottom()),- (from.left_bottom(), to.left_bottom()),- ] {- let (u, v) = xf.screen_to_norm(a);- mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });- }- mesh.add_triangle(0, 1, 2);- mesh.add_triangle(0, 2, 3);- clipped.add(egui::Shape::mesh(mesh));-}--/// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same-/// applies after the pointer leaves the image/page while dragging.-pub(crate) fn image_owns_pointer(ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {- let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };- if selection.drag.is_some() {- return true;- }- let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };- let Some(rect) = image.visible_rect else { return false };- let b = xf.user_rect(info, page, rect.map(|v| v as f32));- let p = if ptr.primary_down { ptr.origin } else { ptr.pos };- let knob = rotate_knob(b, ui.clip_rect()).0;- p.is_some_and(|p| [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom(), knob].iter().any(|c| c.distance(p) < 8.0))-}--/// What a right-click on a selected image asks for.-#[derive(Clone, Copy, Debug, PartialEq)]-pub(crate) enum ImageAction {- Replace(usize, usize),- Save(usize, usize),- Copy(usize, usize),- CopyFile(usize, usize),- /// Copy the picture, then remove it from the page.- Cut(usize, usize),- /// Mark the picture for redaction (applied later from Redact a PDF).- Redact(usize, usize),- /// Create a link over the picture.- Link(usize, usize),- /// Open Recognize Text for the picture's page.- Recognize(usize),-}--/// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the-/// top edge, or below the bottom edge when the area on screen (`view`) has no room above.-pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) {- let above = b.center_top() - egui::vec2(0.0, 22.0);- if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) }-}--/// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`-/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.-pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {- let v = pointer - centre;- if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {- return 0.0;- }- // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).- let d = v.x.atan2(-v.y).to_degrees();- if snap { (d / 15.0).round() * 15.0 } else { d }-}--/// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used.-#[allow(clippy::too_many_arguments)]-pub(crate) fn image_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- ptr: &PagePointer,- page: usize,- info: &DocInfo,- images: &[pdfcraft_engine::PageImage],- view: &mut DocView,- action: &mut Option<ImageAction>,- allow_interaction: bool,-) -> bool {- let boxes: Vec<Rect> = images.iter().map(|im| im.visible_rect.map_or(Rect::NOTHING, |r| xf.user_rect(info, page, r.map(|v| v as f32)))).collect();- let painter = ui.painter();- let hover_pos = ptr.pos;- let image_contains = |index: usize, point: Pos2| {- let (x, y) = xf.screen_to_view(point);- let Some(p) = info.pages.get(page) else { return false };- let user = p.view_to_user(x, y);- images.get(index).is_some_and(|im| im.contains(user.map(f64::from)))- };- let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len());- let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some());- // Few images: faint outlines for all of them, as before. Many: only the selected and- // hovered boxes, so a ~1000-image CAD page stays interactive in Edit text & images.- // Fully clipped placements (empty visible frames) get no outline.- let faint_all = boxes.len() <= MAX_OUTLINES;- // The picture being dragged has its frame at the pointer; its outline where it was would- // trail behind until the release.- let moving = selected.filter(|_| dragging);- if faint_all {- for (_, b) in boxes.iter().enumerate().filter(|(i, b)| b.is_positive() && moving != Some(*i)) {- painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);- }- }- let hovered_box = hover_pos.and_then(|p| boxes.iter().enumerate().rposition(|(i, b)| b.is_positive() && b.contains(p) && image_contains(i, p)));- if !faint_all {- for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) {- if let Some(b) = boxes.get(i).filter(|b| b.is_positive()) {- painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);- }- }- }- for i in selected.into_iter().chain(hovered_box).collect::<Vec<_>>() {- let Some(b) = boxes.get(i).copied().filter(|b| b.is_positive()) else { continue };- if selected == Some(i) {- // The selected frame and handles are drawn below (or the drag preview instead).- if !dragging {- painter.rect_filled(b, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));- }- } else {- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);- }- }- // The selected image: frame, corner handles, dragging.- if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {- let b = boxes[i];- if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some()) {- return crop_input(ui, resp, xf, ptr, page, info, view, i, b, allow_interaction);- }- let corners = [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom()];- let handles = |rect: Rect| {- for c in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] {- painter.rect(- Rect::from_center_size(c, egui::vec2(8.0, 8.0)),- CornerRadius::ZERO,- Color32::WHITE,- Stroke::new(1.0, ACCENT),- egui::StrokeKind::Middle,- );- }- };- // Until the page is rendered again its raster has an applied move or resize's picture- // where it was: it stays blanked there and drawn where it went.- // The whole-page raster and its tiles are replaced separately: the old frame stays blanked- // while anything still shows the picture there, but its pixels come from the old frame- // only while the whole-page raster itself is the old one. Once that is fresh it has the- // picture where it went, and that is where they come from.- let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page));- let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));- // Where the screen may still show the picture from before an applied move, while the page- // isn't drawn again yet. Another drag keeps it blanked too.- let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from);- if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) {- match (s.settled, raster) {- (Some((from, to)), Some(tex)) if out_of_date => {- let source = if raster_old { from } else { to };- stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to));- }- _ => s.settled = None,- }- }- if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {- painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- handles(b);- }- if allow_interaction && let Some(corner) = hover_pos.and_then(|p| corners.iter().position(|c| c.distance(p) < 8.0)) {- ui.ctx().set_cursor_icon(if matches!(corner, 0 | 3) { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });- }- // The rotate handle: a knob above the top edge, joined to it by a short stem.- let (knob, stem) = rotate_knob(b, ui.clip_rect());- if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {- painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT));- painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));- if allow_interaction && hover_pos.is_some_and(|p| p.distance(knob) < 8.0) {- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);- }- }- if allow_interaction- && resp.drag_started()- && let Some(o) = ptr.origin- && o.distance(knob) < 8.0- {- if let Some(s) = view.image_selection.as_mut() {- s.drag = Some((o, None));- s.turning = true;- }- } else if allow_interaction- && resp.drag_started()- && let Some(o) = ptr.origin- {- let corner = corners.iter().position(|c| c.distance(o) < 8.0);- if corner.is_some() || image_contains(i, o) {- let opposite = corner.map(|k| corners[3 - k]);- if let Some(s) = view.image_selection.as_mut() {- s.drag = Some((o, opposite));- }- }- }- if view.image_selection.as_ref().is_some_and(|s| s.turning) {- let shift = ui.input(|i| i.modifiers.shift);- let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));- // The turned outline as a preview; the engine redraws the pixels on release.- let centre = b.center();- let (sin, cos) = degrees.to_radians().sin_cos();- let turn = |c: Pos2| {- let v = c - centre;- centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)- };- let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();- painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));- let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);- let label = Rect::from_center_size(turn(knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0));- painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);- painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT);- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);- if resp.drag_stopped() || !ptr.primary_down {- if let Some(s) = view.image_selection.as_mut() {- s.drag = None;- s.turning = false;- }- if degrees.abs() >= 0.05 {- view.pending_edit =- Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });- }- }- return true;- }- if let Some((start, opposite)) = view.image_selection.as_ref().and_then(|s| s.drag)- && let Some(p) = hover_pos- {- let preview = match opposite {- // Resize from the opposite corner, keeping the aspect ratio.- Some(fixed) => {- let (w0, h0) = (b.width().max(1.0), b.height().max(1.0));- // Use the axis with the larger relative pointer change. Taking the maximum- // absolute size freezes shrinking when the other axis hasn't moved. Measure- // from the press point so grabbing a handle off-centre cannot cause a jump.- let horizontal = (p.x - start.x) * (start.x - fixed.x).signum() / w0;- let vertical = (p.y - start.y) * (start.y - fixed.y).signum() / h0;- let delta = if horizontal.abs() > vertical.abs() { horizontal } else { vertical };- let k = (1.0 + delta).max(0.05);- let (w, h) = (w0 * k, h0 * k);- let x = if start.x < fixed.x { fixed.x - w } else { fixed.x };- let y = if start.y < fixed.y { fixed.y - h } else { fixed.y };- Rect::from_min_size(Pos2::new(x, y), egui::vec2(w, h))- }- None => b.translate(p - start),- };- // Move/resize the full placement by the visible frame's change. The engine- // transforms an isolated crop together with its image, preserving its contents.- let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32)));- // A zero-width or zero-height visible frame (or a degenerate ratio) keeps the- // placement's scale instead of producing inf/NaN.- let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 };- let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height()));- let target = Rect::from_min_max(preview.min + (raw.min - b.min) * factor, preview.min + (raw.max - b.min) * factor);- let visible = preview.intersect(xf.rect);- if visible.is_positive() {- // The pixels follow the frame: the page raster's picture of the image, stretched- // into the preview over a blank where it was. Re-rendering every frame of a drag- // would lag; the edit renders it properly on release.- if preview != b- && let Some(tex) = view.page_raster(page)- {- // Its pixels: where the whole-page raster has it.- let source = left_at.filter(|_| raster_old).map_or(b, screen);- let blank: Vec<Rect> = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect();- stretched_picture(painter, xf, tex, &blank, source, preview);- }- painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));- painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);- handles(preview);- }- if resp.drag_stopped() || !ptr.primary_down {- if let Some(s) = view.image_selection.as_mut() {- s.drag = None;- let norm = |r: Rect| {- let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max));- Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1))- };- s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview)));- }- if preview != b {- view.pending_edit =- Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) });- }- }- ui.ctx().set_cursor_icon(match opposite {- Some(fixed) if (start.x - fixed.x) * (start.y - fixed.y) < 0.0 => egui::CursorIcon::ResizeNeSw,- Some(_) => egui::CursorIcon::ResizeNwSe,- None => egui::CursorIcon::Move,- });- return true;- }- if allow_interaction- && ui.input(|inp| inp.key_pressed(egui::Key::Delete) || inp.key_pressed(egui::Key::Backspace))- && !ui.ctx().egui_wants_keyboard_input()- {- view.image_selection = None;- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Delete });- return true;- }- }- if !allow_interaction {- return false;- }- // An open menu stays drawn wherever the pointer is: most of its items lie outside the picture- // (a logo is smaller than its menu), and a menu that is not drawn for a frame cannot be clicked.- // Only a menu opened by a right-click on the picture: one opened over text or empty page while- // a picture stays selected is the page's own menu.- let menu_key = resp.id.with("image-menu");- if resp.secondary_clicked() {- ui.ctx().data_mut(|d| d.insert_temp(menu_key, false));- }- let mut menu_drawn = false;- if let Some(sel) = selected- && resp.context_menu_opened()- && ui.ctx().data(|d| d.get_temp::<bool>(menu_key)).unwrap_or(false)- {- resp.context_menu(|ui| image_menu(ui, page, sel, images, view, action));- menu_drawn = true;- }- let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };- let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| b.contains(p) && image_contains(i, p)) else { return false };- if selected != Some(hit) {- painter.rect_stroke(boxes[hit], CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);- }- let Some(b) = boxes.get(hit).copied() else { return false };- let corner = [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom()].iter().position(|c| c.distance(p) < 8.0);- ui.ctx().set_cursor_icon(match (selected == Some(hit), corner) {- (true, Some(0 | 3)) => egui::CursorIcon::ResizeNwSe,- (true, Some(_)) => egui::CursorIcon::ResizeNeSw,- (true, None) => egui::CursorIcon::Move,- _ => egui::CursorIcon::PointingHand,- });- if resp.clicked() || resp.secondary_clicked() {- view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, turning: false, settled: None });- }- if resp.secondary_clicked() {- ui.ctx().data_mut(|d| d.insert_temp(menu_key, true));- }- if selected == Some(hit) && !menu_drawn {- resp.context_menu(|ui| image_menu(ui, page, hit, images, view, action));- }- true-}--/// The right-click menu of the picture `hit` (its rotate, flip, replace, copy, cut, redact, link,-/// recognize and delete items).-fn image_menu(- ui: &mut egui::Ui,- page: usize,- hit: usize,- images: &[pdfcraft_engine::PageImage],- view: &mut DocView,- action: &mut Option<ImageAction>,-) {- use pdfcraft_engine::ImageEdit as E;- let items: [(&str, Option<E>); 4] = [- (tl!("Rotate Clockwise"), Some(E::Rotate(1))),- (tl!("Rotate Counterclockwise"), Some(E::Rotate(3))),- (tl!("Flip Horizontal"), Some(E::Flip { horizontal: true })),- (tl!("Flip Vertical"), Some(E::Flip { horizontal: false })),- ];- for (label, change) in items {- if ui.button(label).clicked() {- view.pending_edit = change.map(|c| Edit::EditPageImage { page, index: hit, change: c });- ui.close();- }- }- // Crop: the handles trim instead of resizing until Done.- if ui.button(tl!("Crop Image")).clicked() {- if let (Some(s), Some(im)) = (view.image_selection.as_mut(), images.get(hit)) {- s.crop = Some(CropMode::new(im.visible_rect.unwrap_or(im.rect)));- }- ui.close();- }- let cropped = images.get(hit).is_some_and(|im| im.visible_rect.is_some_and(|v| v.iter().zip(im.rect.iter()).any(|(a, b)| (a - b).abs() > 0.01)));- if ui.add_enabled(cropped, egui::Button::new(tl!("Remove Crop"))).clicked() {- if let Some(im) = images.get(hit) {- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Crop(im.rect) });- }- ui.close();- }- let raster = images.get(hit).is_some_and(|image| !image.is_form);- if ui.add_enabled(raster, egui::Button::new(tl!("Replace Image…"))).clicked() {- *action = Some(ImageAction::Replace(page, hit));- ui.close();- }- if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {- *action = Some(ImageAction::Save(page, hit));- ui.close();- }- // Cutting and copying also find the picture inside grouped Form artwork.- if ui.button(tl!("Cut Image")).clicked() {- *action = Some(ImageAction::Cut(page, hit));- ui.close();- }- if ui.button(tl!("Copy Image")).clicked() {- *action = Some(ImageAction::Copy(page, hit));- ui.close();- }- if ui.button(tl!("Copy Image in Original Format")).clicked() {- *action = Some(ImageAction::CopyFile(page, hit));- ui.close();- }- ui.separator();- if ui.button(tl!("Redact Image")).clicked() {- *action = Some(ImageAction::Redact(page, hit));- ui.close();- }- if ui.button(tl!("Create Link…")).clicked() {- *action = Some(ImageAction::Link(page, hit));- ui.close();- }- if ui.button(tl!("Recognize Text…")).clicked() {- *action = Some(ImageAction::Recognize(page));- ui.close();- }- ui.separator();- if ui.button(tl!("Delete")).clicked() {- view.image_selection = None;- view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });- ui.close();- }-}++use super::*;++use crate::canvas::{ImageObb, PainterExt};++use crate::image_engine::{++ apply_crop, apply_resize, apply_resize_proportional, draw_handle, draw_rule_of_thirds, HandleId, CROP_ACCENT,++};++++/// The 8 resize handles on an image (4 corners + 4 edge centers).++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum ImageHandle {++ TopLeft,++ TopCenter,++ TopRight,++ RightCenter,++ BottomRight,++ BottomCenter,++ BottomLeft,++ LeftCenter,++}++++#[derive(Clone, Copy, Debug, PartialEq, Eq)]++pub enum DragTarget {++ Move,++ Handle(ImageHandle),++ CropHandle(ImageHandle),++ Rotate,++}++++#[derive(Clone, Copy, Debug, PartialEq)]++pub struct ImageDrag {++ pub start: Pos2,++ pub target: DragTarget,++ pub initial_rect: Rect,++ pub initial_matrix: [f64; 6],++}++++/// A selected page image, and what the pointer is doing to it.++#[derive(Clone, Debug, PartialEq)]++pub struct ImageSelection {++ pub page: usize,++ pub index: usize,++ /// Dragging in progress.++ pub drag: Option<ImageDrag>,++ /// Crop mode: the box kept so far.++ pub crop: Option<CropMode>,++ pub crop_mode: bool,++ pub crop_rect: Option<Rect>,++ /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).++ pub turning: bool,++ /// A move or resize applied on release: the frame it had and the one it got, in the page's++ /// 0..1 coordinates, while the page raster still has the picture where it was.++ pub settled: Option<(Rect, Rect)>,++}++++impl ImageSelection {++ /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.++ pub(crate) fn cancel_pointer_gesture(&mut self) {++ self.drag = None;++ self.turning = false;++ if let Some(crop) = &mut self.crop++ && let Some((_, _, before)) = crop.drag.take()++ {++ crop.keep = before;++ }++ }++++ pub(crate) fn dragging(&self) -> bool {++ self.drag.is_some()++ }++}++++/// Cropping a page image: the handles trim instead of resizing, the part that will go is++/// dimmed, Enter or Done applies and Esc or Cancel leaves it.++#[derive(Clone, Debug, PartialEq)]++pub struct CropMode {++ /// The box to keep (user space or normalized UV).++ pub keep: [f64; 4],++ /// A drag in progress: the grip (0–7 handles, 8 inside), where it started and the box then.++ pub(crate) drag: Option<(usize, Pos2, [f64; 4])>,++}++++impl CropMode {++ pub fn new(keep: [f64; 4]) -> Self {++ Self { keep, drag: None }++ }++}++++#[derive(Clone, Copy, Debug, PartialEq)]++pub(crate) struct Matrix(pub(crate) [f64; 6]);++++impl Matrix {++ pub(crate) fn apply(&self, x: f64, y: f64) -> (f64, f64) {++ let [a, b, c, d, e, f] = self.0;++ (a * x + c * y + e, b * x + d * y + f)++ }++++ pub(crate) fn invert(&self) -> Option<Self> {++ let [a, b, c, d, e, f] = self.0;++ let det = a * d - b * c;++ if det.abs() < 1e-12 || !det.is_finite() {++ return None;++ }++ let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);++ Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))++ }++++ pub(crate) fn then(&self, then: &Matrix) -> Matrix {++ let [a, b, c, d, e, f] = self.0;++ let [a2, b2, c2, d2, e2, f2] = then.0;++ Matrix([a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2])++ }++}++++pub(crate) fn user_to_screen(xf: &PageXform, info: &DocInfo, page: usize, x: f64, y: f64) -> Pos2 {++ let Some(p) = info.pages.get(page) else { return Pos2::ZERO };++ let v = p.user_to_view(x as f32, y as f32);++ xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph)++}++++fn screen_to_user(xf: &PageXform, info: &DocInfo, page: usize, pt: Pos2) -> (f64, f64) {++ let (vx, vy) = xf.screen_to_view(pt);++ let Some(p) = info.pages.get(page) else { return (0.0, 0.0) };++ let u = p.view_to_user(vx, vy);++ (f64::from(u[0]), f64::from(u[1]))++}++++pub(crate) fn quad_contains(quad: [Pos2; 4], p: Pos2) -> bool {++ if !p.x.is_finite() || !p.y.is_finite() || quad.iter().any(|pt| !pt.x.is_finite() || !pt.y.is_finite()) {++ return false;++ }++ let mut sign = 0;++ for i in 0..4 {++ let p1 = quad[i];++ let p2 = quad[(i + 1) % 4];++ let cross = (p2.x - p1.x) * (p.y - p1.y) - (p2.y - p1.y) * (p.x - p1.x);++ if cross.abs() > 1e-4 {++ let s = if cross > 0.0 { 1 } else { -1 };++ if sign == 0 {++ sign = s;++ } else if sign != s {++ return false;++ }++ }++ }++ sign != 0++}++++/// The screen positions of the crop's eight handles: corners, then the top, right, bottom and left edge midpoints.++fn crop_handles(k: Rect) -> [Pos2; 8] {++ [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]++}++++/// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`++/// (the pointer and keys are the crop's while it lasts).++#[allow(clippy::too_many_arguments)]++fn crop_input(++ ui: &egui::Ui,++ resp: &egui::Response,++ xf: &PageXform,++ ptr: &PagePointer,++ page: usize,++ info: &DocInfo,++ view: &mut DocView,++ i: usize,++ image: &pdfcraft_engine::PageImage,++ allow_interaction: bool,++) -> bool {++ let painter = ui.painter();++ let Some(sel) = view.image_selection.as_mut() else { return false };++ if let Some(rect) = sel.crop_rect++ && let Some(mode) = sel.crop.as_mut()++ {++ mode.keep = user_box(xf, info, page, rect);++ sel.crop_rect = None;++ }++ let Some(mode) = sel.crop.as_mut() else { return false };++ let hover_pos = ptr.pos;++ let full_b = xf.user_rect(info, page, image.rect.map(|v| v as f32));++ let b = if full_b.is_positive() { full_b } else { xf.user_rect(info, page, image.visible_rect.unwrap_or(image.rect).map(|v| v as f32)) };++ let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);++ let k = keep_screen(mode.keep);++++ if allow_interaction++ && resp.drag_started()++ && let Some(o) = ptr.origin++ {++ let grip = crop_handles(k).iter().position(|h| h.distance(o) < 10.0).or_else(|| k.contains(o).then_some(8));++ if let Some(g) = grip {++ mode.drag = Some((g, o, mode.keep));++ }++ }++++ if let Some((grip, start, at_start)) = mode.drag++ && let Some(p) = hover_pos++ {++ let d = p - start;++ let k0 = keep_screen(at_start);++ if grip < 8 {++ let handle_id = match grip {++ 0 => HandleId::TopLeft,++ 1 => HandleId::TopRight,++ 2 => HandleId::BottomLeft,++ 3 => HandleId::BottomRight,++ 4 => HandleId::TopMid,++ 5 => HandleId::RightMid,++ 6 => HandleId::BottomMid,++ _ => HandleId::LeftMid,++ };++ let uv0 = if b.width() > 0.0 && b.height() > 0.0 {++ Rect::from_min_max(++ pos2(((k0.min.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.min.y - b.min.y) / b.height()).clamp(0.0, 1.0)),++ pos2(((k0.max.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.max.y - b.min.y) / b.height()).clamp(0.0, 1.0)),++ )++ } else {++ Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))++ };++ let (new_screen, _) = apply_crop(k0, uv0, handle_id, d);++ let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));++ let clamped = Rect::from_min_max(++ pos2(new_screen.min.x.clamp(b.min.x, b.max.x - min_w), new_screen.min.y.clamp(b.min.y, b.max.y - min_h)),++ pos2(new_screen.max.x.clamp(b.min.x + min_w, b.max.x), new_screen.max.y.clamp(b.min.y + min_h, b.max.y)),++ );++ mode.keep = user_box(xf, info, page, clamped);++ } else {++ let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));++ mode.keep = user_box(xf, info, page, Rect::from_min_max(k0.min + shift, k0.max + shift));++ }++ if resp.drag_stopped() || !ptr.primary_down {++ mode.drag = None;++ }++ }++++ // Faint ghost outline of the full uncropped image underneath++ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgba_unmultiplied(200, 200, 200, 80)), egui::StrokeKind::Outside);++++ // Dim outer excluded bands++ let dim = Color32::from_black_alpha(96);++ if k.min.y > b.min.y {++ painter.rect_filled(Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)), CornerRadius::ZERO, dim);++ }++ if k.max.y < b.max.y {++ painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max), CornerRadius::ZERO, dim);++ }++ if k.min.x > b.min.x {++ painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)), CornerRadius::ZERO, dim);++ }++ if k.max.x < b.max.x {++ painter.rect_filled(Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)), CornerRadius::ZERO, dim);++ }++++ // Rule-of-Thirds Grid inside crop area++ draw_rule_of_thirds(painter, k, Stroke::new(1.0, CROP_ACCENT.gamma_multiply(0.45)));++++ // Crop border stroke++ painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, CROP_ACCENT), egui::StrokeKind::Outside);++++ // Crop handles++ for (idx, h) in crop_handles(k).iter().enumerate() {++ let is_active = mode.drag.as_ref().is_some_and(|d| d.0 == idx);++ let is_hovered = hover_pos.is_some_and(|p| p.distance(*h) < 10.0);++ draw_handle(painter, *h, is_active, is_hovered, true, CROP_ACCENT);++ }++++ // Action pills++ let font = egui::FontId::proportional(12.5);++ let done_w = painter.layout_no_wrap(tl!("Done").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;++ let cancel_w = painter.layout_no_wrap(tl!("Cancel").to_string(), font.clone(), Color32::WHITE).size().x + 22.0;++ let is_full_rect = (mode.keep[0] - image.rect[0]).abs() < 1e-3++ && (mode.keep[1] - image.rect[1]).abs() < 1e-3++ && (mode.keep[2] - image.rect[2]).abs() < 1e-3++ && (mode.keep[3] - image.rect[3]).abs() < 1e-3;++ let has_crop = !is_full_rect || image.visible_rect.is_some_and(|v| v != image.rect);++ let reset_w =++ if has_crop { Some(painter.layout_no_wrap(tl!("Remove Crop").to_string(), font.clone(), Color32::WHITE).size().x + 22.0) } else { None };++ let spacing = 6.0;++ let total_w = done_w + spacing + cancel_w + reset_w.map_or(0.0, |w| w + spacing);++++ // Position pills below crop box if there's room, otherwise above++ let y = if k.max.y + 32.0 < xf.rect.max.y {++ k.max.y + 6.0++ } else if k.min.y - 28.0 > xf.rect.min.y {++ k.min.y - 28.0++ } else {++ k.max.y + 6.0++ };++++ // Right-align pills with k.max.x, clamped inside the page bounds++ let mut right = k.max.x.min(xf.rect.max.x - 8.0);++ if right - total_w < xf.rect.min.x + 8.0 {++ right = (xf.rect.min.x + 8.0 + total_w).min(xf.rect.max.x - 8.0);++ }++++ let done = Rect::from_min_size(Pos2::new(right - done_w, y), egui::vec2(done_w, 22.0));++ let cancel = Rect::from_min_size(Pos2::new(done.min.x - spacing - cancel_w, y), egui::vec2(cancel_w, 22.0));++ let reset = reset_w.map(|w| Rect::from_min_size(Pos2::new(cancel.min.x - spacing - w, y), egui::vec2(w, 22.0)));++++ let done_id = ui.scope_id().with("crop_pill_done").with(page).with(i);++ let cancel_id = ui.scope_id().with("crop_pill_cancel").with(page).with(i);++ let reset_id = ui.scope_id().with("crop_pill_reset").with(page).with(i);++++ let done_resp = ui.interact(done, done_id, egui::Sense::click());++ let cancel_resp = ui.interact(cancel, cancel_id, egui::Sense::click());++ let reset_resp = reset.map(|r| ui.interact(r, reset_id, egui::Sense::click()));++++ let t = crate::theme::Tokens::get(ui.ctx());++++ // Done button (accent colored)++ let done_bg = if done_resp.is_pointer_button_down_on() {++ ACCENT.gamma_multiply(0.8)++ } else if done_resp.hovered() {++ Color32::from_rgb(40, 145, 255)++ } else {++ ACCENT++ };++ painter.rect_filled(done, CornerRadius::same(11), done_bg);++ painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);++++ // Cancel button (panel style with border)++ let cancel_bg = if cancel_resp.is_pointer_button_down_on() {++ t.pressed++ } else if cancel_resp.hovered() {++ t.hover++ } else {++ t.card++ };++ let cancel_stroke = Stroke::new(1.0, if cancel_resp.hovered() { ACCENT } else { t.border });++ let cancel_text = if cancel_resp.hovered() { ACCENT } else { t.text };++ painter.rect(cancel, CornerRadius::same(11), cancel_bg, cancel_stroke, egui::StrokeKind::Inside);++ painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font.clone(), cancel_text);++++ // Reset button (panel style with border)++ if let (Some(r), Some(r_resp)) = (reset, reset_resp.as_ref()) {++ let reset_bg = if r_resp.is_pointer_button_down_on() {++ t.pressed++ } else if r_resp.hovered() {++ t.hover++ } else {++ t.card++ };++ let reset_stroke = Stroke::new(1.0, if r_resp.hovered() { ACCENT } else { t.border });++ let reset_text = if r_resp.hovered() { ACCENT } else { t.text };++ painter.rect(r, CornerRadius::same(11), reset_bg, reset_stroke, egui::StrokeKind::Inside);++ painter.text(r.center(), egui::Align2::CENTER_CENTER, tl!("Remove Crop"), font.clone(), reset_text);++ }++++ if let Some(p) = hover_pos {++ let icon = if done_resp.hovered()++ || cancel_resp.hovered()++ || reset_resp.as_ref().is_some_and(|r| r.hovered())++ || done.contains(p)++ || cancel.contains(p)++ || reset.is_some_and(|r| r.contains(p))++ {++ egui::CursorIcon::PointingHand++ } else if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {++ match g {++ 0 => HandleId::TopLeft.cursor_icon(),++ 1 => HandleId::TopRight.cursor_icon(),++ 2 => HandleId::BottomLeft.cursor_icon(),++ 3 => HandleId::BottomRight.cursor_icon(),++ 4 => HandleId::TopMid.cursor_icon(),++ 5 => HandleId::RightMid.cursor_icon(),++ 6 => HandleId::BottomMid.cursor_icon(),++ _ => HandleId::LeftMid.cursor_icon(),++ }++ } else if k.contains(p) {++ if mode.drag.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }++ } else {++ egui::CursorIcon::Default++ };++ ui.ctx().set_cursor_icon(icon);++ }++++ let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();++ let done_clicked = allow_interaction && (done_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| done.contains(p))));++ let cancel_clicked = allow_interaction && (cancel_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| cancel.contains(p))));++ let reset_clicked = allow_interaction++ && reset++ .is_some_and(|r| reset_resp.as_ref().is_some_and(|res| res.clicked()) || (resp.clicked() && hover_pos.is_some_and(|p| r.contains(p))));++++ if reset_clicked {++ mode.keep = image.rect;++ mode.drag = None;++ if let Some(s) = view.image_selection.as_mut() {++ s.crop_rect = None;++ }++ } else if done_clicked || keys(egui::Key::Enter) {++ let keep = mode.keep;++ if let Some(s) = view.image_selection.as_mut() {++ s.crop = None;++ s.crop_mode = false;++ s.crop_rect = None;++ }++ let is_full = (keep[0] - image.rect[0]).abs() < 1e-3++ && (keep[1] - image.rect[1]).abs() < 1e-3++ && (keep[2] - image.rect[2]).abs() < 1e-3++ && (keep[3] - image.rect[3]).abs() < 1e-3;++ if is_full {++ if image.visible_rect.is_some_and(|v| v != image.rect) {++ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RemoveCrop });++ }++ } else if image.visible_rect != Some(keep) {++ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });++ }++ } else if (cancel_clicked || keys(egui::Key::Escape))++ && let Some(s) = view.image_selection.as_mut()++ {++ s.crop = None;++ s.crop_mode = false;++ s.crop_rect = None;++ }++ true++}++++/// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where++/// the screen may still show the picture).++fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {++ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));++ for r in blank {++ clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);++ }++ let mut mesh = egui::Mesh::with_texture(tex);++ for (a, b) in [++ (from.left_top(), to.left_top()),++ (from.right_top(), to.right_top()),++ (from.right_bottom(), to.right_bottom()),++ (from.left_bottom(), to.left_bottom()),++ ] {++ let (u, v) = xf.screen_to_norm(a);++ mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });++ }++ mesh.add_triangle(0, 1, 2);++ mesh.add_triangle(0, 2, 3);++ clipped.add(egui::Shape::mesh(mesh));++}++++/// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same++/// applies after the pointer leaves the image/page while dragging.++pub(crate) fn image_owns_pointer(_ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {++ let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };++ if selection.drag.is_some() || selection.crop.is_some() || selection.crop_mode {++ return true;++ }++ let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };++ let obb = ImageObb::from_image(image, xf, info, page);++ let p = if ptr.primary_down { ptr.origin.or(ptr.pos) } else { ptr.pos };++ let Some(p) = p else { return false };++++ obb.handles().iter().any(|(_, h)| h.distance(p) < 8.0) || obb.s_rot.distance(p) < 8.0++}++++/// What a right-click on a selected image asks for.++#[derive(Clone, Copy, Debug, PartialEq)]++pub enum ImageAction {++ Replace(usize, usize),++ Save(usize, usize),++ Copy(usize, usize),++ CopyFile(usize, usize),++ /// Copy the picture, then remove it from the page.++ Cut(usize, usize),++ /// Mark the picture for redaction (applied later from Redact a PDF).++ Redact(usize, usize),++ /// Create a link over the picture.++ Link(usize, usize),++ /// Open Recognize Text for the picture's page.++ Recognize(usize),++ Paste(usize, Option<[f64; 2]>),++ DrawFreehand,++ AddComment(usize, usize),++ Crop,++}++++/// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the++/// top edge, or below the bottom edge when the area on screen (`view`) has no room above.++pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) {++ let above = b.center_top() - egui::vec2(0.0, 22.0);++ if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) }++}++++/// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`++/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.++pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {++ let v = pointer - centre;++ if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {++ return 0.0;++ }++ // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).++ let d = v.x.atan2(-v.y).to_degrees();++ if snap { (d / 15.0).round() * 15.0 } else { d }++}++++#[doc(hidden)]++pub fn image_menu_id() -> egui::Id {++ egui::Id::unique("image-menu")++}++++/// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used.++#[allow(clippy::too_many_arguments)]++pub(crate) fn image_input(++ ui: &egui::Ui,++ resp: &egui::Response,++ xf: &PageXform,++ ptr: &PagePointer,++ page: usize,++ info: &DocInfo,++ images: &[pdfcraft_engine::PageImage],++ view: &mut DocView,++ action: &mut Option<ImageAction>,++ allow_interaction: bool,++) -> bool {++ let _ = &action;++ let boxes: Vec<Rect> = images.iter().map(|im| crate::canvas::image_screen_rect(im, xf, info, page)).collect();++ let painter = ui.painter();++ let hover_pos = ptr.pos;++ let image_contains = |index: usize, point: Pos2| {++ let (x, y) = xf.screen_to_view(point);++ let Some(p) = info.pages.get(page) else { return false };++ let user = p.view_to_user(x, y);++ images.get(index).is_some_and(|im| im.contains(user.map(f64::from)))++ };++ let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len());++ let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some());++ let faint_all = boxes.len() <= MAX_OUTLINES;++ let moving = selected.filter(|_| dragging);++ if faint_all {++ for (idx, im) in images.iter().enumerate() {++ if moving == Some(idx) {++ continue;++ }++ if let Some(b) = boxes.get(idx).filter(|b| b.is_positive()) {++ let obb = ImageObb::from_image(im, xf, info, page);++ if obb.is_rotated {++ let pts = obb.corners();++ for k in 0..4 {++ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));++ }++ } else {++ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);++ }++ }++ }++ }++ let hovered_box = hover_pos.and_then(|p| {++ boxes.iter().enumerate().rposition(|(i, b)| {++ b.is_positive()++ && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))++ && image_contains(i, p)++ })++ });++ if !faint_all {++ for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) {++ if let (Some(b), Some(img)) = (boxes.get(i).filter(|b| b.is_positive()), images.get(i)) {++ let obb = ImageObb::from_image(img, xf, info, page);++ if obb.is_rotated {++ let pts = obb.corners();++ for k in 0..4 {++ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35)));++ }++ } else {++ painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside);++ }++ }++ }++ }++ for i in selected.into_iter().chain(hovered_box).collect::<Vec<_>>() {++ let (Some(b), Some(img)) = (boxes.get(i).copied().filter(|b| b.is_positive()), images.get(i)) else { continue };++ let obb = ImageObb::from_image(img, xf, info, page);++ if selected == Some(i) {++ if !dragging {++ if obb.is_rotated {++ painter.polygon(obb.corners().to_vec(), ACCENT.gamma_multiply(0.04), Stroke::NONE);++ } else {++ painter.rect_filled(b, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));++ }++ }++ } else if obb.is_rotated {++ painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));++ } else {++ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);++ }++ }++ // The selected image: frame, corner handles, dragging.++ if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) {++ let Some(b) = boxes.get(i).copied() else { return false };++ let Some(image) = images.get(i) else { return false };++ let obb = ImageObb::from_image(image, xf, info, page);++ let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page));++ let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y));++ let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from);++ if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) {++ match (s.settled, raster) {++ (Some((from, to)), Some(tex)) if out_of_date => {++ let source = if raster_old { from } else { to };++ stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to));++ }++ _ if !out_of_date => s.settled = None,++ _ => {}++ }++ }++++ if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some() || s.crop_mode) {++ if let Some(s) = view.image_selection.as_mut()++ && s.crop.is_none()++ {++ let rect = images.get(i).and_then(|im| im.visible_rect).unwrap_or(images.get(i).map_or([0.0; 4], |im| im.rect));++ s.crop = Some(CropMode::new(rect));++ }++ return crop_input(ui, resp, xf, ptr, page, info, view, i, image, allow_interaction);++ }++ let (knob, stem) = rotate_knob(b, ui.clip_rect());++ if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {++ if obb.is_rotated {++ painter.polygon(obb.corners().to_vec(), Color32::TRANSPARENT, Stroke::new(1.5, ACCENT));++ painter.line_segment([obb.s_tc, obb.s_rot], Stroke::new(1.2, ACCENT));++ painter.circle(obb.s_rot, 4.5, Color32::WHITE, Stroke::new(1.0, ACCENT));++ } else {++ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT));++ painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));++ }++ for (_, h) in obb.handles() {++ let is_hovered = hover_pos.is_some_and(|p| p.distance(h) < 10.0);++ draw_handle(painter, h, false, is_hovered, false, ACCENT);++ }++ }++++ let mut handle_drag = None;++ for (h, h_pos, handle_id) in obb.handles_with_ids(ui.scope_id().with("img_handle")) {++ let handle_rect = Rect::from_center_size(h_pos, egui::vec2(18.0, 18.0));++ let handle_resp = ui.interact(handle_rect, handle_id, egui::Sense::drag());++ if allow_interaction && handle_resp.drag_started() {++ handle_drag = Some(h);++ }++ }++ let rot_id = ui.scope_id().with("img_handle").with(8);++ let rot_rect = Rect::from_center_size(if obb.is_rotated { obb.s_rot } else { knob }, egui::vec2(12.0, 12.0));++ let rot_resp = ui.interact(rot_rect, rot_id, egui::Sense::drag());++ let rot_drag = allow_interaction && rot_resp.drag_started();++++ if allow_interaction && let Some(p) = hover_pos {++ if obb.s_rot.distance(p) < 8.0 || knob.distance(p) < 8.0 {++ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);++ } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(p) < 8.0) {++ let icon = match h {++ ImageHandle::TopLeft | ImageHandle::BottomRight => {++ if obb.is_rotated {++ let v = obb.handle_pos(*h) - obb.screen_center;++ if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }++ } else {++ egui::CursorIcon::ResizeNwSe++ }++ }++ ImageHandle::TopRight | ImageHandle::BottomLeft => {++ if obb.is_rotated {++ let v = obb.handle_pos(*h) - obb.screen_center;++ if v.x * v.y > 0.0 { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }++ } else {++ egui::CursorIcon::ResizeNeSw++ }++ }++ ImageHandle::TopCenter | ImageHandle::BottomCenter => {++ if obb.is_rotated && (obb.v_axis.0.abs() > obb.v_axis.1.abs()) {++ egui::CursorIcon::ResizeHorizontal++ } else {++ egui::CursorIcon::ResizeVertical++ }++ }++ ImageHandle::RightCenter | ImageHandle::LeftCenter => {++ if obb.is_rotated && (obb.u_axis.1.abs() > obb.u_axis.0.abs()) {++ egui::CursorIcon::ResizeVertical++ } else {++ egui::CursorIcon::ResizeHorizontal++ }++ }++ };++ ui.ctx().set_cursor_icon(icon);++ }++ }++++ let origin = ptr.origin;++ if allow_interaction {++ if let Some(h) = handle_drag {++ if let Some(s) = view.image_selection.as_mut() {++ let o = origin.unwrap_or_else(|| obb.handle_pos(h));++ s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(h), initial_rect: b, initial_matrix: image.matrix });++ }++ } else if rot_drag {++ if let Some(s) = view.image_selection.as_mut() {++ let o = origin.unwrap_or(if obb.is_rotated { obb.s_rot } else { knob });++ s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });++ s.turning = true;++ }++ } else if resp.drag_started()++ && let Some(o) = origin++ {++ if obb.s_rot.distance(o) < 8.0 || knob.distance(o) < 8.0 {++ if let Some(s) = view.image_selection.as_mut() {++ s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix });++ s.turning = true;++ }++ } else if let Some((h, _)) = obb.handles().iter().find(|(_, pos)| pos.distance(o) < 8.0) {++ if let Some(s) = view.image_selection.as_mut() {++ s.drag = Some(ImageDrag { start: o, target: DragTarget::Handle(*h), initial_rect: b, initial_matrix: image.matrix });++ }++ } else if (image_contains(i, o) || quad_contains(obb.corners(), o))++ && let Some(s) = view.image_selection.as_mut()++ {++ s.drag = Some(ImageDrag { start: o, target: DragTarget::Move, initial_rect: b, initial_matrix: image.matrix });++ }++ }++ }++++ if view.image_selection.as_ref().is_some_and(|s| s.turning) {++ let shift = ui.input(|i| i.modifiers.shift);++ let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));++ let centre = b.center();++ let (sin, cos) = degrees.to_radians().sin_cos();++ let turn = |c: Pos2| {++ let v = c - centre;++ centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)++ };++ let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();++ painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));++ let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);++ let label = Rect::from_center_size(turn(knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0));++ painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle);++ painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT);++ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);++ if resp.drag_stopped() || !ptr.primary_down {++ if let Some(s) = view.image_selection.as_mut() {++ s.drag = None;++ s.turning = false;++ }++ if degrees.abs() >= 0.05 {++ view.pending_edit =++ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });++ }++ }++ return true;++ }++++ if let Some(drag) = view.image_selection.as_ref().and_then(|s| s.drag)++ && let Some(p) = hover_pos++ {++ if !obb.is_rotated && !matches!(drag.target, DragTarget::Rotate) {++ let preview = match drag.target {++ DragTarget::Handle(handle) => {++ let handle_id = HandleId::from(handle);++ let delta = p - drag.start;++ let is_corner = matches!(handle_id, HandleId::TopLeft | HandleId::TopRight | HandleId::BottomLeft | HandleId::BottomRight);++ let shift = ui.input(|inp| inp.modifiers.shift);++ if is_corner && !shift {++ apply_resize_proportional(drag.initial_rect, handle_id, delta)++ } else {++ apply_resize(drag.initial_rect, handle_id, delta)++ }++ }++ DragTarget::Move => drag.initial_rect.translate(p - drag.start),++ _ => drag.initial_rect,++ };++++ let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32)));++ let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 };++ let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height()));++ let f_min = egui::vec2((raw.min.x - b.min.x) * factor.x, (raw.min.y - b.min.y) * factor.y);++ let f_max = egui::vec2((raw.max.x - b.min.x) * factor.x, (raw.max.y - b.min.y) * factor.y);++ let target = Rect::from_min_max(preview.min + f_min, preview.min + f_max);++ let visible = preview.intersect(xf.rect);++++ if visible.is_positive() {++ if preview != b++ && let Some(tex) = raster++ {++ let source = left_at.filter(|_| raster_old).map_or(b, screen);++ let blank: Vec<Rect> = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect();++ stretched_picture(painter, xf, tex, &blank, source, preview);++ }++ painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));++ painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ for h in [++ preview.left_top(),++ preview.right_top(),++ preview.left_bottom(),++ preview.right_bottom(),++ preview.center_top(),++ preview.right_center(),++ preview.center_bottom(),++ preview.left_center(),++ ] {++ draw_handle(painter, h, false, false, false, ACCENT);++ }++ }++++ if resp.drag_stopped() || !ptr.primary_down {++ if let Some(s) = view.image_selection.as_mut() {++ s.drag = None;++ let norm = |r: Rect| {++ let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max));++ Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1))++ };++ s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview)));++ }++ if preview != b {++ view.pending_edit =++ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) });++ }++ }++++ let icon = match drag.target {++ DragTarget::Handle(handle) => HandleId::from(handle).cursor_icon(),++ DragTarget::Move => egui::CursorIcon::Grabbing,++ _ => egui::CursorIcon::Move,++ };++ ui.ctx().set_cursor_icon(icon);++ return true;++ }++ let m_init = Matrix(drag.initial_matrix);++ let [a0, b0, c0, d0, e0, f0] = drag.initial_matrix;++ let w0 = (a0 * a0 + b0 * b0).sqrt().max(1e-6);++ let h0 = (c0 * c0 + d0 * d0).sqrt().max(1e-6);++ let u_axis = (a0 / w0, b0 / w0);++ let v_axis = (c0 / h0, d0 / h0);++ let center_user = (e0 + 0.5 * (a0 + c0), f0 + 0.5 * (b0 + d0));++++ let (sx, sy) = screen_to_user(xf, info, page, drag.start);++ let (px, py) = screen_to_user(xf, info, page, p);++++ let (m_new, cursor_icon) = match drag.target {++ DragTarget::Rotate => {++ let v0 = (sx - center_user.0, sy - center_user.1);++ let v1 = (px - center_user.0, py - center_user.1);++ let theta0 = v0.1.atan2(v0.0);++ let theta1 = v1.1.atan2(v1.0);++ let mut delta = theta1 - theta0;++ if ui.input(|i| i.modifiers.shift) {++ let step = std::f64::consts::PI / 12.0;++ delta = (delta / step).round() * step;++ }++ let (cos_d, sin_d) = (delta.cos(), delta.sin());++ let t_rot = [++ cos_d,++ sin_d,++ -sin_d,++ cos_d,++ center_user.0 * (1.0 - cos_d) + center_user.1 * sin_d,++ center_user.1 * (1.0 - cos_d) - center_user.0 * sin_d,++ ];++ (m_init.then(&Matrix(t_rot)), egui::CursorIcon::Grab)++ }++ DragTarget::Move => {++ let (dx, dy) = (px - sx, py - sy);++ (Matrix([a0, b0, c0, d0, e0 + dx, f0 + dy]), egui::CursorIcon::Move)++ }++ DragTarget::Handle(handle) => {++ let p00 = (e0, f0);++ let p10 = (e0 + a0, f0 + b0);++ let p11 = (e0 + a0 + c0, f0 + b0 + d0);++ let p01 = (e0 + c0, f0 + d0);++ let p_curr = (px, py);++++ let (new_w, new_h, p00_new, icon) = match handle {++ ImageHandle::TopRight => {++ let anchor = p00;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = d.0 * u_axis.0 + d.1 * u_axis.1;++ let dv = d.0 * v_axis.0 + d.1 * v_axis.1;++ let su = du / w0;++ let sv = dv / h0;++ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };++ let s = s.max(5.0 / w0).max(5.0 / h0);++ (w0 * s, h0 * s, anchor, egui::CursorIcon::ResizeNeSw)++ }++ ImageHandle::TopLeft => {++ let anchor = p10;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);++ let dv = d.0 * v_axis.0 + d.1 * v_axis.1;++ let su = du / w0;++ let sv = dv / h0;++ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };++ let s = s.max(5.0 / w0).max(5.0 / h0);++ let nw = w0 * s;++ let nh = h0 * s;++ (nw, nh, (anchor.0 - nw * u_axis.0, anchor.1 - nw * u_axis.1), egui::CursorIcon::ResizeNwSe)++ }++ ImageHandle::BottomLeft => {++ let anchor = p11;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = d.0 * (-u_axis.0) + d.1 * (-u_axis.1);++ let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);++ let su = du / w0;++ let sv = dv / h0;++ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };++ let s = s.max(5.0 / w0).max(5.0 / h0);++ let nw = w0 * s;++ let nh = h0 * s;++ (++ nw,++ nh,++ (anchor.0 - nw * u_axis.0 - nh * v_axis.0, anchor.1 - nw * u_axis.1 - nh * v_axis.1),++ egui::CursorIcon::ResizeNeSw,++ )++ }++ ImageHandle::BottomRight => {++ let anchor = p01;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = d.0 * u_axis.0 + d.1 * u_axis.1;++ let dv = d.0 * (-v_axis.0) + d.1 * (-v_axis.1);++ let su = du / w0;++ let sv = dv / h0;++ let s = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv };++ let s = s.max(5.0 / w0).max(5.0 / h0);++ let nw = w0 * s;++ let nh = h0 * s;++ (nw, nh, (anchor.0 - nh * v_axis.0, anchor.1 - nh * v_axis.1), egui::CursorIcon::ResizeNwSe)++ }++ ImageHandle::RightCenter => {++ let anchor = p00;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = (d.0 * u_axis.0 + d.1 * u_axis.1).max(5.0);++ (du, h0, anchor, egui::CursorIcon::ResizeHorizontal)++ }++ ImageHandle::LeftCenter => {++ let anchor = p10;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let du = (d.0 * (-u_axis.0) + d.1 * (-u_axis.1)).max(5.0);++ (du, h0, (anchor.0 - du * u_axis.0, anchor.1 - du * u_axis.1), egui::CursorIcon::ResizeHorizontal)++ }++ ImageHandle::TopCenter => {++ let anchor = p00;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let dv = (d.0 * v_axis.0 + d.1 * v_axis.1).max(5.0);++ (w0, dv, anchor, egui::CursorIcon::ResizeVertical)++ }++ ImageHandle::BottomCenter => {++ let anchor = p01;++ let d = (p_curr.0 - anchor.0, p_curr.1 - anchor.1);++ let dv = (d.0 * (-v_axis.0) + d.1 * (-v_axis.1)).max(5.0);++ (w0, dv, (anchor.0 - dv * v_axis.0, anchor.1 - dv * v_axis.1), egui::CursorIcon::ResizeVertical)++ }++ };++ let mat = Matrix([new_w * u_axis.0, new_w * u_axis.1, new_h * v_axis.0, new_h * v_axis.1, p00_new.0, p00_new.1]);++ (mat, icon)++ }++ _ => (m_init, egui::CursorIcon::Default),++ };++++ let preview_obb = ImageObb::new(m_new.0, xf, info, page);++ if let Some(tex) = view.page_raster(page) {++ let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));++ let mut mesh = egui::Mesh::with_texture(tex);++ let orig_corners = obb.corners();++ let new_corners = preview_obb.corners();++ for (from, to) in [++ (orig_corners[3], new_corners[3]),++ (orig_corners[2], new_corners[2]),++ (orig_corners[1], new_corners[1]),++ (orig_corners[0], new_corners[0]),++ ] {++ let (u, v) = xf.screen_to_norm(from);++ mesh.vertices.push(egui::epaint::Vertex { pos: to, uv: Pos2::new(u, v), color: Color32::WHITE });++ }++ mesh.add_triangle(0, 1, 2);++ mesh.add_triangle(0, 2, 3);++ clipped.add(egui::Shape::mesh(mesh));++ }++++ if preview_obb.is_rotated {++ let pts = preview_obb.corners();++ painter.polygon(pts.to_vec(), ACCENT.gamma_multiply(0.04), Stroke::new(1.5, ACCENT));++ } else {++ let p_rect = Rect::from_two_pos(preview_obb.s01, preview_obb.s10);++ let visible = p_rect.intersect(xf.rect);++ if visible.is_positive() {++ painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04));++ painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);++ }++ }++ for (_, h) in preview_obb.handles() {++ draw_handle(painter, h, false, false, false, ACCENT);++ }++++ if resp.drag_stopped() || !ptr.primary_down {++ if let Some(s) = view.image_selection.as_mut() {++ s.drag = None;++ }++ if m_new.0 != drag.initial_matrix {++ if matches!(drag.target, DragTarget::Move) {++ let (dx, dy) = (px - sx, py - sy);++ let new_rect = [image.rect[0] + dx, image.rect[1] + dy, image.rect[2] + dx, image.rect[3] + dy];++ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(new_rect) });++ } else if let Some(inv) = Matrix(drag.initial_matrix).invert() {++ let t = inv.then(&m_new);++ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Transform(t.0) });++ }++ }++ }++ ui.ctx().set_cursor_icon(cursor_icon);++ return true;++ }++ if allow_interaction++ && ui.input(|inp| inp.key_pressed(egui::Key::Delete) || inp.key_pressed(egui::Key::Backspace))++ && !ui.ctx().egui_wants_keyboard_input()++ {++ view.image_selection = None;++ view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Delete });++ return true;++ }++ }++ if !allow_interaction {++ return false;++ }++ let menu_key = image_menu_id();++ let Some(p) = hover_pos.filter(|p| xf.rect.contains(*p)) else { return false };++ let Some(hit) = boxes.iter().enumerate().rposition(|(i, b)| {++ b.is_positive()++ && images.get(i).is_some_and(|img| b.contains(p) || quad_contains(ImageObb::from_image(img, xf, info, page).corners(), p))++ && image_contains(i, p)++ }) else {++ if resp.secondary_clicked() || resp.clicked() {++ view.image_selection = None;++ ui.ctx().data_mut(|d| d.insert_persisted(menu_key, false));++ }++ return false;++ };++ let Some(hit_img) = images.get(hit) else { return false };++ let hit_obb = ImageObb::from_image(hit_img, xf, info, page);++ if selected != Some(hit) {++ if hit_obb.is_rotated {++ let pts = hit_obb.corners();++ for k in 0..4 {++ painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(1.5, ACCENT.gamma_multiply(0.7)));++ }++ } else if let Some(b) = boxes.get(hit).copied() {++ painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.5, ACCENT.gamma_multiply(0.7)), egui::StrokeKind::Outside);++ }++ }++ let corner = hit_obb.handles().iter().position(|(_, c)| c.distance(p) < 10.0);++ ui.ctx().set_cursor_icon(match (selected == Some(hit), corner) {++ (true, Some(0 | 4)) => egui::CursorIcon::ResizeNwSe,++ (true, Some(2 | 6)) => egui::CursorIcon::ResizeNeSw,++ (true, Some(1 | 5)) => egui::CursorIcon::ResizeVertical,++ (true, Some(3 | 7)) => egui::CursorIcon::ResizeHorizontal,++ (true, None) => egui::CursorIcon::Grab,++ _ => egui::CursorIcon::PointingHand,++ });++ if resp.clicked() || resp.secondary_clicked() {++ view.image_selection =++ Some(ImageSelection { page, index: hit, drag: None, crop: None, crop_mode: false, crop_rect: None, turning: false, settled: None });++ }++ if resp.secondary_clicked() {++ ui.ctx().data_mut(|d| d.insert_persisted(menu_key, true));++ }++ true++}++++/// The right-click context menu for a selected image.++#[allow(clippy::too_many_arguments)]++pub(crate) fn image_context_menu(++ ui: &mut egui::Ui,++ view: &mut DocView,++ images: &[pdfcraft_engine::PageImage],++ page: usize,++ hit: usize,++ can_paste: bool,++ action: &mut Option<ImageAction>,++ at: Option<[f64; 2]>,++) {++ let Some(img) = images.get(hit) else { return };++ use pdfcraft_engine::ImageEdit as E;++ let raster = !img.is_form;++++ let close = |ui: &mut egui::Ui| {++ ui.ctx().data_mut(|d| d.insert_persisted(image_menu_id(), false));++ egui::Popup::close_all(ui.ctx());++ ui.close();++ };++++ // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW++ ui.horizontal(|ui| {++ ui.spacing_mut().item_spacing.x = 4.0;++ if crate::icons::button(ui, "message-square", 24.0, false, tl!("Add a sticky note here")).clicked() {++ *action = Some(ImageAction::AddComment(page, hit));++ close(ui);++ }++ if raster && crate::icons::button(ui, "crop", 24.0, false, tl!("Crop")).clicked() {++ *action = Some(ImageAction::Crop);++ if let Some(s) = view.image_selection.as_mut() {++ let rect = img.visible_rect.unwrap_or(img.rect);++ s.crop = Some(CropMode::new(rect));++ s.crop_mode = true;++ s.crop_rect = None;++ }++ close(ui);++ }++ if crate::icons::button(ui, "rotate-ccw", 24.0, false, tl!("Rotate Counterclockwise")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(3) });++ close(ui);++ }++ if crate::icons::button(ui, "rotate-cw", 24.0, false, tl!("Rotate Clockwise")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Rotate(1) });++ close(ui);++ }++ });++++ ui.separator();++++ if ui.button(tl!("Cut Image")).clicked() {++ *action = Some(ImageAction::Cut(page, hit));++ close(ui);++ }++ if ui.button(tl!("Copy Image")).clicked() {++ *action = Some(ImageAction::Copy(page, hit));++ close(ui);++ }++ if ui.add_enabled(can_paste, egui::Button::new(tl!("Paste"))).clicked() {++ *action = Some(ImageAction::Paste(page, at));++ close(ui);++ }++++ ui.separator();++++ let is_cropped = img.visible_rect.is_some() && img.visible_rect != Some(img.rect);++ if raster && ui.add_enabled(is_cropped, egui::Button::new(tl!("Remove crop"))).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::RemoveCrop });++ close(ui);++ }++++ if ui.button(tl!("Flip horizontal")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: true } });++ close(ui);++ }++ if ui.button(tl!("Flip vertical")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Flip { horizontal: false } });++ close(ui);++ }++++ ui.menu_button(tl!("Arrange image"), |ui| {++ if ui.button(tl!("Bring to front")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront) });++ close(ui);++ }++ if ui.button(tl!("Send to back")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack) });++ close(ui);++ }++ if ui.button(tl!("Bring forward")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::BringForward) });++ close(ui);++ }++ if ui.button(tl!("Send backward")).clicked() {++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward) });++ close(ui);++ }++ });++++ if ui.add_enabled(raster, egui::Button::new(tl!("Replace image"))).clicked() {++ *action = Some(ImageAction::Replace(page, hit));++ close(ui);++ }++ if ui.add_enabled(raster, egui::Button::new(tl!("Save Image As…"))).clicked() {++ *action = Some(ImageAction::Save(page, hit));++ close(ui);++ }++++ ui.separator();++++ if ui.button(tl!("Draw freehand")).clicked() {++ *action = Some(ImageAction::DrawFreehand);++ close(ui);++ }++ if ui.button(tl!("Redact Image")).clicked() {++ *action = Some(ImageAction::Redact(page, hit));++ close(ui);++ }++ if ui.add_enabled(raster, egui::Button::new("Export image")).clicked() {++ *action = Some(ImageAction::Save(page, hit));++ close(ui);++ }++++ ui.separator();++++ if ui.button(tl!("Create Link…")).clicked() {++ *action = Some(ImageAction::Link(page, hit));++ close(ui);++ }++++ ui.menu_button("Edit image using", |ui| {++ ui.add_enabled(false, egui::Button::new("Default image editor"));++ });++++ if ui.button(tl!("Recognize Text…")).clicked() {++ *action = Some(ImageAction::Recognize(page));++ close(ui);++ }++++ ui.separator();++++ if ui.button(tl!("Delete")).clicked() {++ view.image_selection = None;++ view.pending_edit = Some(Edit::EditPageImage { page, index: hit, change: E::Delete });++ close(ui);++ }++}diff --cc crates/ui-egui/src/tools/edit_text_ui/layout.rsindex 000000000,a59c10899..497789005mode 000000,100644..100644--- a/crates/ui-egui/src/tools/edit_text_ui/layout.rs+++ b/crates/ui-egui/src/tools/edit_text_ui/layout.rs@@@ -1,0 -1,270 +1,270 @@@+ use super::*;++ /// The look shown for a paragraph: the family and weight guessed from its PDF font name.-fn source_look(base_font: &str, size: f64, color: [f64; 3], detected_bold: bool, detected_italic: bool) -> pdfcraft_engine::AddedText {++pub(super) fn source_look(base_font: &str, size: f64, color: [f64; 3], detected_bold: bool, detected_italic: bool) -> pdfcraft_engine::AddedText {+ use pdfcraft_engine::FontFamily as F;+ let name = base_font.to_ascii_lowercase();+ let family = if ["courier", "mono", "consolas", "menlo", "monaco", "lucida console"].iter().any(|s| name.contains(s)) {+ F::Courier+ } else if !name.contains("sans") && ["times", "serif", "roman", "cambria", "georgia", "palatino", "garamond"].iter().any(|s| name.contains(s)) {+ F::Times+ } else {+ F::Helvetica+ };+ pdfcraft_engine::AddedText {+ family,+ bold: detected_bold || ["bold", "black", "heavy", "semibold", "demi"].iter().any(|s| name.contains(s)),+ italic: detected_italic || ["italic", "oblique", "slanted"].iter().any(|s| name.contains(s)),+ size: (size * 10.0).round() / 10.0,+ color,+ ..Default::default()+ }+ }++ pub(super) fn look_of(b: &pdfcraft_engine::TextBlock) -> pdfcraft_engine::AddedText {+ source_look(&b.base_font, b.size, b.color, b.bold, b.italic)+ }++ pub(crate) fn editor_font(look: &pdfcraft_engine::AddedText, size: f32) -> FontId {+ let family = match (look.family, look.bold) {+ (pdfcraft_engine::FontFamily::Courier, _) => FontFamily::Monospace,+ (_, true) => FontFamily::Name("semibold".into()),+ (_, false) => FontFamily::Proportional,+ };+ FontId::new(size, family)+ }++ pub(super) fn color32(color: [f64; 3]) -> Color32 {+ Color32::from_rgb(+ (color[0].clamp(0.0, 1.0) * 255.0).round() as u8,+ (color[1].clamp(0.0, 1.0) * 255.0).round() as u8,+ (color[2].clamp(0.0, 1.0) * 255.0).round() as u8,+ )+ }++ /// The dark box behind text too pale to read on white.+ pub(super) const DARK_EDITOR_FILL: Color32 = Color32::from_gray(0x26);++ /// WCAG relative luminance of an sRGB colour.+ pub(super) fn luminance(c: Color32) -> f32 {+ let channel = |v: u8| {+ let v = f32::from(v) / 255.0;+ if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }+ };+ 0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())+ }++ /// WCAG contrast ratio between two colours (1 to 21).+ pub(super) fn contrast(a: Color32, b: Color32) -> f32 {+ let (la, lb) = (luminance(a), luminance(b));+ (la.max(lb) + 0.05) / (la.min(lb) + 0.05)+ }++ /// The inline editor's background for text drawn in `text`: white, or a dark box when the text+ /// reads better on that (white or pale text, which would vanish on white).+ pub(crate) fn editor_fill(text: Color32) -> Color32 {+ if contrast(text, Color32::WHITE) >= contrast(text, DARK_EDITOR_FILL) { Color32::WHITE } else { DARK_EDITOR_FILL }+ }++ /// One TextEdit lays out all source runs; its caret and selection span the whole region.+ pub(crate) fn install_source_fonts(ctx: &egui::Context, doc: &pdfcraft_engine::Document, page: usize) -> BTreeMap<String, String> {+ let programs = doc.text_editor_fonts(page);+ let mut definitions = ctx.fonts(|f| f.definitions().clone());+ // Only the current editor's document fonts live in the atlas. Never accumulate the+ // programs of previously opened files or add them to the interface's default families.+ definitions.font_data.retain(|name, _| !name.starts_with("pdf-source-"));+ definitions.families.retain(|family, _| !matches!(family, FontFamily::Name(name) if name.starts_with("pdf-source-")));+ let mut families = BTreeMap::new();+ for (index, program) in programs.iter().enumerate() {+ let name = format!("pdf-source-{index}");+ definitions.font_data.insert(name.clone(), Arc::new(egui::FontData::from_owned(program.bytes.clone())));+ families.insert(program.resource.clone(), name);+ }+ for program in &programs {+ let Some(name) = families.get(&program.resource) else { continue };+ // Word-created PDFs often split one face into several subsets. Use all of the+ // document's matching subsets before falling back for newly inserted characters.+ let mut stack = vec![name.clone()];+ stack.extend(+ programs+ .iter()+ .filter(|p| {+ pdfcraft_fonts::embedding::face_key(&p.face) == pdfcraft_fonts::embedding::face_key(&program.face)+ && p.resource != program.resource+ })+ .filter_map(|p| families.get(&p.resource).cloned()),+ );+ if let Some(fallback) = definitions.families.get(&FontFamily::Proportional) {+ stack.extend(fallback.iter().cloned());+ }+ definitions.families.insert(FontFamily::Name(name.clone().into()), stack);+ }+ if !families.is_empty() {+ ctx.set_fonts(definitions);+ }+ families+ }++ pub(super) fn editor_job(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> egui::text::LayoutJob {+ let mut job = egui::text::LayoutJob::default();+ // An unchanged PDF row already has an authoritative line break. Do not rewrap it+ // because font rounding or a fallback face measures a fraction of a pixel wider.+ job.wrap.max_width = if text == ed.original && ed.look == ed.look0 && ed.extras == ed.extras0 { f32::INFINITY } else { width };+ if let Some((block, lines)) = &ed.source {+ let lefts: Vec<_> = block.rows.iter().filter_map(|r| r.first().and_then(|i| lines.get(*i)).map(|l| l.rect[0])).collect();+ let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);+ let centered = block.rows.len() > 1+ && left_span > block.size * 0.5+ && block.rows.iter().all(|row| {+ let rect = row+ .iter()+ .filter_map(|i| lines.get(*i))+ .map(|l| l.rect)+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]);+ rect.is_some_and(|r| ((r[0] + r[2] - block.rect[0] - block.rect[2]) / 2.0).abs() < block.size)+ });+ if centered {+ job.halign = egui::Align::Center;+ }+ for (range, index) in block.edited_spans(text) {+ let Some(line) = lines.get(index) else { continue };+ let mut look = source_look(&line.base_font, line.size, line.color, line.bold, line.italic);+ look.size = line.size;+ if ed.look.family != ed.look0.family || ed.family_chosen {+ look.family = ed.look.family;+ }+ if ed.look.bold != ed.look0.bold {+ look.bold = ed.look.bold;+ }+ if ed.look.italic != ed.look0.italic {+ look.italic = ed.look.italic;+ }+ if ed.look.color != ed.look0.color {+ look.color = ed.look.color;+ }+ if ed.look.size != ed.look0.size {+ look.size = ed.look.size;+ }+ let mut font = editor_font(&look, (look.size as f32 * scale).clamp(1.0, 300.0));+ let original_face =+ ed.look.family == ed.look0.family && !ed.family_chosen && ed.look.bold == ed.look0.bold && ed.look.italic == ed.look0.italic;+ let embedded = original_face && ed.fonts.contains_key(&line.font);+ if embedded && let Some(name) = ed.fonts.get(&line.font) {+ font.family = FontFamily::Name(name.clone().into());+ }+ let native_width = ui.fonts_mut(|f| f.layout_no_wrap(line.text.clone(), font.clone(), Color32::BLACK).size().x);+ let target_width = ((line.rect[2] - line.rect[0]) * look.size / line.size.max(0.01)) as f32 * scale;+ let spacing = if original_face { (target_width - native_width) / line.text.chars().count().saturating_sub(1).max(1) as f32 } else { 0.0 };+ job.append(+ text.get(range).unwrap_or_default(),+ 0.0,+ egui::TextFormat {+ font_id: font,+ extra_letter_spacing: spacing + ed.extras.char_spacing as f32 * scale,+ color: color32(look.color),+ italics: look.italic && !embedded,+ ..Default::default()+ },+ );+ }+ } else {+ job.append(+ text,+ 0.0,+ egui::TextFormat {+ font_id: editor_font(&ed.look, ed.size),+ color: color32(ed.look.color),+ italics: ed.look.italic,+ ..Default::default()+ },+ );+ }+ job+ }++ /// `galley` drawn in no colour: its rows still place the caret and the selection.+ pub(super) fn unseen(mut galley: Arc<egui::Galley>) -> Arc<egui::Galley> {+ for placed in &mut Arc::make_mut(&mut galley).rows {+ for vertex in &mut Arc::make_mut(&mut placed.row).visuals.mesh.vertices {+ vertex.color = Color32::TRANSPARENT;+ }+ }+ galley+ }++ /// Align the editable galley's baselines to the source rows instead of egui's interface+ /// leading. Glyphs, meshes, caret and selection receive the same transform.+ pub(super) fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> Arc<egui::Galley> {+ let mut job = editor_job(ui, ed, text, scale, width);+ let centered = job.halign == egui::Align::Center;+ job.halign = egui::Align::LEFT;+ let mut galley = ui.fonts_mut(|fonts| fonts.layout_job(job));+ let Some((block, lines)) = &ed.source else { return galley };+ let sources: Vec<_> = block+ .rows+ .iter()+ .filter_map(|row| {+ let first = row.first().and_then(|i| lines.get(*i))?;+ let rect = row+ .iter()+ .filter_map(|i| lines.get(*i))+ .map(|l| l.rect)+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])?;+ Some((first.baseline()[1], rect))+ })+ .collect();+ let Some((first_baseline, first_rect)) = sources.first().copied() else { return galley };+ let leading = if ed.extras.line_spacing > 0.0 {+ ed.extras.line_spacing * ed.look.size+ } else {+ let fallback = if block.lines.len() == 1 && !text.contains('\n') {+ block.lines.first().and_then(|i| lines.get(*i)).map_or(block.size * 1.2, |line| line.wrap_leading())+ } else {+ block.size * 1.5+ };+ sources.windows(2).map(|r| (r[0].0 - r[1].0).abs()).rfind(|v| *v > 0.0).unwrap_or(fallback)+ };+ let g = Arc::make_mut(&mut galley);+ let mut bounds = Rect::NOTHING;+ let mut meshes = Rect::NOTHING;+ for (index, placed) in g.rows.iter_mut().enumerate() {+ let (last_baseline, last_rect) = sources.last().copied().unwrap_or((first_baseline, first_rect));+ let (baseline, source_rect) = sources+ .get(index)+ .copied()+ .unwrap_or((last_baseline - index.saturating_add(1).saturating_sub(sources.len()) as f64 * leading, last_rect));+ let changed_size = ed.look.size != ed.look0.size;+ let ratio = if changed_size { ed.look.size / ed.look0.size.max(0.01) } else { 1.0 };+ let ascent = (source_rect[3] - sources.get(index).map_or(last_baseline, |s| s.0)) as f32 * scale * ratio as f32;+ let descent = (sources.get(index).map_or(last_baseline, |s| s.0) - source_rect[1]) as f32 * scale * ratio as f32;+ let base_y = (block.rect[3] - baseline) as f32 * scale;+ let row = Arc::make_mut(&mut placed.row);+ placed.pos.y = base_y - ascent;+ placed.pos.x = if centered { (width - row.size.x) / 2.0 } else { (source_rect[0] - block.rect[0]) as f32 * scale };+ for glyph in &mut row.glyphs {+ let dy = ascent - glyph.pos.y;+ glyph.pos.y = ascent;+ glyph.font_ascent = ascent;+ glyph.font_height = ascent + descent;+ glyph.line_height = ascent + descent;+ if !glyph.uv_rect.is_nothing() {+ for vertex in row.visuals.mesh.vertices.iter_mut().skip(glyph.first_vertex as usize).take(4) {+ vertex.pos.y += dy;+ }+ }+ }+ row.size.y = (ascent + descent).max(1.0);+ row.visuals.mesh_bounds = row.visuals.mesh.vertices.iter().fold(Rect::NOTHING, |r, v| r.union(Rect::from_min_max(v.pos, v.pos)));+ bounds = bounds.union(Rect::from_min_size(placed.pos, row.size));+ meshes = meshes.union(row.visuals.mesh_bounds.translate(placed.pos.to_vec2()));+ }+ g.rect = Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(bounds.right().max(0.0), bounds.bottom().max(0.0)));+ g.mesh_bounds = meshes;+ galley+ }++ /// Caret colour that stays visible on a field filled with `fill`: black on light fills, white on dark ones.+ pub(crate) fn caret_color_on(fill: Color32) -> Color32 {+ let luma = 299 * u32::from(fill.r()) + 587 * u32::from(fill.g()) + 114 * u32::from(fill.b());+ if luma > 127_500 { Color32::BLACK } else { Color32::WHITE }+ }