Debian Codegraph @

R/progress.R

raw
1 #' Reporting progress (object-oriented API)
2 #'
3 #' Reports progress to the user during long-running operations.
4 #'
5 #' This package exposes two distinct programming APIs for working with
6 #' progress. [withProgress()] and [setProgress()]
7 #' together provide a simple function-based interface, while the
8 #' `Progress` reference class provides an object-oriented API.
9 #'
10 #' Instantiating a `Progress` object causes a progress panel to be
11 #' created, and it will be displayed the first time the `set`
12 #' method is called. Calling `close` will cause the progress panel
13 #' to be removed.
14 #'
15 #' As of version 0.14, the progress indicators use Shiny's new notification API.
16 #' If you want to use the old styling (for example, you may have used customized
17 #' CSS), you can use `style="old"` each time you call
18 #' `Progress$new()`. If you don't want to set the style each time
19 #' `Progress$new` is called, you can instead call
20 #' [`shinyOptions(progress.style="old")`][shinyOptions] just once, inside the server
21 #' function.
22 #'
23 #' @param message A single-element character vector; the message to be
24 #' displayed to the user, or `NULL` to hide the current message (if any).
25 #' @param detail A single-element character vector; the detail message to be
26 #' displayed to the user, or `NULL` to hide the current detail message (if
27 #' any). The detail message will be shown with a de-emphasized appearance
28 #' relative to `message`.
29 #'
30 #' @examples
31 #' ## Only run examples in interactive R sessions
32 #' if (interactive()) {
33 #'
34 #' ui <- fluidPage(
35 #' plotOutput("plot")
36 #' )
37 #'
38 #' server <- function(input, output, session) {
39 #' output$plot <- renderPlot({
40 #' progress <- Progress$new(session, min=1, max=15)
41 #' on.exit(progress$close())
42 #'
43 #' progress$set(message = 'Calculation in progress',
44 #' detail = 'This may take a while...')
45 #'
46 #' for (i in 1:15) {
47 #' progress$set(value = i)
48 #' Sys.sleep(0.5)
49 #' }
50 #' plot(cars)
51 #' })
52 #' }
53 #'
54 #' shinyApp(ui, server)
55 #' }
56 #' @seealso [withProgress()]
57 #' @format NULL
58 #' @usage NULL
59 #' @export
60 Progress <- R6Class(
61 'Progress',
62 public = list(
63
64 #' @description Creates a new progress panel (but does not display it).
65 #' @param session The Shiny session object, as provided by `shinyServer` to
66 #' the server function.
67 #' @param min The value that represents the starting point of the progress
68 #' bar. Must be less than `max`.
69 #' @param max The value that represents the end of the progress bar. Must be
70 #' greater than `min`.
71 #' @param style Progress display style. If `"notification"` (the default),
72 #' the progress indicator will show using Shiny's notification API. If
73 #' `"old"`, use the same HTML and CSS used in Shiny 0.13.2 and below (this
74 #' is for backward-compatibility).
75 initialize = function(session = getDefaultReactiveDomain(),
76 min = 0, max = 1,
77 style = getShinyOption("progress.style", default = "notification"))
78 {
79 if (is.null(session))
80 rlang::abort("Can only use Progress$new() inside a Shiny app")
81 if (is.null(session$progressStack))
82 rlang::abort("`session` is not a ShinySession object.")
83
84 private$session <- session
85 private$id <- createUniqueId(8)
86 private$min <- min
87 private$max <- max
88 private$value <- NULL
89 private$style <- match.arg(style, choices = c("notification", "old"))
90 private$closed <- FALSE
91
92 session$sendProgress('open', list(id = private$id, style = private$style))
93 },
94
95 #' @description Updates the progress panel. When called the first time, the
96 #' progress panel is displayed.
97 #' @param value Single-element numeric vector; the value at which to set the
98 #' progress bar, relative to `min` and `max`. `NULL` hides the progress
99 #' bar, if it is currently visible.
100 set = function(value = NULL, message = NULL, detail = NULL) {
101 if (private$closed) {
102 warning("Attempting to set progress, but progress already closed.")
103 return()
104 }
105
106 if (is.null(value) || is.na(value))
107 value <- NULL
108
109 if (!is.null(value)) {
110 private$value <- value
111 # Normalize value to number between 0 and 1
112 value <- min(1, max(0, (value - private$min) / (private$max - private$min)))
113 }
114
115 data <- dropNulls(list(
116 id = private$id,
117 message = message,
118 detail = detail,
119 value = value,
120 style = private$style
121 ))
122
123 private$session$sendProgress('update', data)
124 },
125
126 #' @description Like `set`, this updates the progress panel. The difference
127 #' is that `inc` increases the progress bar by `amount`, instead of
128 #' setting it to a specific value.
129 #' @param amount For the `inc()` method, a numeric value to increment the
130 #' progress bar.
131 inc = function(amount = 0.1, message = NULL, detail = NULL) {
132 if (is.null(private$value))
133 private$value <- private$min
134
135 value <- min(private$value + amount, private$max)
136 self$set(value, message, detail)
137 },
138
139 #' @description Returns the minimum value.
140 getMin = function() private$min,
141
142 #' @description Returns the maximum value.
143 getMax = function() private$max,
144
145 #' @description Returns the current value.
146 getValue = function() private$value,
147
148 #' @description Removes the progress panel. Future calls to `set` and
149 #' `close` will be ignored.
150 close = function() {
151 if (private$closed) {
152 warning("Attempting to close progress, but progress already closed.")
153 return()
154 }
155
156 private$session$sendProgress('close',
157 list(id = private$id, style = private$style)
158 )
159 private$closed <- TRUE
160 }
161 ),
162
163 private = list(
164 session = 'ShinySession',
165 id = character(0),
166 min = numeric(0),
167 max = numeric(0),
168 style = character(0),
169 value = numeric(0),
170 closed = logical(0)
171 )
172 )
173
174 #' Reporting progress (functional API)
175 #'
176 #' Reports progress to the user during long-running operations.
177 #'
178 #' This package exposes two distinct programming APIs for working with progress.
179 #' Using `withProgress` with `incProgress` or `setProgress`
180 #' provide a simple function-based interface, while the [Progress()]
181 #' reference class provides an object-oriented API.
182 #'
183 #' Use `withProgress` to wrap the scope of your work; doing so will cause a
184 #' new progress panel to be created, and it will be displayed the first time
185 #' `incProgress` or `setProgress` are called. When `withProgress`
186 #' exits, the corresponding progress panel will be removed.
187 #'
188 #' The `incProgress` function increments the status bar by a specified
189 #' amount, whereas the `setProgress` function sets it to a specific value,
190 #' and can also set the text displayed.
191 #'
192 #' Generally, `withProgress`/`incProgress`/`setProgress` should
193 #' be sufficient; the exception is if the work to be done is asynchronous (this
194 #' is not common) or otherwise cannot be encapsulated by a single scope. In that
195 #' case, you can use the `Progress` reference class.
196 #'
197 #' As of version 0.14, the progress indicators use Shiny's new notification API.
198 #' If you want to use the old styling (for example, you may have used customized
199 #' CSS), you can use `style="old"` each time you call
200 #' `withProgress()`. If you don't want to set the style each time
201 #' `withProgress` is called, you can instead call
202 #' [`shinyOptions(progress.style="old")`][shinyOptions] just once, inside the server
203 #' function.
204 #'
205 #' @param session The Shiny session object, as provided by `shinyServer` to
206 #' the server function. The default is to automatically find the session by
207 #' using the current reactive domain.
208 #' @param expr The work to be done. This expression should contain calls to
209 #' [setProgress()] or [incProgress()].
210 #' @param min The value that represents the starting point of the progress bar.
211 #' Must be less tham `max`. Default is 0.
212 #' @param max The value that represents the end of the progress bar. Must be
213 #' greater than `min`. Default is 1.
214 #' @param amount For `incProgress`, the amount to increment the status bar.
215 #' Default is 0.1.
216 #' @param env The environment in which `expr` should be evaluated.
217 #' @param quoted Whether `expr` is a quoted expression (this is not
218 #' common).
219 #' @param message A single-element character vector; the message to be displayed
220 #' to the user, or `NULL` to hide the current message (if any).
221 #' @param detail A single-element character vector; the detail message to be
222 #' displayed to the user, or `NULL` to hide the current detail message
223 #' (if any). The detail message will be shown with a de-emphasized appearance
224 #' relative to `message`.
225 #' @param style Progress display style. If `"notification"` (the default),
226 #' the progress indicator will show using Shiny's notification API. If
227 #' `"old"`, use the same HTML and CSS used in Shiny 0.13.2 and below
228 #' (this is for backward-compatibility).
229 #' @param value Single-element numeric vector; the value at which to set the
230 #' progress bar, relative to `min` and `max`.
231 #'
232 #' @return The result of `expr`.
233 #' @examples
234 #' ## Only run examples in interactive R sessions
235 #' if (interactive()) {
236 #' options(device.ask.default = FALSE)
237 #'
238 #' ui <- fluidPage(
239 #' plotOutput("plot")
240 #' )
241 #'
242 #' server <- function(input, output) {
243 #' output$plot <- renderPlot({
244 #' withProgress(message = 'Calculation in progress',
245 #' detail = 'This may take a while...', value = 0, {
246 #' for (i in 1:15) {
247 #' incProgress(1/15)
248 #' Sys.sleep(0.25)
249 #' }
250 #' })
251 #' plot(cars)
252 #' })
253 #' }
254 #'
255 #' shinyApp(ui, server)
256 #' }
257 #' @seealso [Progress()]
258 #' @rdname withProgress
259 #' @export
260 withProgress <- function(expr, min = 0, max = 1,
261 value = min + (max - min) * 0.1,
262 message = NULL, detail = NULL,
263 style = getShinyOption("progress.style", default = "notification"),
264 session = getDefaultReactiveDomain(),
265 env = parent.frame(), quoted = FALSE)
266 {
267
268 if (!quoted)
269 expr <- substitute(expr)
270
271 if (is.null(session$progressStack))
272 stop("'session' is not a ShinySession object.")
273
274 style <- match.arg(style, c("notification", "old"))
275
276 p <- Progress$new(session, min = min, max = max, style = style)
277
278 session$progressStack$push(p)
279 on.exit({
280 session$progressStack$pop()
281 p$close()
282 })
283
284 p$set(value, message, detail)
285
286 eval(expr, env)
287 }
288
289 #' @rdname withProgress
290 #' @export
291 setProgress <- function(value = NULL, message = NULL, detail = NULL,
292 session = getDefaultReactiveDomain()) {
293
294 if (is.null(session$progressStack))
295 stop("'session' is not a ShinySession object.")
296
297 if (session$progressStack$size() == 0) {
298 warning('setProgress was called outside of withProgress; ignoring')
299 return()
300 }
301
302 session$progressStack$peek()$set(value, message, detail)
303 invisible()
304 }
305
306 #' @rdname withProgress
307 #' @export
308 incProgress <- function(amount = 0.1, message = NULL, detail = NULL,
309 session = getDefaultReactiveDomain()) {
310
311 if (is.null(session$progressStack))
312 stop("'session' is not a ShinySession object.")
313
314 if (session$progressStack$size() == 0) {
315 warning('incProgress was called outside of withProgress; ignoring')
316 return()
317 }
318
319 p <- session$progressStack$peek()
320 p$inc(amount, message, detail)
321 invisible()
322 }