Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ package/
LruByteCache.kt pure: byte-budgeted LRU
BitmapPool.kt bitmap reuse + eager recycling
MemoryBudgets.kt pure: bitmap pool budget
PdfSourceResolver.kt source → seekable ParcelFileDescriptor (base64: write, open, delete)
PdfSourceResolver.kt source → seekable ParcelFileDescriptor (base64, streamed content://: write, open, delete)
NativeBase64Document.kt JNI entry: base64 text in a native buffer → decoded into a file
DocumentCache.kt fresh copy or shared download/revalidation, stale fallback
DocumentCacheStore.kt copies on disk: session/persistent dirs, metadata
Expand Down Expand Up @@ -129,7 +129,7 @@ the render thread, once per render (see "Cache strategy").
| `getFormFields` | main: the changed fields' values → `com.betterpdf.read` queue: separate `PDFDocument` filled in with them, every widget page read | main → the document's `BetterPdf-render` thread (form work in call order) |
| `setFormFieldValues`, the reader's form edits | main: PDFKit's widgets of the fields' pages only (field → pages index from the page dictionaries) | main → `BetterPdf-render` thread (form work in call order); results on main |
| Remote download (`DocumentCache`) | lookup on `com.betterpdf.cache`; transfer and store on the `URLSession` delegate queue | lookup and transfer on `BetterPdf-download` threads (`HttpURLConnection`); the document worker waits |
| Download progress (throttle ≤ 10/s) | throttled on the delegate queue → main | throttled on the download thread → main |
| Download progress (throttle ≤ 10/s) | throttled on the delegate queue → main | throttled on the download thread → main (`content://` copies: the resolving thread) |
| `PdfCache` (`getEntry`, `remove`, `clear`, `getByteSize`) | `com.betterpdf.cache.api` queue, disk only | `Promise.parallel` thread, disk only |
| `PdfDocument.open` | as the view's open (`PdfDocumentLoader`), plain `PDFDocument` | `BetterPdf-document` thread: source, then a renderer to count pages (closed) |
| `PdfDocument` reads (in call order) | the document's `com.betterpdf.document` serial queue, its own `PDFDocument` | the document's `BetterPdf-document` thread (exits when idle), `DocumentReads` on duplicated FDs |
Expand Down
31 changes: 27 additions & 4 deletions docs/api-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,28 @@ type PdfSource =
an API that returns a PDF as base64 in JSON is better served by returning
the PDF and passing `uri` + `headers`: native download, progress,
caching, offline.
- **`content://` (Android, issue #69).** `PdfRenderer` needs a seekable
descriptor, and a provider may hand out a pipe
(`ContentProvider.openPipeHelper`, AOSP's MTP provider without partial
reads) or part of a larger file (an `AssetFileDescriptor` with an offset,
which `openFileDescriptor` refuses: "Not a whole file"). 1.1 failed them
with `invalid-source` and `file-not-found`. The source is opened with
`openAssetFileDescriptor`; a whole file that `lseek` accepts (the
renderer's own check; `S_ISREG` would refuse seekable descriptors that
are not regular files) is used as is, as FileProvider, MediaStore and the
Downloads provider hand out. Anything else is copied with the downloads'
64 KB loop into the directory base64 writes to, opened, and deleted at
once like base64's file. The copy reports progress like a download
(`totalBytes` from the asset's length or the provider's
`OpenableColumns.SIZE`) and takes disk space outside `PdfCache`'s
accounting. A source change or dispose cancels the open and the size
query (`CancellationSignal`), and the signal's listener closes the descriptor,
which ends a read blocked on a stalled pipe (checked on API 37: the
thread and the partial file are gone at once). A failed read (the
provider's `closeWithError`) or write (a full disk) is `invalid-pdf`,
"The PDF could not be copied to the app's cache", with the cause in
`nativeDescription`; Android's base64 write failures now say the same. react-native-pdf reads
the whole document into memory instead (`openInputStream`).

### Props

Expand All @@ -204,7 +226,7 @@ type PdfSource =
| `horizontal` | `boolean` | `false` | Pages side by side; see "Layout modes". |
| `enablePaging` | `boolean` | `false` | One page per swipe; see "Layout modes". |
| `onLoad` | `(e: PdfLoadEvent)` | — | `{ pageCount, firstPageWidth, firstPageHeight, filePath? }` (PDF points). |
| `onLoadProgress` | `(e: PdfLoadProgressEvent)` | — | `{ loadedBytes, totalBytes? }`; remote only; see "Load progress". |
| `onLoadProgress` | `(e: PdfLoadProgressEvent)` | — | `{ loadedBytes, totalBytes? }`; remote, and Android `content://` copies; see "Load progress". |
| `onPageChange` | `(e: PdfPageChangeEvent)` | — | `{ page, pageCount }`. The page under the viewport centre (the last page once scrolled to the end). |
| `onError` | `(e: PdfError)` | — | Load and render errors. |
| `onLinkPress` | `(e: PdfLinkPressEvent)` | — | `{ url }`. URL links only; see "Links and taps". |
Expand Down Expand Up @@ -416,9 +438,10 @@ onLoadProgress?: (event: { loadedBytes: number; totalBytes?: number }) => void;
download 1% steps still mean 100 events. The time contract bounds JS work
at ~10 events per second for any file size or network speed (unit tested:
400 MB in 2 s → 21 events).
- **Remote downloads only.** Local files open without a download phase;
stored copies that are used, or confirmed unchanged by the server, open
without progress events (see "Caching and offline").
- **Remote downloads, and Android `content://` copies** (see "Source").
Local files open without a download phase; stored copies that are used,
or confirmed unchanged by the server, open without progress events (see
"Caching and offline").
- The throttle runs natively on the download thread
(`ProgressThrottle` in Kotlin and Swift); JS never sees dropped updates.

Expand Down
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Every component, object and type is exported from the package root. The
| `searchHighlightColor` | `ColorValue` | `'rgba(255, 214, 0, 0.4)'` | background of search matches; use a translucent colour |
| `searchCurrentHighlightColor` | `ColorValue` | `'rgba(255, 140, 0, 0.6)'` | background of the current match |
| `onLoad` | `({ pageCount, firstPageWidth, firstPageHeight, filePath?, isStale, sources }) => void` | | first page's size in PDF points, as displayed (crop box, rotation applied); `filePath`: the local file being displayed (downloaded copy, local file or extracted asset; not for `{ base64 }`, `content://` or several sources); `isStale`: an outdated stored copy shown because the server could not be reached (see [Offline reading and caching](guides/offline-and-caching.md)); `sources`: each source's `{ pageCount, firstPage, filePath?, isStale }` |
| `onLoadProgress` | `({ loadedBytes, totalBytes? }) => void` | | remote downloads only (not when a stored copy is used); at most every 100 ms plus once on completion |
| `onLoadProgress` | `({ loadedBytes, totalBytes? }) => void` | | remote downloads (not when a stored copy is used) and, on Android, `content://` documents that are copied (see [Sources and loading](guides/sources-and-loading.md#content-uris-on-android)); at most every 100 ms plus once on completion |
| `onPageChange` | `({ page, pageCount }) => void` | | zero-based |
| `onError` | `(error: PdfLoadError \| PdfPageError) => void` | | without `error.page`: the load failed and nothing is shown; with `error.page` (Android only): a page could not be rendered after `onLoad`, and the document stays open; see [Errors](#errors) |
| `onLinkPress` | `({ url }) => void` | | tap on a URL link; the viewer never opens URLs itself |
Expand Down
16 changes: 16 additions & 0 deletions docs/guides/sources-and-loading.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@ Both platforms follow redirects the same way:
http to https on the same host is another origin too: when you send
credentials, use the https URL.

## `content://` URIs on Android

A `content://` URI (from the document picker, a share intent or another
app's provider) opens through the `ContentResolver`, with the read
permission your app was granted. Most providers (FileProvider, MediaStore,
the Downloads provider) hand out the file itself, which opens as it is.

A document the provider streams instead (through a pipe, for example when
it generates or decrypts the document as it is read), or hands out as part
of a larger file, is first copied into the app's cache. Nothing is shown
until the whole document has arrived, and the copy takes as much disk space
as the document until the document closes or the app ends.
`onLoadProgress` reports the copy, with `totalBytes` when the provider
states the size, and changing the source stops it. `onLoad`'s `filePath` is
`undefined` for every `content://` source.

## Base64 documents

A document you have as a base64 string — made with pdfmake or pdf-lib, or
Expand Down
2 changes: 1 addition & 1 deletion docs/performance/audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ through `BitmapPool`. iOS: PDFKit reuses its internal page views.
| `getStats` | JS → native | COLD (diagnostic) | on demand | 10 numbers |
| `onLoad`, `onError` | native → JS | COLD | per document | small struct |
| `onPageChange` | native → JS | WARM | per page boundary crossed | 2 numbers |
| `onLoadProgress` | native → JS | WARM | ≤ 10/s during a remote download, 0 otherwise | 2 numbers |
| `onLoadProgress` | native → JS | WARM | ≤ 10/s during a remote download or an Android `content://` copy, plus one when it completes; 0 otherwise | 2 numbers |
| `onLinkPress`, `onPageTap` | native → JS | COLD | per user tap | small struct |

HOT crossings: **none**. No scroll, zoom, visibility or render-lifecycle data
Expand Down
1 change: 1 addition & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
| A remote document fails with `http-error` 401 or 403 after a redirect | The server redirects to another origin (another host or port, or http to https), and `headers` are not sent there. Use the final URL, or one the target accepts without your headers, such as a signed URL. |
| A signed URL or rotating token downloads the document on every open | Set `cacheKey` on the source to identify the stored copy. |
| The document is a base64 string | Pass `source={{ base64 }}` (1.1+); for large documents write it to a file. See [Base64 documents](guides/sources-and-loading.md#base64-documents). |
| On Android, a `content://` document fails with `invalid-source` ("The PDF source is not seekable"), or with `file-not-found` and "Not a whole file" | The provider streams the document or hands out part of a file, which 1.1 and earlier cannot open. Later versions copy it first (see [`content://` URIs on Android](guides/sources-and-loading.md#content-uris-on-android)); on 1.1, copy it to a file and open that. |
| A base64 source fails with `invalid-source` | `error.message` says why: a `data:` URI prefix to remove, URL-safe base64 (`-`, `_`) to convert, or another character that is not base64. |
| Tapping a URL link does nothing | The viewer never opens URLs: open them in `onLinkPress`. |
| `onPageTap` arrives about 300 ms after the tap | It waits for a possible double tap; `enableDoubleTapZoom={false}` reports taps at once. |
Expand Down
71 changes: 71 additions & 0 deletions example/documents.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Directory, File, Paths } from 'expo-file-system';
import { Platform } from 'react-native';
import type {
PdfBase64Source,
PdfSource,
Expand Down Expand Up @@ -93,6 +94,75 @@ async function base64Fixture(name: FixtureName): Promise<PdfBase64Source> {
return { base64: await (await ensureFixture(name)).base64() };
}

/** How the example's Android provider hands a fixture out (modules/content-fixtures). */
type ContentKind =
'file' | 'pipe' | 'partial' | 'stalled' | 'broken' | 'slow-size';

/** A `content://` URI for a fixture, served by the example's own provider. */
export async function contentFixture(
kind: ContentKind,
name: FixtureName,
): Promise<PdfSource> {
await ensureFixture(name);
return {
uri: `content://software.gmi.betterpdf.example.fixtures/${kind}/${name}.pdf`,
};
}

const CONTENT_DOCUMENTS: DocumentEntry[] = [
{
id: 'content-file',
title: 'Content file',
subtitle: 'content:// of outline, a seekable file',
resolve: () => contentFixture('file', 'outline'),
},
{
id: 'content-pipe',
title: 'Content pipe',
subtitle: 'content:// of outline, streamed through a pipe',
resolve: () => contentFixture('pipe', 'outline'),
},
{
id: 'content-partial',
title: 'Content partial',
subtitle: 'content:// of outline, part of a larger file',
resolve: () => contentFixture('partial', 'outline'),
},
{
id: 'content-broken',
title: 'Content broken',
subtitle: 'A pipe whose provider fails halfway: expect invalid-pdf',
resolve: () => contentFixture('broken', 'outline'),
},
{
id: 'content-stalled',
title: 'Content stalled',
subtitle: 'A pipe of outline-large that stops; Swap: single-page',
resolve: () => contentFixture('stalled', 'outline-large'),
alternate: () => contentFixture('pipe', 'single-page'),
},
{
id: 'content-sources',
title: 'Content sources',
subtitle: 'links (pipe) + outline (partial) + mixed-sizes (file)',
resolve: async () => [
await contentFixture('pipe', 'links'),
await contentFixture('partial', 'outline'),
await contentFixture('file', 'mixed-sizes'),
],
},
{
id: 'content-failing-sources',
title: 'Content failing sources',
subtitle:
'outline (pipe, size query takes a minute) + outline-large (broken): expect invalid-pdf at once',
resolve: async () => [
await contentFixture('slow-size', 'outline'),
await contentFixture('broken', 'outline-large'),
],
},
];

export const DOCUMENTS: DocumentEntry[] = [
{
id: 'bundled',
Expand Down Expand Up @@ -340,4 +410,5 @@ export const DOCUMENTS: DocumentEntry[] = [
{ uri: `${FIXTURE_SERVER}/does-not-exist.pdf` },
],
},
...(Platform.OS === 'android' ? CONTENT_DOCUMENTS : []),
];
12 changes: 11 additions & 1 deletion example/e2e/pdf-document.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
# a wrong and with the right password; Android cannot read the metadata of
# encrypted documents), rotated and cropped pages (`page-boxes`, as in
# viewer-page-sizes), the outline fixture, the bundled asset and a file that
# is not a PDF. Screenshots show the cover and thumbnails.
# is not a PDF; on Android also a content:// pipe. Screenshots show the
# cover and thumbnails.
appId: software.gmi.betterpdf.example
---
- runFlow: _start.yaml
Expand Down Expand Up @@ -46,6 +47,15 @@ appId: software.gmi.betterpdf.example
- assertVisible: "sizes: 595x842 595x842"
- assertVisible: "cover: 300x425"

- runFlow:
when: { platform: Android }
commands:
- tapOn: "metadata \\(content pipe\\)"
- extendedWaitUntil: { visible: "opened in .* ms", timeout: 15000 }
- assertVisible: "pages 2, stale no, file no"
- assertVisible: "title: Raport kwartalny — żółć"
- assertVisible: "cover: 300x425"

- tapOn: "metadata-encrypted"
- extendedWaitUntil: { visible: "error: password-required", timeout: 15000 }
- tapOn: "Wrong password"
Expand Down
5 changes: 3 additions & 2 deletions example/e2e/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
# Prerequisites: app installed, Metro running (debug) and
# `node benchmarks/serve-fixtures.mjs` running (Android: adb reverse tcp:8090 tcp:8090).
# The default flows need Android's newer renderer (Android 15, or 12–14 with
# SDK extension 13); without it, pass android-legacy/* and viewer-links.
# SDK extension 13); without it, pass android-legacy/*, viewer-links and
# viewer-content.
set -uo pipefail
cd "$(dirname "$0")"
device="$1"; shift
flows=("$@")
if [ ${#flows[@]} -eq 0 ]; then
flows=(viewer-bundled viewer-scroll-zoom viewer-errors viewer-password viewer-layout-modes viewer-fit-policy viewer-single-page viewer-rtl viewer-outline viewer-scroll-enabled viewer-links viewer-double-tap viewer-scale-change viewer-initial viewer-text-selection viewer-accessibility viewer-search viewer-viewport viewer-page-sizes viewer-page-image viewer-offline viewer-short-document viewer-print viewer-spreads viewer-dark viewer-overlays viewer-forms viewer-inset viewer-inset-last-page viewer-base64 viewer-sources viewer-redirects pdf-document)
flows=(viewer-bundled viewer-scroll-zoom viewer-errors viewer-password viewer-layout-modes viewer-fit-policy viewer-single-page viewer-rtl viewer-outline viewer-scroll-enabled viewer-links viewer-double-tap viewer-scale-change viewer-initial viewer-text-selection viewer-accessibility viewer-search viewer-viewport viewer-page-sizes viewer-page-image viewer-offline viewer-short-document viewer-print viewer-spreads viewer-dark viewer-overlays viewer-forms viewer-inset viewer-inset-last-page viewer-base64 viewer-sources viewer-redirects viewer-content pdf-document)
fi
failed=0
is_android=0
Expand Down
51 changes: 51 additions & 0 deletions example/e2e/viewer-content.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# content:// sources (Android only), from the example's provider
# (modules/content-fixtures): a seekable file, a pipe and part of a larger
# file all open; a pipe the provider breaks fails with invalid-pdf; a
# stalled pipe reports progress, and Swap replaces it; a broken source
# fails a set at once, although another's size query has not returned.
appId: software.gmi.betterpdf.example
---
- runFlow:
when: { platform: Android }
commands:
- runFlow: _start.yaml
- tapOn: "Viewer"
- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content file" } }
- extendedWaitUntil: { visible: "1 / 12", timeout: 15000 }
- assertVisible: "file: none"
- tapOn: "‹ Back"

- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content pipe" } }
- extendedWaitUntil: { visible: "1 / 12", timeout: 15000 }
- assertVisible: "file: none"
- tapOn: "Image"
- extendedWaitUntil: { visible: "image p1: 300x.*", timeout: 10000 }
- tapOn: "‹ Back"

- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content partial" } }
- extendedWaitUntil: { visible: "1 / 12", timeout: 15000 }
- tapOn: "‹ Back"

- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content broken" } }
- extendedWaitUntil: { visible: "invalid-pdf", timeout: 15000 }
- assertVisible: "The PDF could not be copied to the app's cache"
- tapOn: "‹ Back"

# 64 KiB of 3.1 MB arrive, then nothing for a minute.
- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content stalled" } }
- extendedWaitUntil: { visible: "Downloading \\d+% \\(.* / 3\\.1 MB\\)", timeout: 15000 }
- tapOn: "Swap"
- extendedWaitUntil: { visible: "1 / 1", timeout: 15000 }
- assertVisible: "loads: 1"
- tapOn: "‹ Back"

- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content sources" } }
- extendedWaitUntil: { visible: "1 / 20", timeout: 15000 }
- assertVisible: "sources: p1\\+3 p4\\+12 p16\\+5"
- tapOn: "‹ Back"

# The broken source fails while the other waits a minute for its size.
- runFlow: { file: _open-list-entry.yaml, env: { ENTRY: "Content failing sources" } }
- extendedWaitUntil: { visible: "invalid-pdf", timeout: 15000 }
- assertVisible: "The PDF could not be copied to the app's cache"
- tapOn: "‹ Back"
15 changes: 15 additions & 0 deletions example/modules/content-fixtures/android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
plugins {
id 'com.android.library'
id 'expo-module-gradle-plugin'
}

group = 'software.gmi.betterpdf.example'
version = '0.0.1'

android {
namespace "software.gmi.betterpdf.example.content"
defaultConfig {
versionCode 1
versionName "0.0.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<provider
android:name="software.gmi.betterpdf.example.content.FixtureContentProvider"
android:authorities="${applicationId}.fixtures"
android:exported="false" />
</application>
</manifest>
Loading
Loading