Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: literal with_dev function #64

Open
DarwinAwardWinner opened this issue Dec 6, 2017 · 0 comments
Open

Suggestion: literal with_dev function #64

DarwinAwardWinner opened this issue Dec 6, 2017 · 0 comments
Labels
feature a feature request or enhancement

Comments

@DarwinAwardWinner
Copy link

Based on code I wrote a while ago to accomplish a similar thing, I'd like to suggest an actual with_dev function:

## Returns TRUE if x refers to the device number of a currently active
## graphics device.
library(rlang)
library(assertthat)
is_dev <- function(x) {
    is_scalar_integer(x) && x %in% dev.list()
}

with_dev <- function(dev, code, closedev) {
    orig.device <- dev.cur()
    new.device <- force(dev)
    # Functions that create devices don't generally return them, they
    # just set them as the new current device, so get the actual
    # device from dev.cur() instead.
    if (is.null(new.device)) {
        new.device <- dev.cur()
    }
    assert_that(is_dev(new.device))
    message(glue("Orig device: {deparse(orig.device)}; new device: {deparse(new.device)}"))
    if (missing(closedev)) {
         closedev <- new.device != orig.device
    }
    on.exit({
        if (closedev) {
            dev.off(new.device)
        }
        if (is_dev(orig.device)) {
            dev.set(orig.device)
        }
    })
    force(code)
}

# Usage:
library(ggplot2)
with_dev(pdf(file.path(tempdir(), "test.pdf")), print(qplot(x=1:50, y=rnorm(50))))

The dev argument should either be code that returns a graphics device, or code that creates a new graphics device, sets it as the current device, and returns NULL. (Functions like png, pdf, etc. fall into the latter category.)

The function tries to auto-detect whether or not is should close the device when done with it. The heuristic is that if evaluating dev changes the value of dev.cur(), then the device will be closed on exit. This can be overridden with the closedev argument.

The is_dev function is just a helper here, but it might be worth including in rlang, named something like is_graphics_device.

My original code: https://github.com/DarwinAwardWinner/CD4-csaw/blob/master/scripts/utilities.R#L143-L169

@jimhester jimhester added the feature a feature request or enhancement label May 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement
Projects
None yet
Development

No branches or pull requests

2 participants