File: handler_pbcol.R

package info (click to toggle)
r-cran-progressr 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,132 kB
  • sloc: sh: 13; makefile: 7
file content (190 lines) | stat: -rw-r--r-- 6,701 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#' Progression Handler: Progress Reported as an ANSI Background Color in the Terminal
#'
#' @inheritParams make_progression_handler 
#'
#' @param adjust (numeric) The adjustment of the progress update,
#' where `adjust = 0` positions the message to the very left, and
#' `adjust = 1` positions the message to the very right.
#'
#' @param pad (integer) Amount of padding on each side of the message,
#' where padding is done by spaces.
#'
#' @param complete,incomplete (function) Functions that take "complete" and
#' "incomplete" strings that comprise the progress bar as input and annotate
#' them to reflect their two different parts.  The default is to annotation
#' them with two different background colors and the same foreground color
#' using the \pkg{cli} package.
#' 
#' @param \ldots Additional arguments passed to [make_progression_handler()].
#'
#' @section Requirements:
#' This progression handler requires the \pkg{cli} package.
#'
#' @section Appearance:
#' Below are a few examples on how to use and customize this progress handler.
#' In all cases, we use `handlers(global = TRUE)`.
#'
#' ```{asciicast handler_pbcol-default}
#' #| asciicast_at = "all",
#' #| asciicast_knitr_output = "svg",
#' #| asciicast_cursor = FALSE
#' handlers("pbcol")
#' y <- slow_sum(1:25)
#' ```
#'
#' ```{asciicast handler_pbcol-adjust-mid}
#' #| asciicast_at = "all",
#' #| asciicast_knitr_output = "svg",
#' #| asciicast_cursor = FALSE
#' handlers(handler_pbcol(adjust = 0.5))
#' y <- slow_sum(1:25)
#' ```
#'
#' ```{asciicast handler_pbcol-adjust-right-complete}
#' #| asciicast_at = "all",
#' #| asciicast_knitr_output = "svg",
#' #| asciicast_cursor = FALSE
#' handlers(handler_pbcol(
#'   adjust = 1,
#'   complete = function(s) cli::bg_red(cli::col_black(s)),
#'   incomplete = function(s) cli::bg_cyan(cli::col_black(s))
#' ))
#' y <- slow_sum(1:25)
#' ```
#'
#' @example incl/handler_pbcol.R
#'
#' @importFrom utils flush.console
#' @export
handler_pbcol <- function(adjust = 0.0, pad = 1L, complete = function(s) cli::bg_blue(cli::col_white(s)), incomplete = function(s) cli::bg_cyan(cli::col_white(s)), intrusiveness = getOption("progressr.intrusiveness.terminal", 1), target = "terminal", ...) {
  crayon_enabled <- getOption("crayon.enabled", NULL)
  if (is.null(crayon_enabled)) crayon_enabled <- (cli::num_ansi_colors() > 1L)

  cat_ <- function(...) {
    cat(..., sep = "", collapse = "", file = stderr())
    flush.console()
  }
  
  erase_progress_bar <- function() {
    cat_(c("\r", rep(" ", times = getOption("width")), "\r"))
  }
  
  redraw_progress_bar <- function(ratio, message, spin = " ") {
    stop_if_not(ratio >= 0, ratio <= 1)
    if (crayon_enabled) {
      options(crayon.enabled = TRUE)
      on.exit(options(crayon.enabled = TRUE), add = TRUE)
    }
    pbstr <- pbcol(
      fraction = ratio,
      msg = message,
      adjust = adjust,
      pad = pad,
      complete = complete,
      incomplete = incomplete,
      spin = spin,
    )
    cat_("\r", pbstr)
  }
  
  reporter <- local({
    spin_state <- 0L
    spinner <- c("-", "\\", "|", "/", "-", "\\", "|", "/")
    
    list(
      initiate = function(config, state, ...) {
        if (!state$enabled || config$times <= 2L) return()
        ratio <- if (config$max_steps == 0) 1 else state$step / config$max_steps
        redraw_progress_bar(ratio = ratio, message = state$message, spin = spinner[spin_state+1L])
      },
      
      reset = function(...) {
        erase_progress_bar()
      },
      
      hide = function(...) {
        erase_progress_bar()
      },

      unhide = function(config, state, ...) {
        if (!state$enabled || config$times <= 2L) return()
        ratio <- if (config$max_steps == 0) 1 else state$step / config$max_steps
        redraw_progress_bar(ratio = ratio, message = state$message, spin = spinner[spin_state+1L])
      },

      interrupt = function(config, state, progression, ...) {
        if (!state$enabled || config$times <= 2L) return()
        erase_progress_bar()
        ratio <- if (config$max_steps == 0) 1 else state$step / config$max_steps
        redraw_progress_bar(ratio = ratio, message = state$message, spin = spinner[spin_state+1L])
        msg <- conditionMessage(progression)
        msg <- paste(c("", msg, ""), collapse = "\n")
        cat_(msg)
      },

      update = function(config, state, progression, ...) {
        if (!state$enabled || config$times <= 2L) return()
        if (state$delta < 0) return()
        spin_state <<- (spin_state+1L) %% length(spinner)
        ratio <- if (config$max_steps == 0) 1 else state$step / config$max_steps
        redraw_progress_bar(ratio = ratio, message = state$message, spin = spinner[spin_state+1L])
      },

      finish = function(config, state, progression, ...) {
        if (config$clear) {
          erase_progress_bar()
        } else {
          redraw_progress_bar(ratio = 1, message = state$message, spin = " ")
          cat("\n", file = stderr())
        }
      }
    )
  })

  make_progression_handler("pbcol", reporter, intrusiveness = intrusiveness, target = target, ...)
}



pbcol <- function(fraction = 0.0, msg = "", adjust = 0, pad = 1L, width = getOption("width") - 1L, complete = function(s) cli::bg_blue(cli::col_white(s)), incomplete = function(s) cli::bg_cyan(cli::col_white(s)), spin = " ") {
  if (length(msg) == 0L) msg <- ""
  stop_if_not(length(msg) == 1L, is.character(msg))

  fraction <- as.numeric(fraction)
  stop_if_not(length(fraction) == 1L, !is.na(fraction),
            fraction >= 0, fraction <= 1)
            
  width <- as.integer(width)
  stop_if_not(length(width) == 1L, !is.na(width), width > 0L)

  msgfraction <- sprintf(" %3.0f%%", 100 * fraction)
  
  ## Pad 'fullmsg' to align horizontally
  nmsg <- nchar(msg) + nchar(msgfraction)
  msgpad <- (width - 2 * pad) - nmsg

  ## Truncate 'msg'?
  if (msgpad < 0) {
    msg <- substr(msg, start = pad, stop = nchar(msg) + msgpad - pad)
    msg <- substr(msg, start = 1L, stop = nchar(msg) - 3L)
    msg <- paste(msg, "...", sep = "")
    msgpad <- (width - 2 * pad) - nchar(msg) - nchar(msgfraction)
    stop_if_not(msgpad >= 0)
  }

  ## Pad 'msg'
  lpad <- floor(   adjust  * msgpad) + pad
  rpad <- floor((1-adjust) * msgpad)
  stop_if_not(lpad >= 0L, rpad >= 0L)
  pmsg <- sprintf("%*s%s%*s%s%s%*s", lpad, "", msg, rpad, "", msgfraction, spin, pad, "")

  ## Make progress bar
  len <- round(fraction * nchar(pmsg), digits = 0L)
  lmsg <- substr(pmsg, start = 1L, stop = len)
  rmsg <- substr(pmsg, start = len + 1L, stop = nchar(pmsg))
  if (!is.null(complete)) lmsg <- complete(lmsg)
  if (!is.null(incomplete)) rmsg <- incomplete(rmsg)
  bar <- paste(lmsg, rmsg, sep = "")
  
  bar
}