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
20 changes: 20 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,26 @@
An annotation handle collected after both its page and its document
had been closed used to leak PDFium's annotation context, together
with the page-objects of its appearance stream (ADR-024).
* `pdf_doc_close()`, and the finalizer of a collected document, now also
close the document's pages, including the pages of `pdf_form_fields()`.
Page and page-object calls on them raise an error ("Page has been
closed: its document was closed.") instead of reading freed memory.
Rendering or extracting text from a page whose document had been
closed read, and for text also wrote, the freed document; the results
looked right, so nothing noticed. A page collected after its document
had been closed also closed itself after the document, the reverse of
the order PDFium expects (ADR-025).
* `pdf_doc_close()` also closes the document's font and XObject handles.
`pdf_obj_form_from_xobject()` with an XObject whose document had been
closed built the form object from the freed document; it now raises an
error.
* `pdf_text_new()` and `pdf_obj_form_from_xobject()` refuse a font or
XObject that belongs to a document other than the page's. With a font
from `pdf_font_load()` or an XObject, the new object pointed into the
other document: `pdf_save()` wrote it out wrongly, and once the other
document was closed, reading the page read freed memory.
* The form object from `pdf_obj_form_from_xobject()` stays usable after
`pdf_xobject_close()`, as documented; it used to raise an error.
* `pdf_page_insert_clip_path()` no longer closes `clip_path`. PDFium
never takes ownership of an inserted clip path, so the path was never
freed. The handle now stays open, can be inserted into other pages,
Expand Down
12 changes: 6 additions & 6 deletions R/RcppExports.R
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,8 @@ cpp_xobject_close <- function(xo_ptr) {
invisible(.Call(`_pdfium_cpp_xobject_close`, xo_ptr))
}

cpp_form_obj_from_xobject <- function(xo_ptr) {
.Call(`_pdfium_cpp_form_obj_from_xobject`, xo_ptr)
}

cpp_page_insert_object <- function(page_ptr, obj_ptr) {
invisible(.Call(`_pdfium_cpp_page_insert_object`, page_ptr, obj_ptr))
cpp_form_obj_from_xobject <- function(xo_ptr, page_ptr) {
.Call(`_pdfium_cpp_form_obj_from_xobject`, xo_ptr, page_ptr)
}

cpp_form_obj_remove_child <- function(form_obj_ptr, child_ptr) {
Expand Down Expand Up @@ -613,6 +609,10 @@ cpp_text_char_font_info <- function(page_ptr) {
.Call(`_pdfium_cpp_text_char_font_info`, page_ptr)
}

cpp_doc_handle_counts <- function(doc_ptr) {
.Call(`_pdfium_cpp_doc_handle_counts`, doc_ptr)
}

cpp_image_new_from_jpeg <- function(doc_ptr, page_ptr, jpeg_bytes) {
.Call(`_pdfium_cpp_image_new_from_jpeg`, doc_ptr, page_ptr, jpeg_bytes)
}
Expand Down
33 changes: 18 additions & 15 deletions R/api_completion.R
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pdf_bookmark_child_count <- function(bookmark) {
pdf_page_has_transparency <- function(page) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
cpp_page_has_transparency(page$ptr)
}
Expand All @@ -123,7 +123,7 @@ pdf_page_has_transparency <- function(page) {
pdf_page_bounding_box <- function(page) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
cpp_page_bounding_box(page$ptr)
}
Expand Down Expand Up @@ -206,7 +206,7 @@ pdf_device_to_page <- function(page, start_x, start_y, size_x, size_y,
rotate, device_x, device_y) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
checkmate::assert_int(start_x)
checkmate::assert_int(start_y)
Expand Down Expand Up @@ -237,7 +237,7 @@ pdf_page_to_device <- function(page, start_x, start_y, size_x, size_y,
rotate, page_x, page_y) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
checkmate::assert_int(start_x)
checkmate::assert_int(start_y)
Expand Down Expand Up @@ -276,7 +276,7 @@ pdf_page_to_device <- function(page, start_x, start_y, size_x, size_y,
pdf_text_rects <- function(page, start_char = 1L, char_count = -1L) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
checkmate::assert_int(start_char, lower = 1L)
checkmate::assert_int(char_count)
Expand Down Expand Up @@ -310,7 +310,7 @@ pdf_text_rects <- function(page, start_char = 1L, char_count = -1L) {
pdf_text_bounded <- function(page, bounds) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
checkmate::assert_numeric(bounds, len = 4L, any.missing = FALSE,
finite = TRUE)
Expand Down Expand Up @@ -345,7 +345,7 @@ pdf_text_bounded <- function(page, bounds) {
pdf_text_char_geometry <- function(page) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
raw <- cpp_text_char_geometry(page$ptr)
mat <- raw$matrix
Expand Down Expand Up @@ -1100,7 +1100,8 @@ print.pdfium_xobject <- function(x, ...) {
#' @param dest_doc A `pdfium_doc` opened with `readwrite = TRUE`.
#' @param src_doc Source `pdfium_doc`. Read-only is fine.
#' @param src_page_num One-based page index in `src_doc`.
#' @return A `pdfium_xobject` handle.
#' @return A `pdfium_xobject` handle. It belongs to `dest_doc`:
#' [pdf_doc_close()] on `dest_doc` closes it.
#' @seealso [pdf_obj_form_from_xobject()] to instantiate as a page
#' object; [pdf_xobject_close()] for deterministic release.
#' @export
Expand All @@ -1123,7 +1124,8 @@ pdf_xobject_from_page <- function(dest_doc, src_doc, src_page_num = 1L) {
#' Wraps `FPDF_CloseXObject`. Idempotent. Closing the XObject does
#' NOT invalidate page-objects created from it via
#' [pdf_obj_form_from_xobject()] — those are owned by their parent
#' page and survive the XObject's release.
#' page and survive the XObject's release. [pdf_doc_close()] on the
#' destination document closes its XObjects as well.
#'
#' @param xobject A `pdfium_xobject` from [pdf_xobject_from_page()].
#' @return Invisibly returns `xobject`.
Expand All @@ -1146,7 +1148,7 @@ pdf_xobject_close <- function(xobject) {
#' [pdf_page_load()] (parent doc must be readwrite).
#' @param xobject A `pdfium_xobject` from [pdf_xobject_from_page()].
#' The XObject must have been created against the same `dest_doc`
#' that owns `page`.
#' that owns `page`; one from another document is an error.
#' @return The new `pdfium_obj` (type `"form"`).
#' @seealso [pdf_xobject_from_page()].
#' @export
Expand All @@ -1157,11 +1159,12 @@ pdf_obj_form_from_xobject <- function(page, xobject) {
}
ph <- as_page_and_doc(page)
assert_readwrite(ph$doc)
obj_ptr <- cpp_form_obj_from_xobject(xobject$ptr)
# cpp_form_obj_from_xobject returns a detached page-object. Insert
# via cpp_page_insert_object (already wrapped for the existing
# creators).
cpp_page_insert_object(ph$page$ptr, obj_ptr)
if (!identical(xobject$doc$ptr, ph$doc$ptr)) {
stop("`xobject` and `page` must belong to the same document.",
call. = FALSE
)
}
obj_ptr <- cpp_form_obj_from_xobject(xobject$ptr, ph$page$ptr)
idx <- cpp_page_object_count(ph$page$ptr)
mark_page_dirty(ph$doc, ph$page$index)
new_pdfium_obj(obj_ptr, ph$page, idx, "form")
Expand Down
10 changes: 6 additions & 4 deletions R/document.R
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,12 @@ validate_pdf_open_path <- function(path) {
#' explicit close is recommended when handling many large documents or when a
#' subsequent operation needs to delete the source file (relevant on Windows).
#'
#' Annotation handles still open on the document, including the form-field
#' handles of [pdf_form_fields()], are closed first, because PDFium releases
#' an annotation's resources only while its document is open. Afterwards they
#' print as closed, and `pdf_annot_*()` calls on them raise an error.
#' Handles still open on the document are closed first, because PDFium
#' expects them to be closed before their document: annotation handles,
#' including the form-field handles of [pdf_form_fields()], then pages, then
#' fonts and XObjects. Afterwards they print as closed, and calls on them, or
#' on page-objects read from the closed pages, raise an error. Close a
#' document when you are done with everything read from it.
#'
#' @param doc A `pdfium_doc` produced by [pdf_doc_open()].
#' @return Invisibly returns `doc` with its underlying pointer marked closed.
Expand Down
9 changes: 6 additions & 3 deletions R/fonts.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
#
# Lifetime: the C-side externalptr carries a finalizer that calls
# FPDFFont_Close. The `prot` slot pins the parent doc so the doc can't
# be GC'd before the font. Calling pdf_font_close() is idempotent.
# be GC'd before the font, and closing the doc closes the font first
# (ADR-025). Calling pdf_font_close() is idempotent.
#
# To draw with a custom font, pass the `pdfium_font` handle as the
# `font` argument of pdf_text_new(); R-side dispatch picks the
Expand Down Expand Up @@ -49,7 +50,7 @@
#' @param name Character scalar — one of the 14 standard font names
#' listed in the **Standard fonts** section below.
#' @return A `pdfium_font` handle. Pass it as the `font` argument
#' of [pdf_text_new()].
#' of [pdf_text_new()] for a page of `doc`.
#'
#' @section Standard fonts:
#' `"Helvetica"`, `"Helvetica-Bold"`, `"Helvetica-Oblique"`,
Expand Down Expand Up @@ -95,7 +96,7 @@ pdf_font_load_standard <- function(doc, name) {
#' disk but limited to the standard PDF encodings. When in doubt,
#' leave this as `TRUE`.
#' @return A `pdfium_font` handle. Pass it as the `font` argument
#' of [pdf_text_new()].
#' of [pdf_text_new()] for a page of `doc`.
#'
#' @seealso [pdf_font_load_standard()], [pdf_text_new()],
#' [pdf_font_close()].
Expand Down Expand Up @@ -137,6 +138,8 @@ pdf_font_load <- function(doc, font_data,
#' used it — PDFium keeps an internal reference. Only the embedder's
#' R-side handle is released.
#'
#' [pdf_doc_close()] closes the document's fonts as well.
#'
#' @param font A `pdfium_font` from [pdf_font_load_standard()] or
#' [pdf_font_load()].
#' @return Invisibly returns `font`.
Expand Down
13 changes: 9 additions & 4 deletions R/obj_creators.R
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ pdf_rect_new <- function(page, x, y, width, height) {
#' @param font Either a character scalar — one of the 14 PDF
#' standard font names (see [pdf_font_load_standard()] for the
#' list) — or a `pdfium_font` handle from
#' [pdf_font_load_standard()] or [pdf_font_load()]. Default
#' `"Helvetica"`. Pass a `pdfium_font` handle when you need a
#' custom TrueType / Type1 font; the standard-font shortcut is
#' purely for convenience.
#' [pdf_font_load_standard()] or [pdf_font_load()], loaded into
#' the document `page` belongs to. Default `"Helvetica"`. Pass a
#' `pdfium_font` handle when you need a custom TrueType / Type1
#' font; the standard-font shortcut is purely for convenience.
#' @param font_size Numeric scalar — font size in points. Default
#' `12`.
#' @param x,y Numeric scalars — baseline position in PDF user-space
Expand All @@ -117,6 +117,11 @@ pdf_text_new <- function(page, text,
if (!is_open(font)) {
stop("Font handle has been closed.", call. = FALSE)
}
if (!identical(font$doc$ptr, ph$doc$ptr)) {
stop("`font` and `page` must belong to the same document.",
call. = FALSE
)
}
ptr <- cpp_text_new_with_font(
ph$doc$ptr, ph$page$ptr, font$ptr,
as.numeric(font_size),
Expand Down
35 changes: 23 additions & 12 deletions R/obj_extras.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,7 @@
check_pdfium_obj <- function(obj, allowed_types = NULL, arg = "obj") {
checkmate::assert_class(obj, "pdfium_obj", .var.name = arg)
if (!is_open(obj)) {
# Trips when the parent page is closed (most common) or when a
# mutator cleared the handle: pdf_obj_delete() and
# pdf_form_obj_remove_object() destroy the object, and
# pdf_annot_append_object() hands it to an annotation. The message
# leads with the page-closed framing for back-compatibility with
# existing tests; the parenthetical covers the cleared handles.
stop("Parent page has been closed; object handle is no longer ",
"valid (or the object was deleted via pdf_obj_delete() or ",
"pdf_form_obj_remove_object(), or moved into an annotation ",
"by pdf_annot_append_object()).",
call. = FALSE
)
stop(obj_closed_message(obj), call. = FALSE)
}
if (!is.null(allowed_types)) {
checkmate::assert_choice(
Expand All @@ -33,6 +22,28 @@ check_pdfium_obj <- function(obj, allowed_types = NULL, arg = "obj") {
invisible(obj)
}

# Internal: the error message for a closed `pdfium_obj`. The handle
# reads as closed when its page is closed, which closing the document
# also does (ADR-025), or when a mutator cleared it: pdf_obj_delete()
# and pdf_form_obj_remove_object() destroy the object, and
# pdf_annot_append_object() hands it to an annotation. The page-closed
# framing leads for back-compatibility with existing tests; the
# parenthetical covers the cleared handles.
obj_closed_message <- function(obj) {
if (!is_open(obj$page$doc)) {
return(paste0(
"Parent page has been closed: its document was closed. ",
"The object handle is no longer valid."
))
}
paste0(
"Parent page has been closed; object handle is no longer ",
"valid (or the object was deleted via pdf_obj_delete() or ",
"pdf_form_obj_remove_object(), or moved into an annotation ",
"by pdf_annot_append_object())."
)
}

#' Stroke line-cap style of a path page-object
#'
#' Returns the PDF line-cap style applied to a path's stroke. Maps to
Expand Down
3 changes: 2 additions & 1 deletion R/objects.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
#' only as long as the parent `pdfium_page` is open. The handle's
#' internal parent reference keeps the page (and transitively the
#' document) alive for as long as you hold the object, but calling
#' [pdf_page_close()] explicitly invalidates all returned objects.
#' [pdf_page_close()] explicitly, or closing the document with
#' [pdf_doc_close()], invalidates all returned objects.
#'
#' @param page A `pdfium_page` from [pdf_page_load()], or a `pdfium_doc`
#' (in which case the first page is loaded and closed automatically).
Expand Down
12 changes: 7 additions & 5 deletions R/page.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
#' [pdf_page_close()] explicitly when you need deterministic release.
#' The page keeps the parent document alive for as long as the page
#' is reachable, so it is safe to drop your reference to `doc` while
#' still holding a page.
#' still holding a page. Closing `doc` with [pdf_doc_close()] closes the
#' page too: later calls on it raise an error.
#'
#' @param doc A `pdfium_doc` from [pdf_doc_open()].
#' @param page_num One-based page index. Must satisfy
Expand Down Expand Up @@ -44,7 +45,8 @@ pdf_page_load <- function(doc, page_num = 1L) {
#' Close a page handle
#'
#' Releases the underlying PDFium handle. Idempotent — calling
#' `pdf_page_close()` on an already-closed page is a no-op.
#' `pdf_page_close()` on an already-closed page, including one that
#' [pdf_doc_close()] closed with its document, is a no-op.
#'
#' @param page A `pdfium_page` from [pdf_page_load()].
#' @return Invisibly returns `page` with its underlying pointer marked closed.
Expand Down Expand Up @@ -102,7 +104,7 @@ pdf_page_close <- function(page) {
pdf_page_size <- function(page, page_num = 1L) {
checkmate::assert_multi_class(page, c("pdfium_page", "pdfium_doc"))
if (inherits(page, "pdfium_page")) {
if (!is_open(page)) stop("Page has been closed.", call. = FALSE)
if (!is_open(page)) stop(page_closed_message(page), call. = FALSE)
return(cpp_page_size(page$ptr))
}
# `page` is a pdfium_doc.
Expand Down Expand Up @@ -145,7 +147,7 @@ pdf_page_size <- function(page, page_num = 1L) {
pdf_page_rotation <- function(page, page_num = 1L) {
checkmate::assert_multi_class(page, c("pdfium_page", "pdfium_doc"))
if (inherits(page, "pdfium_page")) {
if (!is_open(page)) stop("Page has been closed.", call. = FALSE)
if (!is_open(page)) stop(page_closed_message(page), call. = FALSE)
return(cpp_page_rotation(page$ptr))
}
# `page` is a pdfium_doc.
Expand Down Expand Up @@ -258,7 +260,7 @@ pdf_pages_summary <- function(doc, password = NULL) {
#' page-loaded counts.
#' @export
summary.pdfium_page <- function(object, ...) {
if (!is_open(object)) stop("Page has been closed.", call. = FALSE)
if (!is_open(object)) stop(page_closed_message(object), call. = FALSE)
sz <- cpp_page_size(object$ptr)
labels <- tryCatch(pdf_page_labels(object$doc),
error = function(e) NULL)
Expand Down
2 changes: 1 addition & 1 deletion R/save.R
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ flush_page_if_dirty <- function(page) {
pdf_page_flush <- function(page) {
checkmate::assert_class(page, "pdfium_page")
if (!is_open(page)) {
stop("Page has been closed.", call. = FALSE)
stop(page_closed_message(page), call. = FALSE)
}
cpp_page_generate_content(page$ptr)
# If the page lives in a doc with mutation state, clear its
Expand Down
12 changes: 11 additions & 1 deletion R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ as_open_page <- function(page, page_num = 1L, .envir = parent.frame(),
defer_close = TRUE) {
checkmate::assert_multi_class(page, c("pdfium_page", "pdfium_doc"))
if (inherits(page, "pdfium_page")) {
if (!is_open(page)) stop("Page has been closed.", call. = FALSE)
if (!is_open(page)) stop(page_closed_message(page), call. = FALSE)
return(page)
}
# `page` is a pdfium_doc — load `page_num` and arrange for close.
Expand All @@ -65,6 +65,16 @@ as_open_page <- function(page, page_num = 1L, .envir = parent.frame(),
p
}

# Internal: the error message for a closed `pdfium_page`. Closing a
# document closes its pages too (ADR-025), so a caller who never closed
# the page is told why it is closed.
page_closed_message <- function(page) {
if (is_open(page$doc)) {
return("Page has been closed.")
}
"Page has been closed: its document was closed."
}

# Internal: vectorised lookup of a PDFium integer enum code to its
# short character name. `names` is the lookup table; `base` is the
# integer code corresponding to `names[1]` (0 for most PDFium enums,
Expand Down
7 changes: 6 additions & 1 deletion dev/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ Read [ADR-005](decisions/ADR-005-memory-model.md) first. Summary:
4. Children (pages, page objects) hold an R-level reference to their
parent (doc, page) through the `prot` slot of the child
externalptr. R's GC keeps the parent alive while a child exists.
5. PDFium's library lifecycle (`FPDF_InitLibraryWithConfig` /
5. Closing a document, explicitly or in its finalizer, first closes
the annotation, page, font and XObject handles still open on it:
each is registered under its document in `src/handle_registry.h`
(ADR-024, ADR-025). Mint and release these handles only through
that header's `make_*_handle()` / `release_*_handle()`.
6. PDFium's library lifecycle (`FPDF_InitLibraryWithConfig` /
`FPDF_DestroyLibrary`) runs in `.onLoad` / `.onUnload`.

The auto-close test in `tests/testthat/test-document.R` is
Expand Down
Loading
Loading