Skip to content

Commit

Permalink
Make plotting example work in R CMD check
Browse files Browse the repository at this point in the history
And provide more informative error if display list is not enabled.
  • Loading branch information
hadley committed Sep 24, 2024
1 parent 9aa7dbd commit a3844d7
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions R/content.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#' content_image_file(system.file("httr2.png", package = "elmer"))
#' )
#'
#' \dontshow{dev.control('enable')}
#' plot(waiting ~ eruptions, data = faithful)
#' chat <- new_chat_openai(echo = TRUE)
#' chat$chat(
Expand Down Expand Up @@ -120,6 +121,14 @@ content_image_file <- function(path, content_type = "auto", resize = "low") {
#' @param width,height Width and height in pixels.
content_image_plot <- function(width = 768, height = 768) {
plot <- grDevices::recordPlot()

if (is.null(plot[[1]])) {
cli::cli_abort(c(
"Can't record plot because display list is inhibited.",
i = "Turn it on with {.code dev.control('enable')}."
))
}

old <- grDevices::dev.cur()

path <- tempfile("elmer-plot-", fileext = ".png")
Expand Down
1 change: 1 addition & 0 deletions man/content_image_url.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions tests/testthat/_snaps/content.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,12 @@
Error:
! Invalid geometry string: blah

# useful errors if no display

Code
content_image_plot()
Condition
Error in `content_image_plot()`:
! Can't record plot because display list is inhibited.
i Turn it on with `dev.control('enable')`.

6 changes: 6 additions & 0 deletions tests/testthat/test-content.R
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,9 @@ test_that("image resizing", {
expect_no_error(content_image_file(img_file, resize = "100x100"))
expect_no_error(content_image_file(img_file, resize = "100x100>!"))
})

test_that("useful errors if no display", {
# file based devices have display list inhibited
withr::local_pdf(NULL)
expect_snapshot(content_image_plot(), error = TRUE)
})

0 comments on commit a3844d7

Please sign in to comment.