Skip to content

Commit

Permalink
Helper method to capture plot & output (#177)
Browse files Browse the repository at this point in the history
This is a straightforward refactoring to push more logic into the watcher "class".
  • Loading branch information
hadley authored Jun 25, 2024
1 parent 1aa6c64 commit 7703aea
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
19 changes: 7 additions & 12 deletions R/eval.R
Original file line number Diff line number Diff line change
Expand Up @@ -136,17 +136,12 @@ evaluate_top_level_expression <- function(exprs,
if (!is.null(source))
watcher$push(source)

handle_output <- function(plot = TRUE) {
if (plot) watcher$capture_plot()
watcher$capture_output()
}

local_output_handler(function() handle_output(FALSE))
local_plot_hooks(handle_output)
local_output_handler(watcher$capture_output)
local_plot_hooks(watcher$capture_plot_and_output)

# Handlers for warnings, errors and messages
mHandler <- function(cnd) {
handle_output()
watcher$capture_plot_and_output()
if (isTRUE(keep_message)) {
watcher$push(cnd)
output_handler$message(cnd)
Expand All @@ -165,7 +160,7 @@ evaluate_top_level_expression <- function(exprs,
cat_line(format_condition(cnd), file = stderr())
}

handle_output()
watcher$capture_plot_and_output()
if (isTRUE(keep_warning)) {
cnd <- reset_call(cnd)
watcher$push(cnd)
Expand All @@ -176,7 +171,7 @@ evaluate_top_level_expression <- function(exprs,
}
}
eHandler <- function(cnd) {
handle_output()
watcher$capture_plot_and_output()

cnd <- reset_call(cnd)
watcher$push(cnd)
Expand All @@ -198,7 +193,7 @@ evaluate_top_level_expression <- function(exprs,
withVisible(eval(expr, envir)),
handlers
)
handle_output(TRUE)
watcher$capture_plot_and_output()

if (show_value(output_handler, ev$visible)) {
# Ideally we'd evaluate the print() generic in envir in order to find
Expand All @@ -211,7 +206,7 @@ evaluate_top_level_expression <- function(exprs,
),
handlers
)
handle_output(TRUE)
watcher$capture_plot_and_output()
# If the return value is visible, save the value to the output
if (pv$visible) {
watcher$push(pv$value)
Expand Down
6 changes: 6 additions & 0 deletions R/watcher.R
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ watchout <- function(handler = new_output_handler(),
invisible()
}

capture_plot_and_output <- function() {
capture_plot()
capture_output()
}

check_devices <- function() {
# if dev.off() was called, make sure to restore device to the one opened
# when watchout() was called
Expand All @@ -75,6 +80,7 @@ watchout <- function(handler = new_output_handler(),
list(
capture_plot = capture_plot,
capture_output = capture_output,
capture_plot_and_output = capture_plot_and_output,
check_devices = check_devices,
push = push,
get = function() new_evaluation(output)
Expand Down

0 comments on commit 7703aea

Please sign in to comment.