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
10 changes: 10 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ adb reverse tcp:8090 tcp:8090 # Android only
cd example && bunx expo run:ios # or run:android
```

`betterpdfexample://reopen?count=150` opens a document 150 times in a row and
closes each viewer right after it loads. Add `&source=file` or `&source=remote`
for a downloaded copy or a remote document instead of the bundled sample. Read
the result on screen: `Reopened 150 / 150`, or `Stalled: open N never loaded`.
On iOS 26 PDFKit can block a thread for good when page analyses in different
viewers overlap, as they do here, and loads must go on past the process's
constrained thread limit (`sysctl kern.wq_max_constrained_threads`, 64 or more
depending on the Mac). It is not a Maestro flow: once those threads are
blocked, Maestro's hierarchy snapshots slow down enough to time out.

## End-to-end tests (Maestro)

Flows live in `example/e2e/` and run on both platforms:
Expand Down
44 changes: 44 additions & 0 deletions example/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { BenchmarkScreen, type BenchRequest } from './screens/BenchmarkScreen';
import { DocumentsScreen } from './screens/DocumentsScreen';
import { EmbeddedScreen } from './screens/EmbeddedScreen';
import { OfflineScreen } from './screens/OfflineScreen';
import { ReopenScreen, type ReopenSource } from './screens/ReopenScreen';
import {
SHOWCASE_FEATURES,
ShowcaseScreen,
Expand Down Expand Up @@ -60,16 +61,44 @@ function parseShowcaseLink(url: string | null): ShowcaseFeature | null {
return SHOWCASE_FEATURES.find((name) => name === feature) ?? null;
}

/**
* `betterpdfexample://reopen?count=150[&source=bundled|file|remote]` opens a
* document `count` times in a row.
*/
function parseReopenLink(
url: string | null,
): { count: number; source: ReopenSource; key: number } | null {
const match = url == null ? null : /^[a-z]+:\/\/reopen\?(.*)$/.exec(url);
if (match == null) return null;
const params = new URLSearchParams(match[1]);
const count = Number(params.get('count') ?? 150);
const source = params.get('source') ?? 'bundled';
if (!Number.isSafeInteger(count) || count <= 0) return null;
if (source !== 'bundled' && source !== 'file' && source !== 'remote') {
return null;
}
return { count, source, key: Date.now() };
}

export default function App() {
const [tab, setTab] = useState<Tab>('viewer');
const [autoRun, setAutoRun] = useState<BenchRequest | null>(null);
const [showcase, setShowcase] = useState<{
feature: ShowcaseFeature;
key: number;
} | null>(null);
const [reopen, setReopen] =
useState<ReturnType<typeof parseReopenLink>>(null);

useEffect(() => {
const handle = (url: string | null) => {
const reopenRequest = parseReopenLink(url);
if (reopenRequest != null) {
setShowcase(null);
setReopen(reopenRequest);
return;
}
setReopen(null);
const feature = parseShowcaseLink(url);
if (feature != null) {
setShowcase({ feature, key: Date.now() });
Expand All @@ -88,6 +117,21 @@ export default function App() {
return () => subscription.remove();
}, []);

if (reopen != null) {
return (
<SafeAreaProvider>
<SafeAreaView style={styles.fill} edges={['top', 'bottom']}>
<StatusBar style="dark" />
<ReopenScreen
key={reopen.key}
count={reopen.count}
source={reopen.source}
/>
</SafeAreaView>
</SafeAreaProvider>
);
}

if (showcase != null) {
return (
<SafeAreaProvider>
Expand Down
87 changes: 87 additions & 0 deletions example/screens/ReopenScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { PdfView, type PdfSource } from 'react-native-better-pdf';
import { ensureFixture, FIXTURE_SERVER } from '../documents';
import { colors } from '../ui';

export type ReopenSource = 'bundled' | 'file' | 'remote';

/** A load that takes longer than this counts as stalled. */
const STALL_MS = 10_000;

async function resolveSource(source: ReopenSource): Promise<PdfSource> {
switch (source) {
case 'bundled':
// Metro bundles PDF assets through require().
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('../assets/sample.pdf') as number;
case 'file':
return { uri: (await ensureFixture('small')).uri };
case 'remote':
return { uri: `${FIXTURE_SERVER}/small.pdf` };
}
}

/**
* Opens a document `count` times in a row, closing each viewer right after
* its load event, the way a list of documents is browsed quickly. The next
* viewer opens at once, so PDFKit's page analyses overlap, which on iOS 26
* can leave a thread blocked for good; the viewer must keep loading
* documents regardless.
*/
export function ReopenScreen({
count,
source,
}: {
count: number;
source: ReopenSource;
}) {
const [resolved, setResolved] = useState<PdfSource | null>(null);
const [opened, setOpened] = useState(0);
const [stalled, setStalled] = useState(false);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
resolveSource(source).then(setResolved, (e: Error) => setError(e.message));
}, [source]);

const isDone = opened >= count;
useEffect(() => {
if (resolved == null || isDone || error != null) return;
const timer = setTimeout(() => setStalled(true), STALL_MS);
return () => clearTimeout(timer);
}, [resolved, opened, isDone, error]);

let status = `Reopening ${opened} / ${count}`;
if (isDone) status = `Reopened ${count} / ${count}`;
else if (error != null) status = `Failed at ${opened + 1}: ${error}`;
else if (stalled) status = `Stalled: open ${opened + 1} never loaded`;

return (
<View style={styles.fill}>
<Text style={styles.status} testID="reopen-status">
{status}
</Text>
{resolved != null && !isDone && !stalled && error == null && (
<PdfView
key={opened}
source={resolved}
style={styles.pdf}
onLoad={() => setOpened((n) => n + 1)}
onError={(pdfError) => setError(pdfError.code)}
/>
)}
</View>
);
}

const styles = StyleSheet.create({
fill: { flex: 1, backgroundColor: colors.card },
status: {
padding: 16,
fontSize: 16,
color: colors.text,
fontVariant: ['tabular-nums'],
},
pdf: { flex: 1, backgroundColor: colors.canvas },
});
3 changes: 2 additions & 1 deletion package/ios/DocumentCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ final class DocumentCache {

let store: DocumentCacheStore
private let clock: () -> Int64
private let workQueue = DispatchQueue(label: "com.betterpdf.cache", qos: .userInitiated, attributes: .concurrent)
// Serial on purpose; see PdfDocumentLoader.workQueue.
private let workQueue = DispatchQueue(label: "com.betterpdf.cache", qos: .userInitiated)
private let lock = NSLock()
private var inFlight: [String: SharedDownload] = [:]

Expand Down
3 changes: 2 additions & 1 deletion package/ios/HybridBetterPdfCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ final class HybridBetterPdfCache: HybridBetterPdfCacheSpec {
}
}

private static let queue = DispatchQueue(label: "com.betterpdf.cache.api", qos: .userInitiated, attributes: .concurrent)
// Serial on purpose; see PdfDocumentLoader.workQueue.
private static let queue = DispatchQueue(label: "com.betterpdf.cache.api", qos: .userInitiated)

private func finish(_ requestId: Double) {
lock.withLock {
Expand Down
10 changes: 9 additions & 1 deletion package/ios/PdfDocumentLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,15 @@ import PDFKit
/// reads of the same file (outline, page sizes, page images) keep finding it
/// when the copy is replaced or removed while displayed.
final class PdfDocumentLoader {
private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated, attributes: .concurrent)
// Serial, like every queue here: GCD runs a serial queue on its overcommit
// threads. A concurrent queue shares the process's constrained threads
// (`kern.wq_max_constrained_threads`, 64 or more depending on the machine),
// and iOS 26 PDFKit can block one of them for good whenever page analyses
// in different PDFViews overlap (PDFPageAnalyzerV2 → Vision). Once all are
// blocked, no work on a concurrent queue ever starts again, so no document
// would load. Overcommit threads run out too (`kern.wq_max_threads`), much
// later: this delays the stall, it does not remove it.
private static let workQueue = DispatchQueue(label: "com.betterpdf.load", qos: .userInitiated)

/// Loads the document. `progress` (remote downloads only, throttled) and
/// `completion` are called on the main queue, unless cancelled; the final
Expand Down
Loading