# IDEA.md – build your own fast PDF reader This file is a self-contained brief. Give it in full to Claude Code (or a similar tool) to build your own implementation. It is based on what was learned building Pdfer, a PDF reader for Windows and macOS written in Rust, but you don't need to have seen that code. --- ## 1. What to build **The purpose:** a desktop PDF reader that replaces Adobe Acrobat Reader for anyone who wants something fast and light, with no bundled extra programs, and with the features missing from Reader's free version: text recognition (OCR) of scanned documents and correcting text. **The main requirement is perceived speed.** Cold start, opening a file and turning pages must feel instant, even in documents with thousands of pages. Weigh every design decision below against that. **It must be able to:** - Display PDFs with paging (arrow keys, PgUp/PgDn, Home/End, mouse wheel – one wheel step is one page), zoom around the mouse pointer (Ctrl+wheel, Ctrl +/−/0), fit modes (whole page, page width, actual size) and view rotation. - Show the current page and page count ("12 / 348"), with a draggable scrollbar that reaches the whole document and shows the page number while dragging. - Keep several documents open in tabs in one window. Double-clicking a PDF while the program is running must open a new tab, not a new program. - Select and copy text (drag, double-click = word, triple-click = text object), with a text cursor when the pointer is over selectable text. - Search the document as you type, and search every PDF in a folder and its subfolders without any document being open. - Thumbnails and table of contents (bookmarks) in a sidebar. - Run text recognition on scanned pages and write the text as an invisible text layer, so the saved file becomes searchable in every PDF reader. - Correct existing text, one text object at a time, with undo/redo and saving. - Print with page ranges (`1-5, 8, 11-`), copies, scaling and two-sided printing. - Remember the reading position per file. **Explicitly out of scope:** - Comments, form filling and signing. - Text editing with reflow. PDF has no text flow: a paragraph is a number of objects at absolute positions. Don't pretend to be a word processor. - Selection across page boundaries (PDFium numbers characters per page). - Cloud services, accounts, telemetry. --- ## 2. Stack and architecture **Language: Rust.** No GC, no runtime start-up, zero-cost FFI to C libraries. Start-up is measured in tens of milliseconds. Ruled out: Electron/Tauri (a web view costs hundreds of ms at start), C++/Qt (heavier build, licensing questions), .NET (weaker cross-platform GUI). **PDF engine: PDFium**, prebuilt from `bblanchon/pdfium-binaries` (pick the variant without V8 and XFA), loaded at runtime with `libloading`. The same engine as Chrome – the most battle-tested code against broken PDFs there is. BSD-3 licence. It also covers editing (page objects, `FPDFText_SetText`, `FPDFPage_GenerateContent`, saving). **OCR: Tesseract 5.5** with the `swe` and `eng` language data, also loaded at runtime. The program must work without the OCR libraries – the menu item is then greyed out. **Interface: egui via eframe, rendered with wgpu.** Custom-drawn and identical on every platform, GPU-accelerated. Pages are drawn as textures, so turning a page costs almost no CPU. Repaint only when something happens: 0 % CPU when idle. **Structure:** a Cargo workspace with two crates. `core` is entirely UI-free (engine, layout, sessions, text, search, print logic, OCR) so it can be tested and measured without a window. `app` is the window and the input. **Replaceable:** egui for another GUI, Tesseract for another OCR engine (but measure first, see the pitfalls). Put the engine behind a trait so that e.g. MuPDF can be tried. **Not replaceable without rethinking:** that all PDFium use happens on one thread. **Dependencies:** keep them few. No async runtime (tokio) – plain threads and channels (`crossbeam-channel`) are enough and cost nothing at start. Release profile: `lto = "fat"`, `codegen-units = 1`, `panic = "abort"`, `strip = true`. --- ## 3. Decisions that turned out to be decisive **3.1 A single render thread owns PDFium.** PDFium has global state and is not thread-safe. More threads give no parallelism, and a mistake gives SIGABRT, not an error message. All PDFium use – rendering, text, search, printing, writing the OCR layer, saving – therefore happens on *one* thread that owns one engine per open document. The UI thread sends commands and receives events over channels. **3.2 The work loop is a priority ladder.** On each turn the render thread takes *one* unit of work from the highest-priority rung that has something to do, and reads the command queue between turns. Roughly: visible pages → text for visible pages → document search → measuring page sizes → table of contents → folder search. This mechanism is what makes Cancel possible without any thread synchronisation of its own, and what keeps a slow folder search unnoticeable while scrolling. New jobs are added as a rung on the ladder, never as a new thread. **3.3 Rendering must be cancellable in the middle of a page.** Use `FPDF_RenderPageBitmap_Start` / `FPDF_RenderPage_Continue` with an `IFSDK_PAUSE` callback. A heavy vector page (CAD, a map) can take seconds; without this it blocks the thread long after the user has moved on. The UI resends its whole wish list when the view changes, the service replaces the old one, and every job has a sequence number so a late cancellation never hits the next page. **3.4 Write your own FFI bindings.** Ready-made Rust bindings (`pdfium-render`) hide the `FPDF_PAGE` and `FPDF_BITMAP` handles, which makes both cancellable and copy-free rendering impossible. Declare the functions you need yourself. **Read the signatures from the header files** of exactly the library version you use – a wrong signature gives silent memory corruption, not a compile error. Never change library version without re-reading them. **3.5 Open the window first, do everything else in parallel.** Start-up is dominated by window and GPU initialisation, not PDF work (the engine is ready after ~30 ms). Never compute all page sizes at start: assume every page is the size of page 1 and correct the layout incrementally in the background. Use `FPDF_GetPageSizeByIndexF`, which doesn't load the page. **3.6 Virtual layout.** Page heights in a prefix sum give O(log n) mapping between scroll position and page regardless of document size. Keep a scroll anchor so the page under the reader stays put when an estimated size is replaced by the real one. **3.7 Copy-free rendering and a texture cache in the UI layer.** Let PDFium write straight into a buffer that is then uploaded to the GPU. Ask for `FPDF_REVERSE_BYTE_ORDER` so you don't need to convert BGRA→RGBA. Cache GPU textures (not pixel buffers) with a memory budget, keyed on (document, page, zoom step, rotation); quantise zoom in steps so small adjustments reuse textures. Cache ~8 open page handles – `FPDF_LoadPage` costs as much as rendering a text page. **3.8 Tiles at high zoom.** Above ~4 megapixels (≈300 % for A4) split the page into 1024×1024 tiles and render only the visible ones. Without this an A4 page at 800 % is 128 MB and 40–51 ms for a single page. **3.9 Text is extracted once per page, into plain data.** A list of characters and a box per character. Selection, copying, hit highlighting and the text cursor then become plain local arithmetic on the UI thread, with no thread hop per mouse move. **3.10 One shared coordinate system for text: the displayed page.** PDFium reports the page size *after* the page's own `/Rotate`, but places characters in *unrotated* user coordinates with the box's (CropBox/MediaBox) corner as the origin. Convert every character box, search hit and object bound to the displayed page's system when extracting (read `FPDFPage_GetRotation` and `FPDF_GetPageBoundingBox`), and convert the other way when writing text in (the OCR layer). The view's own rotation goes on top of that. **3.11 OCR writes an invisible text layer.** Render the page at 200 dpi, recognise, write one text object per word with render mode 3 (invisible) and a matrix that covers the word's box. The saved file becomes searchable everywhere. The job is modal (the whole document in one go, with progress and Cancel), which lets it be a rung in the work loop instead of a thread of its own with a cache. Never run OCR on pages that already have text. **3.12 One instance per user.** The first instance listens on a local socket (the name includes the user name); later starts send their paths there and exit. Measure it: the hand-off should take a few milliseconds. **3.13 Printing is vectors, not screenshots.** On macOS/Linux the original file is sent untouched to CUPS (`lp`). On Windows PDFium draws straight onto the printer's device context with `FPDF_RenderPage`. All selection logic (page ranges, current page, the document's own print preferences in `/ViewerPreferences`) lives in shared, tested code; the platform layer gets a finished job. **3.14 Saving never overwrites the original directly.** Write to a temp file and swap it in. Over the original: close the document, swap the file, open it again. --- ## 4. Pitfalls – do this, not that - **Never open a PDFium instance of your own outside the render thread**, not even "just for printing". It caused SIGABRT in Windows printing. And the test framework runs tests in parallel: every test that touches PDFium must take a shared mutex. - **Don't rely on ready-made bindings for cancellable rendering.** `pdfium-render` couldn't cancel a heavy page (the thread was blocked for 5.3 s). Our own bindings cancel in ~40 ms. - **Measure FFI overhead, don't assume it.** The first version of our own bindings was slower than the crate (3.6 ms/page) – only 1.45 ms was rendering. The copy and re-loading the page were the rest. Measure in phases before optimising. - **Don't forget the page's own rotation.** Without the conversion in 3.10, selection ends up a quarter turn off on every landscape page that is really a portrait page with `/Rotate 90` – very common. Measured: only 59 % of the character boxes lay over text before the fix, over 95 % after. - **Rotate landscape pages when printing.** Placed unrotated on portrait paper, a landscape page shrinks to barely half the sheet. Turn it 90° counter-clockwise (the same direction as Windows' own landscape orientation) when page and paper orientation differ, in both "fit" and "actual size". Keep the placement maths in platform-independent code so it can be tested. - **A minimised window runs no UI code in eframe.** egui treats it as invisible and skips the whole UI pass, so `ViewportCommand::Minimized(false)` sent from there never arrives. Restore the window directly through the operating system (Windows: `ShowWindowAsync(hwnd, SW_RESTORE)` if `IsIconic`) from the thread that receives the handed-off file; then give focus from the UI. - **Choose the OCR engine by measuring, not by feel.** A pure-Rust engine (ocrs) got 8.7 % of the characters wrong on Swedish text against 0.00 % for Tesseract – its model has no å, ä or ö at all. Keep a reference text next to every test scan. - **Render at 200 dpi for OCR.** 120 dpi gave 1.8 % character errors, 100 dpi 22 %. 200 dpi keeps an A4 page under 4 megapixels, so the page isn't split into tiles. - **Read the text back after every edit.** PDFium silently replaces characters missing from the font subset (measured: `ẞ` became `ÿ`). Compare with what was requested and tell the user – otherwise it's data loss nobody sees. - **Build Tesseract yourself if you link the C runtime statically.** Ready-made packages pull in libcurl, libarchive and six image codecs. With the optional dependencies turned off, the chain goes from eleven libraries to two. Patch upstream portability bugs in the build script and make the script abort if the pattern isn't found, so a version bump stops the build instead of quietly building something else. - **macOS: double-clicking in Finder arrives as an Apple Event**, not as an argument, and eframe/winit don't expose it. Plan for it, or plan your own `NSApplicationDelegate`. - **Don't let tests skip silently** when a library is missing: abort with an explanatory message and have an explicit environment variable for skipping. "20 passed" in zero seconds looks like a green build. --- ## 5. Requirements and measures Benchmarks from Pdfer (Linux/WSL with software rendering – the engine numbers are representative, the window numbers must be re-measured on real hardware): - *Targets, not measured on real hardware:* window < 80 ms; first page visible < 150 ms warm, < 300 ms cold. (Measured in WSL: first frame after 77–250 ms.) - Open a 500-page document: 1.8–3.5 ms. Opening time must not depend on the page count. - Render an A4 page at 108 dpi: 1.4–3.2 ms (p95 3.8 ms). One thread is enough with a good margin (300–700 pages/s). - Cancel a heavy page in progress: ~40 ms. - Page size for a 1-page document: 0.3 ms; all 500 page sizes: ~150 ms (done in the background, never at start). - Hand-off between instances: 2–4 ms. - 0 % CPU when idle. - Memory must level off when zooming 100–800 % (tiles + budget). - OCR on a normal 300 dpi office scan: 0.00 % character errors; about 0.8 s per page. - Binary ~11 MB; installer with PDF engine and OCR ~16 MB. - Windows: statically linked C runtime, no VC++ redistributable needed. --- ## 6. How it's verified - **A test corpus, generated by a dependency-free script and checked in:** 1 page, 500 pages, mixed page sizes (breaks the assumption that every page is like page 1), pages with `/Rotate` 0/90/180/270 and a CropBox that doesn't start at zero, plain colour fields (reveals swapped red/blue channels), a heavy vector page, a file with a broken xref, and scanned pages of varying quality with reference texts – including a file where some pages already have text. - **Unit tests** for layout, page-range parsing, coordinate conversion (every rotation, round trip both ways), print placement, word/object selection. - **Integration tests against the real engine** for what unit tests can't see: that the selection boxes lie over dark pixels in the rendered page (the only thing that proves the selection lands where the text is visible), that a tile at high zoom matches the corresponding part of the full page pixel for pixel, that a heavy page can be cancelled, that an OCR layer survives saving and becomes searchable. - **OCR quality is measured** as character errors against the reference, not judged by eye. - **UI changes are reviewed with a screenshot.** Build in developer aids: environment variables for window size, a start state (open menu, search, zoom) and "save a screenshot and quit", so the agent can review the interface without anyone at the screen. - **Verification chain before anything is done:** clippy with no warnings (also for the Windows target), all tests in release mode, `cargo check` for every target platform. - **Done means tried out.** Anything that needs Windows, a Mac or a printer isn't done until a person has run it. --- ## 7. Way of working - **Plan first.** Start with a plan: technology choices with reasons, architecture, milestones (skeleton and measurement → viewing → reading features → search → printing → packaging → editing). Measure in the first milestone before the design is locked. - **Ask about real decisions, not things you can settle yourself.** When a premise doesn't sit right – an engine missing the characters the language needs, a simplification that removes half the architecture – say so before building anything. - **Issues on a board.** Bugs and requests go in as cards. The agent reads the board at the start of a session, comments its interpretation on unclear cards, builds, and writes what was *measured* on the card. A card is closed only once it's verified. - **Try it out in a real environment.** The development environment (e.g. Linux/WSL) can't show everything: minimised windows, printers, Windows foreground rules. Build an installable package for each round and let a person try it. - **Comments and documentation explain why**, with the measured numbers, so the next person doesn't repeat the same mistakes. --- ## 8. The prompt ``` Build a fast desktop PDF reader according to the attached IDEA.md. Platforms: [Windows and macOS]. Development environment: [e.g. Linux/WSL cross-compiling to Windows with cargo-xwin; macOS is built on a Mac]. Interface language: [English]. Comments and documentation: [English]. Version control: [git/SVN]; don't commit for me. Start by reading IDEA.md in full. Then write a plan (docs/PLAN.md) with technology choices, architecture and milestones, and check it with me before you build. The first milestone is a skeleton and a windowless measuring tool: measure library loading, opening a 500-page document and rendering an A4 page before anything else is built. Rules that apply all the way: - All PDFium use happens on a single render thread. No exceptions. - FFI signatures are read from the header files of exactly the library version in use. - Every feature is verified with tests against the real engine, and every interface change with a screenshot. - Numbers in documentation and comments must be measured. - Ask me about real decisions. Anything that needs hardware or an operating system other than yours, mark as unproven and build a package I can try out. [Add or remove features here, e.g. "OCR isn't needed" or "add page operations: rotate, delete, move, merge".] ```