Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

49.7 KB
Raw Blame
//! PdfCraft on phones: the engine as a native library for the Android app in `android/`, with
//! bindings generated by [UniFFI](https://mozilla.github.io/uniffi-rs).
//!
//! The phone UI is one more frontend next to the desktop app, the CLI/MCP server and the web
//! build. It runs the engine's headless tools by name ([`MobileSession::execute`]: the same tools
//! and JSON arguments as `pdfcraft-cli run` and MCP, `pdfcraft-cli tools` lists them) and asks for
//! pixels ([`MobileSession::render_page`]). A few typed helpers (documents, pages, outline) save
//! the UI from parsing JSON for what it shows all the time.
//!
//! Threading: every method may be called from any thread, and the ones that render block, so the
//! UI calls them off its main thread. A render holds the session lock only to look up the
//! document's bytes; the page is drawn unlocked by a renderer of its own, so the UI can keep
//! running tools (and other renders) while one is in flight.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use pdfcraft_automation::{Automation, Content, ToolError};
use pdfcraft_engine::{DocId, Document};
use pdfcraft_render::{OpenError, PageRenderer, PageText, RenderConfig, RenderRequest, RequestKind, Tile};
use serde_json::{Value, json};

uniffi::setup_scaffolding!();

mod office;
mod photo;
mod ppt;
mod sheets;
mod slides;
mod xls_art;

pub use photo::PhotoEditor;
pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetChart, SheetInfo, SheetPicture, SheetStats};
pub use word::{WordCaret, WordParagraph};
#[cfg(test)]
mod tests;
mod word;

use office::OfficeDoc;

/// What went wrong, as a message the user can act on.
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum MobileError {
    /// A tool failed or was refused: unknown name, bad arguments, not allowed by the document…
    #[error("{0}")]
    Command(String),
    /// The file could not be opened as a PDF.
    #[error("{0}")]
    Open(String),
    /// The document needs a password to open.
    #[error("the document is protected by a password")]
    NeedsPassword,
    /// The password given doesn't open the document.
    #[error("the password is incorrect")]
    WrongPassword,
    /// A page could not be drawn.
    #[error("{0}")]
    Render(String),
    #[error("no open document with id {0}")]
    NoDocument(u64),
}

/// A page as the viewer lays it out.
#[derive(Debug, Clone, uniffi::Record)]
pub struct PageInfo {
    /// Displayed size in points (after `/Rotate`).
    pub width: f32,
    pub height: f32,
    /// The page label (`/PageLabels`), else the 1-based page number.
    pub label: String,
    /// Clockwise rotation in degrees (0, 90, 180, 270).
    pub rotation: u16,
}

/// What kind of document is open: which engine reads it, and so which tools apply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum DocumentKind {
    Pdf,
    /// A word-processor document (.docx, .doc, .odt, .rtf), read by WordCraft's engine.
    Word,
    /// A presentation (.pptx), read by DeckCraft: each slide is a page.
    Slides,
    /// A workbook (.xlsx, .xlsb, .ods, .csv), read by GridCraft: each sheet is a page, drawn by the
    /// app as a grid of its own (see [`MobileSession::sheets`]).
    Sheets,
}

/// An open document as the viewer's title, menus and properties show it.
#[derive(Debug, Clone, uniffi::Record)]
pub struct DocumentInfo {
    pub id: u64,
    pub kind: DocumentKind,
    /// The file name.
    pub name: String,
    pub path: Option<String>,
    pub pages: Vec<PageInfo>,
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
    pub creator: Option<String>,
    pub producer: Option<String>,
    pub pdf_version: String,
    pub file_size: u64,
    pub encrypted: bool,
    pub tagged: bool,
    /// Why the document can't be edited, if it can't.
    pub read_only_reason: Option<String>,
    pub allows_printing: bool,
    pub allows_copying: bool,
    pub allows_annotation: bool,
    pub allows_form_filling: bool,
    pub allows_assembly: bool,
    /// Edits not saved yet.
    pub dirty: bool,
    /// What Undo and Redo would take back or redo, if anything.
    pub undo: Option<String>,
    pub redo: Option<String>,
    /// Interactive form fields.
    pub fields: u32,
    pub has_outline: bool,
    /// Files attached to the document itself (not to comments).
    pub attachments: u32,
    pub signed: bool,
    pub comments_hidden: bool,
    /// Bumped by every change to the working file: page caches key on it.
    pub generation: u64,
}

/// A bookmark, flattened in reading order.
#[derive(Debug, Clone, uniffi::Record)]
pub struct OutlineEntry {
    pub title: String,
    /// 0 for a top-level bookmark.
    pub level: u32,
    /// The 0-based page it goes to, when it goes to one.
    pub page: Option<u32>,
    /// Bookmarks under it.
    pub children: u32,
}

/// A region of a page rendered at some scale, in device pixels.
#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct TileRect {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

/// Rendered pixels: premultiplied RGBA8, row-major (Android's `ARGB_8888` memory layout).
#[derive(Debug, Clone, uniffi::Record)]
pub struct RenderedImage {
    pub width: u32,
    pub height: u32,
    pub rgba: Vec<u8>,
}

/// A tool of the headless tool table, for the UI's "run anything" paths and diagnostics.
#[derive(Debug, Clone, uniffi::Record)]
pub struct ToolInfo {
    pub name: String,
    pub title: String,
    pub description: String,
    /// The JSON schema of its arguments.
    pub input_schema: String,
    pub read_only: bool,
}

/// Page 1 of the document (a PDF, a Word document or a presentation) at absolute path `path` drawn to fit
/// `max_side` pixels, for file lists. The file is read but not opened in any session; a protected
/// or unreadable file is an error.
#[uniffi::export]
pub fn file_thumbnail(path: String, max_side: u32) -> Result<RenderedImage, MobileError> {
    if let Some((kind, bytes)) = office::file_at(&path)? {
        return office::open(&path, kind, &bytes, None, None)?.thumbnail(max_side);
    }
    let bytes = std::fs::read(&path).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;
    let mut r = PageRenderer::new(Arc::new(bytes), RenderConfig::default());
    if r.page_count() == 0 {
        return Err(MobileError::Open("the file has no pages".into()));
    }
    // a first, tiny render gives the page's aspect; the real one fits it into max_side
    let probe = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.05, tag: 0, preview: true });
    if let Some(e) = probe.error {
        return Err(MobileError::Render(e));
    }
    let (w, h) = (probe.width.max(1) as f32 / 0.05, probe.height.max(1) as f32 / 0.05);
    let scale = (max_side.clamp(16, 2048) as f32 / w.max(h)).max(0.01);
    let out = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale, tag: 0, preview: true });
    if let Some(e) = out.error {
        return Err(MobileError::Render(e));
    }
    Ok(RenderedImage { width: out.width, height: out.height, rgba: out.rgba.to_vec() })
}

/// A digital ID file's certificate, as the app lists the IDs it can sign with.
#[derive(Debug, Clone, uniffi::Record)]
pub struct DigitalIdInfo {
    /// Whose it is (the certificate's common name, else its whole subject).
    pub name: String,
    pub issuer: String,
    pub email: Option<String>,
    /// When it starts and stops being valid (seconds since 1970).
    pub valid_from: i64,
    pub valid_to: i64,
    pub self_signed: bool,
    /// The certificate's SHA-256 fingerprint (hex), which tells IDs apart.
    pub sha256: String,
    /// Why it can't sign documents, if it can't (its key usage doesn't allow it).
    pub problem: Option<String>,
}

/// The largest digital ID file read: real ones are a few kilobytes.
const MAX_ID_FILE: u64 = 1 << 20;

/// What the digital ID file (.p12 / .pfx) at absolute path `path` holds, unlocked with
/// `password`: a wrong password is [`MobileError::WrongPassword`].
#[uniffi::export]
pub fn digital_id_info(path: String, password: String) -> Result<DigitalIdInfo, MobileError> {
    use pdfcraft_engine::sign::{SignError, pkcs12};
    let size = std::fs::metadata(&path).map_err(|e| MobileError::Command(format!("{path}: {e}")))?.len();
    if size > MAX_ID_FILE {
        return Err(MobileError::Command("this is not a digital ID file (it is too large)".into()));
    }
    let bytes = std::fs::read(&path).map_err(|e| MobileError::Command(format!("{path}: {e}")))?;
    let id = pkcs12::open(&bytes, &password).map_err(|e| match e {
        SignError::WrongPassword => MobileError::WrongPassword,
        e => MobileError::Command(e.to_string()),
    })?;
    let c = &id.certificate;
    Ok(DigitalIdInfo {
        name: c.display_name(),
        issuer: c.issuer.display(),
        email: c.subject.email().map(str::to_string),
        valid_from: c.not_before.unix(),
        valid_to: c.not_after.unix(),
        self_signed: c.is_self_signed(),
        sha256: c.fingerprint(),
        problem: c.signing_problem().map(|d| d.message),
    })
}

/// The engine version (`0.6.0`).
#[uniffi::export]
pub fn engine_version() -> String {
    env!("CARGO_PKG_VERSION").into()
}

/// Send the engine's log to logcat (Android; elsewhere it does nothing). Safe to call repeatedly.
#[uniffi::export]
pub fn init_logging() {
    #[cfg(target_os = "android")]
    android_logger::init_once(android_logger::Config::default().with_max_level(log::LevelFilter::Info).with_tag("PdfCraft"));
}

/// A run of text on one page: glyphs `start..end` of its text layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)]
pub struct TextRange {
    pub page: u32,
    pub start: u32,
    pub end: u32,
}

/// A paragraph of a page as Read Aloud speaks it: its text, the glyphs it covers, and for each
/// character of the text the glyph it came from (to find the word being spoken).
#[derive(Debug, Clone, uniffi::Record)]
pub struct ReadingBlock {
    pub text: String,
    pub range: TextRange,
    pub glyph_of_char: Vec<u32>,
}

/// A search hit: where it is, and the rectangles that cover it (points, top-left origin, flattened
/// `x0, y0, x1, y1` per line).
#[derive(Debug, Clone, uniffi::Record)]
pub struct SearchHit {
    pub range: TextRange,
    pub rects: Vec<f32>,
    /// The line the hit is on, for the results list.
    pub context: String,
}

/// A link on a page: where it is (points, top-left origin: `x0, y0, x1, y1`) and where it goes.
#[derive(Debug, Clone, uniffi::Record)]
pub struct LinkInfo {
    pub rect: Vec<f32>,
    /// A web or mail address.
    pub uri: Option<String>,
    /// A page of this document (0-based).
    pub page: Option<u32>,
    /// Where on that page the view goes (points from its top), when the link says.
    pub top: Option<f32>,
}

/// A comment (annotation) as the comment list shows it.
#[derive(Debug, Clone, uniffi::Record)]
pub struct CommentInfo {
    /// 0-based page, and its index on the page (what the comment tools take, 1-based there).
    pub page: u32,
    pub index: u32,
    /// The PDF subtype (`Highlight`, `Text`, `Ink`, …) and its display name.
    pub subtype: String,
    pub kind: String,
    pub author: Option<String>,
    pub contents: Option<String>,
    /// When it was last changed, as the PDF says (`D:20261011171900Z`, with its time zone), if it does.
    pub modified: Option<String>,
    /// Its rectangle on the page (points, top-left origin).
    pub rect: Vec<f32>,
    /// `0xRRGGBB`, when it has a colour.
    pub color: Option<u32>,
    /// Its own name (`/NM`) and the comment it replies to, for threads.
    pub name: Option<String>,
    pub reply_to: Option<String>,
    /// Review status (`Accepted`, …).
    pub state: Option<String>,
    pub locked: bool,
    /// Placed with Fill & Sign rather than the comment tools.
    pub fill_sign: bool,
    /// Its opacity, 0 to 1.
    pub opacity: f32,
    /// Its line width in points, when it draws a line (ink, shapes, lines).
    pub width: Option<f32>,
}

/// A form field's widget on a page: what a tap there fills.
#[derive(Debug, Clone, uniffi::Record)]
pub struct WidgetInfo {
    /// The field's full name (what `form_fill` takes).
    pub field: String,
    /// `text`, `checkbox`, `radio`, `button`, `combo`, `list` or `signature`.
    pub kind: String,
    pub page: u32,
    /// Its rectangle (points, top-left origin).
    pub rect: Vec<f32>,
    /// Check boxes and radio buttons: the value this widget stands for, and whether it is on.
    pub export: Option<String>,
    pub on: bool,
    /// The field's value (text, or the chosen option's export value).
    pub value: Option<String>,
    /// Choices: (export value, label) flattened in pairs.
    pub options: Vec<String>,
    pub read_only: bool,
    pub multiline: bool,
    pub password: bool,
    pub max_length: Option<u32>,
    /// A choice field where any text may be typed too.
    pub editable: bool,
    pub multi_select: bool,
}

/// A file embedded in the document.
#[derive(Debug, Clone, uniffi::Record)]
pub struct AttachmentInfo {
    pub name: String,
    pub description: Option<String>,
    pub size: Option<u64>,
    /// Attached to a comment on a page (a file attachment annotation) rather than to the document.
    pub on_page: bool,
}

/// A rectangle in PDF user space as the page shows it (view space: points, y down).
fn view_rect(p: &pdfcraft_render::PageInfo, r: [f32; 4]) -> Vec<f32> {
    let [ax, ay] = p.user_to_view(r[0], r[1]);
    let [bx, by] = p.user_to_view(r[2], r[3]);
    vec![ax.min(bx), ay.min(by), ax.max(bx), ay.max(by)]
}

/// The paragraphs of `text` (see [`MobileSession::reading_blocks`]).
fn reading_blocks(text: &PageText, page: u32) -> Vec<ReadingBlock> {
    // each line's glyph span and box
    let mut lines: Vec<(usize, usize, f32, f32)> = Vec::new();
    for (i, g) in text.glyphs.iter().enumerate() {
        let line = text.line_of.get(i).copied().unwrap_or(0);
        match lines.last_mut() {
            Some(l) if text.line_of.get(l.0).copied() == Some(line) => {
                l.1 = i;
                l.2 = l.2.min(g.rect[1]);
                l.3 = l.3.max(g.rect[3]);
            }
            _ => lines.push((i, i, g.rect[1], g.rect[3])),
        }
    }
    let mut blocks: Vec<ReadingBlock> = Vec::new();
    let mut current: Option<(usize, usize, f32, f32)> = None;
    let flush = |c: Option<(usize, usize, f32, f32)>, blocks: &mut Vec<ReadingBlock>| {
        let Some((start, end, _, _)) = c else { return };
        let mut out = String::new();
        let mut map = Vec::new();
        for i in start..=end {
            let Some(g) = text.glyphs.get(i) else { continue };
            let new_line = i > start && text.line_of.get(i) != text.line_of.get(i - 1);
            if (new_line || text.space_before.get(i).copied().unwrap_or(false)) && !out.ends_with(' ') {
                out.push(' ');
                map.push(u32::try_from(i).unwrap_or(u32::MAX));
            }
            for ch in g.text.chars() {
                out.push(ch);
                map.push(u32::try_from(i).unwrap_or(u32::MAX));
            }
        }
        let trimmed = out.trim_end();
        if !trimmed.is_empty() {
            map.truncate(trimmed.chars().count());
            blocks.push(ReadingBlock {
                text: trimmed.to_string(),
                range: TextRange { page, start: start as u32, end: end.saturating_add(1) as u32 },
                glyph_of_char: map,
            });
        }
    };
    for &(s, e, top, bottom) in &lines {
        let height = (bottom - top).max(0.1);
        current = match current {
            Some((cs, _, ctop, cbottom)) => {
                let prev_height = (cbottom - ctop).max(0.1);
                let gap = top - cbottom;
                let breaks = gap > prev_height * 0.5 || top < ctop - prev_height * 0.5 || (height / prev_height - 1.0).abs() > 0.3;
                if breaks {
                    flush(current, &mut blocks);
                    Some((s, e, top, bottom))
                } else {
                    Some((cs, e, top, bottom))
                }
            }
            None => Some((s, e, top, bottom)),
        };
    }
    flush(current, &mut blocks);
    blocks
}

fn rgb(c: [f32; 3]) -> u32 {
    let ch = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u32;
    (ch(c[0]) << 16) | (ch(c[1]) << 8) | ch(c[2])
}

/// How many idle renderers a document keeps (a page view and its thumbnails can render at once).
const RENDERERS_PER_DOC: usize = 3;

/// The documents' idle renderers: the bytes they render, and the renderers themselves.
type RendererCache = HashMap<u64, (Arc<Vec<u8>>, Vec<PageRenderer>)>;

/// A document's text layers: the bytes they were taken from, a renderer to extract more, and one
/// slot per page.
struct TextCache {
    bytes: Arc<Vec<u8>>,
    renderer: PageRenderer,
    pages: Vec<Option<Arc<PageText>>>,
}

/// The engine's session: the open documents, their edit history and the tools that act on them.
/// PDFs are the PDF engine's; office documents are kept beside them under ids of their own.
#[derive(uniffi::Object)]
pub struct MobileSession {
    auto: Mutex<Automation>,
    renderers: Mutex<RendererCache>,
    texts: Mutex<HashMap<u64, TextCache>>,
    office: Mutex<HashMap<u64, Arc<dyn OfficeDoc>>>,
    next_office: AtomicU64,
    /// The reader's language (BCP 47), for the paper of documents that give none.
    locale: Mutex<Option<String>>,
}

impl MobileSession {
    fn lock(&self) -> MutexGuard<'_, Automation> {
        self.auto.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn cache(&self) -> MutexGuard<'_, RendererCache> {
        self.renderers.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Run tool `name`; its JSON result (`null` if it gave none).
    fn call(&self, name: &str, args: &Value) -> Result<Value, MobileError> {
        let out = self.lock().call(name, args).map_err(|e| MobileError::Command(e.to_string()))?;
        Ok(first_json(out))
    }

    /// An idle renderer for `bytes`, or a new one.
    fn take_renderer(&self, doc: u64, bytes: &Arc<Vec<u8>>, config: RenderConfig) -> PageRenderer {
        let mut cache = self.cache();
        match cache.get_mut(&doc) {
            Some((b, idle)) if Arc::ptr_eq(b, bytes) => idle.pop(),
            _ => None,
        }
        .unwrap_or_else(|| PageRenderer::new(bytes.clone(), config))
    }

    /// Give a renderer back for the next render, unless the document has changed since.
    fn return_renderer(&self, doc: u64, bytes: &Arc<Vec<u8>>, renderer: PageRenderer) {
        let mut cache = self.cache();
        let entry = cache.entry(doc).or_insert_with(|| (bytes.clone(), Vec::new()));
        if !Arc::ptr_eq(&entry.0, bytes) {
            // the renderers of an older version of the document are no use any more
            *entry = (bytes.clone(), Vec::new());
        }
        if entry.1.len() < RENDERERS_PER_DOC {
            entry.1.push(renderer);
        }
    }

    /// The office document `doc`, if it is one.
    fn office(&self, doc: u64) -> Option<Arc<dyn OfficeDoc>> {
        self.office.lock().unwrap_or_else(PoisonError::into_inner).get(&doc).cloned()
    }

    /// Run `f` on workbook `doc`.
    fn with_sheets<T>(&self, doc: u64, f: impl FnOnce(&sheets::SheetBook) -> Result<T, MobileError>) -> Result<T, MobileError> {
        let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
        d.as_sheets().ok_or(MobileError::NoDocument(doc)).and_then(f)
    }

    fn with_doc<T>(&self, doc: u64, f: impl FnOnce(&Document) -> T) -> Result<T, MobileError> {
        let a = self.lock();
        let d = a.session().get(DocId(doc)).ok_or(MobileError::NoDocument(doc))?;
        Ok(f(d))
    }

    /// The text layer of page `page` of `doc` as it is now (extracted once per document version).
    fn page_text(&self, doc: u64, page: u32) -> Result<Arc<PageText>, MobileError> {
        if let Some(w) = self.office(doc) {
            return w.page_text(page);
        }
        let (bytes, password, pages) = self.with_doc(doc, |d| (d.bytes.clone(), d.password.clone(), d.info.pages.len()))?;
        let index = page as usize;
        if index >= pages {
            return Err(MobileError::Command(format!("page {} is out of range: the document has {pages} pages", index.saturating_add(1))));
        }
        let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);
        let fresh = || TextCache {
            bytes: bytes.clone(),
            renderer: PageRenderer::new(bytes.clone(), RenderConfig { password: password.as_deref().map(Arc::from), ..RenderConfig::default() }),
            pages: vec![None; pages],
        };
        let entry = texts.entry(doc).or_insert_with(fresh);
        if !Arc::ptr_eq(&entry.bytes, &bytes) || entry.pages.len() != pages {
            *entry = fresh();
        }
        if let Some(Some(t)) = entry.pages.get(index) {
            return Ok(t.clone());
        }
        let out = entry.renderer.render(RenderRequest { page: index, kind: RequestKind::Text, tile: None, scale: 1.0, tag: 0, preview: false });
        let text = match (out.error, out.text) {
            (None, Some(t)) => t,
            (Some(e), _) => return Err(MobileError::Command(format!("the text of page {} could not be read: {e}", index.saturating_add(1)))),
            (None, None) => Arc::new(PageText::default()),
        };
        if let Some(slot) = entry.pages.get_mut(index) {
            *slot = Some(text.clone());
        }
        Ok(text)
    }
}

/// `start..end` clamped to the glyphs of `text`.
fn glyph_range(text: &PageText, start: u32, end: u32) -> std::ops::Range<usize> {
    let n = text.glyphs.len();
    let s = (start as usize).min(n);
    let e = (end as usize).clamp(s, n);
    s..e
}

fn flatten_rects(rects: &[[f32; 4]]) -> Vec<f32> {
    rects.iter().flat_map(|r| r.iter().copied()).collect()
}

#[uniffi::export]
impl MobileSession {
    /// A session with no documents open.
    #[uniffi::constructor]
    #[allow(clippy::new_without_default)]
    pub fn new() -> Arc<Self> {
        Arc::new(MobileSession {
            auto: Mutex::new(Automation::new()),
            renderers: Mutex::new(HashMap::new()),
            texts: Mutex::new(HashMap::new()),
            office: Mutex::new(HashMap::new()),
            next_office: AtomicU64::new(office::OFFICE_IDS),
            locale: Mutex::new(None),
        })
    }

    /// The reader's language as a BCP 47 tag (`en-US`): documents that give no paper size (plain
    /// text, Markdown, HTML) open on that region's paper.
    pub fn set_locale(&self, tag: String) {
        *self.locale.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
    }

    /// Open the document at absolute path `path` (with `password` if it needs one): a PDF, a Word
    /// document (.docx, .doc, .odt, .rtf) or a presentation (.pptx), told apart by its bytes.
    pub fn open(&self, path: String, password: Option<String>) -> Result<DocumentInfo, MobileError> {
        if !std::path::Path::new(&path).is_absolute() {
            return Err(MobileError::Open(format!("the path must be absolute, not `{path}`")));
        }
        if let Some((kind, bytes)) = office::file_at(&path)? {
            let locale = self.locale.lock().unwrap_or_else(PoisonError::into_inner).clone();
            let d = office::open(&path, kind, &bytes, password.as_deref(), locale.as_deref())?;
            let id = self.next_office.fetch_add(1, Ordering::Relaxed);
            self.office.lock().unwrap_or_else(PoisonError::into_inner).insert(id, d.clone());
            return Ok(d.info(id));
        }
        let mut args = json!({ "path": path });
        if let (Some(p), Some(o)) = (password, args.as_object_mut()) {
            o.insert("password".into(), Value::String(p));
        }
        let out = self.lock().call("doc_open", &args).map_err(open_error)?;
        let id = first_json(out).get("doc").and_then(Value::as_u64).ok_or_else(|| MobileError::Open("the document did not open".into()))?;
        self.document(id)
    }

    /// Close document `doc`. Unsaved edits are refused unless `discard_changes` is set.
    pub fn close(&self, doc: u64, discard_changes: bool) -> Result<(), MobileError> {
        if self.office.lock().unwrap_or_else(PoisonError::into_inner).remove(&doc).is_some() {
            return Ok(());
        }
        self.call("doc_close", &json!({ "doc": doc, "discard_changes": discard_changes }))?;
        self.cache().remove(&doc);
        self.texts.lock().unwrap_or_else(PoisonError::into_inner).remove(&doc);
        Ok(())
    }

    /// The ids of the open documents.
    pub fn documents(&self) -> Vec<u64> {
        let mut ids: Vec<u64> = self.lock().session().docs().iter().map(|d| d.id.0).collect();
        let mut office: Vec<u64> = self.office.lock().unwrap_or_else(PoisonError::into_inner).keys().copied().collect();
        office.sort_unstable();
        ids.extend(office);
        ids
    }

    /// Document `doc` as it is now.
    pub fn document(&self, doc: u64) -> Result<DocumentInfo, MobileError> {
        if let Some(w) = self.office(doc) {
            return Ok(w.info(doc));
        }
        self.with_doc(doc, document_info)
    }

    /// The speaker notes of slide `page` (0-based) of presentation `doc`; empty when it has none.
    pub fn slide_notes(&self, doc: u64, page: u32) -> Result<String, MobileError> {
        let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
        Ok(d.notes(page).unwrap_or_default())
    }

    /// Document `doc`'s bookmarks, flattened in reading order (at most as many as the engine reads).
    pub fn outline(&self, doc: u64) -> Result<Vec<OutlineEntry>, MobileError> {
        if let Some(d) = self.office(doc) {
            return Ok(d.outline());
        }
        self.with_doc(doc, |d| {
            let mut out = Vec::new();
            flatten_outline(&d.info.outline, 0, &mut out);
            out
        })
    }

    /// Draw page `page` (0-based) of document `doc` at `scale` device pixels per point: the whole
    /// page, or only `tile` of it (device pixels at that scale). The scale is capped so that the
    /// result stays within the renderer's size limits. Sticky notes are left out: the app draws
    /// them as icons of its own.
    pub fn render_page(&self, doc: u64, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {
        if !(scale.is_finite() && scale > 0.0) {
            return Err(MobileError::Render(format!("the scale must be a positive number, not {scale}")));
        }
        if let Some(w) = self.office(doc) {
            return w.render_page(page, scale, tile);
        }
        let (bytes, config, pages) = self.with_doc(doc, |d| {
            // the app draws sticky notes itself, as fixed-size icons over the page
            let config = RenderConfig {
                password: d.password.as_deref().map(Arc::from),
                hide_comments: d.comments_hidden(),
                hide_notes: true,
                ..RenderConfig::default()
            };
            (d.display.clone(), config, d.info.pages.len())
        })?;
        let index = page as usize;
        if index >= pages {
            return Err(MobileError::Render(format!("page {} is out of range: the document has {pages} pages", index.saturating_add(1))));
        }
        let mut renderer = self.take_renderer(doc, &bytes, config);
        let tile = tile.map(|t| Tile { x: t.x, y: t.y, w: t.width, h: t.height });
        let out = renderer.render(RenderRequest { page: index, kind: RequestKind::Pixels, tile, scale, tag: 0, preview: false });
        self.return_renderer(doc, &bytes, renderer);
        if let Some(e) = out.error {
            return Err(MobileError::Render(format!("page {} could not be drawn: {e}", index.saturating_add(1))));
        }
        Ok(RenderedImage { width: out.width, height: out.height, rgba: out.rgba.to_vec() })
    }

    /// Run tool `name` with JSON arguments (`""` = none) and return its JSON result: the tools and
    /// arguments of `pdfcraft-cli run` and MCP (pages are 1-based there).
    pub fn execute(&self, name: String, args_json: String) -> Result<String, MobileError> {
        let args = if args_json.trim().is_empty() {
            Value::Null
        } else {
            serde_json::from_str(&args_json).map_err(|e| MobileError::Command(format!("`{name}`: the arguments are not valid JSON: {e}")))?
        };
        Ok(self.call(&name, &args)?.to_string())
    }

    /// Every tool, with its argument schema.
    pub fn tools(&self) -> Vec<ToolInfo> {
        pdfcraft_automation::tools()
            .into_iter()
            .map(|t| ToolInfo {
                name: t.name.to_string(),
                title: t.title.to_string(),
                description: t.description.to_string(),
                input_schema: t.input_schema.to_string(),
                read_only: t.read_only,
            })
            .collect()
    }

    /// The links on page `page`.
    pub fn links(&self, doc: u64, page: u32) -> Result<Vec<LinkInfo>, MobileError> {
        if let Some(w) = self.office(doc) {
            return w.links(page);
        }
        self.with_doc(doc, |d| {
            let Some(p) = d.info.pages.get(page as usize) else { return Vec::new() };
            d.info
                .links
                .iter()
                .filter(|l| l.page == page as usize)
                .filter_map(|l| {
                    let (uri, target, top) = match &l.target {
                        pdfcraft_render::LinkTarget::Uri(u) => (Some(u.clone()), None, None),
                        pdfcraft_render::LinkTarget::Page(n, view) => {
                            let top = match view {
                                pdfcraft_render::DestView::Xyz { top: Some(t), .. } | pdfcraft_render::DestView::FitH { top: Some(t) } => {
                                    d.info.pages.get(*n).map(|tp| tp.user_to_view(0.0, *t)[1])
                                }
                                _ => None,
                            };
                            (None, u32::try_from(*n).ok(), top)
                        }
                        _ => return None,
                    };
                    Some(LinkInfo { rect: view_rect(p, l.rect), uri, page: target, top })
                })
                .collect()
        })
    }

    /// Every comment of the document, page by page (replies included; see `reply_to`).
    pub fn comments(&self, doc: u64) -> Result<Vec<CommentInfo>, MobileError> {
        if self.office(doc).is_some() {
            return Ok(Vec::new());
        }
        self.with_doc(doc, |d| {
            d.info
                .annotations
                .iter()
                .filter(|a| a.subtype != "Link" && a.subtype != "Widget" && a.subtype != "Popup")
                .map(|a| CommentInfo {
                    page: u32::try_from(a.page).unwrap_or(u32::MAX),
                    index: u32::try_from(a.index).unwrap_or(u32::MAX),
                    subtype: a.subtype.clone(),
                    kind: pdfcraft_engine::comment_kind(a).to_string(),
                    author: a.author.clone(),
                    contents: a.contents.clone(),
                    modified: a.modified_raw.clone().or_else(|| a.modified.clone()),
                    rect: d.info.pages.get(a.page).map(|p| view_rect(p, a.rect)).unwrap_or_default(),
                    color: a.color.map(rgb),
                    name: a.name.clone(),
                    reply_to: a.in_reply_to.clone(),
                    state: a.state.clone(),
                    locked: a.locked,
                    fill_sign: a.fill_sign,
                    opacity: a.opacity,
                    width: a.width,
                })
                .collect()
        })
    }

    /// The files embedded in the document.
    pub fn attachments(&self, doc: u64) -> Result<Vec<AttachmentInfo>, MobileError> {
        if self.office(doc).is_some() {
            return Ok(Vec::new());
        }
        self.with_doc(doc, |d| {
            d.info
                .attachments
                .iter()
                .map(|a| AttachmentInfo {
                    name: a.name.clone(),
                    description: a.description.clone(),
                    size: a.size.map(|s| s as u64),
                    on_page: matches!(a.source, pdfcraft_render::AttachmentSource::Annotation { .. }),
                })
                .collect()
        })
    }

    /// Write the embedded file `index` (in the order [`MobileSession::attachments`] lists them) to
    /// absolute path `path`; returns its name.
    pub fn save_attachment(&self, doc: u64, index: u32, path: String) -> Result<String, MobileError> {
        if !std::path::Path::new(&path).is_absolute() {
            return Err(MobileError::Command(format!("the path must be absolute, not `{path}`")));
        }
        let (bytes, password, att) =
            self.with_doc(doc, |d| (d.bytes.clone(), d.password.clone(), d.info.attachments.get(index as usize).cloned()))?;
        let att = att.ok_or_else(|| MobileError::Command(format!("the document has no attachment {}", index.saturating_add(1))))?;
        let data = pdfcraft_render::attachment_data(&bytes, password.as_deref(), &att).map_err(MobileError::Command)?;
        std::fs::write(&path, data).map_err(|e| MobileError::Command(format!("{path}: {e}")))?;
        Ok(att.name)
    }

    /// Write the recording of voice comment `index` on page `page` (as [`MobileSession::comments`]
    /// numbers them) to absolute path `path` as a WAV file, for the player.
    pub fn save_sound(&self, doc: u64, page: u32, index: u32, path: String) -> Result<(), MobileError> {
        if !std::path::Path::new(&path).is_absolute() {
            return Err(MobileError::Command(format!("the path must be absolute, not `{path}`")));
        }
        let (bytes, password) = self.with_doc(doc, |d| (d.bytes.clone(), d.password.clone()))?;
        let wav = pdfcraft_render::sound_wav(&bytes, password.as_deref(), page as usize, index as usize).map_err(MobileError::Command)?;
        std::fs::write(&path, wav).map_err(|e| MobileError::Command(format!("{path}: {e}")))
    }

    /// The certificate (DER) that signed signature field `field`, if it is signed: what the app
    /// saves when the reader chooses to trust that signer.
    pub fn signer_certificate(&self, doc: u64, field: String) -> Result<Option<Vec<u8>>, MobileError> {
        if self.office(doc).is_some() {
            return Ok(None);
        }
        self.with_doc(doc, |d| d.signatures.iter().find(|s| s.signed && s.field == field).and_then(|s| s.certificate.as_ref()).map(|c| c.raw.clone()))
    }

    /// Every visible widget of the document's form fields, page by page.
    pub fn widgets(&self, doc: u64) -> Result<Vec<WidgetInfo>, MobileError> {
        if self.office(doc).is_some() {
            return Ok(Vec::new());
        }
        use pdfcraft_engine::{FormFieldKind as K, field_flags as fl};
        self.with_doc(doc, |d| {
            let mut out = Vec::new();
            for f in d.form.iter() {
                let kind = match f.kind {
                    K::Text => "text",
                    K::CheckBox => "checkbox",
                    K::Radio => "radio",
                    K::PushButton => "button",
                    K::Combo => "combo",
                    K::List => "list",
                    K::Signature => "signature",
                };
                for (i, w) in f.widgets.iter().enumerate() {
                    if w.hidden {
                        continue;
                    }
                    let Some(page) = w.page else { continue };
                    let Some(p) = d.info.pages.get(page) else { continue };
                    let r = [w.rect[0] as f32, w.rect[1] as f32, w.rect[2] as f32, w.rect[3] as f32];
                    let on = match (&w.on_state, f.value.first()) {
                        (Some(s), Some(v)) => s == v,
                        _ => false,
                    };
                    out.push(WidgetInfo {
                        field: f.name.clone(),
                        kind: kind.into(),
                        page: u32::try_from(page).unwrap_or(u32::MAX),
                        rect: view_rect(p, r),
                        export: f.export_of(i).map(str::to_string),
                        on,
                        value: f.value.first().cloned(),
                        options: f.options.iter().flat_map(|(e, l)| [e.clone(), l.clone()]).collect(),
                        read_only: f.read_only(),
                        multiline: f.has(fl::MULTILINE),
                        password: f.has(fl::PASSWORD),
                        max_length: f.max_len.and_then(|m| u32::try_from(m).ok()),
                        editable: f.has(fl::EDIT),
                        multi_select: f.has(fl::MULTI_SELECT),
                    });
                }
            }
            out
        })
    }

    /// Write office document `doc` (Word, slides or a workbook) as `format` to absolute path `path`:
    /// `pdf`, or another format its engine writes ([`MobileSession::export_formats`]).
    pub fn export_office(&self, doc: u64, format: String, path: String) -> Result<(), MobileError> {
        let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
        let bytes = d.export(&format.to_ascii_lowercase())?;
        std::fs::write(&path, bytes).map_err(|e| MobileError::Command(format!("{path}: {e}")))
    }

    /// The formats office document `doc` can be written as, PDF first (empty for a PDF).
    pub fn export_formats(&self, doc: u64) -> Vec<String> {
        self.office(doc).map(|d| office::formats(d.info(doc).kind).iter().map(|f| f.to_string()).collect()).unwrap_or_default()
    }

    /// Save office document `doc`'s edits to absolute path `path` (its working copy), in its own format.
    pub fn save_office(&self, doc: u64, path: String) -> Result<(), MobileError> {
        self.office(doc).ok_or(MobileError::NoDocument(doc))?.save(&path)
    }

    /// Run GridCraft command `command` (JSON `params_json`, `""` = none) on `area` of sheet `sheet`
    /// of workbook `doc`, the area selected first: formatting (`home.bold`, `home.fillColor`,
    /// `home.alignCenter`, `home.percent`, ...), `cell.set`, `home.insertRows`, `edit.undo`, ...
    /// Its JSON result.
    pub fn sheet_command(&self, doc: u64, sheet: u32, area: CellSpan, command: String, params_json: String) -> Result<String, MobileError> {
        let params = if params_json.trim().is_empty() {
            serde_json::json!({})
        } else {
            serde_json::from_str(&params_json).map_err(|e| MobileError::Command(format!("`{command}`: the arguments are not valid JSON: {e}")))?
        };
        self.with_sheets(doc, |b| b.command(sheet, area, &command, params)).map(|v| v.to_string())
    }

    /// Run WordCraft command `command` (JSON `params_json`, `""` = none) on Word document `doc`:
    /// `caret.set {page, x, y, extend?}`, `text.insert {text}`, `text.backspace`, `text.newParagraph`,
    /// `format.bold`, `para.alignCenter`, `para.bullets`, `para.style {style}`, `edit.undo`, ...
    /// Its JSON result.
    pub fn word_command(&self, doc: u64, command: String, params_json: String) -> Result<String, MobileError> {
        let params = if params_json.trim().is_empty() {
            serde_json::json!({})
        } else {
            serde_json::from_str(&params_json).map_err(|e| MobileError::Command(format!("`{command}`: the arguments are not valid JSON: {e}")))?
        };
        let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
        let w = d.as_word().ok_or(MobileError::NoDocument(doc))?;
        w.run(&command, &params).map(|v| v.to_string())
    }

    /// The paragraph at a point of Word document `doc`, selected for editing in place.
    pub fn word_paragraph_at(&self, doc: u64, page: u32, x: f32, y: f32) -> Result<Option<WordParagraph>, MobileError> {
        let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
        d.as_word().ok_or(MobileError::NoDocument(doc))?.paragraph_at(page, x, y)
    }

    /// Where Word document `doc`'s caret is, and its selection.
    pub fn word_caret(&self, doc: u64) -> Option<WordCaret> {
        self.office(doc).and_then(|d| d.as_word().and_then(|w| w.caret()))
    }

    /// Put `input` (text, a number or `=formula`) in a cell, as typing it in the formula bar does.
    pub fn sheet_set_cell(&self, doc: u64, sheet: u32, row: u32, col: u32, input: String) -> Result<(), MobileError> {
        let cell = CellSpan { row0: row, col0: col, row1: row, col1: col };
        self.with_sheets(doc, |b| b.command(sheet, cell, "cell.set", serde_json::json!({ "input": input }))).map(|_| ())
    }

    /// What the formula bar shows for a cell: its formula, else its value as typed.
    pub fn sheet_input(&self, doc: u64, sheet: u32, row: u32, col: u32) -> Result<String, MobileError> {
        self.with_sheets(doc, |b| b.input(sheet, row, col))
    }

    /// The sheets of workbook `doc`, in tab order.
    pub fn sheets(&self, doc: u64) -> Result<Vec<SheetInfo>, MobileError> {
        self.with_sheets(doc, |b| Ok(b.sheets()))
    }

    /// Column widths and row heights (points) of a window of sheet `sheet`.
    pub fn sheet_axes(&self, doc: u64, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<SheetAxes, MobileError> {
        self.with_sheets(doc, |b| b.axes(sheet, row0, rows, col0, cols))
    }

    /// The cells of a window of sheet `sheet` that show something, with their looks.
    pub fn sheet_cells(&self, doc: u64, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<Vec<CellView>, MobileError> {
        self.with_sheets(doc, |b| b.cells(sheet, row0, rows, col0, cols))
    }

    /// The pictures floating over sheet `sheet` of workbook `doc`.
    pub fn sheet_pictures(&self, doc: u64, sheet: u32) -> Result<Vec<SheetPicture>, MobileError> {
        self.with_sheets(doc, |b| b.pictures(sheet))
    }

    /// What the cells of `area` on sheet `sheet` hold: counts, and the sum, smallest and largest of its numbers.
    pub fn sheet_stats(&self, doc: u64, sheet: u32, area: CellSpan) -> Result<SheetStats, MobileError> {
        self.with_sheets(doc, |b| b.stats(sheet, area))
    }

    /// The charts over sheet `sheet` of workbook `doc`, laid out by GridCraft as drawing steps.
    pub fn sheet_charts(&self, doc: u64, sheet: u32) -> Result<Vec<SheetChart>, MobileError> {
        self.with_sheets(doc, |b| b.charts(sheet))
    }

    /// The merged areas of sheet `sheet`.
    pub fn sheet_merges(&self, doc: u64, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {
        self.with_sheets(doc, |b| b.merges(sheet))
    }

    /// The cells of sheet `sheet` showing `query`, at most `limit`, in reading order.
    pub fn sheet_find(&self, doc: u64, sheet: u32, query: String, case_sensitive: bool, limit: u32) -> Result<Vec<CellSpan>, MobileError> {
        self.with_sheets(doc, |b| b.find(sheet, &query, case_sensitive, limit))
    }

    /// Drop the idle renderers and text layers (the system is short of memory); the next render
    /// or text call makes new ones.
    pub fn release_memory(&self) {
        self.cache().clear();
        self.texts.lock().unwrap_or_else(PoisonError::into_inner).clear();
        for w in self.office.lock().unwrap_or_else(PoisonError::into_inner).values() {
            w.release_memory();
        }
    }

    /// The word at point (`x`, `y`) on page `page` (points, top-left origin), or the one nearest it
    /// within `slop` points: what a long press selects.
    pub fn word_at(&self, doc: u64, page: u32, x: f32, y: f32, slop: f32) -> Result<Option<TextRange>, MobileError> {
        let text = self.page_text(doc, page)?;
        let Some(i) = text.nearest(x, y) else { return Ok(None) };
        let Some(g) = text.glyphs.get(i) else { return Ok(None) };
        let [x0, y0, x1, y1] = g.rect;
        let slop = if slop.is_finite() { slop.max(0.0) } else { 0.0 };
        if x < x0 - slop || x > x1 + slop || y < y0 - slop || y > y1 + slop {
            return Ok(None);
        }
        Ok(text.word_at(i).map(|(s, e)| TextRange { page, start: s as u32, end: e.saturating_add(1) as u32 }))
    }

    /// The glyph nearest point (`x`, `y`) on page `page`: where a selection handle lands.
    pub fn nearest_glyph(&self, doc: u64, page: u32, x: f32, y: f32) -> Result<Option<u32>, MobileError> {
        Ok(self.page_text(doc, page)?.nearest(x, y).and_then(|i| u32::try_from(i).ok()))
    }

    /// How many glyphs page `page` has (0: no text, e.g. a scan without OCR).
    pub fn glyph_count(&self, doc: u64, page: u32) -> Result<u32, MobileError> {
        Ok(u32::try_from(self.page_text(doc, page)?.glyphs.len()).unwrap_or(u32::MAX))
    }

    /// The rectangles covering `range`, one per line (flattened `x0, y0, x1, y1`, points).
    pub fn text_rects(&self, doc: u64, range: TextRange) -> Result<Vec<f32>, MobileError> {
        let text = self.page_text(doc, range.page)?;
        Ok(flatten_rects(&text.line_rects(glyph_range(&text, range.start, range.end))))
    }

    /// The rectangle of glyph `index` on page `page` (`x0, y0, x1, y1`): where a selection handle sits.
    pub fn glyph_rect(&self, doc: u64, page: u32, index: u32) -> Result<Vec<f32>, MobileError> {
        let text = self.page_text(doc, page)?;
        Ok(text.glyphs.get(index as usize).map(|g| g.rect.to_vec()).unwrap_or_default())
    }

    /// The text of `range`, with spaces and line breaks.
    pub fn text_of(&self, doc: u64, range: TextRange) -> Result<String, MobileError> {
        let text = self.page_text(doc, range.page)?;
        Ok(text.text_of(glyph_range(&text, range.start, range.end)))
    }

    /// Page `page`'s text as paragraphs in reading order (Read Aloud). A new paragraph starts
    /// where a line sits clearly lower than the line before would lead on to (a gap of over half
    /// a line), goes back up (a new column), or is set in a markedly different size.
    pub fn reading_blocks(&self, doc: u64, page: u32) -> Result<Vec<ReadingBlock>, MobileError> {
        let text = self.page_text(doc, page)?;
        Ok(reading_blocks(&text, page))
    }

    /// All of page `page`'s text (Read Aloud, select all).
    pub fn page_plain_text(&self, doc: u64, page: u32) -> Result<String, MobileError> {
        Ok(self.page_text(doc, page)?.plain_text())
    }

    /// Where `query` occurs on page `page`. The app searches page by page so it can show hits as
    /// they come and stop when the reader moves on.
    pub fn find_in_page(&self, doc: u64, page: u32, query: String, case_sensitive: bool, whole_words: bool) -> Result<Vec<SearchHit>, MobileError> {
        if query.trim().is_empty() {
            return Ok(Vec::new());
        }
        let text = self.page_text(doc, page)?;
        Ok(text
            .find_opts(&query, case_sensitive, whole_words)
            .into_iter()
            .map(|r| {
                let context = text.line_at(r.start).map(|(s, e)| text.text_of(s..e.saturating_add(1))).unwrap_or_default();
                SearchHit { range: TextRange { page, start: r.start as u32, end: r.end as u32 }, rects: flatten_rects(&text.line_rects(r)), context }
            })
            .collect())
    }
}

/// The first JSON result of a tool (`null` if it gave none).
fn first_json(out: Vec<Content>) -> Value {
    out.into_iter()
        .find_map(|c| match c {
            Content::Json(v) => Some(v),
            Content::Png { .. } => None,
        })
        .unwrap_or(Value::Null)
}

/// A failed `doc_open`, with the password cases told apart so the app can ask for one.
fn open_error(e: ToolError) -> MobileError {
    let message = e.to_string();
    if message == OpenError::NeedsPassword.to_string() {
        MobileError::NeedsPassword
    } else if message == OpenError::WrongPassword.to_string() {
        MobileError::WrongPassword
    } else {
        MobileError::Open(message)
    }
}

fn document_info(d: &Document) -> DocumentInfo {
    let info = &d.info;
    DocumentInfo {
        id: d.id.0,
        kind: DocumentKind::Pdf,
        name: d.name.clone(),
        path: d.path.clone(),
        pages: info.pages.iter().map(|p| PageInfo { width: p.width, height: p.height, label: p.label.clone(), rotation: p.rotation }).collect(),
        title: info.title.clone(),
        author: info.author.clone(),
        subject: info.subject.clone(),
        keywords: info.keywords.clone(),
        creator: info.creator.clone(),
        producer: info.producer.clone(),
        pdf_version: info.pdf_version.clone(),
        file_size: info.file_size as u64,
        encrypted: info.encrypted,
        tagged: info.tagged,
        read_only_reason: d.read_only_reason.clone(),
        allows_printing: d.allows_printing(),
        allows_copying: d.allows_copying(),
        allows_annotation: d.allows_annotation(),
        allows_form_filling: d.allows_form_filling(),
        allows_assembly: d.allows_assembly(),
        dirty: d.dirty,
        undo: d.can_undo().map(str::to_string),
        redo: d.can_redo().map(str::to_string),
        fields: u32::try_from(d.form.len()).unwrap_or(u32::MAX),
        has_outline: !info.outline.is_empty(),
        // the document's own files: those on comments are reached through the comment
        attachments: u32::try_from(
            info.attachments.iter().filter(|a| matches!(a.source, pdfcraft_render::AttachmentSource::Document { .. })).count(),
        )
        .unwrap_or(u32::MAX),
        signed: d.is_signed(),
        comments_hidden: d.comments_hidden(),
        generation: d.edit_generation(),
    }
}

/// How deep the flattened outline goes (the engine already bounds what it reads).
const OUTLINE_DEPTH: u32 = 32;

fn flatten_outline(items: &[pdfcraft_render::OutlineItem], level: u32, out: &mut Vec<OutlineEntry>) {
    if level > OUTLINE_DEPTH {
        return;
    }
    for item in items {
        out.push(OutlineEntry {
            title: item.title.clone(),
            level,
            page: item.page.and_then(|p| u32::try_from(p).ok()),
            children: u32::try_from(item.children.len()).unwrap_or(u32::MAX),
        });
        flatten_outline(&item.children, level.saturating_add(1), out);
    }
}