Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.github.barteksc.pdfviewer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

// Lives in AndroidPdfViewer's package to reach PDFView.renderingHandler, which is package-private.
public final class RenderingDrain {
private static final long TIMEOUT_MS = 1000;

private RenderingDrain() {}

// Stops the renderer and waits for the page it is drawing, so PDFView.recycle() can't close the document mid-render.
public static void drain(PDFView view) {
RenderingHandler renderingHandler = view.renderingHandler;
if (renderingHandler == null) {
return;
}
renderingHandler.stop();
renderingHandler.removeMessages(RenderingHandler.MSG_RENDER_TASK);
CountDownLatch idle = new CountDownLatch(1);
if (!renderingHandler.postAtFrontOfQueue(idle::countDown)) {
return;
}
try {
idle.await(TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
10 changes: 10 additions & 0 deletions android/src/main/java/org/wonday/pdf/PdfView.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIManagerHelper;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.RenderingDrain;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
Expand Down Expand Up @@ -329,6 +330,15 @@ protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}

// The base recycle() closes the document on the UI thread while the "PDF renderer"
// thread may still be drawing a page from it, which crashes the app. Every recycle
// (reload, detach, load error) goes through here, so wait for that page first.
@Override
public void recycle() {
RenderingDrain.drain(this);
super.recycle();
}

private int getPdfPageCount(File pdfFile) throws IOException {
ParcelFileDescriptor fileDescriptor =
ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
Expand Down