Debian Codegraph @

R/shiny.R

raw
1 #' @include utils.R
2 NULL
3
4 #' Web Application Framework for R
5 #'
6 #' Shiny makes it incredibly easy to build interactive web applications with R.
7 #' Automatic "reactive" binding between inputs and outputs and extensive
8 #' prebuilt widgets make it possible to build beautiful, responsive, and
9 #' powerful applications with minimal effort.
10 #'
11 #' The Shiny tutorial at <https://shiny.rstudio.com/tutorial/> explains
12 #' the framework in depth, walks you through building a simple application, and
13 #' includes extensive annotated examples.
14 #'
15 #' @seealso [shiny-options] for documentation about global options.
16 #'
17 #' @name shiny-package
18 #' @aliases shiny
19 "_PACKAGE"
20
21 createUniqueId <- function(bytes, prefix = "", suffix = "") {
22 withPrivateSeed({
23 paste(
24 prefix,
25 paste(
26 format(as.hexmode(sample(256, bytes, replace = TRUE)-1), width=2),
27 collapse = ""),
28 suffix,
29 sep = ""
30 )
31 })
32 }
33
34 toJSON <- function(x, ..., dataframe = "columns", null = "null", na = "null",
35 auto_unbox = TRUE,
36 # Shiny has had a legacy value of 16 significant digits
37 # We can use `I(16)` mixed with the default behavior in jsonlite's `use_signif=`
38 # https://github.com/jeroen/jsonlite/commit/728efa9
39 digits = getOption("shiny.json.digits", I(16)), use_signif = is(digits, "AsIs"),
40 force = TRUE, POSIXt = "ISO8601", UTC = TRUE,
41 rownames = FALSE, keep_vec_names = TRUE, strict_atomic = TRUE) {
42
43 if (strict_atomic) {
44 x <- I(x)
45 }
46
47 # I(x) is so that length-1 atomic vectors get put in [].
48 jsonlite::toJSON(x, dataframe = dataframe, null = null, na = na,
49 auto_unbox = auto_unbox, digits = digits, use_signif = use_signif,
50 force = force, POSIXt = POSIXt, UTC = UTC, rownames = rownames,
51 keep_vec_names = keep_vec_names, json_verbatim = TRUE, ...)
52 }
53
54 # If the input to jsonlite::fromJSON is not valid JSON, it will try to fetch a
55 # URL or read a file from disk. We don't want to allow that.
56 safeFromJSON <- function(txt, ...) {
57 if (!jsonlite::validate(txt)) {
58 stop("Argument 'txt' is not a valid JSON string.")
59 }
60 jsonlite::fromJSON(txt, ...)
61 }
62
63 # Call the workerId func with no args to get the worker id, and with an arg to
64 # set it.
65 #
66 # A worker ID is an opaque string that is passed in by the caller. The ID is
67 # added as a URL parameter (?w=<worker_id>) to any URLs that need to refer back
68 # to the app. This can be used as a hint for load balancers to direct requests
69 # to this particular process. Since the worker refers to a process, it's
70 # inherently global, and should never need to change.
71 workerId <- local({
72 .workerId <- NULL
73 function(value) {
74 if (missing(value)) {
75 .workerId
76 } else {
77 if (!is.null(.workerId)) {
78 if (!identical(value, .workerId)) {
79 warning("Ignoring workerId value--",
80 "it's already been set to a different value")
81 }
82 } else {
83 .workerId <<- value
84 }
85 }
86 }
87 })
88
89 #' Session object
90 #'
91 #' Shiny server functions can optionally include `session` as a parameter
92 #' (e.g. `function(input, output, session)`). The session object is an
93 #' environment that can be used to access information and functionality
94 #' relating to the session. The following list describes the items available
95 #' in the environment; they can be accessed using the `$` operator (for
96 #' example, `session$clientData$url_search`).
97 #'
98 #' @return
99 #' \item{allowReconnect(value)}{
100 #' If `value` is `TRUE` and run in a hosting environment (Shiny
101 #' Server or Connect) with reconnections enabled, then when the session ends
102 #' due to the network connection closing, the client will attempt to
103 #' reconnect to the server. If a reconnection is successful, the browser will
104 #' send all the current input values to the new session on the server, and
105 #' the server will recalculate any outputs and send them back to the client.
106 #' If `value` is `FALSE`, reconnections will be disabled (this is
107 #' the default state). If `"force"`, then the client browser will always
108 #' attempt to reconnect. The only reason to use `"force"` is for testing
109 #' on a local connection (without Shiny Server or Connect).
110 #' }
111 #' \item{clientData}{
112 #' A [reactiveValues()] object that contains information about the client.
113 #' \itemize{
114 #' \item{`pixelratio` reports the "device pixel ratio" from the web browser,
115 #' or 1 if none is reported. The value is 2 for Apple Retina displays.
116 #' }
117 #' \item{`singletons` - for internal use}
118 #' \item{`url_protocol`, `url_hostname`, `url_port`,
119 #' `url_pathname`, `url_search`, `url_hash_initial`
120 #' and `url_hash` can be used to get the components of the URL
121 #' that was requested by the browser to load the Shiny app page.
122 #' These values are from the browser's perspective, so neither HTTP
123 #' proxies nor Shiny Server will affect these values. The
124 #' `url_search` value may be used with [parseQueryString()]
125 #' to access query string parameters.
126 #' }
127 #' }
128 #' `clientData` also contains information about each output.
129 #' \code{output_\var{outputId}_width} and \code{output_\var{outputId}_height}
130 #' give the dimensions (using `offsetWidth` and `offsetHeight`) of
131 #' the DOM element that is bound to \code{\var{outputId}}, and
132 #' \code{output_\var{outputId}_hidden} is a logical that indicates whether
133 #' the element is hidden. These values may be `NULL` if the output is
134 #' not bound.
135 #' }
136 #' \item{input}{
137 #' The session's `input` object (the same as is passed into the Shiny
138 #' server function as an argument).
139 #' }
140 #' \item{isClosed()}{A function that returns `TRUE` if the client has
141 #' disconnected.
142 #' }
143 #' \item{ns(id)}{
144 #' Server-side version of [`ns <- NS(id)`][NS]. If bare IDs need to be
145 #' explicitly namespaced for the current module, `session$ns("name")`
146 #' will return the fully-qualified ID.
147 #' }
148 #' \item{onEnded(callback)}{
149 #' Synonym for `onSessionEnded`.
150 #' }
151 #' \item{onFlush(func, once=TRUE)}{
152 #' Registers a function to be called before the next time (if `once=TRUE`)
153 #' or every time (if `once=FALSE`) Shiny flushes the reactive system.
154 #' Returns a function that can be called with no arguments to cancel the
155 #' registration.
156 #' }
157 #' \item{onFlushed(func, once=TRUE)}{
158 #' Registers a function to be called after the next time (if `once=TRUE`)
159 #' or every time (if `once=FALSE`) Shiny flushes the reactive system.
160 #' Returns a function that can be called with no arguments to cancel the
161 #' registration.
162 #' }
163 #' \item{onSessionEnded(callback)}{
164 #' Registers a function to be called after the client has disconnected.
165 #' Returns a function that can be called with no arguments to cancel the
166 #' registration.
167 #' }
168 #' \item{output}{
169 #' The session's `output` object (the same as is passed into the Shiny
170 #' server function as an argument).
171 #' }
172 #' \item{reactlog}{
173 #' For internal use.
174 #' }
175 #' \item{registerDataObj(name, data, filterFunc)}{
176 #' Publishes any R object as a URL endpoint that is unique to this session.
177 #' `name` must be a single element character vector; it will be used
178 #' to form part of the URL. `filterFunc` must be a function that takes
179 #' two arguments: `data` (the value that was passed into
180 #' `registerDataObj`) and `req` (an environment that implements
181 #' the Rook specification for HTTP requests). `filterFunc` will be
182 #' called with these values whenever an HTTP request is made to the URL
183 #' endpoint. The return value of `filterFunc` should be a Rook-style
184 #' response.
185 #' }
186 #' \item{reload()}{
187 #' The equivalent of hitting the browser's Reload button. Only works if the
188 #' session is actually connected.
189 #' }
190 #' \item{request}{
191 #' An environment that implements the [Rook
192 #' specification](https://github.com/jeffreyhorner/Rook#the-environment) for
193 #' HTTP requests. This is the request that was used to initiate the websocket
194 #' connection (as opposed to the request that downloaded the web page for the
195 #' app).
196 #' }
197 #' \item{userData}{
198 #' An environment for app authors and module/package authors to store whatever
199 #' session-specific data they want.
200 #' }
201 #' \item{user}{
202 #' User's log-in information. Useful for identifying users on hosted platforms
203 #' such as RStudio Connect and Shiny Server.
204 #' }
205 #' \item{groups}{
206 #' The `user`'s relevant group information. Useful for determining what
207 #' privileges the user should or shouldn't have.
208 #' }
209 #' \item{resetBrush(brushId)}{
210 #' Resets/clears the brush with the given `brushId`, if it exists on
211 #' any `imageOutput` or `plotOutput` in the app.
212 #' }
213 #' \item{sendCustomMessage(type, message)}{
214 #' Sends a custom message to the web page. `type` must be a
215 #' single-element character vector giving the type of message, while
216 #' `message` can be any jsonlite-encodable value. Custom messages
217 #' have no meaning to Shiny itself; they are used solely to convey information
218 #' to custom JavaScript logic in the browser. You can do this by adding
219 #' JavaScript code to the browser that calls
220 #' \code{Shiny.addCustomMessageHandler(type, function(message){...})}
221 #' as the page loads; the function you provide to
222 #' `addCustomMessageHandler` will be invoked each time
223 #' `sendCustomMessage` is called on the server.
224 #' }
225 #' \item{sendBinaryMessage(type, message)}{
226 #' Similar to `sendCustomMessage`, but the message must be a raw vector
227 #' and the registration method on the client is
228 #' \code{Shiny.addBinaryMessageHandler(type, function(message){...})}. The
229 #' message argument on the client will be a
230 #' [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView).
231 #' }
232 #' \item{sendInputMessage(inputId, message)}{
233 #' Sends a message to an input on the session's client web page; if the input
234 #' is present and bound on the page at the time the message is received, then
235 #' the input binding object's `receiveMessage(el, message)` method will
236 #' be called. `sendInputMessage` should generally not be called directly
237 #' from Shiny apps, but through friendlier wrapper functions like
238 #' [updateTextInput()].
239 #' }
240 #' \item{setBookmarkExclude(names)}{
241 #' Set input names to be excluded from bookmarking.
242 #' }
243 #' \item{getBookmarkExclude()}{
244 #' Returns the set of input names to be excluded from bookmarking.
245 #' }
246 #' \item{onBookmark(fun)}{
247 #' Registers a function that will be called just before bookmarking state.
248 #' }
249 #' \item{onBookmarked(fun)}{
250 #' Registers a function that will be called just after bookmarking state.
251 #' }
252 #' \item{onRestore(fun)}{
253 #' Registers a function that will be called when a session is restored, before
254 #' all other reactives, observers, and render functions are run.
255 #' }
256 #' \item{onRestored(fun)}{
257 #' Registers a function that will be called when a session is restored, after
258 #' all other reactives, observers, and render functions are run.
259 #' }
260 #' \item{doBookmark()}{
261 #' Do bookmarking and invoke the onBookmark and onBookmarked callback functions.
262 #' }
263 #' \item{exportTestValues()}{
264 #' Registers expressions for export in test mode, available at the test
265 #' snapshot URL.
266 #' }
267 #' \item{getTestSnapshotUrl(input=TRUE, output=TRUE, export=TRUE,
268 #' format="json")}{
269 #' Returns a URL for the test snapshots. Only has an effect when the
270 #' `shiny.testmode` option is set to TRUE. For the input, output, and
271 #' export arguments, TRUE means to return all of these values. It is also
272 #' possible to specify by name which values to return by providing a
273 #' character vector, as in `input=c("x", "y")`. The format can be
274 #' "rds" or "json".
275 #' }
276 #' \item{setCurrentTheme(theme)}{
277 #' Sets the current [bootstrapLib()] theme, which updates the value of
278 #' [getCurrentTheme()], invalidates `session$getCurrentTheme()`, and calls
279 #' function(s) registered with [registerThemeDependency()] with provided
280 #' `theme`. If those function calls return [htmltools::htmlDependency()]s with
281 #' `stylesheet`s, then those stylesheets are "refreshed" (i.e., the new
282 #' stylesheets are inserted on the page and the old ones are disabled and
283 #' removed).
284 #' }
285 #' \item{getCurrentTheme()}{
286 #' A reactive read of the current [bootstrapLib()] theme.
287 #' }
288 #'
289 #' @name session
290 NULL
291
292 #' Namespaced IDs for inputs/outputs
293 #'
294 #' The `NS` function creates namespaced IDs out of bare IDs, by joining
295 #' them using `ns.sep` as the delimiter. It is intended for use in Shiny
296 #' modules. See <https://shiny.rstudio.com/articles/modules.html>.
297 #'
298 #' Shiny applications use IDs to identify inputs and outputs. These IDs must be
299 #' unique within an application, as accidentally using the same input/output ID
300 #' more than once will result in unexpected behavior. The traditional solution
301 #' for preventing name collisions is *namespaces*; a namespace is to an ID
302 #' as a directory is to a file. Use the `NS` function to turn a bare ID
303 #' into a namespaced one, by combining them with `ns.sep` in between.
304 #'
305 #' @param namespace The character vector to use for the namespace. This can have
306 #' any length, though a single element is most common. Length 0 will cause the
307 #' `id` to be returned without a namespace, and length 2 will be
308 #' interpreted as multiple namespaces, in increasing order of specificity
309 #' (i.e. starting with the top-level namespace).
310 #' @param id The id string to be namespaced (optional).
311 #' @return If `id` is missing, returns a function that expects an id string
312 #' as its only argument and returns that id with the namespace prepended.
313 #' @seealso <https://shiny.rstudio.com/articles/modules.html>
314 #' @export
315 NS <- function(namespace, id = NULL) {
316 if (length(namespace) == 0)
317 ns_prefix <- character(0)
318 else
319 ns_prefix <- paste(namespace, collapse = ns.sep)
320
321 f <- function(id) {
322 if (length(id) == 0)
323 return(ns_prefix)
324 if (length(ns_prefix) == 0)
325 return(id)
326
327 paste(ns_prefix, id, sep = ns.sep)
328 }
329
330 if (missing(id)) {
331 f
332 } else {
333 f(id)
334 }
335 }
336
337 #' @rdname NS
338 #' @export
339 ns.sep <- "-"
340
341
342 #' @include utils.R
343 ShinySession <- R6Class(
344 'ShinySession',
345 private = list(
346 # There are some private items with a leading "."; except for the dot, these
347 # items share a name with a public item.
348 websocket = 'ANY',
349 invalidatedOutputValues = 'Map',
350 invalidatedOutputErrors = 'Map',
351 inputMessageQueue = 'fastqueue', # A list of inputMessages to send when flushed
352 cycleStartActionQueue = 'fastqueue', # A list of actions to perform to start a cycle
353 .outputs = list(), # Keeps track of all the output observer objects
354 .outputOptions = list(), # Options for each of the output observer objects
355 progressKeys = 'character',
356 showcase = FALSE,
357 fileUploadContext = 'FileUploadContext',
358 .input = 'ANY', # Internal ReactiveValues object for normal input sent from client
359 .clientData = 'ANY', # Internal ReactiveValues object for other data sent from the client
360 busyCount = 0L, # Number of observer callbacks that are pending. When 0, we are idle
361 closedCallbacks = 'Callbacks',
362 flushCallbacks = 'Callbacks',
363 flushedCallbacks = 'Callbacks',
364 inputReceivedCallbacks = 'Callbacks',
365 unhandledErrorCallbacks = 'Callbacks',
366 bookmarkCallbacks = 'Callbacks',
367 bookmarkedCallbacks = 'Callbacks',
368 restoreCallbacks = 'Callbacks',
369 restoredCallbacks = 'Callbacks',
370 bookmarkExclude = character(0), # Names of inputs to exclude from bookmarking
371 getBookmarkExcludeFuns = list(),
372 timingRecorder = 'ShinyServerTimingRecorder',
373
374 testMode = FALSE, # Are we running in test mode?
375 testExportExprs = list(),
376 outputValues = list(), # Saved output values (for testing mode)
377 currentOutputName = NULL, # Name of the currently-running output
378 outputInfo = list(), # List of information for each output
379 testSnapshotUrl = character(0),
380 currentThemeDependency = NULL, # ReactiveVal for taking dependency on theme
381
382 sendResponse = function(requestMsg, value) {
383 if (is.null(requestMsg$tag)) {
384 warning("Tried to send response for untagged message; method: ",
385 requestMsg$method)
386 return()
387 }
388 private$sendMessage(
389 response = list(tag = requestMsg$tag, value = value)
390 )
391 },
392 sendErrorResponse = function(requestMsg, error) {
393 if (is.null(requestMsg$tag))
394 return()
395 private$sendMessage(
396 response = list(tag = requestMsg$tag, error = error)
397 )
398 },
399 write = function(json) {
400 if (self$closed){
401 return()
402 }
403 traceOption <- getOption('shiny.trace', FALSE)
404 if (isTRUE(traceOption) || traceOption == "send")
405 message('SEND ',
406 gsub('(?m)base64,[a-zA-Z0-9+/=]+','[base64 data]',json,perl=TRUE))
407 private$websocket$send(json)
408 },
409 sendMessage = function(...) {
410 # This function is a wrapper for $write
411 msg <- list(...)
412 if (any_unnamed(msg)) {
413 stop("All arguments to sendMessage must be named.")
414 }
415 private$write(toJSON(msg))
416 },
417 getOutputOption = function(outputName, propertyName, defaultValue) {
418 opts <- private$.outputOptions[[outputName]]
419 if (is.null(opts))
420 return(defaultValue)
421 result <- opts[[propertyName]]
422 if (is.null(result))
423 return(defaultValue)
424 return(result)
425 },
426 withCurrentOutput = function(name, expr) {
427 if (!is.null(private$currentOutputName)) {
428 stop("Nested calls to withCurrentOutput() are not allowed.")
429 }
430
431 with_promise_domain(
432 createVarPromiseDomain(private, "currentOutputName", name),
433 expr
434 )
435 },
436 shouldSuspend = function(name) {
437 # Find corresponding hidden state clientData variable, with the format
438 # "output_foo_hidden". (It comes from .clientdata_output_foo_hidden
439 # on the JS side)
440 # Some tricky stuff: instead of accessing names using input$names(),
441 # get the names directly via input$.values, to avoid triggering reactivity.
442 # Need to handle cases where the output object isn't actually used
443 # in the web page; in these cases, there's no output_foo_hidden flag,
444 # and hidden should be TRUE. In other words, NULL and TRUE should map to
445 # TRUE, FALSE should map to FALSE.
446 hidden <- private$.clientData$.values$get(paste0("output_", name, "_hidden"))
447 if (is.null(hidden)) hidden <- TRUE
448
449 return(hidden && private$getOutputOption(name, 'suspendWhenHidden', TRUE))
450 },
451
452 registerSessionEndCallbacks = function() {
453 # This is to be called from the initialization. It registers functions
454 # that are called when a session ends.
455
456 # Clear file upload directories, if present
457 self$onSessionEnded(private$fileUploadContext$rmUploadDirs)
458 },
459
460 # Modules (scopes) call this to register a function that returns a vector
461 # of names to exclude from bookmarking. The function should return
462 # something like c("scope1-x", "scope1-y"). This doesn't use a Callback
463 # object because the return values of the functions are needed, but
464 # Callback$invoke() discards return values.
465 registerBookmarkExclude = function(fun) {
466 len <- length(private$getBookmarkExcludeFuns) + 1
467 private$getBookmarkExcludeFuns[[len]] <- fun
468 },
469
470 # Save output values and errors. This is only used for testing mode.
471 storeOutputValues = function(values = NULL) {
472 private$outputValues <- mergeVectors(private$outputValues, values)
473 },
474
475 enableTestSnapshot = function() {
476 private$testSnapshotUrl <- self$registerDataObj("shinytest", NULL,
477 function(data, req) {
478 if (!isTRUE(private$testMode)) {
479 return()
480 }
481
482 params <- parseQueryString(req$QUERY_STRING)
483 # The format of the response that will be sent back. Defaults to
484 # "json" unless requested otherwise. The only other valid value is
485 # "rds".
486 format <- params$format %||% "json"
487 # Machines can test their snapshot under different locales.
488 # R CMD check runs under the `C` locale.
489 # However, before this parameter, existing snapshots were most likely not
490 # under the `C` locale is would cause failures. This parameter allows
491 # users to opt-in to the `C` locale.
492 # From ?sort:
493 # However, there are some caveats with the radix sort:
494 # If ‘x’ is a ‘character’ vector, all elements must share the
495 # same encoding. Only UTF-8 (including ASCII) and Latin-1
496 # encodings are supported. Collation always follows the "C"
497 # locale.
498 # {shinytest2} will always set `sortC=1`
499 # {shinytest} does not have `sortC` functionality.
500 # Users should set `options(shiny.snapshotsortc = TRUE)` within their app.
501 # The sortingMethod should always be `radix` going forward.
502 sortMethod <-
503 if (!is.null(params$sortC)) {
504 if (params$sortC != "1") {
505 stop("The `sortC` parameter can only be `1` or not supplied")
506 }
507 "radix"
508 } else {
509 # Allow users to set an option for {shinytest2}.
510 if (isTRUE(getShinyOption("snapshotsortc", default = FALSE))) {
511 "radix"
512 } else {
513 "auto"
514 }
515 }
516
517 values <- list()
518
519 if (!is.null(params$input)) {
520
521 # The isolate and reactiveValuesToList calls are being executed
522 # in a non-reactive context, but will produce output in the reactlog
523 # Seeing new, unlabelled reactives ONLY when calling shinytest is
524 # jarring / frustrating to debug.
525 # Since labeling these values is not currently supported in reactlog,
526 # it is better to hide them.
527 # Hopefully we can replace this with something like
528 # `with_reactlog_group("shinytest", {})`, which would visibily explain
529 # why the new reactives are added when calling shinytest
530 withr::with_options(
531 list(shiny.reactlog = FALSE),
532 {
533 allInputs <- isolate(
534 reactiveValuesToList(self$input, all.names = TRUE)
535 )
536 }
537 )
538
539 # If params$input is "1", return all; otherwise return just the
540 # inputs that are named in params$input, like "x,y,z".
541 if (params$input == "1") {
542 values$input <- allInputs
543 } else {
544 items <- strsplit(params$input, ",")[[1]]
545 items <- intersect(items, names(allInputs))
546 values$input <- allInputs[items]
547 }
548
549 # Apply preprocessor functions for inputs that have them.
550 values$input <- lapply(
551 stats::setNames(names(values$input), names(values$input)),
552 function(name) {
553 preprocess <- private$getSnapshotPreprocessInput(name)
554 preprocess(values$input[[name]])
555 }
556 )
557
558 values$input <- sortByName(values$input, method = sortMethod)
559 }
560
561 if (!is.null(params$output)) {
562
563 if (params$output == "1") {
564 values$output <- private$outputValues
565 } else {
566 items <- strsplit(params$output, ",")[[1]]
567 items <- intersect(items, names(private$outputValues))
568 values$output <- private$outputValues[items]
569 }
570
571 # Filter out those outputs that have the snapshotExclude attribute.
572 exclude_idx <- vapply(names(values$output), function(name) {
573 isTRUE(attr(private$.outputs[[name]], "snapshotExclude", TRUE))
574 }, logical(1))
575 values$output <- values$output[!exclude_idx]
576
577 # Apply snapshotPreprocess functions for outputs that have them.
578 values$output <- lapply(
579 stats::setNames(names(values$output), names(values$output)),
580 function(name) {
581 preprocess <- private$getSnapshotPreprocessOutput(name)
582 preprocess(values$output[[name]])
583 }
584 )
585
586 values$output <- sortByName(values$output, method = sortMethod)
587 }
588
589 if (!is.null(params$export)) {
590
591 if (params$export == "1") {
592 values$export <- isolate(
593 lapply(private$testExportExprs, function(item) {
594 eval(item$expr, envir = item$env)
595 })
596 )
597 } else {
598 items <- strsplit(params$export, ",")[[1]]
599 items <- intersect(items, names(private$testExportExprs))
600 values$export <- isolate(
601 lapply(private$testExportExprs[items], function(item) {
602 eval(item$expr, envir = item$env)
603 })
604 )
605 }
606
607 values$export <- sortByName(values$export, method = sortMethod)
608 }
609
610 # Make sure input, output, and export are all named lists (at this
611 # point, they could be unnamed if they are empty lists). This is so
612 # that the resulting object is represented as an object in JSON
613 # instead of an array, and so that the RDS data structure is of a
614 # consistent type.
615 values <- lapply(values, asNamed)
616
617 if (length(values) == 0) {
618 return(httpResponse(400, "text/plain",
619 "None of export, input, or output requested."
620 ))
621 }
622
623 if (identical(format, "json")) {
624 content <- toJSON(values, pretty = TRUE)
625 httpResponse(200, "application/json", content)
626
627 } else if (identical(format, "rds")) {
628 tmpfile <- tempfile("shinytest", fileext = ".rds")
629 saveRDS(values, tmpfile)
630 on.exit(unlink(tmpfile), add = TRUE)
631
632 content <- readBin(tmpfile, "raw", n = file.info(tmpfile)$size)
633 httpResponse(200, "application/octet-stream", content)
634
635 } else {
636 httpResponse(400, "text/plain", paste("Invalid format requested:", format))
637 }
638 }
639 )
640 },
641
642 # Get the snapshotPreprocessOutput function for an output name. If no preprocess
643 # function has been set, return the identity function.
644 getSnapshotPreprocessOutput = function(name) {
645 fun <- attr(private$.outputs[[name]], "snapshotPreprocess", exact = TRUE)
646 fun %||% identity
647 },
648
649 # Get the snapshotPreprocessInput function for an input name. If no preprocess
650 # function has been set, return the identity function.
651 getSnapshotPreprocessInput = function(name) {
652 fun <- private$.input$getMeta(name, "shiny.snapshot.preprocess")
653 fun %||% identity
654 },
655
656 # See cycleStartAction
657 startCycle = function() {
658 # TODO: This should check for busyCount == 0L, and remove the checks from
659 # the call sites
660 if (private$cycleStartActionQueue$size() > 0) {
661 head <- private$cycleStartActionQueue$remove()
662
663 # After we execute the current cycleStartAction (head), there may be
664 # more items left on the queue. If the current busyCount > 0, then that
665 # means an async task is running; whenever that task finishes, it will
666 # decrement the busyCount back to 0 and a startCycle will then be
667 # scheduled. But if the current busyCount is 0, it means that either
668 # busyCount was incremented and then decremented; OR that running head()
669 # never touched busyCount (one example of the latter is that an input
670 # changed that didn't actually cause any observers to be invalidated,
671 # i.e. an input that's used in the body of an observeEvent). Because of
672 # the possibility of the latter case, we need to conditionally schedule
673 # a startCycle ourselves to ensure that the remaining queue items get
674 # processed.
675 #
676 # Since we can't actually tell whether head() increment and decremented
677 # busyCount, it's possible we're calling startCycle spuriously; that's
678 # OK, it's essentially a no-op in that case.
679 on.exit({
680 if (private$busyCount == 0L && private$cycleStartActionQueue$size() > 0L) {
681 later::later(function() {
682 if (private$busyCount == 0L) {
683 private$startCycle()
684 }
685 })
686 }
687 }, add = TRUE)
688
689 head()
690 }
691
692 invisible()
693 }
694 ),
695 public = list(
696 restoreContext = NULL,
697 progressStack = 'Stack', # Stack of progress objects
698 input = 'reactivevalues', # Externally-usable S3 wrapper object for .input
699 output = 'ANY', # Externally-usable S3 wrapper object for .outputs
700 clientData = 'reactivevalues', # Externally-usable S3 wrapper object for .clientData
701 token = 'character', # Used to identify this instance in URLs
702 files = 'Map', # For keeping track of files sent to client
703 downloads = 'Map',
704 closed = logical(0),
705 request = 'ANY', # Websocket request object
706 singletons = character(0), # Tracks singleton HTML fragments sent to the page
707 userData = 'environment',
708 cache = NULL, # A cache object used in the session
709 user = NULL,
710 groups = NULL,
711 options = NULL, # For session-specific shinyOptions()
712
713 initialize = function(websocket) {
714 private$websocket <- websocket
715 self$closed <- FALSE
716 # TODO: Put file upload context in user/app-specific dir if possible
717
718 private$inputMessageQueue <- fastmap::fastqueue()
719 private$cycleStartActionQueue <- fastmap::fastqueue()
720 private$invalidatedOutputValues <- Map$new()
721 private$invalidatedOutputErrors <- Map$new()
722 private$fileUploadContext <- FileUploadContext$new()
723 private$closedCallbacks <- Callbacks$new()
724 private$flushCallbacks <- Callbacks$new()
725 private$flushedCallbacks <- Callbacks$new()
726 private$inputReceivedCallbacks <- Callbacks$new()
727 private$unhandledErrorCallbacks <- Callbacks$new()
728 private$.input <- ReactiveValues$new(dedupe = FALSE, label = "input")
729 private$.clientData <- ReactiveValues$new(dedupe = TRUE, label = "clientData")
730 private$timingRecorder <- ShinyServerTimingRecorder$new()
731 self$progressStack <- fastmap::faststack()
732 self$files <- Map$new()
733 self$downloads <- Map$new()
734 self$userData <- new.env(parent = emptyenv())
735
736 self$input <- .createReactiveValues(private$.input, readonly=TRUE)
737 self$clientData <- .createReactiveValues(private$.clientData, readonly=TRUE)
738
739 self$output <- .createOutputWriter(self)
740
741 self$token <- createUniqueId(16)
742 private$.outputs <- list()
743 private$.outputOptions <- list()
744
745 # Copy app-level options
746 self$options <- getCurrentAppState()$options
747
748 self$cache <- cachem::cache_mem(max_size = 200 * 1024^2)
749
750 private$bookmarkCallbacks <- Callbacks$new()
751 private$bookmarkedCallbacks <- Callbacks$new()
752 private$restoreCallbacks <- Callbacks$new()
753 private$restoredCallbacks <- Callbacks$new()
754
755 private$testMode <- getShinyOption("testmode", default = FALSE)
756 private$enableTestSnapshot()
757
758 # This `withReactiveDomain` is used only to satisfy the reactlog, so that
759 # it knows to scope this reactiveVal to this session.
760 # https://github.com/rstudio/shiny/pull/3182
761 withReactiveDomain(self,
762 private$currentThemeDependency <- reactiveVal(0, label = "Theme Counter")
763 )
764
765 private$registerSessionEndCallbacks()
766
767 if (!is.null(websocket$request$HTTP_SHINY_SERVER_CREDENTIALS)) {
768 try({
769 creds <- safeFromJSON(websocket$request$HTTP_SHINY_SERVER_CREDENTIALS)
770 self$user <- creds$user
771 self$groups <- creds$groups
772 }, silent=FALSE)
773 }
774
775 # session$request should throw an error if httpuv doesn't have
776 # websocket$request, but don't throw it until a caller actually
777 # tries to access session$request
778 delayedAssign('request', websocket$request, assign.env = self)
779
780 private$sendMessage(
781 config = list(
782 workerId = workerId(),
783 sessionId = self$token,
784 user = self$user
785 )
786 )
787 },
788 startTiming = function(guid) {
789 if (!is.null(guid)) {
790 private$timingRecorder$start(guid)
791 self$onFlush(private$timingRecorder$stop)
792 }
793 },
794 requestFlush = function() {
795 appsNeedingFlush$set(self$token, self)
796 },
797 .scheduleTask = function(millis, callback) {
798 scheduleTask(millis, callback)
799 },
800 .now = function(){
801 getTimeMs()
802 },
803 rootScope = function() {
804 self
805 },
806 makeScope = function(namespace) {
807 ns <- NS(namespace)
808
809 # Private items for this scope. Can't be part of the scope object because
810 # `$<-.session_proxy` doesn't allow assignment on overidden names.
811 bookmarkCallbacks <- Callbacks$new()
812 restoreCallbacks <- Callbacks$new()
813 restoredCallbacks <- Callbacks$new()
814 bookmarkExclude <- character(0)
815
816 scope <- createSessionProxy(self,
817 input = .createReactiveValues(private$.input, readonly = TRUE, ns = ns),
818 output = .createOutputWriter(self, ns = ns),
819 sendInputMessage = function(inputId, message) {
820 .subset2(self, "sendInputMessage")(ns(inputId), message)
821 },
822 registerDataObj = function(name, data, filterFunc) {
823 .subset2(self, "registerDataObj")(ns(name), data, filterFunc)
824 },
825 ns = ns,
826 makeScope = function(namespace) {
827 self$makeScope(ns(namespace))
828 },
829
830 setBookmarkExclude = function(names) {
831 bookmarkExclude <<- names
832 },
833 getBookmarkExclude = function() {
834 bookmarkExclude
835 },
836 onBookmark = function(fun) {
837 if (!is.function(fun) || length(fun) != 1) {
838 stop("`fun` must be a function that takes one argument")
839 }
840 bookmarkCallbacks$register(fun)
841 },
842 onBookmarked = function(fun) {
843 stop("onBookmarked() can't be used in a module.")
844 },
845 onRestore = function(fun) {
846 if (!is.function(fun) || length(fun) != 1) {
847 stop("`fun` must be a function that takes one argument")
848 }
849 restoreCallbacks$register(fun)
850 },
851 onRestored = function(fun) {
852 if (!is.function(fun) || length(fun) != 1) {
853 stop("`fun` must be a function that takes one argument")
854 }
855 restoredCallbacks$register(fun)
856 },
857 exportTestValues = function(..., quoted_ = FALSE, env_ = parent.frame()) {
858 if (quoted_) {
859 dots <- list(...)
860 } else {
861 dots <- eval(substitute(alist(...)))
862 }
863
864 if (any_unnamed(dots))
865 stop("exportTestValues: all arguments must be named.")
866
867 names(dots) <- ns(names(dots))
868
869 do.call(
870 .subset2(self, "exportTestValues"),
871 c(dots, quoted_ = TRUE, env_ = env_),
872 quote = TRUE
873 )
874 }
875 )
876
877 # Given a char vector, return a logical vector indicating which of those
878 # strings are names of things in the namespace.
879 filterNamespace <- function(x) {
880 nsString <- paste0(namespace, ns.sep)
881 substr(x, 1, nchar(nsString)) == nsString
882 }
883
884 # Given a char vector of namespaced names, return a char vector of corresponding
885 # names with namespace prefix removed.
886 unNamespace <- function(x) {
887 if (!all(filterNamespace(x))) {
888 stop("x contains strings(s) that do not have namespace prefix ", namespace)
889 }
890
891 nsString <- paste0(namespace, ns.sep)
892 substring(x, nchar(nsString) + 1)
893 }
894
895 # Given a restore state object (a list), return a modified version that's
896 # scoped to this namespace.
897 scopeRestoreState <- function(state) {
898 # State is a list. We need to copy and transform some things for the
899 # scope.
900 scopeState <- state
901 # `values` is an environment and we don't want to modify the original.
902 scopeState$values <- new.env(parent = emptyenv())
903
904 # Keep only inputs that are in the scope, and rename them
905 scopeState$input <- scopeState$input[filterNamespace(names(scopeState$input))]
906 names(scopeState$input) <- unNamespace(names(scopeState$input))
907
908 # Same for values. This is an environment so we have to handle a little
909 # differently.
910 origNames <- names(state$values)
911 origNames <- origNames[filterNamespace(origNames)]
912 lapply(origNames, function(origName) {
913 scopedName <- unNamespace(origName)
914 scopeState$values[[scopedName]] <- state$values[[origName]]
915 })
916
917 if (!is.null(state$dir)) {
918 dir <- file.path(state$dir, namespace)
919 if (dirExists(dir))
920 scopeState$dir <- dir
921 }
922
923 scopeState
924 }
925
926 # When scope is created, register these bookmarking callbacks on the main
927 # session object. They will invoke the scope's own callbacks, if any are
928 # present.
929 self$onBookmark(function(state) {
930 # Exit if no user-defined callbacks.
931 if (bookmarkCallbacks$count() == 0)
932 return()
933
934 scopeState <- ShinySaveState$new(scope$input, scope$getBookmarkExclude())
935
936 # Create subdir for this scope
937 if (!is.null(state$dir)) {
938 scopeState$dir <- file.path(state$dir, namespace)
939 if (!dirExists(scopeState$dir)) {
940 res <- dir.create(scopeState$dir)
941 if (res == FALSE) {
942 stop("Error creating subdirectory for scope ", namespace)
943 }
944 }
945 }
946
947 # Invoke the callback on the scopeState object
948 bookmarkCallbacks$invoke(scopeState)
949
950 # Copy `values` from scopeState to state, adding namespace
951 if (length(scopeState$values) != 0) {
952 if (any_unnamed(scopeState$values)) {
953 stop("All scope values in must be named.")
954 }
955
956 lapply(names(scopeState$values), function(origName) {
957 scopedName <- ns(origName)
958 state$values[[scopedName]] <- scopeState$values[[origName]]
959 })
960 }
961 })
962
963 self$onRestore(function(state) {
964 # Exit if no user-defined callbacks.
965 if (restoreCallbacks$count() == 0)
966 return()
967
968 scopeState <- scopeRestoreState(state)
969 # Invoke user callbacks
970 restoreCallbacks$invoke(scopeState)
971 })
972
973 self$onRestored(function(state) {
974 # Exit if no user-defined callbacks.
975 if (restoredCallbacks$count() == 0)
976 return()
977
978 scopeState <- scopeRestoreState(state)
979 # Invoke user callbacks
980 restoredCallbacks$invoke(scopeState)
981 })
982
983 # Returns the excluded names with the scope's ns prefix on them.
984 private$registerBookmarkExclude(function() {
985 excluded <- scope$getBookmarkExclude()
986 ns(excluded)
987 })
988
989 scope
990 },
991 ns = function(id) {
992 NS(NULL, id)
993 },
994
995 # Freeze a value until the flush cycle completes
996 freezeValue = function(x, name) {
997 if (!is.reactivevalues(x))
998 stop("x must be a reactivevalues object")
999
1000 impl <- .subset2(x, 'impl')
1001 key <- .subset2(x, 'ns')(name)
1002
1003 is_input <- identical(impl, private$.input)
1004
1005 # There's no good reason for us not to just do force=TRUE, except that we
1006 # know this fixes problems for freezeReactiveValue(input) but we don't
1007 # currently even know what you would use freezeReactiveValue(rv) for. In
1008 # the spirit of not breaking things we don't understand, we're making as
1009 # targeted a fix as possible, while emitting a deprecation warning (below)
1010 # that should help us gather more data about the other case.
1011 impl$freeze(key, invalidate = is_input)
1012
1013 if (is_input) {
1014 # Notify the client that this input was frozen. The client will ensure
1015 # that the next time it sees a value for that input, even if the value
1016 # has not changed from the last known value of that input, it will be
1017 # sent to the server anyway.
1018 private$sendMessage(frozen = list(
1019 ids = list(key)
1020 ))
1021 } else {
1022 if (getOption("shiny.deprecation.messages", TRUE) && getOption("shiny.deprecation.messages.freeze", TRUE)) {
1023 rlang::warn(
1024 "Support for calling freezeReactiveValue() with non-`input` reactiveValues objects is soft-deprecated, and may be removed in a future version of Shiny. (See https://github.com/rstudio/shiny/issues/3063)",
1025 .frequency = "once", .frequency_id = "freezeReactiveValue")
1026 }
1027 }
1028
1029 self$onFlushed(function() impl$thaw(key))
1030 },
1031
1032 onSessionEnded = function(sessionEndedCallback) {
1033 "Registers the given callback to be invoked when the session is closed
1034 (i.e. the connection to the client has been severed). The return value
1035 is a function which unregisters the callback. If multiple callbacks are
1036 registered, the order in which they are invoked is not guaranteed."
1037 return(private$closedCallbacks$register(sessionEndedCallback))
1038 },
1039 onEnded = function(endedCallback) {
1040 "Synonym for onSessionEnded"
1041 return(self$onSessionEnded(endedCallback))
1042 },
1043 onInputReceived = function(callback) {
1044 "Registers the given callback to be invoked when the session receives
1045 new data from the client."
1046 return(private$inputReceivedCallbacks$register(callback))
1047 },
1048 onUnhandledError = function(callback) {
1049 "Registers the callback to be invoked when an unhandled error occurs."
1050 return(private$unhandledErrorCallbacks$register(callback))
1051 },
1052 unhandledError = function(e, close = TRUE) {
1053 "Call the global and session unhandled error handlers and then close the
1054 session if the error is fatal."
1055 if (close) {
1056 class(e) <- c("shiny.error.fatal", class(e))
1057 }
1058
1059 # For fatal errors, always log.
1060 # For non-fatal errors, only log if we haven't seen this error before.
1061 if (close || !has_seen_otel_exception(e)) {
1062 otel_log(
1063 if (close) "Fatal error" else "Unhandled error",
1064 severity = if (close) "fatal" else "error",
1065 attributes = otel::as_attributes(list(
1066 session.id = self$token,
1067 error = get_otel_error_obj(e)
1068 ))
1069 )
1070 }
1071
1072 private$unhandledErrorCallbacks$invoke(e, onError = printError)
1073 .globals$onUnhandledErrorCallbacks$invoke(e, onError = printError)
1074
1075 if (close) self$close()
1076 },
1077 close = function() {
1078 if (!self$closed) {
1079 private$websocket$close()
1080 }
1081 },
1082 wsClosed = function() {
1083 self$closed <- TRUE
1084 for (output in private$.outputs) {
1085 output$suspend()
1086 }
1087 # ..stacktraceon matches with the top-level ..stacktraceoff..
1088 withReactiveDomain(self, {
1089 otel_span_session_end(domain = self, {
1090 private$closedCallbacks$invoke(onError = printError, ..stacktraceon = TRUE)
1091 })
1092 })
1093 },
1094 isClosed = function() {
1095 return(self$closed)
1096 },
1097 isEnded = function() {
1098 return(self$isClosed())
1099 },
1100 setShowcase = function(value) {
1101 private$showcase <- !is.null(value) && as.logical(value)
1102 },
1103
1104 allowReconnect = function(value) {
1105 if (!(identical(value, TRUE) || identical(value, FALSE) || identical(value, "force"))) {
1106 stop('value must be TRUE, FALSE, or "force"')
1107 }
1108 private$write(toJSON(list(allowReconnect = value)))
1109 },
1110
1111 defineOutput = function(name, func, label) {
1112 "Binds an output generating function to this name. The function can either
1113 take no parameters, or have named parameters for \\code{name} and
1114 \\code{shinysession} (in the future this list may expand, so it is a good idea
1115 to also include \\code{...} in your function signature)."
1116
1117 # jcheng 08/31/2012: User submitted an example of a dynamically calculated
1118 # name not working unless name was eagerly evaluated. Yikes!
1119 force(name)
1120
1121 # If overwriting an output object, destroy the previous copy of it
1122 if (!is.null(private$.outputs[[name]])) {
1123 private$.outputs[[name]]$destroy()
1124 }
1125
1126 if (is.null(func)) {
1127 # If func is null, give it an "empty" output function so it can go
1128 # through the logic below. If we simply returned at this point, the
1129 # previous output (if any) would continue to show in the client.
1130 func <- missingOutput
1131 }
1132
1133 if (is.function(func)) {
1134 # Extract any output attributes attached to the render function. These
1135 # will be attached to the observer after it's created.
1136 outputAttrs <- attr(func, "outputAttrs", TRUE)
1137
1138 # Save this for getOutput purposes
1139 outputAttrs$renderFunc <- func
1140
1141 funcFormals <- formals(func)
1142 # ..stacktraceon matches with the top-level ..stacktraceoff.., because
1143 # the observer we set up below has ..stacktraceon=FALSE
1144 func <- wrapFunctionLabel(func, paste0("output$", name), ..stacktraceon = TRUE)
1145 if (length(funcFormals) != 0) {
1146 orig <- func
1147 func <- function() {
1148 orig(name=name, shinysession=self)
1149 }
1150 }
1151
1152 # Preserve source reference and file information when formatting the
1153 # label for display in the reactive graph
1154 srcref <- attr(label, "srcref")
1155 srcfile <- attr(label, "srcfile")
1156 label <- sprintf('output$%s', name)
1157 attr(label, "srcref") <- srcref
1158 attr(label, "srcfile") <- srcfile
1159
1160 # Do not bind this `observe()` call
1161 obs <- with_no_otel_collect(observe(..stacktraceon = FALSE, {
1162
1163 private$sendMessage(recalculating = list(
1164 name = name, status = 'recalculating'
1165 ))
1166
1167 # This shinyCallingHandlers should maybe be at a higher level,
1168 # to include the $then/$catch calls below?
1169 hybrid_chain(
1170 hybrid_chain(
1171 {
1172 private$withCurrentOutput(name, {
1173 maybe_with_otel_span_reactive_update({
1174 shinyCallingHandlers(func())
1175 }, domain = self)
1176 })
1177 },
1178 catch = function(cond) {
1179 if (inherits(cond, "shiny.custom.error")) {
1180 if (isTRUE(getOption("show.error.messages"))) printError(cond)
1181 structure(list(), class = "try-error", condition = cond)
1182 } else if (inherits(cond, "shiny.output.cancel")) {
1183 structure(list(), class = "cancel-output")
1184 } else if (inherits(cond, "shiny.output.progress")) {
1185 structure(list(), class = "progress-output")
1186 } else if (cnd_inherits(cond, "shiny.silent.error")) {
1187 # The error condition might have been chained by
1188 # foreign code, e.g. dplyr. Find the original error.
1189 while (!inherits(cond, "shiny.silent.error")) {
1190 cond <- cond$parent
1191 }
1192 # Don't let shiny.silent.error go through the normal stop
1193 # path of try, because we don't want it to print. But we
1194 # do want to try to return the same looking result so that
1195 # the code below can send the error to the browser.
1196 structure(list(), class = "try-error", condition = cond)
1197 } else {
1198 if (isTRUE(getOption("show.error.messages"))) printError(cond)
1199 if (getOption("shiny.sanitize.errors", FALSE)) {
1200 cond <- sanitized_error()
1201 }
1202 self$unhandledError(cond, close = FALSE)
1203 invisible(structure(list(), class = "try-error", condition = cond))
1204 }
1205 }
1206 ),
1207 function(value) {
1208 # Needed so that Shiny knows to flush the outputs. Even if no
1209 # outputs/errors are queued, it's necessary to flush so that the
1210 # client knows that progress is over.
1211 self$requestFlush()
1212
1213 if (inherits(value, "progress-output")) {
1214 # This is the case where an output needs to compute for longer
1215 # than this reactive flush. We put the output into progress mode
1216 # (i.e. adding .recalculating) with a special flag that means
1217 # the progress indication should not be cleared until this
1218 # specific output receives a new value or error.
1219 self$showProgress(name, persistent=TRUE)
1220
1221 # It's conceivable that this output already ran successfully
1222 # within this reactive flush, in which case we could either show
1223 # the new output while simultaneously making it .recalculating;
1224 # or we squelch the new output and make whatever output is in
1225 # the client .recalculating. I (jcheng) decided on the latter as
1226 # it seems more in keeping with what we do with these kinds of
1227 # intermediate output values/errors in general, i.e. ignore them
1228 # and wait until we have a final answer. (Also kind of feels
1229 # like a bug in the app code if you routinely have outputs that
1230 # are executing successfully, only to be invalidated again
1231 # within the same reactive flush--use priority to fix that.)
1232 private$invalidatedOutputErrors$remove(name)
1233 private$invalidatedOutputValues$remove(name)
1234
1235 # It's important that we return so that the existing output in
1236 # the client remains untouched.
1237 return()
1238 }
1239
1240 private$sendMessage(recalculating = list(
1241 name = name, status = 'recalculated'
1242 ))
1243
1244 if (inherits(value, "cancel-output")) {
1245 return()
1246 }
1247
1248 private$invalidatedOutputErrors$remove(name)
1249 private$invalidatedOutputValues$remove(name)
1250
1251 if (inherits(value, 'try-error')) {
1252 cond <- attr(value, 'condition')
1253 type <- setdiff(class(cond), c('simpleError', 'error', 'condition'))
1254 private$invalidatedOutputErrors$set(
1255 name,
1256 list(message = cond$message,
1257 call = utils::capture.output(print(cond$call)),
1258 type = if (length(type)) type))
1259 }
1260 else
1261 private$invalidatedOutputValues$set(name, value)
1262 }
1263 )
1264 }, suspended=private$shouldSuspend(name), label=label))
1265
1266 # If any output attributes were added to the render function attach
1267 # them to observer.
1268 lapply(names(outputAttrs), function(name) {
1269 attr(obs, name) <- outputAttrs[[name]]
1270 })
1271
1272 obs$onInvalidate(function() {
1273 self$showProgress(name)
1274 })
1275
1276 private$.outputs[[name]] <- obs
1277 if (is.null(private$.outputOptions[[name]]))
1278 private$.outputOptions[[name]] <- list()
1279 }
1280 else {
1281 rlang::abort(c(
1282 paste0("Unexpected ", class(func)[[1]], " object for output$", name),
1283 i = "Did you forget to use a render function?"
1284 ))
1285 }
1286 },
1287 getOutput = function(name) {
1288 attr(private$.outputs[[name]], "renderFunc", exact = TRUE)
1289 },
1290 flushOutput = function() {
1291 if (private$busyCount > 0)
1292 return()
1293
1294 appsNeedingFlush$remove(self$token)
1295
1296 if (self$isClosed())
1297 return()
1298
1299 # This is the only place in the session where the restoreContext is
1300 # flushed.
1301 if (!is.null(self$restoreContext))
1302 self$restoreContext$flushPending()
1303
1304 # Return TRUE if there's any stuff to send to the client.
1305 hasPendingUpdates <- function() {
1306 # Even though progressKeys isn't sent to the client, we use it in this
1307 # check. This is because if it is non-empty, sending `values` to the
1308 # client tells it that the flushReact loop is finished, and the client
1309 # then knows to stop showing progress.
1310 return(
1311 length(private$progressKeys) != 0 ||
1312 length(private$invalidatedOutputValues) != 0 ||
1313 length(private$invalidatedOutputErrors) != 0 ||
1314 private$inputMessageQueue$size() != 0
1315 )
1316 }
1317
1318 withReactiveDomain(self, {
1319 # ..stacktraceon matches with the top-level ..stacktraceoff..
1320 private$flushCallbacks$invoke(..stacktraceon = TRUE)
1321
1322 # Schedule execution of onFlushed callbacks
1323 on.exit({
1324 withReactiveDomain(self, {
1325 # ..stacktraceon matches with the top-level ..stacktraceoff..
1326 private$flushedCallbacks$invoke(..stacktraceon = TRUE)
1327 })
1328 }, add = TRUE)
1329
1330 if (!hasPendingUpdates()) {
1331 # Normally, if there are no updates, simply return without sending
1332 # anything to the client. But if we are in test mode, we still want to
1333 # send a message with blank `values`, so that the client knows that
1334 # any changed inputs have been received by the server and processed.
1335 if (isTRUE(private$testMode)) {
1336 private$sendMessage( values = list() )
1337 }
1338 return(invisible())
1339 }
1340
1341 private$progressKeys <- character(0)
1342 values <- as.list(private$invalidatedOutputValues)
1343 private$invalidatedOutputValues <- Map$new()
1344 errors <- as.list(private$invalidatedOutputErrors)
1345 private$invalidatedOutputErrors <- Map$new()
1346 inputMessages <- private$inputMessageQueue$as_list()
1347 private$inputMessageQueue$reset()
1348
1349 if (isTRUE(private$testMode)) {
1350 private$storeOutputValues(mergeVectors(values, errors))
1351 }
1352
1353 private$sendMessage(
1354 errors = errors,
1355 values = values,
1356 inputMessages = inputMessages
1357 )
1358 })
1359 },
1360 # Schedule an action to execute not (necessarily) now, but when no observers
1361 # that belong to this session are busy executing. This helps prevent (but
1362 # does not guarantee) inputs and reactive values from changing underneath
1363 # async observers as they run.
1364 cycleStartAction = function(callback) {
1365 private$cycleStartActionQueue$add(callback)
1366 # If no observers are running in this session, we're safe to proceed.
1367 # Otherwise, startCycle() will be called later, via decrementBusyCount().
1368 if (private$busyCount == 0L) {
1369 private$startCycle()
1370 }
1371 },
1372 showProgress = function(id, persistent=FALSE) {
1373 'Send a message to the client that recalculation of the output identified
1374 by \\code{id} is in progress. There is currently no mechanism for
1375 explicitly turning off progress for an output component; instead, all
1376 progress is implicitly turned off when flushOutput is next called.
1377
1378 You can use persistent=TRUE if the progress for this output component
1379 should stay on beyond the flushOutput (or any subsequent flushOutputs); in
1380 that case, progress is only turned off (and the persistent flag cleared)
1381 when the output component receives a value or error, or, if
1382 showProgress(id, persistent=FALSE) is called and a subsequent flushOutput
1383 occurs.'
1384
1385 # If app is already closed, be sure not to show progress, otherwise we
1386 # will get an error because of the closed websocket
1387 if (self$closed)
1388 return()
1389
1390 if (!id %in% private$progressKeys) {
1391 private$progressKeys <- c(private$progressKeys, id)
1392 }
1393
1394 self$sendProgress('binding', list(id = id, persistent = persistent))
1395 },
1396 sendProgress = function(type, message) {
1397 private$sendMessage(
1398 progress = list(type = type, message = message)
1399 )
1400 },
1401 sendNotification = function(type, message) {
1402 private$sendMessage(
1403 notification = list(type = type, message = message)
1404 )
1405 },
1406 sendModal = function(type, message) {
1407 private$sendMessage(
1408 modal = list(type = type, message = message)
1409 )
1410 },
1411
1412 getCurrentTheme = function() {
1413 private$currentThemeDependency()
1414 getCurrentTheme()
1415 },
1416
1417 setCurrentTheme = function(theme) {
1418 # This function does three things: (1) sets theme as the current
1419 # bootstrapTheme, (2) re-executes any registered theme dependencies, and
1420 # (3) sends the resulting dependencies to the client.
1421
1422 if (!is_bs_theme(theme)) {
1423 stop("`session$setCurrentTheme()` expects a `bslib::bs_theme()` object.", call. = FALSE)
1424 }
1425
1426 # Switching Bootstrap versions has weird & complex consequences
1427 # for the JS logic, so we forbid it
1428 current_version <- bslib::theme_version(getCurrentTheme())
1429 next_version <- bslib::theme_version(theme)
1430 if (!identical(current_version, next_version)) {
1431 stop(
1432 "session$setCurrentTheme() cannot be used to change the Bootstrap version ",
1433 "from ", current_version, " to ", next_version, ". ",
1434 "Try using `bs_theme(version = ", next_version, ")` for initial theme.",
1435 call. = FALSE
1436 )
1437 }
1438
1439 # Note that this will automatically scope to the session.
1440 setCurrentTheme(theme)
1441
1442 # Invalidate
1443 private$currentThemeDependency(isolate(private$currentThemeDependency()) + 1)
1444
1445 # Call any theme dependency functions and make sure we get a list of deps back
1446 funcs <- getShinyOption("themeDependencyFuncs", default = list())
1447 deps <- lapply(funcs, function(func) {
1448 deps <- func(theme)
1449 if (length(deps) == 0) return(NULL)
1450 if (inherits(deps, "html_dependency")) return(list(deps))
1451 is_dep <- vapply(deps, inherits, logical(1), "html_dependency")
1452 if (all(is_dep)) return(deps)
1453 stop("All registerThemeDependency() functions must yield htmlDependency() object(s)", call. = FALSE)
1454 })
1455 # Work with a flat list of dependencies
1456 deps <- unlist(dropNulls(deps), recursive = FALSE)
1457 # Add a special flag to let Shiny.renderDependencies() know that, even
1458 # though we've already rendered the dependency, that we need to re-render
1459 # the stylesheets
1460 deps <- lapply(deps, function(dep) {
1461 dep$restyle <- TRUE
1462 dep
1463 })
1464
1465 # Send any dependencies to be re-rendered
1466 if (length(deps)) {
1467 insertUI(selector = "body", where = "afterEnd", ui = tagList(deps))
1468 }
1469 },
1470
1471 dispatch = function(msg) {
1472 method <- paste('@', msg$method, sep='')
1473 func <- try(self[[method]], silent = TRUE)
1474 if (inherits(func, 'try-error')) {
1475 private$sendErrorResponse(msg, paste('Unknown method', msg$method))
1476 }
1477
1478 value <- try(do.call(func, as.list(append(msg$args, msg$blobs))),
1479 silent=TRUE)
1480 if (inherits(value, 'try-error')) {
1481 private$sendErrorResponse(msg, conditionMessage(attr(value, 'condition')))
1482 }
1483 else {
1484 private$sendResponse(msg, value)
1485 }
1486 },
1487 sendBinaryMessage = function(type, message) {
1488 typeBytes <- charToRaw(type)
1489 if (length(typeBytes) > 255) {
1490 stop("'type' argument is too long")
1491 }
1492 private$write(c(as.raw(length(typeBytes)), typeBytes, message))
1493 },
1494 sendCustomMessage = function(type, message) {
1495 data <- list()
1496 data[[type]] <- message
1497 private$sendMessage(custom = data)
1498 },
1499 sendInputMessage = function(inputId, message) {
1500 data <- list(id = inputId, message = message)
1501
1502 private$inputMessageQueue$add(data)
1503 # Needed so that Shiny knows to actually flush the input message queue
1504 self$requestFlush()
1505 },
1506 onFlush = function(flushCallback, once = TRUE) {
1507 if (!isTRUE(once)) {
1508 return(private$flushCallbacks$register(flushCallback))
1509 } else {
1510 dereg <- private$flushCallbacks$register(function() {
1511 dereg()
1512 flushCallback()
1513 })
1514 return(dereg)
1515 }
1516 },
1517 onFlushed = function(flushedCallback, once = TRUE) {
1518 if (!isTRUE(once)) {
1519 return(private$flushedCallbacks$register(flushedCallback))
1520 } else {
1521 dereg <- private$flushedCallbacks$register(function() {
1522 dereg()
1523 flushedCallback()
1524 })
1525 return(dereg)
1526 }
1527 },
1528
1529 getCurrentOutputInfo = function() {
1530 name <- private$currentOutputName
1531 if (is.null(name)) {
1532 return(NULL)
1533 }
1534
1535 if (!is.null(private$outputInfo[[name]])) {
1536 return(private$outputInfo[[name]])
1537 }
1538
1539 # The following code will only run the first time this function has been
1540 # called for this output.
1541
1542 tmp_info <- list(name = name)
1543
1544 # cd_names() returns names of all items in clientData, without taking a
1545 # reactive dependency. It is a function and it's memoized, so that we do
1546 # the (relatively) expensive isolate(names(...)) call only when needed,
1547 # and at most one time in this function.
1548 cd_names <- isolate(names(self$clientData))
1549
1550 # parseCssColors() currently errors out if you hand it any NAs
1551 # This'll make sure we're always working with a string (and if
1552 # that string isn't a valid CSS color, will return NA)
1553 # https://github.com/rstudio/htmltools/issues/161
1554 parse_css_colors <- function(x) {
1555 htmltools::parseCssColors(x %||% "", mustWork = FALSE)
1556 }
1557
1558
1559 # This function conditionally adds an item to tmp_info (for "width", it
1560 # would create tmp_info$width). It is added _if_ there is an entry in
1561 # clientData like "output_foo_width", where "foo" is the name of the
1562 # output. The first time `tmp_info$width()` is called, it creates a
1563 # reactive expression that reads `clientData$output_foo_width`, saves it,
1564 # then invokes that reactive. On subsequent calls, the reactive already
1565 # exists, so it simply invokes it.
1566 #
1567 # The reason it creates the reactive only on first use is so that it
1568 # doesn't spuriously create reactives.
1569 #
1570 # This function essentially generalizes the code below for names other
1571 # than just "width".
1572 #
1573 # width_name <- paste0("output_", name, "_width")
1574 # if (width_name %in% cd_names()) {
1575 # width_r <- NULL
1576 # tmp_info$width <- function() {
1577 # if (is.null(width_r)) {
1578 # width_r <<- reactive({
1579 # parse_css_colors(self$clientData[[width_name]])
1580 # })
1581 # }
1582 #
1583 # width_r()
1584 # }
1585 # }
1586 add_conditional_reactive <- function(prop, wrapfun = identity) {
1587 force(prop)
1588 force(wrapfun)
1589
1590 prop_name <- paste0("output_", name, "_", prop)
1591
1592 # Only add tmp_info$width if clientData has "output_foo_width"
1593 if (prop_name %in% cd_names) {
1594 r <- NULL
1595
1596 # Turn it into a function that creates a reactive on the first
1597 # invocation of getCurrentOutputInfo()$width() and saves it; future
1598 # invocations of getCurrentOutputInfo()$width() use the existing
1599 # reactive and save it.
1600 tmp_info[[prop]] <<- function() {
1601 if (is.null(r)) {
1602 r <<- reactive(label = prop_name, {
1603 wrapfun(self$clientData[[prop_name]])
1604 })
1605 }
1606
1607 r()
1608 }
1609 }
1610 }
1611
1612
1613 # Note that all the following clientData values (which are reactiveValues)
1614 # are wrapped in reactive() so that users can take a dependency on
1615 # particular output info (i.e., just depend on width/height, or just
1616 # depend on bg, fg, etc). To put it another way, if getCurrentOutputInfo()
1617 # simply returned a list of values from self$clientData, than anything
1618 # that calls getCurrentOutputInfo() would take a reactive dependency on
1619 # all of these values.
1620 add_conditional_reactive("width")
1621 add_conditional_reactive("height")
1622 add_conditional_reactive("bg", parse_css_colors)
1623 add_conditional_reactive("fg", parse_css_colors)
1624 add_conditional_reactive("accent", parse_css_colors)
1625 add_conditional_reactive("font")
1626
1627 private$outputInfo[[name]] <- tmp_info
1628 private$outputInfo[[name]]
1629 },
1630
1631 createBookmarkObservers = function() {
1632 # This registers observers for bookmarking to work.
1633
1634 # Get bookmarking config
1635 store <- getShinyOption("bookmarkStore", default = "disable")
1636 if (store == "disable")
1637 return()
1638
1639 # Warn if trying to enable save-to-server bookmarking on a version of SS,
1640 # SSP, or Connect that doesn't support it.
1641 if (store == "server" && inShinyServer() &&
1642 is.null(getShinyOption("save.interface", default = NULL)))
1643 {
1644 showNotification(
1645 "This app tried to enable saved-to-server bookmarking, but it is not supported by the hosting environment.",
1646 duration = NULL, type = "warning", session = self
1647 )
1648 return()
1649 }
1650
1651 withReactiveDomain(self, {
1652 # This observer fires when the bookmark button is clicked.
1653 observeEvent(self$input[["._bookmark_"]], {
1654 self$doBookmark()
1655 })
1656
1657 # If there was an error initializing the current restore context, show
1658 # notification in the client.
1659 observe({
1660 rc <- getCurrentRestoreContext()
1661 if (!is.null(rc$initErrorMessage)) {
1662 showNotification(
1663 paste("Error in RestoreContext initialization:", rc$initErrorMessage),
1664 duration = NULL, type = "error"
1665 )
1666 }
1667 })
1668
1669 # Run the onRestore function at the beginning of the flush cycle, but after
1670 # the server function has been executed.
1671 observe({
1672 if (private$restoreCallbacks$count() > 0) {
1673 tryCatch(
1674 withLogErrors(
1675 isolate({
1676 rc <- getCurrentRestoreContext()
1677 if (rc$active) {
1678 restoreState <- getCurrentRestoreContext()$asList()
1679 private$restoreCallbacks$invoke(restoreState)
1680 }
1681 })
1682 ),
1683 error = function(e) {
1684 showNotification(
1685 paste0("Error calling onRestore callback: ", e$message),
1686 duration = NULL, type = "error"
1687 )
1688 }
1689 )
1690 }
1691 }, priority = 1000000)
1692
1693 # Run the onRestored function after the flush cycle completes and information
1694 # is sent to the client.
1695 self$onFlushed(function() {
1696 if (private$restoredCallbacks$count() > 0) {
1697
1698 tryCatch(
1699 withLogErrors(
1700 isolate({
1701 rc <- getCurrentRestoreContext()
1702 if (rc$active) {
1703 restoreState <- getCurrentRestoreContext()$asList()
1704 private$restoredCallbacks$invoke(restoreState)
1705 }
1706 })
1707 ),
1708 error = function(e) {
1709 msg <- paste0("Error calling onRestored callback: ", e$message)
1710 showNotification(msg, duration = NULL, type = "error")
1711 }
1712 )
1713 }
1714 })
1715
1716 }) # withReactiveDomain
1717 },
1718
1719 setBookmarkExclude = function(names) {
1720 private$bookmarkExclude <- names
1721 },
1722 getBookmarkExclude = function() {
1723 scopedExcludes <- lapply(private$getBookmarkExcludeFuns, function(f) f())
1724 scopedExcludes <- unlist(scopedExcludes)
1725
1726 c(private$bookmarkExclude, scopedExcludes)
1727 },
1728
1729 onBookmark = function(fun) {
1730 if (!is.function(fun) || length(fun) != 1) {
1731 stop("`fun` must be a function that takes one argument")
1732 }
1733 private$bookmarkCallbacks$register(fun)
1734 },
1735 onBookmarked = function(fun) {
1736 if (!is.function(fun) || length(fun) != 1) {
1737 stop("`fun` must be a function that takes one argument")
1738 }
1739 private$bookmarkedCallbacks$register(fun)
1740 },
1741 onRestore = function(fun) {
1742 if (!is.function(fun) || length(fun) != 1) {
1743 stop("`fun` must be a function that takes one argument")
1744 }
1745 private$restoreCallbacks$register(fun)
1746 },
1747 onRestored = function(fun) {
1748 if (!is.function(fun) || length(fun) != 1) {
1749 stop("`fun` must be a function that takes one argument")
1750 }
1751 private$restoredCallbacks$register(fun)
1752 },
1753 doBookmark = function() {
1754 # Get bookmarking store config
1755 store <- getShinyOption("bookmarkStore", default = "disable")
1756 if (store == "disable")
1757 return()
1758
1759 tryCatch(
1760 withLogErrors({
1761 saveState <- ShinySaveState$new(
1762 input = self$input,
1763 exclude = self$getBookmarkExclude(),
1764 onSave = function(state) {
1765 private$bookmarkCallbacks$invoke(state)
1766 }
1767 )
1768
1769 if (store == "server") {
1770 url <- saveShinySaveState(saveState)
1771 } else if (store == "url") {
1772 url <- encodeShinySaveState(saveState)
1773 } else {
1774 stop("Unknown store type: ", store)
1775 }
1776
1777 clientData <- self$clientData
1778 url <- paste0(
1779 clientData$url_protocol, "//",
1780 clientData$url_hostname,
1781 if (nzchar(clientData$url_port)) paste0(":", clientData$url_port),
1782 clientData$url_pathname,
1783 "?", url
1784 )
1785
1786
1787 # If onBookmarked callback was provided, invoke it; if not call
1788 # the default.
1789 if (private$bookmarkedCallbacks$count() > 0) {
1790 private$bookmarkedCallbacks$invoke(url)
1791 } else {
1792 showBookmarkUrlModal(url)
1793 }
1794 }),
1795 error = function(e) {
1796 msg <- paste0("Error bookmarking state: ", e$message)
1797 showNotification(msg, duration = NULL, type = "error")
1798 }
1799 )
1800 },
1801
1802 exportTestValues = function(..., quoted_ = FALSE, env_ = parent.frame()) {
1803 # Get a named list of unevaluated expressions.
1804 if (quoted_) {
1805 dots <- list(...)
1806 } else {
1807 dots <- eval(substitute(alist(...)))
1808 }
1809
1810 if (any_unnamed(dots))
1811 stop("exportTestValues: all arguments must be named.")
1812
1813 # Create a named list where each item is a list with an expression and
1814 # environment in which to eval the expression.
1815 items <- lapply(dots, function(expr) {
1816 list(expr = expr, env = env_)
1817 })
1818
1819 private$testExportExprs <- mergeVectors(private$testExportExprs, items)
1820 },
1821
1822 getTestSnapshotUrl = function(input = TRUE, output = TRUE, export = TRUE,
1823 format = "json", sortC = FALSE) {
1824 reqString <- function(group, value) {
1825 if (isTRUE(value))
1826 paste0(group, "=1")
1827 else if (is.character(value))
1828 paste0(group, "=", paste(value, collapse = ","))
1829 else
1830 ""
1831 }
1832 paste(
1833 private$testSnapshotUrl,
1834 reqString("input", input),
1835 reqString("output", output),
1836 reqString("export", export),
1837 reqString("sortC", sortC),
1838 paste0("format=", format),
1839 sep = "&"
1840 )
1841 },
1842
1843 reactlog = function(logEntry) {
1844 # Use sendCustomMessage instead of sendMessage, because the handler in
1845 # shiny-showcase.js only has access to public API of the Shiny object.
1846 if (private$showcase) {
1847 srcref <- logEntry$srcref
1848 srcfile <- logEntry$srcfile
1849 if (!is.null(srcref) && !is.null(srcfile)) {
1850 # only send needed information, not all of reactlog info.
1851 self$sendCustomMessage("showcase-src", list(srcref = srcref, srcfile = srcfile))
1852 }
1853 }
1854 },
1855 reload = function() {
1856 private$sendMessage(reload = TRUE)
1857 },
1858 sendInsertUI = function(selector, multiple, where, content) {
1859 private$sendMessage(
1860 `shiny-insert-ui` = list(
1861 selector = selector,
1862 multiple = multiple,
1863 where = where,
1864 content = content
1865 )
1866 )
1867 },
1868 sendRemoveUI = function(selector, multiple) {
1869 private$sendMessage(
1870 `shiny-remove-ui` = list(
1871 selector = selector,
1872 multiple = multiple
1873 )
1874 )
1875 },
1876 sendInsertTab = function(inputId, liTag, divTag, menuName,
1877 target, position, select) {
1878 private$sendMessage(
1879 `shiny-insert-tab` = list(
1880 inputId = inputId,
1881 liTag = liTag,
1882 divTag = divTag,
1883 menuName = menuName,
1884 target = target,
1885 position = position,
1886 select = select
1887 )
1888 )
1889 },
1890 sendRemoveTab = function(inputId, target) {
1891 private$sendMessage(
1892 `shiny-remove-tab` = list(
1893 inputId = inputId,
1894 target = target
1895 )
1896 )
1897 },
1898 sendChangeTabVisibility = function(inputId, target, type) {
1899 private$sendMessage(
1900 `shiny-change-tab-visibility` = list(
1901 inputId = inputId,
1902 target = target,
1903 type = type
1904 )
1905 )
1906 },
1907 updateQueryString = function(queryString, mode) {
1908 private$sendMessage(updateQueryString = list(
1909 queryString = queryString, mode = mode))
1910 },
1911 resetBrush = function(brushId) {
1912 private$sendMessage(
1913 resetBrush = list(
1914 brushId = brushId
1915 )
1916 )
1917 },
1918
1919 `@uploadInit` = function(fileInfos) {
1920 maxSize <- getOption('shiny.maxRequestSize', 5 * 1024 * 1024)
1921 fileInfos <- lapply(fileInfos, function(fi) {
1922 if (is.null(fi$type))
1923 fi$type <- getContentType(fi$name)
1924 fi
1925 })
1926 sizes <- sapply(fileInfos, function(fi){ fi$size })
1927 if (maxSize > 0 && any(sizes > maxSize)) {
1928 stop("Maximum upload size exceeded")
1929 }
1930
1931 jobId <- private$fileUploadContext$createUploadOperation(fileInfos)
1932 return(list(jobId=jobId,
1933 uploadUrl=paste('session', self$token, 'upload',
1934 paste(jobId, "?w=", workerId(), sep=""),
1935 sep='/')))
1936 },
1937 `@uploadEnd` = function(jobId, inputId) {
1938 fileData <- private$fileUploadContext$getUploadOperation(jobId)$finish()
1939 private$.input$set(inputId, fileData)
1940
1941 setSerializer(inputId, serializerFileInput)
1942 snapshotPreprocessInput(inputId, snapshotPreprocessorFileInput)
1943
1944 invisible()
1945 },
1946 # Provides a mechanism for handling direct HTTP requests that are posted
1947 # to the session (rather than going through the websocket)
1948 handleRequest = function(req) {
1949 # TODO: Turn off caching for the response
1950 subpath <- req$PATH_INFO
1951
1952 matches <- regmatches(subpath,
1953 regexec("^/([a-z]+)/([^?]*)",
1954 subpath,
1955 ignore.case=TRUE))[[1]]
1956 if (length(matches) == 0)
1957 return(httpResponse(400, 'text/html', '<h1>Bad Request</h1>'))
1958
1959 if (matches[2] == 'file') {
1960 savedFile <- self$files$get(URLdecode(matches[3]))
1961 if (is.null(savedFile))
1962 return(httpResponse(404, 'text/html', '<h1>Not Found</h1>'))
1963
1964 return(httpResponse(200, savedFile$contentType, savedFile$data))
1965 }
1966
1967 if (matches[2] == 'upload' && identical(req$REQUEST_METHOD, "POST")) {
1968 job <- private$fileUploadContext$getUploadOperation(matches[3])
1969 if (!is.null(job)) {
1970 fileName <- req$HTTP_SHINY_FILE_NAME
1971 fileType <- req$HTTP_SHINY_FILE_TYPE
1972 fileSize <- req$CONTENT_LENGTH
1973 job$fileBegin()
1974
1975 reqInput <- req$rook.input
1976 while (length(buf <- reqInput$read(2^16)) > 0)
1977 job$fileChunk(buf)
1978
1979 job$fileEnd()
1980
1981 return(httpResponse(200, 'text/plain', 'OK'))
1982 }
1983 }
1984
1985
1986 if (matches[2] == 'download') {
1987
1988 # A bunch of ugliness here. Filenames can be dynamically generated by
1989 # the user code, so we don't know what they'll be in advance. But the
1990 # most reliable way to use non-ASCII filenames for downloads is to
1991 # put the actual filename in the URL. So we will start with URLs in
1992 # the form:
1993 #
1994 # /session/$TOKEN/download/$NAME
1995 #
1996 # When a request matching that pattern is received, we will calculate
1997 # the filename and see if it's non-ASCII; if so, we'll redirect to
1998 #
1999 # /session/$TOKEN/download/$NAME/$FILENAME
2000 #
2001 # And when that pattern is received, we will actually return the file.
2002 # Note that this means the filename and contents could be determined
2003 # a few moments apart from each other (an HTTP roundtrip basically),
2004 # hopefully that won't be enough to matter for anyone.
2005
2006 dlmatches <- regmatches(matches[3],
2007 regexec("^([^/]+)(/[^/]+)?$",
2008 matches[3]))[[1]]
2009 dlname <- URLdecode(dlmatches[2])
2010 download <- self$downloads$get(dlname)
2011 if (is.null(download))
2012 return(httpResponse(404, 'text/html', '<h1>Not Found</h1>'))
2013
2014 filename <- ifelse(is.function(download$filename),
2015 Context$new(getDefaultReactiveDomain(), '[download]')$run(
2016 download$filename
2017 ),
2018 download$filename)
2019
2020 # If the URL does not contain the filename, and the desired filename
2021 # contains non-ASCII characters, then do a redirect with the desired
2022 # name tacked on the end.
2023 if (dlmatches[3] == '' && grepl('[^ -~]', filename)) {
2024
2025 return(httpResponse(302, 'text/html', '<h1>Found</h1>', c(
2026 'Location' = sprintf('%s/%s',
2027 URLencode(dlname, TRUE),
2028 URLencode(filename, TRUE)),
2029 'Cache-Control' = 'no-cache')))
2030 }
2031
2032 # Make temp file with the same extension as the user-visible filename.
2033 # If the extension is not used, some functions such as pdf() and zip()
2034 # may append the extension they expect, meaning the data we want will
2035 # be written to a file other than our temp file (e.g. file1231.zip
2036 # instead of file1231.zip).
2037 ext <- tools::file_ext(filename)
2038 if (nzchar(ext))
2039 ext <- paste(".", ext, sep = "")
2040 tmpdata <- tempfile(fileext = ext)
2041 return(Context$new(getDefaultReactiveDomain(), '[download]')$run(function() {
2042 with_promise_domain(reactivePromiseDomain(), {
2043 captureStackTraces({
2044 self$incrementBusyCount()
2045 hybrid_chain(
2046 # ..stacktraceon matches with the top-level ..stacktraceoff..
2047 try(..stacktraceon..(download$func(tmpdata)), silent = TRUE),
2048 function(result) {
2049 if (inherits(result, 'try-error')) {
2050 unlink(tmpdata)
2051 stop(attr(result, "condition", exact = TRUE))
2052 }
2053 if (!file.exists(tmpdata)) {
2054 # If no file was created, return a 404
2055 return(httpResponse(404, content = "404 Not found"))
2056 }
2057 return(httpResponse(
2058 200,
2059 download$contentType %||% getContentType(filename),
2060 # owned=TRUE means tmpdata will be deleted after response completes
2061 list(file=tmpdata, owned=TRUE),
2062 c(
2063 'Content-Disposition' = ifelse(
2064 dlmatches[3] == '',
2065 paste0(
2066 'attachment; filename="',
2067 gsub('(["\\\\])', '\\\\\\1', filename),
2068 '"'
2069 ),
2070 'attachment'
2071 ),
2072 'Cache-Control'='no-cache')))
2073 },
2074 finally = function() {
2075 self$decrementBusyCount()
2076 }
2077 )
2078 })
2079 })
2080 }))
2081 }
2082
2083 if (matches[2] == 'dataobj') {
2084 # /session/$TOKEN/dataobj/$NAME
2085 dlmatches <- regmatches(matches[3],
2086 regexec("^([^/]+)(/[^/]+)?$",
2087 matches[3]))[[1]]
2088 dlname <- URLdecode(dlmatches[2])
2089 download <- self$downloads$get(dlname)
2090 return(download$filter(download$data, req))
2091 }
2092
2093 return(httpResponse(404, 'text/html', '<h1>Not Found</h1>'))
2094 },
2095 # Send a file to the client
2096 fileUrl = function(name, file, contentType='application/octet-stream') {
2097 "Return a URL for a file to be sent to the client. The file will be base64
2098 encoded and embedded in the URL."
2099 bytes <- file.info(file)$size
2100 if (is.na(bytes))
2101 return(NULL)
2102
2103 fileData <- readBin(file, 'raw', n=bytes)
2104
2105 b64 <- rawToBase64(fileData)
2106 return(paste('data:', contentType, ';base64,', b64, sep=''))
2107 },
2108 registerDownload = function(name, filename, contentType, func) {
2109
2110 self$downloads$set(name, list(filename = filename,
2111 contentType = contentType,
2112 func = func))
2113 return(sprintf('session/%s/download/%s?w=%s',
2114 URLencode(self$token, TRUE),
2115 URLencode(name, TRUE),
2116 workerId()))
2117 },
2118 # register a data object on the server side (for datatable or selectize, etc)
2119 registerDataObj = function(name, data, filterFunc) {
2120 # abusing downloads at the moment
2121 self$downloads$set(name, list(data = data, filter = filterFunc))
2122 return(sprintf('session/%s/dataobj/%s?w=%s&nonce=%s',
2123 URLencode(self$token, TRUE),
2124 URLencode(name, TRUE),
2125 workerId(),
2126 URLencode(createUniqueId(8), TRUE)))
2127 },
2128 # This function suspends observers for hidden outputs and resumes observers
2129 # for un-hidden outputs.
2130 manageHiddenOutputs = function(outputsToCheck = NULL) {
2131 if (is.null(outputsToCheck)) {
2132 outputsToCheck <- names(private$.outputs)
2133 }
2134
2135 # Find hidden state for each output, and suspend/resume accordingly
2136 for (outputName in outputsToCheck) {
2137 if (private$shouldSuspend(outputName)) {
2138 private$.outputs[[outputName]]$suspend()
2139 } else {
2140 private$.outputs[[outputName]]$resume()
2141 }
2142 }
2143 },
2144 # Set the normal and client data input variables. Normally, managing
2145 # inputs doesn't take immediate effect when there are observers that
2146 # are pending execution or currently executing (including having
2147 # started async operations that have yielded control, but not yet
2148 # completed). The `now` argument can force this. It should generally
2149 # not be used, but we're adding it to get around a show-stopping bug
2150 # for Shiny v1.1 (see the call site for more details).
2151 manageInputs = function(data, now = FALSE) {
2152 force(data)
2153 doManageInputs <- function() {
2154 private$inputReceivedCallbacks$invoke(data)
2155
2156 data_names <- names(data)
2157
2158 # Separate normal input variables from client data input variables
2159 clientdata_idx <- grepl("^.clientdata_", data_names)
2160
2161 # Set normal (non-clientData) input values
2162 private$.input$mset(data[data_names[!clientdata_idx]])
2163
2164 # Strip off .clientdata_ from clientdata input names, and set values
2165 input_clientdata <- data[data_names[clientdata_idx]]
2166 names(input_clientdata) <- sub("^.clientdata_", "",
2167 names(input_clientdata))
2168 private$.clientData$mset(input_clientdata)
2169
2170 self$manageHiddenOutputs()
2171 }
2172 if (isTRUE(now)) {
2173 doManageInputs()
2174 } else {
2175 self$cycleStartAction(doManageInputs)
2176 }
2177 },
2178 outputOptions = function(name, ...) {
2179 # If no name supplied, return the list of options for all outputs
2180 if (is.null(name))
2181 return(private$.outputOptions)
2182 if (! name %in% names(private$.outputs))
2183 stop(name, " is not in list of output objects")
2184
2185 opts <- list(...)
2186 # If no options are set, return the options for the specified output
2187 if (length(opts) == 0)
2188 return(private$.outputOptions[[name]])
2189
2190 # Set the appropriate option
2191 validOpts <- c("suspendWhenHidden", "priority")
2192 for (optname in names(opts)) {
2193 if (! optname %in% validOpts)
2194 stop(optname, " is not a valid option")
2195
2196 private$.outputOptions[[name]][[optname]] <- opts[[optname]]
2197 }
2198
2199 # If any changes to suspendWhenHidden, need to re-run manageHiddenOutputs
2200 if ("suspendWhenHidden" %in% names(opts)) {
2201 self$manageHiddenOutputs(name)
2202 }
2203
2204 if ("priority" %in% names(opts)) {
2205 private$.outputs[[name]]$setPriority(opts[['priority']])
2206 }
2207
2208 invisible()
2209 },
2210 incrementBusyCount = function() {
2211 if (private$busyCount == 0L) {
2212 rLog$asyncStart(domain = self)
2213 private$sendMessage(busy = "busy")
2214
2215 otel_span_reactive_update_init(domain = self)
2216 }
2217 private$busyCount <- private$busyCount + 1L
2218 },
2219 decrementBusyCount = function() {
2220 private$busyCount <- private$busyCount - 1L
2221 if (private$busyCount == 0L) {
2222 rLog$asyncStop(domain = self)
2223 private$sendMessage(busy = "idle")
2224 self$requestFlush()
2225 # We defer the call to startCycle() using later(), to defend against
2226 # cycles where we continually call startCycle which causes an observer
2227 # to fire which calls startCycle which causes an observer to fire...
2228 #
2229 # It's OK for these cycles to occur, but we must return control to the
2230 # event loop between iterations (or at least sometimes) in order to not
2231 # make the whole Shiny app go unresponsive.
2232 later::later(function() {
2233 if (private$busyCount == 0L) {
2234 private$startCycle()
2235 }
2236 })
2237
2238 otel_span_reactive_update_teardown(domain = self)
2239 }
2240 }
2241 )
2242 )
2243
2244 .createOutputWriter <- function(shinysession, ns = identity) {
2245 structure(list(impl=shinysession, ns=ns), class='shinyoutput')
2246 }
2247
2248 #' @export
2249 `$<-.shinyoutput` <- function(x, name, value) {
2250 name <- .subset2(x, 'ns')(name)
2251
2252 label <- deparse(substitute(value))
2253 if (length(substitute(value)) > 1) {
2254 # value is an object consisting of a call and its arguments. Here we want
2255 # to find the source references for the first argument (if there are
2256 # arguments), which generally corresponds to the reactive expression--
2257 # e.g. in renderTable({ x }), { x } is the expression to trace.
2258 attr(label, "srcref") <- srcrefFromShinyCall(substitute(value)[[2]])
2259 srcref <- attr(substitute(value)[[2]], "srcref")
2260 if (length(srcref) > 0)
2261 attr(label, "srcfile") <- srcFileOfRef(srcref[[1]])
2262 }
2263 .subset2(x, 'impl')$defineOutput(name, value, label)
2264 return(invisible(x))
2265 }
2266
2267 #' @export
2268 `[[<-.shinyoutput` <- `$<-.shinyoutput`
2269
2270 #' @export
2271 `$.shinyoutput` <- function(x, name) {
2272 name <- .subset2(x, 'ns')(name)
2273
2274 if (getOption("shiny.allowoutputreads", FALSE)) {
2275 .subset2(x, 'impl')$getOutput(name)
2276 } else {
2277 rlang::abort(paste0("Can't read output '", name, "'"))
2278 }
2279 }
2280
2281 #' @export
2282 `[[.shinyoutput` <- `$.shinyoutput`
2283
2284 #' @export
2285 `[.shinyoutput` <- function(values, name) {
2286 rlang::abort("Can't index shinyoutput with `[`.")
2287 }
2288
2289 #' @export
2290 `[<-.shinyoutput` <- function(values, name, value) {
2291 rlang::abort("Can't index shinyoutput with `[[`.")
2292 }
2293
2294 #' Set options for an output object.
2295 #'
2296 #' These are the available options for an output object:
2297 #' \itemize{
2298 #' \item suspendWhenHidden. When `TRUE` (the default), the output object
2299 #' will be suspended (not execute) when it is hidden on the web page. When
2300 #' `FALSE`, the output object will not suspend when hidden, and if it
2301 #' was already hidden and suspended, then it will resume immediately.
2302 #' \item priority. The priority level of the output object. Queued outputs
2303 #' with higher priority values will execute before those with lower values.
2304 #' }
2305 #'
2306 #' @examples
2307 #' \dontrun{
2308 #' # Get the list of options for all observers within output
2309 #' outputOptions(output)
2310 #'
2311 #' # Disable suspend for output$myplot
2312 #' outputOptions(output, "myplot", suspendWhenHidden = FALSE)
2313 #'
2314 #' # Change priority for output$myplot
2315 #' outputOptions(output, "myplot", priority = 10)
2316 #'
2317 #' # Get the list of options for output$myplot
2318 #' outputOptions(output, "myplot")
2319 #' }
2320 #'
2321 #' @param x A shinyoutput object (typically `output`).
2322 #' @param name The name of an output observer in the shinyoutput object.
2323 #' @param ... Options to set for the output observer.
2324 #' @export
2325 outputOptions <- function(x, name, ...) {
2326 if (!inherits(x, "shinyoutput")) {
2327 stop("x must be a shinyoutput object.")
2328 }
2329
2330 if (!missing(name)) {
2331 name <- .subset2(x, 'ns')(name)
2332 } else {
2333 name <- NULL
2334 }
2335
2336 .subset2(x, 'impl')$outputOptions(name, ...)
2337 }
2338
2339
2340 #' Get output information
2341 #'
2342 #' Returns information about the currently executing output, including its `name` (i.e., `outputId`);
2343 #' and in some cases, relevant sizing and styling information.
2344 #'
2345 #' @param session The current Shiny session.
2346 #'
2347 #' @return `NULL` if called outside of an output context; otherwise,
2348 #' a list which includes:
2349 #' * The `name` of the output (reported for any output).
2350 #' * If the output is a `plotOutput()` or `imageOutput()`, then:
2351 #' * `height`: a reactive expression which returns the height in pixels.
2352 #' * `width`: a reactive expression which returns the width in pixels.
2353 #' * If the output is a `plotOutput()`, `imageOutput()`, or contains a `shiny-report-theme` class, then:
2354 #' * `bg`: a reactive expression which returns the background color.
2355 #' * `fg`: a reactive expression which returns the foreground color.
2356 #' * `accent`: a reactive expression which returns the hyperlink color.
2357 #' * `font`: a reactive expression which returns a list of font information, including:
2358 #' * `families`: a character vector containing the CSS `font-family` property.
2359 #' * `size`: a character string containing the CSS `font-size` property
2360 #'
2361 #' @export
2362 #' @examples
2363 #'
2364 #' if (interactive()) {
2365 #' shinyApp(
2366 #' fluidPage(
2367 #' tags$style(HTML("body {background-color: black; color: white; }")),
2368 #' tags$style(HTML("body a {color: purple}")),
2369 #' tags$style(HTML("#info {background-color: teal; color: orange; }")),
2370 #' plotOutput("p"),
2371 #' "Computed CSS styles for the output named info:",
2372 #' tagAppendAttributes(
2373 #' textOutput("info"),
2374 #' class = "shiny-report-theme"
2375 #' )
2376 #' ),
2377 #' function(input, output) {
2378 #' output$p <- renderPlot({
2379 #' info <- getCurrentOutputInfo()
2380 #' par(bg = info$bg(), fg = info$fg(), col.axis = info$fg(), col.main = info$fg())
2381 #' plot(1:10, col = info$accent(), pch = 19)
2382 #' title("A simple R plot that uses its CSS styling")
2383 #' })
2384 #' output$info <- renderText({
2385 #' info <- getCurrentOutputInfo()
2386 #' jsonlite::toJSON(
2387 #' list(
2388 #' bg = info$bg(),
2389 #' fg = info$fg(),
2390 #' accent = info$accent(),
2391 #' font = info$font()
2392 #' ),
2393 #' auto_unbox = TRUE
2394 #' )
2395 #' })
2396 #' }
2397 #' )
2398 #' }
2399 #'
2400 #'
2401 getCurrentOutputInfo <- function(session = getDefaultReactiveDomain()) {
2402 if (is.null(session)) return(NULL)
2403 session$getCurrentOutputInfo()
2404 }
2405
2406 #' Add callbacks for Shiny session events
2407 #'
2408 #' @description
2409 #' These functions are for registering callbacks on Shiny session events.
2410 #' `onFlush` registers a function that will be called before Shiny flushes the
2411 #' reactive system. `onFlushed` registers a function that will be called after
2412 #' Shiny flushes the reactive system. `onUnhandledError` registers a function to
2413 #' be called when an unhandled error occurs before the session is closed.
2414 #' `onSessionEnded` registers a function to be called after the client has
2415 #' disconnected.
2416 #'
2417 #' These functions should be called within the application's server function.
2418 #'
2419 #' All of these functions return a function which can be called with no
2420 #' arguments to cancel the registration.
2421 #'
2422 #' @section Unhandled Errors:
2423 #' Unhandled errors are errors that aren't otherwise handled by Shiny or by the
2424 #' application logic. In other words, they are errors that will either cause the
2425 #' application to crash or will result in "Error" output in the UI.
2426 #'
2427 #' You can use `onUnhandledError()` to register a function that will be called
2428 #' when an unhandled error occurs. This function will be called with the error
2429 #' object as its first argument. If the error is fatal and will result in the
2430 #' session closing, the error condition will have the `shiny.error.fatal` class.
2431 #'
2432 #' Note that the `onUnhandledError()` callbacks cannot be used to prevent the
2433 #' app from closing or to modify the error condition. Instead, they are intended
2434 #' to give you an opportunity to log the error or perform other cleanup
2435 #' operations.
2436 #'
2437 #' @param fun A callback function.
2438 #' @param once Should the function be run once, and then cleared, or should it
2439 #' re-run each time the event occurs. (Only for `onFlush` and
2440 #' `onFlushed`.)
2441 #' @param session A shiny session object.
2442 #'
2443 #' @examplesIf interactive()
2444 #' library(shiny)
2445 #'
2446 #' ui <- fixedPage(
2447 #' markdown(c(
2448 #' "Set the number to 8 or higher to cause an error",
2449 #' "in the `renderText()` output."
2450 #' )),
2451 #' sliderInput("number", "Number", 0, 10, 4),
2452 #' textOutput("text"),
2453 #' hr(),
2454 #' markdown(c(
2455 #' "Click the button below to crash the app with an unhandled error",
2456 #' "in an `observe()` block."
2457 #' )),
2458 #' actionButton("crash", "Crash the app!")
2459 #' )
2460 #'
2461 #' log_event <- function(level, ...) {
2462 #' ts <- strftime(Sys.time(), " [%F %T] ")
2463 #' message(level, ts, ...)
2464 #' }
2465 #'
2466 #' server <- function(input, output, session) {
2467 #' log_event("INFO", "Session started")
2468 #'
2469 #' onUnhandledError(function(err) {
2470 #' # log the unhandled error
2471 #' level <- if (inherits(err, "shiny.error.fatal")) "FATAL" else "ERROR"
2472 #' log_event(level, conditionMessage(err))
2473 #' })
2474 #'
2475 #' onStop(function() {
2476 #' log_event("INFO", "Session ended")
2477 #' })
2478 #'
2479 #' observeEvent(input$crash, stop("Oops, an unhandled error happened!"))
2480 #'
2481 #' output$text <- renderText({
2482 #' if (input$number > 7) {
2483 #' stop("that's too high!")
2484 #' }
2485 #' sprintf("You picked number %d.", input$number)
2486 #' })
2487 #' }
2488 #'
2489 #' shinyApp(ui, server)
2490 #'
2491 #' @export
2492 onFlush <- function(fun, once = TRUE, session = getDefaultReactiveDomain()) {
2493 session$onFlush(fun, once = once)
2494 }
2495
2496 #' @rdname onFlush
2497 #' @export
2498 onFlushed <- function(fun, once = TRUE, session = getDefaultReactiveDomain()) {
2499 session$onFlushed(fun, once = once)
2500 }
2501
2502 #' @rdname onFlush
2503 #'
2504 #' @seealso [onStop()] for registering callbacks that will be
2505 #' invoked when the application exits, or when a session ends.
2506 #' @export
2507 onSessionEnded <- function(fun, session = getDefaultReactiveDomain()) {
2508 session$onSessionEnded(fun)
2509 }
2510
2511 .globals$onUnhandledErrorCallbacks <- NULL
2512 on_load({
2513 .globals$onUnhandledErrorCallbacks <- Callbacks$new()
2514 })
2515
2516 #' @rdname onFlush
2517 #' @export
2518 onUnhandledError <- function(fun, session = getDefaultReactiveDomain()) {
2519 if (!is.function(fun) || length(formals(fun)) == 0) {
2520 rlang::abort(
2521 "The unhandled error callback must be a function that takes an error object as its first argument."
2522 )
2523 }
2524
2525 if (is.null(session)) {
2526 .globals$onUnhandledErrorCallbacks$register(fun)
2527 } else {
2528 session$onUnhandledError(fun)
2529 }
2530 }
2531
2532
2533 flushPendingSessions <- function() {
2534 lapply(appsNeedingFlush$values(), function(shinysession) {
2535 tryCatch(
2536 shinysession$flushOutput(),
2537
2538 stop = function(e) {
2539 # If there are any uncaught errors that bubbled up to here, close the
2540 # session.
2541 shinysession$close()
2542 }
2543 )
2544 NULL
2545 })
2546 }
2547
2548 .globals$onStopCallbacks <- Callbacks$new()
2549
2550 #' Run code after an application or session ends
2551 #'
2552 #' This function registers callback functions that are invoked when the
2553 #' application exits (when [runApp()] exits), or after each user
2554 #' session ends (when a client disconnects).
2555 #'
2556 #' @param fun A function that will be called after the app has finished running.
2557 #' @param session A scope for when the callback will run. If `onStop` is
2558 #' called from within the server function, this will default to the current
2559 #' session, and the callback will be invoked when the current session ends. If
2560 #' `onStop` is called outside a server function, then the callback will
2561 #' be invoked with the application exits. If `NULL`, it is the same as
2562 #' calling `onStop` outside of the server function, and the callback will
2563 #' be invoked when the application exits.
2564 #'
2565 #'
2566 #' @seealso [onSessionEnded()] for the same functionality, but at
2567 #' the session level only.
2568 #'
2569 #' @return A function which, if invoked, will cancel the callback.
2570 #' @examples
2571 #' ## Only run this example in interactive R sessions
2572 #' if (interactive()) {
2573 #' # Open this application in multiple browsers, then close the browsers.
2574 #' shinyApp(
2575 #' ui = basicPage("onStop demo"),
2576 #'
2577 #' server = function(input, output, session) {
2578 #' onStop(function() cat("Session stopped\n"))
2579 #' },
2580 #'
2581 #' onStart = function() {
2582 #' cat("Doing application setup\n")
2583 #'
2584 #' onStop(function() {
2585 #' cat("Doing application cleanup\n")
2586 #' })
2587 #' }
2588 #' )
2589 #' }
2590 #' # In the example above, onStop() is called inside of onStart(). This is
2591 #' # the pattern that should be used when creating a shinyApp() object from
2592 #' # a function, or at the console. If instead you are writing an app.R which
2593 #' # will be invoked with runApp(), you can do it that way, or put the onStop()
2594 #' # before the shinyApp() call, as shown below.
2595 #'
2596 #' \dontrun{
2597 #' # ==== app.R ====
2598 #' cat("Doing application setup\n")
2599 #' onStop(function() {
2600 #' cat("Doing application cleanup\n")
2601 #' })
2602 #'
2603 #' shinyApp(
2604 #' ui = basicPage("onStop demo"),
2605 #'
2606 #' server = function(input, output, session) {
2607 #' onStop(function() cat("Session stopped\n"))
2608 #' }
2609 #' )
2610 #' # ==== end app.R ====
2611 #'
2612 #'
2613 #' # Similarly, if you have a global.R, you can call onStop() from there.
2614 #' # ==== global.R ====
2615 #' cat("Doing application setup\n")
2616 #' onStop(function() {
2617 #' cat("Doing application cleanup\n")
2618 #' })
2619 #' # ==== end global.R ====
2620 #' }
2621 #' @export
2622 onStop <- function(fun, session = getDefaultReactiveDomain()) {
2623 if (is.null(session)) {
2624 return(.globals$onStopCallbacks$register(fun))
2625 } else {
2626 # Note: In the future if we allow scoping the onStop() callback to modules
2627 # and allow modules to be stopped, then session_proxy objects will need
2628 # its own implementation of $onSessionEnded.
2629 return(session$onSessionEnded(fun))
2630 }
2631 }
2632
2633 # Helper class for emitting log messages to stdout that will be interpreted by
2634 # a Shiny Server parent process. The duration it's trying to record is the time
2635 # between a websocket message being received, and the next flush to the client.
2636 ShinyServerTimingRecorder <- R6Class("ShinyServerTimingRecorder",
2637 cloneable = FALSE,
2638 public = list(
2639 initialize = function() {
2640 private$shiny_stdout <- if (exists(".shiny__stdout", globalenv()))
2641 get(".shiny__stdout", globalenv())
2642 else
2643 NULL
2644 private$guid <- NULL
2645 },
2646 start = function(guid) {
2647 if (is.null(private$shiny_stdout)) return()
2648
2649 private$guid <- guid
2650 if (!is.null(guid)) {
2651 private$write("n")
2652 }
2653 },
2654 stop = function() {
2655 if (is.null(private$shiny_stdout)) return()
2656
2657 if (!is.null(private$guid)) {
2658 private$write("x")
2659 private$guid <- NULL
2660 }
2661 }
2662 ),
2663 private = list(
2664 shiny_stdout = NULL,
2665 guid = character(),
2666 write = function(code) {
2667 # eNter or eXit a flushReact
2668 writeLines(paste("_", code, "_flushReact ", private$guid,
2669 " @ ", sprintf("%.3f", as.numeric(Sys.time())),
2670 sep=""), con=private$shiny_stdout)
2671 flush(private$shiny_stdout)
2672 }
2673 )
2674 )
2675
2676 missingOutput <- function(...) req(FALSE)
2677
2678 #' Insert inline Markdown
2679 #'
2680 #' This function accepts
2681 #' [Markdown](https://en.wikipedia.org/wiki/Markdown)-syntax text and returns
2682 #' HTML that may be included in Shiny UIs.
2683 #'
2684 #' Leading whitespace is trimmed from Markdown text with [glue::trim()].
2685 #' Whitespace trimming ensures Markdown is processed correctly even when the
2686 #' call to `markdown()` is indented within surrounding R code.
2687 #'
2688 #' By default, [Github extensions][commonmark::extensions] are enabled, but this
2689 #' can be disabled by passing `extensions = FALSE`.
2690 #'
2691 #' Markdown rendering is performed by [commonmark::markdown_html()]. Additional
2692 #' arguments to `markdown()` are passed as arguments to `markdown_html()`
2693 #'
2694 #' @param mds A character vector of Markdown source to convert to HTML. If the
2695 #' vector has more than one element, a single-element character vector of
2696 #' concatenated HTML is returned.
2697 #' @param extensions Enable Github syntax extensions; defaults to `TRUE`.
2698 #' @param .noWS Character vector used to omit some of the whitespace that would
2699 #' normally be written around generated HTML. Valid options include `before`,
2700 #' `after`, and `outside` (equivalent to `before` and `end`).
2701 #' @param ... Additional arguments to pass to [commonmark::markdown_html()].
2702 #' These arguments are _[dynamic][rlang::dyn-dots]_.
2703 #'
2704 #' @return a character vector marked as HTML.
2705 #' @export
2706 #' @examples
2707 #' ui <- fluidPage(
2708 #' markdown("
2709 #' # Markdown Example
2710 #'
2711 #' This is a markdown paragraph, and will be contained within a `<p>` tag
2712 #' in the UI.
2713 #'
2714 #' The following is an unordered list, which will be represented in the UI as
2715 #' a `<ul>` with `<li>` children:
2716 #'
2717 #' * a bullet
2718 #' * another
2719 #'
2720 #' [Links](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) work;
2721 #' so does *emphasis*.
2722 #'
2723 #' To see more of what's possible, check out [commonmark.org/help](https://commonmark.org/help).
2724 #' ")
2725 #' )
2726 markdown <- function(mds, extensions = TRUE, .noWS = NULL, ...) {
2727 html <- rlang::exec(commonmark::markdown_html, glue::trim(mds), extensions = extensions, ...)
2728 htmltools::HTML(html, .noWS = .noWS)
2729 }
2730
2731
2732 # Check that an object is a ShinySession object, and give an informative error.
2733 # The default label is the caller function's name.
2734 validate_session_object <- function(session, label = as.character(sys.call(sys.parent())[[1]])) {
2735 if (missing(session) ||
2736 !inherits(session, c("ShinySession", "MockShinySession", "session_proxy")))
2737 {
2738 stop(call. = FALSE,
2739 sprintf(
2740 "`session` must be a 'ShinySession' object. Did you forget to pass `session` to `%s()`?",
2741 label
2742 )
2743 )
2744 }
2745 }
2746
2747
2748 sanitized_error <- function() {
2749 simpleError(paste("An error has occurred. Check your",
2750 "logs or contact the app author for",
2751 "clarification."))
2752 }