Debian Codegraph @

R/utils.R

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #' @include globals.R
2 #' @include map.R
3 NULL
4
5 # @staticimports pkg:staticimports
6 # is_installed get_package_version system_file
7 # s3_register
8 # any_named any_unnamed
9
10 #' Make a random number generator repeatable
11 #'
12 #' Given a function that generates random data, returns a wrapped version of
13 #' that function that always uses the same seed when called. The seed to use can
14 #' be passed in explicitly if desired; otherwise, a random number is used.
15 #'
16 #' @param rngfunc The function that is affected by the R session's seed.
17 #' @param seed The seed to set every time the resulting function is called.
18 #' @return A repeatable version of the function that was passed in.
19 #'
20 #' @note When called, the returned function attempts to preserve the R session's
21 #' current seed by snapshotting and restoring
22 #' [base::.Random.seed()].
23 #'
24 #' @examples
25 #' rnormA <- repeatable(rnorm)
26 #' rnormB <- repeatable(rnorm)
27 #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111
28 #' rnormA(3) # [1] 1.8285879 -0.7468041 -0.4639111
29 #' rnormA(5) # [1] 1.8285879 -0.7468041 -0.4639111 -1.6510126 -1.4686924
30 #' rnormB(5) # [1] -0.7946034 0.2568374 -0.6567597 1.2451387 -0.8375699
31 #' @export
32 repeatable <- function(rngfunc, seed = stats::runif(1, 0, .Machine$integer.max)) {
33 force(seed)
34
35 function(...) {
36 # When we exit, restore the seed to its original state
37 if (exists('.Random.seed', where=globalenv())) {
38 currentSeed <- get('.Random.seed', pos=globalenv())
39 on.exit(assign('.Random.seed', currentSeed, pos=globalenv()))
40 }
41 else {
42 on.exit(rm('.Random.seed', pos=globalenv()))
43 }
44
45 set.seed(seed)
46
47 rngfunc(...)
48 }
49 }
50
51 .globals$ownSeed <- NULL
52 # Evaluate an expression using Shiny's own private stream of
53 # randomness (not affected by set.seed).
54 withPrivateSeed <- function(expr) {
55 # Save the old seed if present.
56 if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
57 hasOrigSeed <- TRUE
58 origSeed <- .GlobalEnv$.Random.seed
59 } else {
60 hasOrigSeed <- FALSE
61 }
62
63 # Swap in the private seed.
64 if (is.null(.globals$ownSeed)) {
65 if (hasOrigSeed) {
66 # Move old seed out of the way if present.
67 rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE)
68 }
69 } else {
70 .GlobalEnv$.Random.seed <- .globals$ownSeed
71 }
72
73 # On exit, save the modified private seed, and put the old seed back.
74 on.exit({
75 .globals$ownSeed <- .GlobalEnv$.Random.seed
76
77 if (hasOrigSeed) {
78 .GlobalEnv$.Random.seed <- origSeed
79 } else {
80 rm(.Random.seed, envir = .GlobalEnv, inherits = FALSE)
81 }
82 # Need to call this to make sure that the value of .Random.seed gets put
83 # into R's internal RNG state. (Issue #1763)
84 httpuv::getRNGState()
85 })
86
87 expr
88 }
89
90 # Version of runif that runs with private seed
91 p_runif <- function(...) {
92 withPrivateSeed(stats::runif(...))
93 }
94
95 # Version of sample that runs with private seed
96 p_sample <- function(...) {
97 withPrivateSeed(sample(...))
98 }
99
100 # Return a random integral value in the range [min, max).
101 # If only one argument is passed, then min=0 and max=argument.
102 randomInt <- function(min, max) {
103 if (missing(max)) {
104 max <- min
105 min <- 0
106 }
107 if (min < 0 || max <= min)
108 stop("Invalid min/max values")
109
110 min + sample(max-min, 1)-1
111 }
112
113 p_randomInt <- function(...) {
114 withPrivateSeed(randomInt(...))
115 }
116
117 isWholeNum <- function(x, tol = .Machine$double.eps^0.5) {
118 abs(x - round(x)) < tol
119 }
120
121 # Given a vector or list, drop all the NULL items in it
122 dropNulls <- function(x) {
123 x[!vapply(x, is.null, FUN.VALUE=logical(1))]
124 }
125
126 nullOrEmpty <- function(x) {
127 is.null(x) || length(x) == 0
128 }
129 # Given a vector or list, drop all the NULL items in it
130 dropNullsOrEmpty <- function(x) {
131 x[!vapply(x, nullOrEmpty, FUN.VALUE=logical(1))]
132 }
133
134
135 # Given a vector/list, returns a named vector/list (the labels will be blank).
136 asNamed <- function(x) {
137 if (is.null(names(x))) {
138 names(x) <- character(length(x))
139 }
140
141 x
142 }
143
144 empty_named_list <- function() {
145 list(a = 1)[0]
146 }
147
148 # Given two named vectors, join them together, and keep only the last element
149 # with a given name in the resulting vector. If b has any elements with the same
150 # name as elements in a, the element in a is dropped. Also, if there are any
151 # duplicated names in a or b, only the last one with that name is kept.
152 mergeVectors <- function(a, b) {
153 if (any_unnamed(a) || any_unnamed(b)) {
154 stop("Vectors must be either NULL or have names for all elements")
155 }
156
157 x <- c(a, b)
158 drop_idx <- duplicated(names(x), fromLast = TRUE)
159 x[!drop_idx]
160 }
161
162 # Sort a vector by the names of items. If there are multiple items with the
163 # same name, preserve the original order of those items. For empty
164 # vectors/lists/NULL, return the original value.
165 sortByName <- function(x, method = "auto") {
166 if (any_unnamed(x))
167 stop("All items must be named")
168
169 # Special case for empty vectors/lists, and NULL
170 if (length(x) == 0)
171 return(x)
172
173 # Must provide consistent sort order
174 # https://github.com/rstudio/shinytest/issues/409
175 # Using a flag in the snapshot url to determine the method
176 # `method="radix"` uses `C` locale, which is consistent across platforms
177 # Even if two platforms share `en_us.UTF-8`, they may not sort consistently
178 # https://blog.zhimingwang.org/macos-lc_collate-hunt
179 # (macOS) $ LC_ALL=en_US.UTF-8 sort <<<$'python-dev\npython3-dev'
180 # python-dev
181 # python3-dev
182 # (Linux) $ LC_ALL=en_US.UTF-8 sort <<<$'python-dev\npython3-dev'
183 # python3-dev
184 # python-dev
185 x[order(names(x), method = method)]
186 }
187
188 # Sort a vector. If a character vector, sort using C locale, which is consistent
189 # across platforms. Note that radix sort uses C locale according to ?sort.
190 sort_c <- function(x, ...) {
191 # Use UTF-8 encoding, because if encoding is "unknown" for non-ASCII
192 # characters, the sort() will throw an error.
193 if (is.character(x))
194 x <- enc2utf8(x)
195 sort(x, method = "radix", ...)
196 }
197
198
199 # Wrapper around list2env with a NULL check. In R <3.2.0, if an empty unnamed
200 # list is passed to list2env(), it errors. But an empty named list is OK. For
201 # R >=3.2.0, this wrapper is not necessary.
202 list2env2 <- function(x, ...) {
203 # Ensure that zero-length lists have a name attribute
204 if (length(x) == 0)
205 attr(x, "names") <- character(0)
206
207 list2env(x, ...)
208 }
209
210 # Combine dir and (file)name into a file path. If a file already exists with a
211 # name differing only by case, then use it instead.
212 file.path.ci <- function(...) {
213 result <- find.file.ci(...)
214 if (!is.null(result))
215 return(result)
216
217 # If not found, return the file path that was given to us.
218 return(file.path(...))
219 }
220
221 # Does a particular file exist? Case-insensitive for filename, case-sensitive
222 # for path (on platforms with case-sensitive file system).
223 file.exists.ci <- function(...) {
224 !is.null(find.file.ci(...))
225 }
226
227 # Look for a file, case-insensitive for filename, case-sensitive for path (on
228 # platforms with case-sensitive filesystem). If found, return the path to the
229 # file, with the correct case. If not found, return NULL.
230 find.file.ci <- function(...) {
231 default <- file.path(...)
232 if (length(default) > 1)
233 stop("find.file.ci can only check for one file at a time.")
234 if (file.exists(default))
235 return(default)
236
237 dir <- dirname(default)
238 name <- basename(default)
239
240 # If we got here, then we'll check for a directory with the exact case, and a
241 # name with any case.
242 all_files <- list.files(dir, all.files=TRUE, full.names=TRUE,
243 include.dirs=TRUE)
244 match_idx <- tolower(name) == tolower(basename(all_files))
245 matches <- all_files[match_idx]
246 if (length(matches) == 0)
247 return(NULL)
248
249 return(matches[1])
250 }
251
252 # The function base::dir.exists was added in R 3.2.0, but for backward
253 # compatibility we need to add this function
254 dirExists <- function(paths) {
255 file.exists(paths) & file.info(paths)$isdir
256 }
257
258 # Removes empty directory (vectorized). This is needed because file.remove()
259 # on Unix will remove empty directories, but on Windows, it will not. On
260 # Windows, you would need to use unlink(recursive=TRUE), which is not very
261 # safe. This function does it safely on Unix and Windows.
262 dirRemove <- function(path) {
263 for (p in path) {
264 if (!dirExists(p)) {
265 stop("Cannot remove non-existent directory ", p, ".")
266 }
267 if (length(dir(p, all.files = TRUE, no.. = TRUE)) != 0) {
268 stop("Cannot remove non-empty directory ", p, ".")
269 }
270 result <- unlink(p, recursive = TRUE)
271 if (result == 1) {
272 stop("Error removing directory ", p, ".")
273 }
274 }
275 }
276
277 # Attempt to join a path and relative path, and turn the result into a
278 # (normalized) absolute path. The result will only be returned if it is an
279 # existing file/directory and is a descendant of dir.
280 #
281 # Example:
282 # resolve("/Users/jcheng", "shiny") # "/Users/jcheng/shiny"
283 # resolve("/Users/jcheng", "./shiny") # "/Users/jcheng/shiny"
284 # resolve("/Users/jcheng", "shiny/../shiny/") # "/Users/jcheng/shiny"
285 # resolve("/Users/jcheng", ".") # NULL
286 # resolve("/Users/jcheng", "..") # NULL
287 # resolve("/Users/jcheng", "shiny/..") # NULL
288 resolve <- function(dir, relpath) {
289 abs.path <- file.path(dir, relpath)
290 if (!file.exists(abs.path))
291 return(NULL)
292 abs.path <- normalizePath(abs.path, winslash='/', mustWork=TRUE)
293 dir <- normalizePath(dir, winslash='/', mustWork=TRUE)
294 # trim the possible trailing slash under Windows (#306)
295 if (isWindows()) dir <- sub('/$', '', dir)
296 if (nchar(abs.path) <= nchar(dir) + 1)
297 return(NULL)
298 if (substr(abs.path, 1, nchar(dir)) != dir ||
299 substr(abs.path, nchar(dir)+1, nchar(dir)+1) != '/') {
300 return(NULL)
301 }
302 return(abs.path)
303 }
304
305 # Given a string, make sure it has a trailing slash.
306 ensure_trailing_slash <- function(path) {
307 if (!grepl("/$", path)) {
308 path <- paste0(path, "/")
309 }
310 path
311 }
312
313
314 isWindows <- function() .Platform$OS.type == 'windows'
315
316 # This is a wrapper for download.file and has the same interface.
317 # The only difference is that, if the protocol is https, it changes the
318 # download settings, depending on platform.
319 download <- function(url, ...) {
320 # First, check protocol. If http or https, check platform:
321 if (grepl('^https?://', url)) {
322
323 # Check whether we are running R 3.2
324 isR32 <- getRversion() >= "3.2"
325
326 # Windows
327 if (.Platform$OS.type == "windows") {
328
329 if (isR32) {
330 method <- "wininet"
331 } else {
332
333 # If we directly use setInternet2, R CMD CHECK gives a Note on Mac/Linux
334 seti2 <- `::`(utils, 'setInternet2')
335
336 # Check whether we are already using internet2 for internal
337 internet2_start <- seti2(NA)
338
339 # If not then temporarily set it
340 if (!internet2_start) {
341 # Store initial settings, and restore on exit
342 on.exit(suppressWarnings(seti2(internet2_start)))
343
344 # Needed for https. Will get warning if setInternet2(FALSE) already run
345 # and internet routines are used. But the warnings don't seem to matter.
346 suppressWarnings(seti2(TRUE))
347 }
348
349 method <- "internal"
350 }
351
352 # download.file will complain about file size with something like:
353 # Warning message:
354 # In download.file(url, ...) : downloaded length 19457 != reported length 200
355 # because apparently it compares the length with the status code returned (?)
356 # so we supress that
357 suppressWarnings(utils::download.file(url, method = method, ...))
358
359 } else {
360 # If non-Windows, check for libcurl/curl/wget/lynx, then call download.file with
361 # appropriate method.
362
363 if (isR32 && capabilities("libcurl")) {
364 method <- "libcurl"
365 } else if (nzchar(Sys.which("wget")[1])) {
366 method <- "wget"
367 } else if (nzchar(Sys.which("curl")[1])) {
368 method <- "curl"
369
370 # curl needs to add a -L option to follow redirects.
371 # Save the original options and restore when we exit.
372 orig_extra_options <- getOption("download.file.extra")
373 on.exit(options(download.file.extra = orig_extra_options))
374
375 options(download.file.extra = paste("-L", orig_extra_options))
376
377 } else if (nzchar(Sys.which("lynx")[1])) {
378 method <- "lynx"
379 } else {
380 stop("no download method found")
381 }
382
383 utils::download.file(url, method = method, ...)
384 }
385
386 } else {
387 utils::download.file(url, ...)
388 }
389 }
390
391 getContentType <- function(file, defaultType = 'application/octet-stream') {
392 subtype <- ifelse(grepl('[.]html?$', file), 'charset=UTF-8', '')
393 mime::guess_type(file, unknown = defaultType, subtype = subtype)
394 }
395
396 #' Parse a GET query string from a URL
397 #'
398 #' Returns a named list of key-value pairs.
399 #'
400 #' @noMd
401 #' @param str The query string. It can have a leading \code{"?"} or not.
402 #' @param nested Whether to parse the query string of as a nested list when it
403 #' contains pairs of square brackets \code{[]}. For example, the query
404 #' \samp{a[i1][j1]=x&b[i1][j1]=y&b[i2][j1]=z} will be parsed as \code{list(a =
405 #' list(i1 = list(j1 = 'x')), b = list(i1 = list(j1 = 'y'), i2 = list(j1 =
406 #' 'z')))} when \code{nested = TRUE}, and \code{list(`a[i1][j1]` = 'x',
407 #' `b[i1][j1]` = 'y', `b[i2][j1]` = 'z')} when \code{nested = FALSE}.
408 #' @export
409 #' @examples
410 #' parseQueryString("?foo=1&bar=b%20a%20r")
411 #'
412 #' \dontrun{
413 #' # Example of usage within a Shiny app
414 #' function(input, output, session) {
415 #'
416 #' output$queryText <- renderText({
417 #' query <- parseQueryString(session$clientData$url_search)
418 #'
419 #' # Ways of accessing the values
420 #' if (as.numeric(query$foo) == 1) {
421 #' # Do something
422 #' }
423 #' if (query[["bar"]] == "targetstring") {
424 #' # Do something else
425 #' }
426 #'
427 #' # Return a string with key-value pairs
428 #' paste(names(query), query, sep = "=", collapse=", ")
429 #' })
430 #' }
431 #' }
432 #'
433 parseQueryString <- function(str, nested = FALSE) {
434 if (is.null(str) || nchar(str) == 0)
435 return(list())
436
437 # Remove leading ?
438 if (substr(str, 1, 1) == '?')
439 str <- substr(str, 2, nchar(str))
440
441 pairs <- strsplit(str, '&', fixed = TRUE)[[1]]
442 # Drop any empty items (if there's leading/trailing/consecutive '&' chars)
443 pairs <- pairs[pairs != ""]
444 pairs <- strsplit(pairs, '=', fixed = TRUE)
445
446 keys <- vapply(pairs, function(x) x[1], FUN.VALUE = character(1))
447 values <- vapply(pairs, function(x) x[2], FUN.VALUE = character(1))
448 # Replace NA with '', so they don't get converted to 'NA' by URLdecode
449 values[is.na(values)] <- ''
450
451 # Convert "+" to " ", since URLdecode doesn't do it
452 keys <- gsub('+', ' ', keys, fixed = TRUE)
453 values <- gsub('+', ' ', values, fixed = TRUE)
454
455 keys <- URLdecode(keys)
456 values <- URLdecode(values)
457
458 res <- stats::setNames(as.list(values), keys)
459 if (!nested) return(res)
460
461 # Make a nested list from a query of the form ?a[1][1]=x11&a[1][2]=x12&...
462 for (i in grep('\\[.+\\]', keys)) {
463 k <- strsplit(keys[i], '[][]')[[1L]] # split by [ or ]
464 res <- assignNestedList(res, k[k != ''], values[i])
465 res[[keys[i]]] <- NULL # remove res[['a[1][1]']]
466 }
467 res
468 }
469
470 # Assign value to the bottom element of the list x using recursive indices idx
471 assignNestedList <- function(x = list(), idx, value) {
472 for (i in seq_along(idx)) {
473 sub <- idx[seq_len(i)]
474 if (is.null(x[[sub]])) x[[sub]] <- list()
475 }
476 x[[idx]] <- value
477 x
478 }
479
480 # decide what to do in case of errors; it is customizable using the shiny.error
481 # option (e.g. we can set options(shiny.error = recover))
482 #' @include conditions.R
483 shinyCallingHandlers <- function(expr) {
484 withCallingHandlers(captureStackTraces(expr),
485 error = function(e) {
486 # Don't intercept shiny.silent.error (i.e. validation errors)
487 if (cnd_inherits(e, "shiny.silent.error"))
488 return()
489
490 handle <- getOption('shiny.error')
491 if (is.function(handle)) handle()
492 }
493 )
494 }
495
496 #' Register a function with the debugger (if one is active).
497 #'
498 #' Call this function after exprToFunction to give any active debugger a hook
499 #' to set and clear breakpoints in the function. A debugger may implement
500 #' registerShinyDebugHook to receive callbacks when Shiny functions are
501 #' instantiated at runtime.
502 #'
503 #' @param name Name of the field or object containing the function.
504 #' @param where The reference object or environment containing the function.
505 #' @param label A label to display on the function in the debugger.
506 #' @noRd
507 registerDebugHook <- function(name, where, label) {
508 if (exists("registerShinyDebugHook", mode = "function")) {
509 registerShinyDebugHook <- get("registerShinyDebugHook", mode = "function")
510 params <- new.env(parent = emptyenv())
511 params$name <- name
512 params$where <- where
513 params$label <- label
514 registerShinyDebugHook(params)
515 }
516 }
517
518 Callbacks <- R6Class(
519 'Callbacks',
520 portable = FALSE,
521 class = FALSE,
522 public = list(
523 .nextId = integer(0),
524 .callbacks = 'Map',
525
526 initialize = function() {
527 # NOTE: we avoid using '.Machine$integer.max' directly
528 # as R 3.3.0's 'radixsort' could segfault when sorting
529 # an integer vector containing this value
530 .nextId <<- as.integer(.Machine$integer.max - 1L)
531 .callbacks <<- Map$new()
532 },
533 register = function(callback) {
534 if (!is.function(callback)) {
535 stop("callback must be a function")
536 }
537 id <- as.character(.nextId)
538 .nextId <<- .nextId - 1L
539 .callbacks$set(id, callback)
540 return(function() {
541 .callbacks$remove(id)
542 })
543 },
544 invoke = function(..., onError=NULL, ..stacktraceon = FALSE) {
545 # Ensure that calls are invoked in the order that they were registered
546 keys <- as.character(sort(as.integer(.callbacks$keys()), decreasing = TRUE))
547 callbacks <- .callbacks$mget(keys)
548
549 for (callback in callbacks) {
550 if (is.null(onError)) {
551 if (..stacktraceon) {
552 ..stacktraceon..(callback(...))
553 } else {
554 callback(...)
555 }
556 } else {
557 tryCatch(
558 captureStackTraces(
559 if (..stacktraceon)
560 ..stacktraceon..(callback(...))
561 else
562 callback(...)
563 ),
564 error = onError
565 )
566 }
567 }
568 },
569 count = function() {
570 .callbacks$size()
571 }
572 )
573 )
574
575 # convert a data frame to JSON as required by DataTables request
576 dataTablesJSON <- function(data, req) {
577 n <- nrow(data)
578 # DataTables requests were sent via POST
579 params <- URLdecode(rawToChar(req$rook.input$read()))
580 q <- parseQueryString(params, nested = TRUE)
581 ci <- q$search[['caseInsensitive']] == 'true'
582
583 # data may have been replaced/updated in the new table while the Ajax request
584 # from the previous table is still on its way, so it is possible that the old
585 # request asks for more columns than the current data, in which case we should
586 # discard this request and return empty data; the next Ajax request from the
587 # new table will retrieve the correct number of columns of data
588 if (length(q$columns) != ncol(data)) {
589 res <- toJSON(list(
590 draw = as.integer(q$draw),
591 recordsTotal = n,
592 recordsFiltered = 0,
593 data = NULL
594 ))
595 return(httpResponse(200, 'application/json', enc2utf8(res)))
596 }
597
598 # global searching
599 i <- seq_len(n)
600 if (length(q$search[['value']]) && q$search[['value']] != '') {
601 i0 <- apply(data, 2, function(x) {
602 grep2(q$search[['value']], as.character(x),
603 fixed = q$search[['regex']] == 'false', ignore.case = ci)
604 })
605 i <- intersect(i, unique(unlist(i0)))
606 }
607
608 # search by columns
609 if (length(i)) for (j in names(q$columns)) {
610 col <- q$columns[[j]]
611 # if the j-th column is not searchable or the search string is "", skip it
612 if (col[['searchable']] != 'true') next
613 if ((k <- col[['search']][['value']]) == '') next
614 j <- as.integer(j)
615 dj <- data[, j + 1]
616 r <- commaToRange(k)
617 ij <- if (length(r) == 2 && is.numeric(dj)) {
618 which(dj >= r[1] & dj <= r[2])
619 } else {
620 grep2(k, as.character(dj), fixed = col[['search']][['regex']] == 'false',
621 ignore.case = ci)
622 }
623 i <- intersect(ij, i)
624 if (length(i) == 0) break
625 }
626 if (length(i) != n) data <- data[i, , drop = FALSE]
627
628 # sorting
629 oList <- list()
630 for (ord in q$order) {
631 k <- ord[['column']] # which column to sort
632 d <- ord[['dir']] # direction asc/desc
633 if (q$columns[[k]][['orderable']] != 'true') next
634 col <- data[, as.integer(k) + 1]
635 oList[[length(oList) + 1]] <- (if (d == 'asc') identity else `-`)(
636 if (is.numeric(col)) col else xtfrm(col)
637 )
638 }
639 if (length(oList)) {
640 i <- do.call(order, oList)
641 data <- data[i, , drop = FALSE]
642 }
643 # paging
644 if (q$length != '-1') {
645 i <- seq(as.integer(q$start) + 1L, length.out = as.integer(q$length))
646 i <- i[i <= nrow(data)]
647 fdata <- data[i, , drop = FALSE] # filtered data
648 } else fdata <- data
649
650 fdata <- unname(as.matrix(fdata))
651 if (is.character(fdata) && q$escape != 'false') {
652 if (q$escape == 'true') {
653 # fdata must be a matrix at this point, and we need to preserve
654 # dimensions. Note that it could be a 1xn matrix.
655 dims <- dim(fdata)
656 fdata <- htmlEscape(fdata)
657 dim(fdata) <- dims
658
659 } else {
660 k <- as.integer(strsplit(q$escape, ',')[[1]])
661 # use seq_len() in case escape = negative indices, e.g. c(-1, -5)
662 for (j in seq_len(ncol(fdata))[k]) fdata[, j] <- htmlEscape(fdata[, j])
663 }
664 }
665
666 res <- toJSON(list(
667 draw = as.integer(q$draw),
668 recordsTotal = n,
669 recordsFiltered = nrow(data),
670 data = fdata
671 ))
672 httpResponse(200, 'application/json', enc2utf8(res))
673 }
674
675 # when both ignore.case and fixed are TRUE, we use grep(ignore.case = FALSE,
676 # fixed = TRUE) to do lower-case matching of pattern on x
677 grep2 <- function(pattern, x, ignore.case = FALSE, fixed = FALSE, ...) {
678 if (fixed && ignore.case) {
679 pattern <- tolower(pattern)
680 x <- tolower(x)
681 ignore.case <- FALSE
682 }
683 # when the user types in the search box, the regular expression may not be
684 # complete before it is sent to the server, in which case we do not search
685 if (!fixed && inherits(try(grep(pattern, ''), silent = TRUE), 'try-error'))
686 return(seq_along(x))
687 grep(pattern, x, ignore.case = ignore.case, fixed = fixed, ...)
688 }
689
690 getExists <- function(x, mode, envir = parent.frame()) {
691 if (exists(x, envir = envir, mode = mode, inherits = FALSE))
692 get(x, envir = envir, mode = mode, inherits = FALSE)
693 }
694
695 # convert a string of the form "lower,upper" to c(lower, upper)
696 commaToRange <- function(string) {
697 if (!grepl(',', string)) return()
698 r <- strsplit(string, ',')[[1]]
699 if (length(r) > 2) return()
700 if (length(r) == 1) r <- c(r, '') # lower,
701 r <- as.numeric(r)
702 if (is.na(r[1])) r[1] <- -Inf
703 if (is.na(r[2])) r[2] <- Inf
704 r
705 }
706
707 # for options passed to DataTables/Selectize/..., the options of the class AsIs
708 # will be evaluated as literal JavaScript code
709 checkAsIs <- function(options) {
710 evalOptions <- if (length(options)) {
711 nms <- names(options)
712 if (length(nms) == 0L || any(nms == '')) stop("'options' must be a named list")
713 i <- unlist(lapply(options, function(x) {
714 is.character(x) && inherits(x, 'AsIs')
715 }))
716 if (any(i)) {
717 # must convert to character, otherwise toJSON() turns it to an array []
718 options[i] <- lapply(options[i], paste, collapse = '\n')
719 nms[i] # options of these names will be evaluated in JS
720 }
721 }
722 list(options = options, eval = evalOptions)
723 }
724
725 srcrefFromShinyCall <- function(expr) {
726 srcrefs <- attr(expr, "srcref")
727 num_exprs <- length(srcrefs)
728 if (num_exprs < 1)
729 return(NULL)
730 c(srcrefs[[1]][1], srcrefs[[1]][2],
731 srcrefs[[num_exprs]][3], srcrefs[[num_exprs]][4],
732 srcrefs[[1]][5], srcrefs[[num_exprs]][6])
733 }
734
735 # Indicates whether the given querystring should cause the associated request
736 # to be handled in showcase mode. Returns the showcase mode if set, or NULL
737 # if no showcase mode is set.
738 showcaseModeOfQuerystring <- function(querystring) {
739 if (nchar(querystring) > 0) {
740 qs <- parseQueryString(querystring)
741 if (exists("showcase", where = qs)) {
742 return(as.numeric(qs$showcase))
743 }
744 }
745 return(NULL)
746 }
747
748 showcaseModeOfReq <- function(req) {
749 showcaseModeOfQuerystring(req$QUERY_STRING)
750 }
751
752 # Returns (just) the filename containing the given source reference, or an
753 # empty string if the source reference doesn't include file information.
754 srcFileOfRef <- function(srcref) {
755 fileEnv <- attr(srcref, "srcfile")
756 # The 'srcfile' attribute should be a non-null environment containing the
757 # variable 'filename', which gives the full path to the source file.
758 if (!is.null(fileEnv) &&
759 is.environment(fileEnv) &&
760 exists("filename", where = fileEnv))
761 basename(fileEnv[["filename"]])
762 else
763 ""
764 }
765
766 # Format a number without sci notation, and keep as many digits as possible (do
767 # we really need to go beyond 15 digits?)
768 formatNoSci <- function(x) {
769 if (is.null(x)) return(NULL)
770 format(x, scientific = FALSE, digits = 15)
771 }
772
773 # A simple getter/setting to track the last time the auto-reload process
774 # updated. This value is used by `cachedFuncWithFile()` when auto-reload is
775 # enabled to reload app/ui/server files when watched supporting files change.
776 cachedAutoReloadLastChanged <- local({
777 last_update <- 0
778
779 list(
780 set = function() {
781 last_update <<- as.integer(Sys.time())
782 invisible(last_update)
783 },
784 get = function() {
785 last_update
786 }
787 )
788 })
789
790 # Returns a function that calls the given func and caches the result for
791 # subsequent calls, unless the given file's mtime changes.
792 cachedFuncWithFile <- function(dir, file, func, case.sensitive = FALSE) {
793 dir <- normalizePath(dir, mustWork = TRUE)
794
795 value <- NULL
796 last_mtime_file <- NA
797 last_autoreload <- 0
798
799 function(...) {
800 fname <- if (case.sensitive) {
801 file.path(dir, file)
802 } else {
803 file.path.ci(dir, file)
804 }
805
806 now <- file.info(fname)$mtime
807 autoreload <- last_autoreload < cachedAutoReloadLastChanged$get()
808 if (autoreload || !identical(last_mtime_file, now)) {
809 value <<- func(fname, ...)
810 last_mtime_file <<- now
811 last_autoreload <<- cachedAutoReloadLastChanged$get()
812 }
813 value
814 }
815 }
816
817 # turn column-based data to row-based data (mainly for JSON), e.g. data.frame(x
818 # = 1:10, y = 10:1) ==> list(list(x = 1, y = 10), list(x = 2, y = 9), ...)
819 columnToRowData <- function(data) {
820 do.call(
821 mapply, c(
822 list(FUN = function(...) list(...), SIMPLIFY = FALSE, USE.NAMES = FALSE),
823 as.list(data)
824 )
825 )
826 }
827
828 #' Declare an error safe for the user to see
829 #'
830 #' This should be used when you want to let the user see an error
831 #' message even if the default is to sanitize all errors. If you have an
832 #' error `e` and call `stop(safeError(e))`, then Shiny will
833 #' ignore the value of `getOption("shiny.sanitize.errors")` and always
834 #' display the error in the app itself.
835 #'
836 #' @param error Either an "error" object or a "character" object (string).
837 #' In the latter case, the string will become the message of the error
838 #' returned by `safeError`.
839 #'
840 #' @return An "error" object
841 #'
842 #' @details An error generated by `safeError` has priority over all
843 #' other Shiny errors. This can be dangerous. For example, if you have set
844 #' `options(shiny.sanitize.errors = TRUE)`, then by default all error
845 #' messages are omitted in the app, and replaced by a generic error message.
846 #' However, this does not apply to `safeError`: whatever you pass
847 #' through `error` will be displayed to the user. So, this should only
848 #' be used when you are sure that your error message does not contain any
849 #' sensitive information. In those situations, `safeError` can make
850 #' your users' lives much easier by giving them a hint as to where the
851 #' error occurred.
852 #'
853 #' @seealso [shiny-options()]
854 #'
855 #' @examples
856 #' ## Only run examples in interactive R sessions
857 #' if (interactive()) {
858 #'
859 #' # uncomment the desired line to experiment with shiny.sanitize.errors
860 #' # options(shiny.sanitize.errors = TRUE)
861 #' # options(shiny.sanitize.errors = FALSE)
862 #'
863 #' # Define UI
864 #' ui <- fluidPage(
865 #' textInput('number', 'Enter your favorite number from 1 to 10', '5'),
866 #' textOutput('normalError'),
867 #' textOutput('safeError')
868 #' )
869 #'
870 #' # Server logic
871 #' server <- function(input, output) {
872 #' output$normalError <- renderText({
873 #' number <- input$number
874 #' if (number %in% 1:10) {
875 #' return(paste('You chose', number, '!'))
876 #' } else {
877 #' stop(
878 #' paste(number, 'is not a number between 1 and 10')
879 #' )
880 #' }
881 #' })
882 #' output$safeError <- renderText({
883 #' number <- input$number
884 #' if (number %in% 1:10) {
885 #' return(paste('You chose', number, '!'))
886 #' } else {
887 #' stop(safeError(
888 #' paste(number, 'is not a number between 1 and 10')
889 #' ))
890 #' }
891 #' })
892 #' }
893 #'
894 #' # Complete app with UI and server components
895 #' shinyApp(ui, server)
896 #' }
897 #' @export
898 safeError <- function(error) {
899 if (inherits(error, "character")) {
900 error <- simpleError(error)
901 }
902 if (!inherits(error, "error")) {
903 stop("The class of the `error` parameter must be either 'error' or 'character'")
904 }
905 class(error) <- c("shiny.custom.error", class(error))
906 error
907 }
908
909 #***********************************************************************#
910 #**** Keep this function internal for now, may chnage in the future ****#
911 #***********************************************************************#
912 # #' Propagate an error through Shiny, but catch it before it throws
913 # #'
914 # #' Throws a type of exception that is caught by observers. When such an
915 # #' exception is triggered, all reactive links are broken. So, essentially,
916 # #' \code{reactiveStop()} behaves just like \code{stop()}, except that
917 # #' instead of ending the session, it is silently swalowed by Shiny.
918 # #'
919 # #' This function should be used when you want to disrupt the reactive
920 # #' links in a reactive chain, but do not want to end the session. For
921 # #' example, this enables you to disallow certain inputs, but get back
922 # #' to business as usual when valid inputs are re-entered.
923 # #' \code{reactiveStop} is also called internally by Shiny to create
924 # #' special errors, such as the ones generated by \code{\link{validate}()},
925 # #' \code{\link{req}()} and \code{\link{cancelOutput}()}.
926 # #'
927 # #' @param message An optional error message.
928 # #' @param class An optional class to add to the error.
929 # #' @export
930 # #' @examples
931 # #' ## Note: the breaking of the reactive chain that happens in the app
932 # #' ## below (when input$txt = 'bad' and input$allowBad = 'FALSE') is
933 # #' ## easily visualized with `reactlogShow()`
934 # #'
935 # #' ## Only run examples in interactive R sessions
936 # #' if (interactive()) {
937 # #'
938 # #' ui <- fluidPage(
939 # #' textInput('txt', 'Enter some text...'),
940 # #' selectInput('allowBad', 'Allow the string \'bad\'?',
941 # #' c('TRUE', 'FALSE'), selected = 'FALSE')
942 # #' )
943 # #'
944 # #' server <- function(input, output) {
945 # #' val <- reactive({
946 # #' if (!(as.logical(input$allowBad))) {
947 # #' if (identical(input$txt, "bad")) {
948 # #' reactiveStop()
949 # #' }
950 # #' }
951 ## ' })
952 # #'
953 # #' observe({
954 # #' val()
955 # #' })
956 # #' }
957 # #'
958 # #' shinyApp(ui, server)
959 # #' }
960 # #' @export
961 reactiveStop <- function(message = "", class = NULL) {
962 stopWithCondition(c("shiny.silent.error", class), message)
963 }
964
965 #' Validate input values and other conditions
966 #'
967 #' @description
968 #' `validate()` provides convenient mechanism for validating that an output
969 #' has all the inputs necessary for successful rendering. It takes any number
970 #' of (unnamed) arguments, each representing a condition to test. If any
971 #' of condition fails (i.e. is not ["truthy"][isTruthy]), a special type of
972 #' error is signaled to stop execution. If this error is not handled by
973 #' application-specific code, it is displayed to the user by Shiny.
974 #'
975 #' If you use `validate()` in a [reactive()] validation failures will
976 #' automatically propagate to outputs that use the reactive.
977 #'
978 #' @section `need()`:
979 #' An easy way to provide arguments to `validate()` is to use `need()`, which
980 #' takes an expression and a string. If the expression is not
981 #' ["truthy"][isTruthy] then the string will be used as the error message.
982 #'
983 #' If "truthiness" is flexible for your use case, you'll need to explicitly
984 #' generate a logical values. For example, if you want allow `NA` but not
985 #' `NULL`, you can `!is.null(input$foo)`.
986 #'
987 #' If you need validation logic that differs significantly from `need()`, you
988 #' can create your own validation test functions. A passing test should return
989 #' `NULL`. A failing test should return either a string providing the error
990 #' to display to the user, or if the failure should happen silently, `FALSE`.
991 #'
992 #' Alternatively you can use `validate()` within an `if` statement, which is
993 #' particularly useful for more complex conditions:
994 #'
995 #' ```
996 #' if (input$x < 0 && input$choice == "positive") {
997 #' validate("If choice is positive then x must be greater than 0")
998 #' }
999 #' ```
1000 #'
1001 #' @param ... A list of tests. Each test should equal `NULL` for success,
1002 #' `FALSE` for silent failure, or a string for failure with an error
1003 #' message.
1004 #' @param errorClass A CSS class to apply. The actual CSS string will have
1005 #' `shiny-output-error-` prepended to this value.
1006 #' @export
1007 #' @examples
1008 #' ## Only run examples in interactive R sessions
1009 #' if (interactive()) {
1010 #' options(device.ask.default = FALSE)
1011 #'
1012 #' ui <- fluidPage(
1013 #' checkboxGroupInput('in1', 'Check some letters', choices = head(LETTERS)),
1014 #' selectizeInput('in2', 'Select a state', choices = c("", state.name)),
1015 #' plotOutput('plot')
1016 #' )
1017 #'
1018 #' server <- function(input, output) {
1019 #' output$plot <- renderPlot({
1020 #' validate(
1021 #' need(input$in1, 'Check at least one letter!'),
1022 #' need(input$in2 != '', 'Please choose a state.')
1023 #' )
1024 #' plot(1:10, main = paste(c(input$in1, input$in2), collapse = ', '))
1025 #' })
1026 #' }
1027 #'
1028 #' shinyApp(ui, server)
1029 #'
1030 #' }
1031 validate <- function(..., errorClass = character(0)) {
1032 results <- sapply(list2(...), function(x) {
1033 # Detect NULL or NA
1034 if (is.null(x))
1035 return(NA_character_)
1036 else if (identical(x, FALSE))
1037 return("")
1038 else if (is.character(x))
1039 return(paste(as.character(x), collapse = "\n"))
1040 else
1041 stop("Unexpected validation result: ", as.character(x))
1042 })
1043
1044 results <- stats::na.omit(results)
1045 if (length(results) == 0)
1046 return(invisible())
1047
1048 # There may be empty strings remaining; these are message-less failures that
1049 # started as FALSE
1050 results <- results[nzchar(results)]
1051 reactiveStop(paste(results, collapse="\n"), c(errorClass, "validation"))
1052 }
1053
1054 #' @param expr An expression to test. The condition will pass if the expression
1055 #' meets the conditions spelled out in Details.
1056 #' @param message A message to convey to the user if the validation condition is
1057 #' not met. If no message is provided, one will be created using `label`.
1058 #' To fail with no message, use `FALSE` for the message.
1059 #' @param label A human-readable name for the field that may be missing. This
1060 #' parameter is not needed if `message` is provided, but must be provided
1061 #' otherwise.
1062 #' @export
1063 #' @rdname validate
1064 need <- function(expr, message = paste(label, "must be provided"), label) {
1065
1066 force(message) # Fail fast on message/label both being missing
1067
1068 if (!isTruthy(expr))
1069 return(message)
1070 else
1071 return(invisible(NULL))
1072 }
1073
1074 #' Check for required values
1075 #'
1076 #' Ensure that values are available (["truthy"][isTruthy]) before proceeding
1077 #' with a calculation or action. If any of the given values is not truthy, the
1078 #' operation is stopped by raising a "silent" exception (not logged by Shiny,
1079 #' nor displayed in the Shiny app's UI).
1080 #'
1081 #' The `req` function was designed to be used in one of two ways. The first
1082 #' is to call it like a statement (ignoring its return value) before attempting
1083 #' operations using the required values:
1084 #'
1085 #' ```
1086 #' rv <- reactiveValues(state = FALSE)
1087 #' r <- reactive({
1088 #' req(input$a, input$b, rv$state)
1089 #' # Code that uses input$a, input$b, and/or rv$state...
1090 #' })
1091 #' ```
1092 #'
1093 #' In this example, if `r()` is called and any of `input$a`,
1094 #' `input$b`, and `rv$state` are `NULL`, `FALSE`, `""`,
1095 #' etc., then the `req` call will trigger an error that propagates all the
1096 #' way up to whatever render block or observer is executing.
1097 #'
1098 #' The second is to use it to wrap an expression that must be truthy:
1099 #'
1100 #' ```
1101 #' output$plot <- renderPlot({
1102 #' if (req(input$plotType) == "histogram") {
1103 #' hist(dataset())
1104 #' } else if (input$plotType == "scatter") {
1105 #' qplot(dataset(), aes(x = x, y = y))
1106 #' }
1107 #' })
1108 #' ```
1109 #'
1110 #' In this example, `req(input$plotType)` first checks that
1111 #' `input$plotType` is truthy, and if so, returns it. This is a convenient
1112 #' way to check for a value "inline" with its first use.
1113 #'
1114 #' @section Using `req(FALSE)`:
1115 #'
1116 #' You can use `req(FALSE)` (i.e. no condition) if you've already performed
1117 #' all the checks you needed to by that point and just want to stop the reactive
1118 #' chain now. There is no advantage to this, except perhaps ease of readability
1119 #' if you have a complicated condition to check for (or perhaps if you'd like to
1120 #' divide your condition into nested `if` statements).
1121 #'
1122 #' @section Using `cancelOutput = TRUE`:
1123 #'
1124 #' When `req(..., cancelOutput = TRUE)` is used, the "silent" exception is
1125 #' also raised, but it is treated slightly differently if one or more outputs are
1126 #' currently being evaluated. In those cases, the reactive chain does not proceed
1127 #' or update, but the output(s) are left is whatever state they happen to be in
1128 #' (whatever was their last valid state).
1129 #'
1130 #' Note that this is always going to be the case if
1131 #' this is used inside an output context (e.g. `output$txt <- ...`). It may
1132 #' or may not be the case if it is used inside a non-output context (e.g.
1133 #' [reactive()], [observe()] or [observeEvent()])
1134 #' --- depending on whether or not there is an `output$...` that is triggered
1135 #' as a result of those calls. See the examples below for concrete scenarios.
1136 #'
1137 #' @param ... Values to check for truthiness.
1138 #' @param cancelOutput If `TRUE` and an output is being evaluated, stop
1139 #' processing as usual but instead of clearing the output, leave it in
1140 #' whatever state it happens to be in. If `"progress"`, do the same as `TRUE`,
1141 #' but also keep the output in recalculating state; this is intended for cases
1142 #' when an in-progress calculation will not be completed in this reactive
1143 #' flush cycle, but is still expected to provide a result in the future.
1144 #' @return The first value that was passed in.
1145 #' @export
1146 #' @examples
1147 #' ## Only run examples in interactive R sessions
1148 #' if (interactive()) {
1149 #' ui <- fluidPage(
1150 #' textInput('data', 'Enter a dataset from the "datasets" package', 'cars'),
1151 #' p('(E.g. "cars", "mtcars", "pressure", "faithful")'), hr(),
1152 #' tableOutput('tbl')
1153 #' )
1154 #'
1155 #' server <- function(input, output) {
1156 #' output$tbl <- renderTable({
1157 #'
1158 #' ## to require that the user types something, use: `req(input$data)`
1159 #' ## but better: require that input$data is valid and leave the last
1160 #' ## valid table up
1161 #' req(exists(input$data, "package:datasets", inherits = FALSE),
1162 #' cancelOutput = TRUE)
1163 #'
1164 #' head(get(input$data, "package:datasets", inherits = FALSE))
1165 #' })
1166 #' }
1167 #'
1168 #' shinyApp(ui, server)
1169 #' }
1170 req <- function(..., cancelOutput = FALSE) {
1171 dotloop(function(item) {
1172 if (!isTruthy(item)) {
1173 if (isTRUE(cancelOutput)) {
1174 cancelOutput()
1175 } else if (identical(cancelOutput, "progress")) {
1176 reactiveStop(class = "shiny.output.progress")
1177 } else {
1178 reactiveStop(class = "validation")
1179 }
1180 }
1181 }, ...)
1182
1183 if (!missing(..1))
1184 ..1
1185 else
1186 invisible()
1187 }
1188
1189 #***********************************************************************#
1190 #**** Keep this function internal for now, may chnage in the future ****#
1191 #***********************************************************************#
1192 # #' Cancel processing of the current output
1193 # #'
1194 # #' Signals an error that Shiny treats specially if an output is currently being
1195 # #' evaluated. Execution will stop, but rather than clearing the output (as
1196 # #' \code{\link{req}} does) or showing an error message (as \code{\link{stop}}
1197 # #' does), the output simply remains unchanged.
1198 # #'
1199 # #' If \code{cancelOutput} is called in any non-output context (like in an
1200 # #' \code{\link{observe}} or \code{\link{observeEvent}}), the effect is the same
1201 # #' as \code{\link{req}(FALSE)}.
1202 # #' @export
1203 # #' @examples
1204 # #' ## Only run examples in interactive R sessions
1205 # #' if (interactive()) {
1206 # #'
1207 # #' # uncomment the desired line to experiment with cancelOutput() vs. req()
1208 # #'
1209 # #' ui <- fluidPage(
1210 # #' textInput('txt', 'Enter text'),
1211 # #' textOutput('check')
1212 # #' )
1213 # #'
1214 # #' server <- function(input, output) {
1215 # #' output$check <- renderText({
1216 # #' # req(input$txt)
1217 # #' if (input$txt == 'hi') return('hi')
1218 # #' else if (input$txt == 'bye') return('bye')
1219 # #' # else cancelOutput()
1220 # #' })
1221 # #' }
1222 # #'
1223 # #' shinyApp(ui, server)
1224 # #' }
1225 cancelOutput <- function() {
1226 reactiveStop(class = "shiny.output.cancel")
1227 }
1228
1229 # Execute a function against each element of ..., but only evaluate each element
1230 # after the previous element has been passed to fun_. The return value of fun_
1231 # is discarded, and only invisible() is returned from dotloop.
1232 #
1233 # Can be used to facilitate short-circuit eval on dots.
1234 dotloop <- function(fun_, ...) {
1235 for (i in seq_len(nargs() - 1)) {
1236 fun_(eval(as.symbol(paste0("..", i))))
1237 }
1238 invisible()
1239 }
1240
1241 #' Truthy and falsy values
1242 #'
1243 #' The terms "truthy" and "falsy" generally indicate whether a value, when
1244 #' coerced to a [base::logical()], is `TRUE` or `FALSE`. We use
1245 #' the term a little loosely here; our usage tries to match the intuitive
1246 #' notions of "Is this value missing or available?", or "Has the user provided
1247 #' an answer?", or in the case of action buttons, "Has the button been
1248 #' clicked?".
1249 #'
1250 #' For example, a `textInput` that has not been filled out by the user has
1251 #' a value of `""`, so that is considered a falsy value.
1252 #'
1253 #' To be precise, a value is truthy *unless* it is one of:
1254 #'
1255 #' * `FALSE`
1256 #' * `NULL`
1257 #' * `""`
1258 #' * An empty atomic vector
1259 #' * An atomic vector that contains only missing values
1260 #' * A logical vector that contains all `FALSE` or missing values
1261 #' * An object of class `"try-error"`
1262 #' * A value that represents an unclicked [actionButton()]
1263 #'
1264 #' Note in particular that the value `0` is considered truthy, even though
1265 #' `as.logical(0)` is `FALSE`.
1266 #'
1267 #' @param x An expression whose truthiness value we want to determine
1268 #' @export
1269 isTruthy <- function(x) {
1270 if (is.null(x))
1271 return(FALSE)
1272 if (inherits(x, 'try-error'))
1273 return(FALSE)
1274 if (!is.atomic(x))
1275 return(TRUE)
1276 if (length(x) == 0)
1277 return(FALSE)
1278 if (all(is.na(x)))
1279 return(FALSE)
1280 if (is.character(x) && !any(nzchar(stats::na.omit(x))))
1281 return(FALSE)
1282 if (inherits(x, 'shinyActionButtonValue') && x == 0)
1283 return(FALSE)
1284 if (is.logical(x) && !any(stats::na.omit(x)))
1285 return(FALSE)
1286
1287 return(TRUE)
1288 }
1289
1290 # add class(es) to the error condition, which will be used as names of CSS
1291 # classes, e.g. shiny-output-error shiny-output-error-validation
1292 stopWithCondition <- function(class, message) {
1293 cond <- structure(
1294 list(message = message),
1295 class = c(class, 'error', 'condition')
1296 )
1297 stop(cond)
1298 }
1299
1300 #' Collect information about the Shiny Server environment
1301 #'
1302 #' This function returns the information about the current Shiny Server, such as
1303 #' its version, and whether it is the open source edition or professional
1304 #' edition. If the app is not served through the Shiny Server, this function
1305 #' just returns `list(shinyServer = FALSE)`.
1306 #'
1307 #' This function will only return meaningful data when using Shiny Server
1308 #' version 1.2.2 or later.
1309 #' @export
1310 #' @return A list of the Shiny Server information.
1311 serverInfo <- function() {
1312 .globals$serverInfo
1313 }
1314 .globals$serverInfo <- list(shinyServer = FALSE)
1315
1316 setServerInfo <- function(...) {
1317 infoOld <- serverInfo()
1318 infoNew <- list(...)
1319 infoOld[names(infoNew)] <- infoNew
1320 .globals$serverInfo <- infoOld
1321 }
1322
1323 # assume file is encoded in UTF-8, but warn against BOM
1324 checkEncoding <- function(file) {
1325 # skip *nix because its locale is normally UTF-8 based (e.g. en_US.UTF-8), and
1326 # *nix users have to make a conscious effort to save a file with an encoding
1327 # that is not UTF-8; if they choose to do so, we cannot do much about it
1328 # except sitting back and seeing them punished after they choose to escape a
1329 # world of consistency (falling back to getOption('encoding') will not help
1330 # because native.enc is also normally UTF-8 based on *nix)
1331 if (!isWindows()) return('UTF-8')
1332 size <- file.info(file)[, 'size']
1333 if (is.na(size)) stop('Cannot access the file ', file)
1334 # BOM is 3 bytes, so if the file contains BOM, it must be at least 3 bytes
1335 if (size < 3L) return('UTF-8')
1336
1337 # check if there is a BOM character: this is also skipped on *nix, because R
1338 # on *nix simply ignores this meaningless character if present, but it hurts
1339 # on Windows
1340 if (identical(charToRaw(readChar(file, 3L, TRUE)), charToRaw('\UFEFF'))) {
1341 warning('You should not include the Byte Order Mark (BOM) in ', file, '. ',
1342 'Please re-save it in UTF-8 without BOM. See ',
1343 'https://shiny.rstudio.com/articles/unicode.html for more info.')
1344 return('UTF-8-BOM')
1345 }
1346 x <- readChar(file, size, useBytes = TRUE)
1347 if (is.na(iconv(x, 'UTF-8', 'UTF-8'))) {
1348 warning('The input file ', file, ' does not seem to be encoded in UTF8')
1349 }
1350 'UTF-8'
1351 }
1352
1353 # read a file using UTF-8 and (on Windows) convert to native encoding if possible
1354 readUTF8 <- function(file) {
1355 enc <- checkEncoding(file)
1356 file <- base::file(file, encoding = enc)
1357 on.exit(close(file), add = TRUE)
1358 x <- enc2utf8(readLines(file, warn = FALSE))
1359 tryNativeEncoding(x)
1360 }
1361
1362 # if the UTF-8 string can be represented in the native encoding, use native encoding
1363 tryNativeEncoding <- function(string) {
1364 if (!isWindows()) return(string)
1365 string2 <- enc2native(string)
1366 if (identical(enc2utf8(string2), string)) string2 else string
1367 }
1368
1369 maybeAnnotateSourceForArk <- function(file, lines) {
1370 ark_annotate_source <- get0(".ark_annotate_source", baseenv())
1371
1372 if (is.null(ark_annotate_source)) {
1373 return(lines)
1374 }
1375
1376 file <- normalizePath(file, mustWork = TRUE, winslash = "/") # Just to be safe
1377 uri <- paste0("file:///", sub("^/", "", file)) # Ark expects URIs
1378 lines_str <- paste(lines, collapse = "\n")
1379 tryCatch(
1380 {
1381 annotated <- ark_annotate_source(lines_str, uri)
1382 if (!is.null(annotated)) {
1383 lines <- strsplit(annotated, "\n", fixed = TRUE)[[1]]
1384 }
1385 },
1386 error = function(cnd) {
1387 rlang::warn("Can't inject breakpoints for Ark", parent = cnd)
1388 }
1389 )
1390
1391
1392 lines
1393 }
1394
1395 # similarly, try to source() a file with UTF-8
1396 sourceUTF8 <- function(file, envir = globalenv()) {
1397 file_norm <- normalizePath(file, mustWork = TRUE, winslash = "/")
1398 lines <- readUTF8(file)
1399 enc <- if (any(Encoding(lines) == 'UTF-8')) 'UTF-8' else 'unknown'
1400
1401 # Inject Ark annotations for breakpoints if available
1402 lines <- maybeAnnotateSourceForArk(file, lines)
1403
1404 # Wrap in `..stacktraceon..({...})` using string manipulation before parsing,
1405 # with a `#line` directive to map source references back to the original file
1406 lines <- c(
1407 "..stacktraceon..({",
1408 sprintf('#line 1 "%s"', file_norm),
1409 lines,
1410 "})"
1411 )
1412
1413 # Create a source file copy, i.e. an in-memory srcfile that contains all the
1414 # code but refers to an original file
1415 src <- srcfilecopy(file, lines, isFile = TRUE)
1416
1417 # Parse from our annotated lines
1418 exprs <- tryCatch(
1419 parse(text = lines, keep.source = FALSE, srcfile = src, encoding = enc),
1420 error = function(cnd) {
1421 diagnoseCode(file)
1422 stop("Error sourcing ", file)
1423 }
1424 )
1425
1426 eval(exprs, envir)
1427 }
1428
1429 # @param func Name of function, in unquoted form
1430 # @param args An evaluated list of unevaluated argument expressions
1431 makeCall <- function(func, args) {
1432 as.call(c(list(substitute(func)), args))
1433 }
1434
1435 # a workaround for https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=16264
1436 srcfilecopy <- function(filename, lines, ...) {
1437 if (getRversion() > '3.2.2') return(base::srcfilecopy(filename, lines, ...))
1438 src <- base::srcfilecopy(filename, lines = '', ...)
1439 src$lines <- lines
1440 src
1441 }
1442
1443 # write text as UTF-8
1444 writeUTF8 <- function(text, ...) {
1445 text <- enc2utf8(text)
1446 writeLines(text, ..., useBytes = TRUE)
1447 }
1448
1449 URLdecode <- function(value) {
1450 decodeURIComponent(value)
1451 }
1452
1453 URLencode <- function(value, reserved = FALSE) {
1454 value <- enc2utf8(value)
1455 if (reserved) encodeURIComponent(value) else encodeURI(value)
1456 }
1457
1458 # Make sure user-supplied dates are either NULL or can be coerced to a
1459 # yyyy-mm-dd formatted string. If a date is specified, this function returns a
1460 # string for consistency across locales. Also, `as.Date()` is used to coerce
1461 # strings to date objects so that strings like "2016-08-9" are expanded to
1462 # "2016-08-09". If any of the values result in error or NA, then the input
1463 # `date` is returned unchanged.
1464 dateYMD <- function(date = NULL, argName = "value") {
1465 if (!length(date)) return(NULL)
1466 tryCatch({
1467 if (inherits(date, "POSIXt")) {
1468 res <- format(date, "%Y-%m-%d")
1469 } else {
1470 res <- format(as.Date(date), "%Y-%m-%d")
1471 }
1472 if (any(is.na(res))) stop()
1473 date <- res
1474 },
1475 error = function(e) {
1476 warning(
1477 "Couldn't coerce the `", argName,
1478 "` argument to a date string with format yyyy-mm-dd",
1479 call. = FALSE
1480 )
1481 }
1482 )
1483 date
1484 }
1485
1486 # This function takes a name and function, and it wraps that function in a new
1487 # function which calls the original function using the specified name. This can
1488 # be helpful for profiling, because the specified name will show up on the stack
1489 # trace.
1490 wrapFunctionLabel <- function(func, name, ..stacktraceon = FALSE, dots = TRUE) {
1491 if (name == "name" || name == "func" || name == "relabelWrapper") {
1492 stop("Invalid name for wrapFunctionLabel: ", name)
1493 }
1494 if (nchar(name, "bytes") > 10000) {
1495 # Max variable length in R is 10000 bytes. Truncate to a shorter number of
1496 # chars because some characters could be multi-byte.
1497 name <- substr(name, 1, 5000)
1498 }
1499
1500 assign(name, func, environment())
1501 registerDebugHook(name, environment(), name)
1502
1503 if (isTRUE(dots)) {
1504 if (..stacktraceon) {
1505 # We need to wrap the `...` in `!!quote(...)` so that R CMD check won't
1506 # complain about "... may be used in an incorrect context"
1507 body <- expr({ ..stacktraceon..((!!name)(!!quote(...))) })
1508 } else {
1509 body <- expr({ (!!name)(!!quote(...)) })
1510 }
1511 relabelWrapper <- new_function(pairlist2(... =), body, environment())
1512 } else {
1513 # Same logic as when `dots = TRUE`, but without the `...`
1514 if (..stacktraceon) {
1515 body <- expr({ ..stacktraceon..((!!name)()) })
1516 } else {
1517 body <- expr({ (!!name)() })
1518 }
1519 relabelWrapper <- new_function(list(), body, environment())
1520 }
1521
1522 # Preserve the original function that was passed in; is used for caching.
1523 attr(relabelWrapper, "wrappedFunc") <- func
1524 relabelWrapper
1525 }
1526
1527
1528 # This is a very simple mutable object which only stores one value
1529 # (which we can set and get). Using this class is sometimes useful
1530 # when communicating persistent changes across functions.
1531 Mutable <- R6Class("Mutable",
1532 private = list(
1533 value = NULL
1534 ),
1535 public = list(
1536 set = function(value) { private$value <- value },
1537 get = function() { private$value }
1538 )
1539 )
1540
1541 # More convenient way of chaining together promises than then/catch/finally,
1542 # without the performance impact of %...>%.
1543 promise_chain <- function(promise, ..., catch = NULL, finally = NULL,
1544 domain = NULL, replace = FALSE) {
1545
1546 do <- function() {
1547 p <- Reduce(function(memo, func) {
1548 promises::then(memo, func)
1549 }, list(...), promise)
1550
1551 if (!is.null(catch)) {
1552 p <- promises::catch(p, catch)
1553 }
1554
1555 if (!is.null(finally)) {
1556 p <- promises::finally(p, finally)
1557 }
1558
1559 p
1560 }
1561
1562 if (!is.null(domain)) {
1563 with_promise_domain(domain, do(), replace = replace)
1564 } else {
1565 do()
1566 }
1567 }
1568
1569 # Like promise_chain, but if `expr` returns a non-promise, then `...`, `catch`,
1570 # and `finally` are all executed synchronously
1571 hybrid_chain <- function(expr, ..., catch = NULL, finally = NULL,
1572 domain = NULL, replace = FALSE) {
1573
1574 do <- function() {
1575 runFinally <- TRUE
1576 tryCatch(
1577 {
1578 captureStackTraces({
1579 result <- withVisible(force(expr))
1580 if (is.promising(result$value)) {
1581 # Purposefully NOT including domain (nor replace), as we're already in
1582 # the domain at this point
1583 p <- promise_chain(valueWithVisible(result), ..., catch = catch, finally = finally)
1584 runFinally <- FALSE
1585 p
1586 } else {
1587 result <- Reduce(
1588 function(v, func) {
1589 if (v$visible) {
1590 withVisible(func(v$value))
1591 } else {
1592 withVisible(func(invisible(v$value)))
1593 }
1594 },
1595 list(...),
1596 result
1597 )
1598
1599 valueWithVisible(result)
1600 }
1601 })
1602 },
1603 error = function(e) {
1604 if (!is.null(catch))
1605 catch(e)
1606 else
1607 stop(e)
1608 },
1609 finally = if (runFinally && !is.null(finally)) finally()
1610 )
1611 }
1612
1613 if (!is.null(domain)) {
1614 with_promise_domain(domain, do(), replace = replace)
1615 } else {
1616 do()
1617 }
1618 }
1619
1620 # Given a list with items named `value` and `visible`, return `x$value` either
1621 # visibly, or invisibly, depending on the value of `x$visible`.
1622 valueWithVisible <- function(x) {
1623 if (x$visible) x$value else invisible(x$value)
1624 }
1625
1626
1627 createVarPromiseDomain <- function(env, name, value) {
1628 force(env)
1629 force(name)
1630 force(value)
1631
1632 new_promise_domain(
1633 wrapOnFulfilled = function(onFulfilled) {
1634 function(...) {
1635 orig <- env[[name]]
1636 env[[name]] <- value
1637 on.exit(env[[name]] <- orig)
1638
1639 onFulfilled(...)
1640 }
1641 },
1642 wrapOnRejected = function(onRejected) {
1643 function(...) {
1644 orig <- env[[name]]
1645 env[[name]] <- value
1646 on.exit(env[[name]] <- orig)
1647
1648 onRejected(...)
1649 }
1650 },
1651 wrapSync = function(expr) {
1652 orig <- env[[name]]
1653 env[[name]] <- value
1654 on.exit(env[[name]] <- orig)
1655
1656 force(expr)
1657 }
1658 )
1659 }
1660
1661 getSliderType <- function(min, max, value) {
1662 vals <- dropNulls(list(value, min, max))
1663 if (length(vals) == 0) return("")
1664 type <- unique(lapply(vals, function(x) {
1665 if (inherits(x, "Date")) "date"
1666 else if (inherits(x, "POSIXt")) "datetime"
1667 else "number"
1668 }))
1669 if (length(type) > 1) {
1670 rlang::abort(c(
1671 "Type mismatch for `min`, `max`, and `value`.",
1672 "All values must either be numeric, Date, or POSIXt."
1673 ))
1674 }
1675 type[[1]]
1676 }
1677
1678 # Reads the `shiny.sharedSecret` global option, and returns a function that can
1679 # be used to test header values for a match.
1680 loadSharedSecret <- function() {
1681 normalizeToRaw <- function(value, label = "value") {
1682 if (is.null(value)) {
1683 raw()
1684 } else if (is.character(value)) {
1685 charToRaw(paste(value, collapse = "\n"))
1686 } else if (is.raw(value)) {
1687 value
1688 } else {
1689 stop("Wrong type for ", label, "; character or raw expected")
1690 }
1691 }
1692
1693 sharedSecret <- normalizeToRaw(getOption("shiny.sharedSecret"))
1694 if (is.null(sharedSecret)) {
1695 function(x) TRUE
1696 } else {
1697 # We compare the digest of the two values so that their lengths are equalized
1698 function(x) {
1699 x <- normalizeToRaw(x)
1700 # Constant time comparison to avoid timing attacks
1701 constantTimeEquals(sharedSecret, x)
1702 }
1703 }
1704 }
1705
1706 # Compares two raw vectors of equal length for equality, in constant time
1707 constantTimeEquals <- function(raw1, raw2) {
1708 stopifnot(is.raw(raw1))
1709 stopifnot(is.raw(raw2))
1710 if (length(raw1) != length(raw2)) {
1711 return(FALSE)
1712 }
1713
1714 sum(as.integer(xor(raw1, raw2))) == 0
1715 }
1716
1717 cat_line <- function(...) {
1718 cat(paste(..., "\n", collapse = ""))
1719 }
1720
1721 select_menu <- function(choices, title = NULL, msg = "Enter one or more numbers (with spaces), or an empty line to exit: \n")
1722 {
1723 if (!is.null(title)) {
1724 cat(title, "\n", sep = "")
1725 }
1726 nc <- length(choices)
1727 op <- paste0(format(seq_len(nc)), ": ", choices)
1728 fop <- format(op)
1729 cat("", fop, "", sep = "\n")
1730 repeat {
1731 answer <- readline(msg)
1732 answer <- strsplit(answer, "[ ,]+")[[1]]
1733 if (all(answer %in% seq_along(choices))) {
1734 return(choices[as.integer(answer)])
1735 }
1736 }
1737 }
1738
1739 #' @noRd
1740 isAppDir <- function(path) {
1741
1742 if (file.exists(file.path.ci(path, "app.R")))
1743 return(TRUE)
1744
1745 if (file.exists(file.path.ci(path, "server.R"))
1746 && file.exists(file.path.ci(path, "ui.R")))
1747 return(TRUE)
1748
1749 FALSE
1750 }
1751
1752 # Borrowed from rprojroot which borrowed from devtools
1753 #' @noRd
1754 is_root <- function(path) {
1755 identical(
1756 normalizePath(path, winslash = "/"),
1757 normalizePath(dirname(path), winslash = "/")
1758 )
1759 }
1760
1761 #' @noRd
1762 findEnclosingApp <- function(path = ".") {
1763 orig_path <- path
1764 path <- normalizePath(path, winslash = "/", mustWork = TRUE)
1765 repeat {
1766 if (isAppDir(path))
1767 return(path)
1768 if (is_root(path))
1769 stop("Shiny app not found at ", orig_path, " or in any parent directory.")
1770 path <- dirname(path)
1771 }
1772 }
1773
1774 # Until `rlang::cnd_inherits()` is on CRAN
1775 cnd_inherits <- function(cnd, class) {
1776 cnd_some(cnd, ~ inherits(.x, class))
1777 }
1778 cnd_some <- function(.cnd, .p, ...) {
1779 .p <- rlang::as_function(.p)
1780
1781 while (rlang::is_condition(.cnd)) {
1782 if (.p(.cnd, ...)) {
1783 return(TRUE)
1784 }
1785
1786 .cnd <- .cnd$parent
1787 }
1788
1789 FALSE
1790 }