Debian Codegraph @

R/runapp.R

raw
1 #' Run Shiny Application
2 #'
3 #' Runs a Shiny application. This function normally does not return; interrupt R
4 #' to stop the application (usually by pressing Ctrl+C or Esc).
5 #'
6 #' The host parameter was introduced in Shiny 0.9.0. Its default value of
7 #' `"127.0.0.1"` means that, contrary to previous versions of Shiny, only
8 #' the current machine can access locally hosted Shiny apps. To allow other
9 #' clients to connect, use the value `"0.0.0.0"` instead (which was the
10 #' value that was hard-coded into Shiny in 0.8.0 and earlier).
11 #'
12 #' @param appDir The application to run. Should be one of the following:
13 #' \itemize{
14 #' \item A directory containing `server.R`, plus, either `ui.R` or
15 #' a `www` directory that contains the file `index.html`.
16 #' \item A directory containing `app.R`.
17 #' \item An `.R` file containing a Shiny application, ending with an
18 #' expression that produces a Shiny app object.
19 #' \item A list with `ui` and `server` components.
20 #' \item A Shiny app object created by [shinyApp()].
21 #' }
22 #' @param port The TCP port that the application should listen on. If the
23 #' `port` is not specified, and the `shiny.port` option is set (with
24 #' `options(shiny.port = XX)`), then that port will be used. Otherwise,
25 #' use a random port between 3000:8000, excluding ports that are blocked
26 #' by Google Chrome for being considered unsafe: 3659, 4045, 5060,
27 #' 5061, 6000, 6566, 6665:6669 and 6697. Up to twenty random
28 #' ports will be tried.
29 #' @param launch.browser If true, the system's default web browser will be
30 #' launched automatically after the app is started. Defaults to true in
31 #' interactive sessions only. The value of this parameter can also be a
32 #' function to call with the application's URL.
33 #' @param host The IPv4 address that the application should listen on. Defaults
34 #' to the `shiny.host` option, if set, or `"127.0.0.1"` if not. See
35 #' Details.
36 #' @param workerId Can generally be ignored. Exists to help some editions of
37 #' Shiny Server Pro route requests to the correct process.
38 #' @param quiet Should Shiny status messages be shown? Defaults to FALSE.
39 #' @param display.mode The mode in which to display the application. If set to
40 #' the value `"showcase"`, shows application code and metadata from a
41 #' `DESCRIPTION` file in the application directory alongside the
42 #' application. If set to `"normal"`, displays the application normally.
43 #' Defaults to `"auto"`, which displays the application in the mode given
44 #' in its `DESCRIPTION` file, if any.
45 #' @param test.mode Should the application be launched in test mode? This is
46 #' only used for recording or running automated tests. Defaults to the
47 #' `shiny.testmode` option, or FALSE if the option is not set.
48 #'
49 #' @examples
50 #' \dontrun{
51 #' # Start app in the current working directory
52 #' runApp()
53 #'
54 #' # Start app in a subdirectory called myapp
55 #' runApp("myapp")
56 #' }
57 #'
58 #' ## Only run this example in interactive R sessions
59 #' if (interactive()) {
60 #' options(device.ask.default = FALSE)
61 #'
62 #' # Apps can be run without a server.r and ui.r file
63 #' runApp(list(
64 #' ui = bootstrapPage(
65 #' numericInput('n', 'Number of obs', 100),
66 #' plotOutput('plot')
67 #' ),
68 #' server = function(input, output) {
69 #' output$plot <- renderPlot({ hist(runif(input$n)) })
70 #' }
71 #' ))
72 #'
73 #'
74 #' # Running a Shiny app object
75 #' app <- shinyApp(
76 #' ui = bootstrapPage(
77 #' numericInput('n', 'Number of obs', 100),
78 #' plotOutput('plot')
79 #' ),
80 #' server = function(input, output) {
81 #' output$plot <- renderPlot({ hist(runif(input$n)) })
82 #' }
83 #' )
84 #' runApp(app)
85 #' }
86 #' @export
87 runApp <- function(
88 appDir=getwd(),
89 port=getOption('shiny.port'),
90 launch.browser = getOption('shiny.launch.browser', interactive()),
91 host=getOption('shiny.host', '127.0.0.1'),
92 workerId="", quiet=FALSE,
93 display.mode=c("auto", "normal", "showcase"),
94 test.mode=getOption('shiny.testmode', FALSE)
95 ) {
96
97 # * Wrap **all** execution of the app inside the otel promise domain
98 # * While this could be done at a lower level, it allows for _anything_ within
99 # shiny's control to allow for the opportunity to have otel active spans be
100 # reactivated upon promise domain restoration
101 promises::local_otel_promise_domain()
102
103 on.exit({
104 handlerManager$clear()
105 }, add = TRUE)
106
107 if (isRunning()) {
108 stop("Can't call `runApp()` from within `runApp()`. If your ",
109 "application code contains `runApp()`, please remove it.")
110 }
111
112 # Make warnings print immediately
113 # Set pool.scheduler to support pool package
114 ops <- options(
115 # Raise warn level to 1, but don't lower it
116 warn = max(1, getOption("warn", default = 1)),
117 pool.scheduler = scheduleTask
118 )
119 on.exit(options(ops), add = TRUE)
120
121 # ============================================================================
122 # Global onStart/onStop callbacks
123 # ============================================================================
124 # Invoke user-defined onStop callbacks, before the application's internal
125 # onStop callbacks.
126 on.exit({
127 .globals$onStopCallbacks$invoke()
128 .globals$onStopCallbacks <- Callbacks$new()
129 }, add = TRUE)
130
131 require(shiny)
132
133 # ============================================================================
134 # Convert to Shiny app object
135 # ============================================================================
136 appParts <- as.shiny.appobj(appDir)
137
138 # ============================================================================
139 # Initialize app state object
140 # ============================================================================
141 # This is so calls to getCurrentAppState() can be used to find (A) whether an
142 # app is running and (B), get options and data associated with the app.
143 initCurrentAppState(appParts)
144 on.exit(clearCurrentAppState(), add = TRUE)
145 # Any shinyOptions set after this point will apply to the current app only
146 # (and will not persist after the app stops).
147
148 # ============================================================================
149 # shinyOptions
150 # ============================================================================
151 # A unique identifier associated with this run of this application. It is
152 # shared across sessions.
153 shinyOptions(appToken = createUniqueId(8))
154
155 # Set up default cache for app.
156 if (is.null(getShinyOption("cache", default = NULL))) {
157 shinyOptions(cache = cachem::cache_mem(max_size = 200 * 1024^2))
158 }
159
160 # Extract appOptions (which is a list) and store them as shinyOptions, for
161 # this app. (This is the only place we have to store settings that are
162 # accessible both the UI and server portion of the app.)
163 applyCapturedAppOptions(appParts$appOptions)
164
165 # ============================================================================
166 # runApp options set via shinyApp(options = list(...))
167 # ============================================================================
168 # The lines below set some of the app's running options, which
169 # can be:
170 # - left unspecified (in which case the arguments' default
171 # values from `runApp` kick in);
172 # - passed through `shinyApp`
173 # - passed through `runApp` (this function)
174 # - passed through both `shinyApp` and `runApp` (the latter
175 # takes precedence)
176 #
177 # Matrix of possibilities:
178 # | IN shinyApp | IN runApp | result | check |
179 # |-------------|-----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------|
180 # | no | no | use defaults | exhaust all possibilities: if it's missing (runApp does not specify); THEN if it's not in shinyApp appParts$options; THEN use defaults |
181 # | yes | no | use shinyApp | if it's missing (runApp does not specify); THEN if it's in shinyApp appParts$options; THEN use shinyApp |
182 # | no | yes | use runApp | if it's not missing (runApp specifies), use those |
183 # | yes | yes | use runApp | if it's not missing (runApp specifies), use those |
184 #
185 # I tried to make this as compact and intuitive as possible,
186 # given that there are four distinct possibilities to check
187 appOps <- appParts$options
188 findVal <- function(arg, default) {
189 if (arg %in% names(appOps)) appOps[[arg]] else default
190 }
191
192 if (missing(port))
193 port <- findVal("port", port)
194 if (missing(launch.browser))
195 launch.browser <- findVal("launch.browser", launch.browser)
196 if (missing(host))
197 host <- findVal("host", host)
198 if (missing(quiet))
199 quiet <- findVal("quiet", quiet)
200 if (missing(display.mode))
201 display.mode <- findVal("display.mode", display.mode)
202 if (missing(test.mode))
203 test.mode <- findVal("test.mode", test.mode)
204
205 if (is.null(host) || is.na(host)) host <- '0.0.0.0'
206
207 # ============================================================================
208 # Hosted environment
209 # ============================================================================
210 workerId(workerId)
211
212 if (inShinyServer()) {
213 # If SHINY_PORT is set, we're running under Shiny Server. Check the version
214 # to make sure it is compatible. Older versions of Shiny Server don't set
215 # SHINY_SERVER_VERSION, those will return "" which is considered less than
216 # any valid version.
217 ver <- Sys.getenv('SHINY_SERVER_VERSION')
218 if (utils::compareVersion(ver, .shinyServerMinVersion) < 0) {
219 rlang::warn(c(
220 sprintf(
221 "Shiny Server v%s or later is required; please upgrade.",
222 .shinyServerMinVersion
223 ),
224 "i" = "If you are not using Shiny Server, you are likely seeing this message because the `SHINY_PORT` environment variable is set in your environment.",
225 "i" = "Avoid using `SHINY_PORT` to prevent this warning."
226 ))
227 }
228 }
229
230 # ============================================================================
231 # Shinytest
232 # ============================================================================
233 # Set the testmode shinyoption so that this can be read by both the
234 # ShinySession and the UI code (which executes separately from the
235 # ShinySession code).
236 shinyOptions(testmode = test.mode)
237 if (test.mode) {
238 message("Running application in test mode.")
239 }
240
241 # ============================================================================
242 # Showcase mode
243 # ============================================================================
244 # Showcase mode is disabled by default; it must be explicitly enabled in
245 # either the DESCRIPTION file for directory-based apps, or via
246 # the display.mode parameter. The latter takes precedence.
247 setShowcaseDefault(0)
248
249 # If appDir specifies a path, and display mode is specified in the
250 # DESCRIPTION file at that path, apply it here.
251 if (is.character(appDir)) {
252 # if appDir specifies a .R file (single-file Shiny app), look for the
253 # DESCRIPTION in the parent directory
254 desc <- file.path.ci(
255 if (tolower(tools::file_ext(appDir)) == "r")
256 dirname(appDir)
257 else
258 appDir, "DESCRIPTION")
259 if (file.exists(desc)) {
260 con <- file(desc, encoding = checkEncoding(desc))
261 on.exit(close(con), add = TRUE)
262 settings <- read.dcf(con)
263 if ("DisplayMode" %in% colnames(settings)) {
264 mode <- settings[1, "DisplayMode"]
265 if (mode == "Showcase") {
266 setShowcaseDefault(1)
267 if ("IncludeWWW" %in% colnames(settings)) {
268 .globals$IncludeWWW <- as.logical(settings[1, "IncludeWWW"])
269 if (is.na(.globals$IncludeWWW)) {
270 stop("In your Description file, `IncludeWWW` ",
271 "must be set to `True` (default) or `False`")
272 }
273 } else {
274 .globals$IncludeWWW <- TRUE
275 }
276 }
277 }
278 }
279 }
280
281 ## default is to show the .js, .css and .html files in the www directory
282 ## (if not in showcase mode, this variable will simply be ignored)
283 if (is.null(.globals$IncludeWWW) || is.na(.globals$IncludeWWW)) {
284 .globals$IncludeWWW <- TRUE
285 }
286
287 # If display mode is specified as an argument, apply it (overriding the
288 # value specified in DESCRIPTION, if any).
289 display.mode <- match.arg(display.mode)
290 if (display.mode == "normal") {
291 setShowcaseDefault(0)
292 }
293 else if (display.mode == "showcase") {
294 setShowcaseDefault(1)
295 }
296
297 # ============================================================================
298 # Server port
299 # ============================================================================
300 # determine port if we need to
301 if (is.null(port)) {
302
303 # Try up to 20 random ports. If we don't succeed just plow ahead
304 # with the final value we tried, and let the "real" startServer
305 # somewhere down the line fail and throw the error to the user.
306 #
307 # If we (think we) succeed, save the value as .globals$lastPort,
308 # and try that first next time the user wants a random port.
309
310 for (i in 1:20) {
311 if (!is.null(.globals$lastPort)) {
312 port <- .globals$lastPort
313 .globals$lastPort <- NULL
314 }
315 else {
316 # Try up to 20 random ports
317 while (TRUE) {
318 port <- p_randomInt(3000, 8000)
319 # Reject ports in this range that are considered unsafe by Chrome
320 # http://superuser.com/questions/188058/which-ports-are-considered-unsafe-on-chrome
321 # https://github.com/rstudio/shiny/issues/1784
322 # https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc
323 if (!port %in% c(3659, 4045, 5060, 5061, 6000, 6566, 6665:6669, 6697)) {
324 break
325 }
326 }
327 }
328
329 # Test port to see if we can use it
330 tmp <- try(startServer(host, port, list()), silent=TRUE)
331 if (!inherits(tmp, 'try-error')) {
332 stopServer(tmp)
333 .globals$lastPort <- port
334 break
335 }
336 }
337 }
338
339 # ============================================================================
340 # onStart/onStop callbacks
341 # ============================================================================
342 # Set up the onStop before we call onStart, so that it gets called even if an
343 # error happens in onStart.
344 if (!is.null(appParts$onStop))
345 on.exit(appParts$onStop(), add = TRUE)
346 if (!is.null(appParts$onStart))
347 appParts$onStart()
348
349 # ============================================================================
350 # Start/stop httpuv app
351 # ============================================================================
352 server <- startApp(appParts, port, host, quiet)
353
354 # Make the httpuv server object accessible. Needed for calling
355 # addResourcePath while app is running.
356 shinyOptions(server = server)
357
358 on.exit({
359 stopServer(server)
360 }, add = TRUE)
361
362 # ============================================================================
363 # Launch web browser
364 # ============================================================================
365 if (!is.character(port)) {
366 browseHost <- host
367 if (identical(host, "0.0.0.0")) {
368 # http://0.0.0.0/ doesn't work on QtWebKit (i.e. RStudio viewer)
369 browseHost <- "127.0.0.1"
370 } else if (identical(host, "::")) {
371 browseHost <- "::1"
372 }
373
374 if (httpuv::ipFamily(browseHost) == 6L) {
375 browseHost <- paste0("[", browseHost, "]")
376 }
377
378 appUrl <- paste("http://", browseHost, ":", port, sep="")
379 if (is.function(launch.browser))
380 launch.browser(appUrl)
381 else if (launch.browser)
382 utils::browseURL(appUrl)
383 } else {
384 appUrl <- NULL
385 }
386
387 # ============================================================================
388 # Application hooks
389 # ============================================================================
390 callAppHook("onAppStart", appUrl)
391 on.exit({
392 callAppHook("onAppStop", appUrl)
393 }, add = TRUE)
394
395 # ============================================================================
396 # Run event loop via httpuv
397 # ============================================================================
398 .globals$reterror <- NULL
399 .globals$retval <- NULL
400 .globals$stopped <- FALSE
401 # Top-level ..stacktraceoff..; matches with ..stacktraceon in observe(),
402 # reactive(), Callbacks$invoke(), and others
403 ..stacktraceoff..(
404 captureStackTraces({
405 while (!.globals$stopped) {
406 ..stacktracefloor..(serviceApp())
407 }
408 })
409 )
410
411 if (isTRUE(.globals$reterror)) {
412 stop(.globals$retval)
413 }
414 else if (.globals$retval$visible)
415 .globals$retval$value
416 else
417 invisible(.globals$retval$value)
418 }
419
420 #' Stop the currently running Shiny app
421 #'
422 #' Stops the currently running Shiny app, returning control to the caller of
423 #' [runApp()].
424 #'
425 #' @param returnValue The value that should be returned from
426 #' [runApp()].
427 #' @export
428 stopApp <- function(returnValue = invisible()) {
429 # reterror will indicate whether retval is an error (i.e. it should be passed
430 # to stop() when the serviceApp loop stops) or a regular value (in which case
431 # it should simply be returned with the appropriate visibility).
432 .globals$reterror <- FALSE
433 ..stacktraceoff..(
434 tryCatch(
435 {
436 captureStackTraces(
437 .globals$retval <- withVisible(..stacktraceon..(force(returnValue)))
438 )
439 },
440 error = function(e) {
441 .globals$retval <- e
442 .globals$reterror <- TRUE
443 }
444 )
445 )
446
447 .globals$stopped <- TRUE
448 httpuv::interrupt()
449 }
450
451 #' Run Shiny Example Applications
452 #'
453 #' Launch Shiny example applications, and optionally, your system's web browser.
454 #'
455 #' @param example The name of the example to run, or `NA` (the default) to
456 #' list the available examples.
457 #' @param launch.browser If true, the system's default web browser will be
458 #' launched automatically after the app is started. Defaults to true in
459 #' interactive sessions only.
460 #' @param host The IPv4 address that the application should listen on. Defaults
461 #' to the `shiny.host` option, if set, or `"127.0.0.1"` if not.
462 #' @param display.mode The mode in which to display the example. Defaults to
463 #' `"auto"`, which uses the value of `DisplayMode` in the example's
464 #' `DESCRIPTION` file. Set to `"showcase"` to show the app code and
465 #' description with the running app, or `"normal"` to see the example without
466 #' code or commentary.
467 #' @param package The package in which to find the example (defaults to
468 #' `"shiny"`).
469 #'
470 #' To provide examples in your package, store examples in the
471 #' `inst/examples-shiny` directory of your package. Each example should be
472 #' in its own subdirectory and should be runnable when [runApp()] is called
473 #' on the subdirectory. Example apps can include a `DESCRIPTION` file and a
474 #' `README.md` file to provide metadata and commentary about the example. See
475 #' the article on [Display Modes](https://shiny.posit.co/r/articles/build/display-modes/)
476 #' on the Shiny website for more information.
477 #' @inheritParams runApp
478 #'
479 #' @examples
480 #' ## Only run this example in interactive R sessions
481 #' if (interactive()) {
482 #' # List all available examples
483 #' runExample()
484 #'
485 #' # Run one of the examples
486 #' runExample("01_hello")
487 #'
488 #' # Print the directory containing the code for all examples
489 #' system.file("examples", package="shiny")
490 #' }
491 #' @export
492 runExample <- function(
493 example = NA,
494 port = getOption("shiny.port"),
495 launch.browser = getOption("shiny.launch.browser", interactive()),
496 host = getOption("shiny.host", "127.0.0.1"),
497 display.mode = c("auto", "normal", "showcase"),
498 package = "shiny"
499 ) {
500 if (!identical(package, "shiny") && !is_installed(package)) {
501 rlang::check_installed(package)
502 }
503
504 use_legacy_shiny_examples <-
505 identical(package, "shiny") &&
506 isTRUE(getOption('shiny.legacy.examples', FALSE))
507
508 examplesDir <- system_file(
509 if (use_legacy_shiny_examples) "examples" else "examples-shiny",
510 package = package
511 )
512
513 dir <- resolve(examplesDir, example)
514
515 if (is.null(dir)) {
516 valid_examples <- sprintf(
517 'Valid examples in {%s}: "%s"',
518 package,
519 paste(list.files(examplesDir), collapse = '", "')
520 )
521
522 if (is.na(example)) {
523 message(valid_examples)
524 return(invisible())
525 }
526
527 stop("Example '", example, "' does not exist. ", valid_examples)
528 }
529
530 runApp(dir, port = port, host = host, launch.browser = launch.browser,
531 display.mode = display.mode)
532 }
533
534 #' Run a gadget
535 #'
536 #' Similar to `runApp`, but handles `input$cancel` automatically, and
537 #' if running in RStudio, defaults to viewing the app in the Viewer pane.
538 #'
539 #' @param app Either a Shiny app object as created by
540 #' [`shinyApp()`][shiny] et al, or, a UI object.
541 #' @param server Ignored if `app` is a Shiny app object; otherwise, passed
542 #' along to `shinyApp` (i.e. `shinyApp(ui = app, server = server)`).
543 #' @param port See [`runApp()`][shiny].
544 #' @param viewer Specify where the gadget should be displayed--viewer pane,
545 #' dialog window, or external browser--by passing in a call to one of the
546 #' [viewer()] functions.
547 #' @param stopOnCancel If `TRUE` (the default), then an `observeEvent`
548 #' is automatically created that handles `input$cancel` by calling
549 #' `stopApp()` with an error. Pass `FALSE` if you want to handle
550 #' `input$cancel` yourself.
551 #' @return The value returned by the gadget.
552 #'
553 #' @examples
554 #' \dontrun{
555 #' library(shiny)
556 #'
557 #' ui <- fillPage(...)
558 #'
559 #' server <- function(input, output, session) {
560 #' ...
561 #' }
562 #'
563 #' # Either pass ui/server as separate arguments...
564 #' runGadget(ui, server)
565 #'
566 #' # ...or as a single app object
567 #' runGadget(shinyApp(ui, server))
568 #' }
569 #' @export
570 runGadget <- function(app, server = NULL, port = getOption("shiny.port"),
571 viewer = paneViewer(), stopOnCancel = TRUE) {
572
573 if (!is.shiny.appobj(app)) {
574 app <- shinyApp(app, server)
575 }
576
577 if (isTRUE(stopOnCancel)) {
578 app <- decorateServerFunc(app, function(input, output, session) {
579 observeEvent(input$cancel, {
580 stopApp(stop("User cancel", call. = FALSE))
581 })
582 })
583 }
584
585 if (is.null(viewer)) {
586 viewer <- utils::browseURL
587 }
588
589 shiny::runApp(app, port = port, launch.browser = viewer)
590 }
591
592 # Add custom functionality to a Shiny app object's server func
593 decorateServerFunc <- function(appobj, serverFunc) {
594 origServerFuncSource <- appobj$serverFuncSource
595 appobj$serverFuncSource <- function() {
596 origServerFunc <- origServerFuncSource()
597 function(input, output, session) {
598 serverFunc(input, output, session)
599
600 # The clientData and session arguments are optional; check if
601 # each exists
602 args <- argsForServerFunc(origServerFunc, session)
603 do.call(origServerFunc, args)
604 }
605 }
606 appobj
607 }