| 1 |
# graphics devices in base R, plus those in Cairo, tikzDevice |
| 2 |
auto_exts = c( |
| 3 |
bmp = 'bmp', postscript = 'eps', pdf = 'pdf', png = 'png', svg = 'svg', |
| 4 |
jpeg = 'jpeg', pictex = 'tex', tiff = 'tiff', win.metafile = 'wmf', |
| 5 |
cairo_pdf = 'pdf', cairo_ps = 'eps', |
| 6 |
|
| 7 |
quartz_pdf = 'pdf', quartz_png = 'png', quartz_jpeg = 'jpeg', |
| 8 |
quartz_tiff = 'tiff', quartz_gif = 'gif', quartz_psd = 'psd', |
| 9 |
quartz_bmp = 'bmp', |
| 10 |
|
| 11 |
CairoJPEG = 'jpeg', CairoPNG = 'png', CairoPS = 'eps', CairoPDF = 'pdf', |
| 12 |
CairoSVG = 'svg', CairoTIFF = 'tiff', |
| 13 |
|
| 14 |
svglite = 'svg', gridSVG = 'svg', |
| 15 |
|
| 16 |
ragg_png = 'png', |
| 17 |
|
| 18 |
tikz = 'tex' |
| 19 |
) |
| 20 |
|
| 21 |
# choose a file extension according to the device, unless fig.ext is provided |
| 22 |
dev2ext = function(options) { |
| 23 |
if (length(ext <- options$fig.ext)) return(ext) |
| 24 |
x = options$dev |
| 25 |
res = auto_exts[x] |
| 26 |
if (any(idx <- is.na(res))) { |
| 27 |
for (i in x[idx]) dev_get(i) |
| 28 |
stop2( |
| 29 |
'cannot find appropriate filename extensions for device ', x[idx], '; ', |
| 30 |
"please use chunk option 'fig.ext' (https://yihui.org/knitr/options/)" |
| 31 |
) |
| 32 |
} |
| 33 |
unname(res) |
| 34 |
} |
| 35 |
|
| 36 |
# test if a device is available (and remember it), e.g., dev_available('png', |
| 37 |
# png); capabilities() gives similar results for some devices but this function |
| 38 |
# is more general |
| 39 |
dev_available = local({ |
| 40 |
res = list() |
| 41 |
function(name, fun = dev_get(name)) { |
| 42 |
if (!is.null(res[[name]])) return(res[[name]]) |
| 43 |
res[[name]] <<- tryCatch({ |
| 44 |
f = tempfile(); on.exit(unlink(f)) |
| 45 |
fun(f, width = 5, height = 5) |
| 46 |
grDevices::dev.off() |
| 47 |
TRUE |
| 48 |
}, error = function(e) FALSE) |
| 49 |
} |
| 50 |
}) |
| 51 |
|
| 52 |
dev_get = function(dev, options = opts_current$get(), dpi = options$dpi[1]) { |
| 53 |
if (is.null(dpi) || is.na(dpi)) dpi = 72 |
| 54 |
device = switch( |
| 55 |
dev, |
| 56 |
bmp = function(...) bmp(..., res = dpi, units = 'in'), |
| 57 |
postscript = function(...) { |
| 58 |
postscript(..., onefile = FALSE, horizontal = FALSE, paper = 'special') |
| 59 |
}, |
| 60 |
jpeg = function(...) jpeg(..., res = dpi, units = 'in'), |
| 61 |
pdf = grDevices::pdf, |
| 62 |
png = function(...) png(..., res = dpi, units = 'in'), |
| 63 |
svg = grDevices::svg, |
| 64 |
gridSVG = function(filename, width, height, ...) { |
| 65 |
# use svg() only for redrawing the plot, and will use gridSVG::grid.export() later |
| 66 |
grDevices::svg(filename, width, height) |
| 67 |
}, |
| 68 |
pictex = grDevices::pictex, |
| 69 |
tiff = function(...) tiff(..., res = dpi, units = 'in'), |
| 70 |
win.metafile = grDevices::win.metafile, |
| 71 |
cairo_pdf = grDevices::cairo_pdf, |
| 72 |
cairo_ps = grDevices::cairo_ps, |
| 73 |
|
| 74 |
quartz_pdf = quartz_dev('pdf', dpi), |
| 75 |
quartz_png = quartz_dev('png', dpi), |
| 76 |
quartz_jpeg = quartz_dev('jpeg', dpi), |
| 77 |
quartz_tiff = quartz_dev('tiff', dpi), |
| 78 |
quartz_gif = quartz_dev('gif', dpi), |
| 79 |
quartz_psd = quartz_dev('psd', dpi), |
| 80 |
quartz_bmp = quartz_dev('bmp', dpi), |
| 81 |
|
| 82 |
CairoJPEG = load_device('CairoJPEG', 'Cairo', dpi = dpi), |
| 83 |
CairoPNG = load_device('CairoPNG', 'Cairo', dpi = dpi), |
| 84 |
CairoTIFF = load_device('CairoTIFF', 'Cairo', dpi = dpi), |
| 85 |
CairoPS = load_device('CairoPS', 'Cairo'), |
| 86 |
CairoPDF = load_device('CairoPDF', 'Cairo'), |
| 87 |
CairoSVG = load_device('CairoSVG', 'Cairo'), |
| 88 |
|
| 89 |
svglite = load_device('svglite', 'svglite'), |
| 90 |
|
| 91 |
# similar to load_device(), but the `dpi` argument is named `res` |
| 92 |
ragg_png = function(...) { |
| 93 |
ragg_png_dev(..., res = dpi, units = 'in') |
| 94 |
}, |
| 95 |
|
| 96 |
tikz = function(...) { |
| 97 |
tikz_dev(..., sanitize = options$sanitize, standAlone = options$external) |
| 98 |
} |
| 99 |
) |
| 100 |
if (!is.null(device)) return(device) |
| 101 |
# custom device provided by user as a character string |
| 102 |
if (!exists(dev, mode = 'function', envir = knit_global())) |
| 103 |
stop('The graphical device ', sQuote(dev), ' was not found (as a function).') |
| 104 |
get(dev, mode = 'function', envir = knit_global()) |
| 105 |
} |
| 106 |
|
| 107 |
# quartz devices under Mac |
| 108 |
quartz_dev = function(type, dpi) { |
| 109 |
force(type); force(dpi) |
| 110 |
function(file, width, height, ...) { |
| 111 |
grDevices::quartz(file = file, width = width, height = height, type = type, dpi = dpi, ...) |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
# a wrapper of the tikzDevice::tikz device |
| 116 |
tikz_dev = function(..., engine = getOption('tikzDefaultEngine')) { |
| 117 |
loadNamespace('tikzDevice') |
| 118 |
packages = switch( |
| 119 |
engine, |
| 120 |
pdftex = getOption('tikzLatexPackages'), |
| 121 |
xetex = getOption('tikzXelatexPackages'), |
| 122 |
luatex = getOption('tikzLualatexPackages') |
| 123 |
) |
| 124 |
tikzDevice::tikz(..., packages = c('\n\\nonstopmode\n', packages, .knitEnv$tikzPackages)) |
| 125 |
} |
| 126 |
|
| 127 |
# a wrapper of the ragg::agg_png device |
| 128 |
ragg_png_dev = function(...) { |
| 129 |
loadNamespace('ragg') |
| 130 |
args = list(...) |
| 131 |
# handle bg -> background gracefully |
| 132 |
args$background = args$background %n% args$bg |
| 133 |
args$bg = NULL |
| 134 |
do.call(ragg::agg_png, args) |
| 135 |
} |
| 136 |
|
| 137 |
# save a recorded plot |
| 138 |
save_plot = function(plot, name, dev, width, height, ext, dpi, options) { |
| 139 |
|
| 140 |
path = paste(name, ext, sep = '.') |
| 141 |
# when cache=2 and plot file exists, just return the filename |
| 142 |
if (options$cache == 2 && cache$exists(options$hash, options$cache.lazy)) { |
| 143 |
if (in_base_dir(!file.exists(path))) { |
| 144 |
purge_cache(options) |
| 145 |
stop('cannot find ', path, '; the cache has been purged; please re-compile') |
| 146 |
} |
| 147 |
return(paste(name, if (dev == 'tikz' && options$external) 'pdf' else ext, sep = '.')) |
| 148 |
} |
| 149 |
device = dev_get(dev, options, dpi) |
| 150 |
in_base_dir(plot2dev(plot, name, dev, device, path, width, height, options)) |
| 151 |
} |
| 152 |
|
| 153 |
plot2dev = function(plot, name, dev, device, path, width, height, options) { |
| 154 |
dargs = get_dargs(options$dev.args, dev) |
| 155 |
# re-plot the recorded plot to an off-screen device |
| 156 |
do.call(device, c(list(path, width = width, height = height), dargs)) |
| 157 |
showtext(options) # maybe begin showtext and set options |
| 158 |
print(plot) |
| 159 |
# hack: if the device is gridSVG, save the plot to a temp path (with suffix ~) |
| 160 |
path2 = if (dev == 'gridSVG') paste0(path, '~') |
| 161 |
if (!is.null(path2)) do.call(gridSVG::grid.export, c(list(name = path2), dargs)) |
| 162 |
dev.off() |
| 163 |
# move the temp svg file to `path` |
| 164 |
if (!is.null(path2)) file.rename(path2, path) |
| 165 |
|
| 166 |
# Cairo::CairoPS always adds the extension .ps, even if you have specified an |
| 167 |
# extension like .eps (https://github.com/yihui/knitr/issues/1364) |
| 168 |
if (dev == 'CairoPS') { |
| 169 |
path2 = paste0(path, '.ps') |
| 170 |
if (file.exists(path2)) file.rename(path2, path) |
| 171 |
} |
| 172 |
|
| 173 |
# compile tikz to pdf |
| 174 |
if (dev == 'tikz') { |
| 175 |
patch_tikz_tex(path) |
| 176 |
if (options$external) path = tinytex::latexmk( |
| 177 |
path, dargs$engine %n% getOption('tikzDefaultEngine') |
| 178 |
) |
| 179 |
} |
| 180 |
|
| 181 |
fig_process(options$fig.process, path, options) |
| 182 |
} |
| 183 |
|
| 184 |
# the tikz plot may contain raster legends, in which case we need to adjust the |
| 185 |
# paths of these PNG files: https://stackoverflow.com/a/58410965/559676 |
| 186 |
patch_tikz_tex = function(path) { |
| 187 |
d = dirname(path) |
| 188 |
p = list.files(d, r <- '_ras[0-9]+[.]png$') |
| 189 |
b = sans_ext(basename(path)); bs = sub(r, '', p) |
| 190 |
# for foo.tex, there must be foo_ras[N].png, otherwise no need to patch foo.tex |
| 191 |
if (!(b %in% bs)) return() |
| 192 |
x = read_utf8(path) |
| 193 |
r = '^(\\s*\\\\pgfimage\\[.+?]\\{)(.+?_ras[0-9]+}};\\s*)$' |
| 194 |
i = grep(r, x) |
| 195 |
i = i[grep(b, x[i], fixed = TRUE)] |
| 196 |
x1 = sub(r, '\\1', x[i]) |
| 197 |
x2 = sub(r, '\\2', x[i]) |
| 198 |
if (is_windows()) d = gsub('\\\\', '/', d) |
| 199 |
x[i] = paste0(x1, d, '/', x2) |
| 200 |
write_utf8(x, path) |
| 201 |
} |
| 202 |
|
| 203 |
# filter the dev.args option |
| 204 |
get_dargs = function(dargs, dev) { |
| 205 |
if (length(dargs) == 0) return() |
| 206 |
nms = names(dargs) |
| 207 |
if (is.list(dargs) && all(sapply(dargs, is.list)) && length(nms) && |
| 208 |
(dev %in% nms || all(nms %in% names(auto_exts)))) { |
| 209 |
# dev.args is list(dev1 = list(arg1 = val1, ...), dev2 = list(arg2, ...)) |
| 210 |
dargs = dargs[[dev]] |
| 211 |
} |
| 212 |
dargs |
| 213 |
} |
| 214 |
|
| 215 |
# this is mainly for Cairo |
| 216 |
load_device = function(name, package, dpi = NULL) { |
| 217 |
dev = getFromNamespace(name, package) |
| 218 |
# dpi is for bitmap devices; units must be inches! |
| 219 |
if (is.null(dpi)) dev else function(...) dev(..., dpi = dpi, units = 'in') |
| 220 |
} |
| 221 |
|
| 222 |
|
| 223 |
# merge low-level plotting changes |
| 224 |
merge_low_plot = function(x, idx = sapply(x, evaluate::is.recordedplot)) { |
| 225 |
idx = which(idx); n = length(idx); m = NULL # store indices that will be removed |
| 226 |
if (n <= 1) return(x) |
| 227 |
i1 = idx[1]; i2 = idx[2] # compare plots sequentially |
| 228 |
for (i in 1:(n - 1)) { |
| 229 |
# remove the previous plot and move its index to the next plot |
| 230 |
if (is_low_change(x[[i1]], x[[i2]])) m = c(m, i1) |
| 231 |
i1 = idx[i + 1] |
| 232 |
i2 = idx[i + 2] |
| 233 |
} |
| 234 |
if (is.null(m)) x else x[-m] |
| 235 |
} |
| 236 |
|
| 237 |
#' Compare two recorded plots |
| 238 |
#' |
| 239 |
#' Check if one plot only contains a low-level update of another plot. |
| 240 |
#' @param p1,p2 Plot objects. |
| 241 |
#' @return Logical value indicating whether \code{p2} is a low-level update of |
| 242 |
#' \code{p1}. |
| 243 |
#' @export |
| 244 |
#' @examples |
| 245 |
#' pdf(NULL) |
| 246 |
#' dev.control('enable') # enable plot recording |
| 247 |
#' plot(1:10) |
| 248 |
#' p1 = recordPlot() |
| 249 |
#' abline(0, 1) # add a line (a low-level change) |
| 250 |
#' p2 = recordPlot() |
| 251 |
#' plot(rnorm(100)) |
| 252 |
#' p3 = recordPlot() # draw a completely new plot |
| 253 |
#' dev.off() |
| 254 |
#' knitr::is_low_change(p1, p2) # true |
| 255 |
#' knitr::is_low_change(p1, p3) # false |
| 256 |
is_low_change = function(p1, p2) { |
| 257 |
UseMethod('is_low_change') |
| 258 |
} |
| 259 |
|
| 260 |
#' @export |
| 261 |
is_low_change.default = function(p1, p2) { |
| 262 |
p1 = p1[[1]]; p2 = p2[[1]] # real plot info is in [[1]] |
| 263 |
if (length(p2) < (n1 <- length(p1))) return(FALSE) # length must increase |
| 264 |
identical(p1[1:n1], p2[1:n1]) |
| 265 |
} |
| 266 |
|
| 267 |
# recycle some plot options such as fig.cap, out.width/height, etc when there |
| 268 |
# are multiple plots per chunk |
| 269 |
.recyle.opts = c('fig.cap', 'fig.scap', 'fig.alt', 'fig.env', 'fig.pos', 'fig.subcap', |
| 270 |
'out.width', 'out.height', 'out.extra', 'fig.link') |
| 271 |
|
| 272 |
# when passing options to plot hooks, reduce the recycled options to scalars |
| 273 |
reduce_plot_opts = function(options) { |
| 274 |
i = options$fig.cur %n% 1L |
| 275 |
for (o in .recyle.opts) { |
| 276 |
v = options[[o]] |
| 277 |
if ((n <- length(v)) == 0) next |
| 278 |
if ((j <- i %% n) == 0) j = n |
| 279 |
options[o] = list(v[j]) |
| 280 |
} |
| 281 |
options |
| 282 |
} |
| 283 |
|
| 284 |
# remove the plots from the evaluate results for the case of cache=2; if we only |
| 285 |
# want to keep high-level plots, we need MD5 digests of the plot components so |
| 286 |
# that we will be able to filter out low-level changes later |
| 287 |
remove_plot = function(list, keep.high = TRUE) { |
| 288 |
lapply(list, function(x) { |
| 289 |
if (evaluate::is.recordedplot(x)) structure( |
| 290 |
if (keep.high) digest_plot(x) else NULL, class = 'recordedplot' |
| 291 |
) else x |
| 292 |
}) |
| 293 |
} |
| 294 |
# replace the content of the recorded plot with MD5 digests so that merge_plot() |
| 295 |
# will still work, and this will also save disk space for the case of cache=2 |
| 296 |
digest_plot = function(x, level = 1) { |
| 297 |
if (!is.list(x) || level >= 3) return(digest(x)) |
| 298 |
lapply(x, digest_plot, level = level + 1) |
| 299 |
} |
| 300 |
|
| 301 |
# a null device |
| 302 |
pdf_null = function(width = 7, height = 7, ...) { |
| 303 |
grDevices::pdf(NULL, width, height, ...) |
| 304 |
} |
| 305 |
|
| 306 |
fig_process = function(FUN, path, options) { |
| 307 |
if (is.function(FUN)) { |
| 308 |
ARG = intersect(c("options", names(options)), names(formals(FUN))) |
| 309 |
path2 = do.call(FUN, c(path, c(options = list(options), options)[ARG])) |
| 310 |
if (!is.character(path2) || length(path2) != 1L) |
| 311 |
stop("'fig.process' must be a function that returns a character string") |
| 312 |
path = path2 |
| 313 |
} |
| 314 |
path |
| 315 |
} |
| 316 |
|
| 317 |
#' Crop a plot (remove the edges) using PDFCrop or ImageMagick |
| 318 |
#' |
| 319 |
#' The program \command{pdfcrop} (often shipped with a LaTeX distribution) is |
| 320 |
#' executed on a PDF plot file, and |
| 321 |
#' \code{magick::\link[magick:transform]{image_trim}()} is executed for other |
| 322 |
#' types of plot files. |
| 323 |
#' |
| 324 |
#' The program \command{pdfcrop} can crop the extra white margins when the plot |
| 325 |
#' format is PDF, to make better use of the space in the output document, |
| 326 |
#' otherwise we often have to struggle with \code{graphics::\link{par}()} to set |
| 327 |
#' appropriate margins. Note \command{pdfcrop} often comes with a LaTeX |
| 328 |
#' distribution such as TinyTeX, MiKTeX, or TeX Live, and you may not need to |
| 329 |
#' install it separately (use \code{Sys.which('pdfcrop')} to check it; if it not |
| 330 |
#' empty, you are able to use it). Note that \command{pdfcrop} depends on |
| 331 |
#' GhostScript. You can check if GhostScript is installed via |
| 332 |
#' \code{tools::find_gs_cmd()}. |
| 333 |
#' @param x Filename of the plot. |
| 334 |
#' @param quiet Whether to suppress standard output from the command. |
| 335 |
#' @export |
| 336 |
#' @references PDFCrop: \url{https://www.ctan.org/pkg/pdfcrop}. If you use |
| 337 |
#' TinyTeX, you may install \command{pdfcrop} with |
| 338 |
#' \code{tinytex::tlmgr_install('pdfcrop')}. |
| 339 |
#' @return The original filename. |
| 340 |
plot_crop = function(x, quiet = TRUE) { |
| 341 |
is_pdf = grepl('[.]pdf$', x, ignore.case = TRUE) |
| 342 |
x2 = x |
| 343 |
x = path.expand(x) |
| 344 |
tinytex:::tweak_path() # in case TinyTeX is installed but not on PATH |
| 345 |
if (is_pdf && !has_utility('pdfcrop')) return(x2) |
| 346 |
|
| 347 |
if (!quiet) message('cropping ', x) |
| 348 |
if (is_pdf) { |
| 349 |
system2('pdfcrop', shQuote(c(x, x)), stdout = if (quiet) FALSE else "") |
| 350 |
} else if (loadable('magick')) { |
| 351 |
img = magick::image_read(x) |
| 352 |
magick::image_write(magick::image_trim(img), x) |
| 353 |
} else message( |
| 354 |
'The magick package is required to crop "', x2, '" but not available.' |
| 355 |
) |
| 356 |
x2 |
| 357 |
} |
| 358 |
|
| 359 |
showtext = function(options) { |
| 360 |
if (!isTRUE(options$fig.showtext)) return() |
| 361 |
showtext::showtext_opts(dpi = options$dpi) |
| 362 |
showtext::showtext_begin() |
| 363 |
} |
| 364 |
|
| 365 |
# handle some special cases of par() |
| 366 |
par2 = function(x) { |
| 367 |
if (length(x) == 0) return() |
| 368 |
# this may not be correct, but there is no way to tell if the user set mfrow |
| 369 |
# or mfcol in par() (either setting will change mfrow/mfcol simultaneously), |
| 370 |
# and I just assume it was mfrow |
| 371 |
if (!is.null(x$mfrow)) { |
| 372 |
# do this before the rest of pars because setting mfrow/mfcol will reset cex |
| 373 |
par(mfrow = x$mfrow) |
| 374 |
x$mfrow = x$mfcol = NULL |
| 375 |
# do not restore mfg (#1215); this is unlikely to make sense, e.g. for |
| 376 |
# par(mfrow = c(1, 2)), mfg will be c(1, 2, 1, 2) when the second plot is |
| 377 |
# completed, but when the user generate a new plot, it should typically be |
| 378 |
# drawn at (1, 1) instead of (1, 2) |
| 379 |
x$mfg = NULL |
| 380 |
} |
| 381 |
if (!is.null(x$fg)) { |
| 382 |
# set fg before the rest of the par because |
| 383 |
# it resets col to the same value #1603 |
| 384 |
par(fg = x$fg) |
| 385 |
x$fg = NULL |
| 386 |
} |
| 387 |
# you are unlikely to want to reset these pars |
| 388 |
x$fig = x$fin = x$pin = x$plt = x$usr = NULL |
| 389 |
x$ask = NULL # does not make sense for typical non-interactive R sessions |
| 390 |
par(x) |
| 391 |
} |
| 392 |
|
| 393 |
#' Embed external images in \pkg{knitr} documents |
| 394 |
#' |
| 395 |
#' When plots are not generated from R code, there is no way for \pkg{knitr} to |
| 396 |
#' capture plots automatically. In this case, you may generate the images |
| 397 |
#' manually and pass their file paths to this function to include them in the |
| 398 |
#' output. The major advantage of using this function is that it is portable in |
| 399 |
#' the sense that it works for all document formats that \pkg{knitr} supports, |
| 400 |
#' so you do not need to think if you have to use, for example, LaTeX or |
| 401 |
#' Markdown syntax, to embed an external image. Chunk options related to |
| 402 |
#' graphics output that work for normal R plots also work for these images, such |
| 403 |
#' as \code{out.width} and \code{out.height}. |
| 404 |
#' @param path A character vector of image paths. Both local file paths and web |
| 405 |
#' paths are supported. Note that the \code{auto_pdf} and \code{dpi} arguments |
| 406 |
#' are not supported for web paths. |
| 407 |
#' @param auto_pdf Whether to use PDF images automatically when the output |
| 408 |
#' format is LaTeX. If \code{TRUE}, then e.g. \file{foo/bar.png} will be |
| 409 |
#' replaced by \file{foo/bar.pdf} if the latter exists. This can be useful |
| 410 |
#' since normally PDF images are of higher quality than raster images like |
| 411 |
#' PNG, when the output is LaTeX/PDF. |
| 412 |
#' @param dpi DPI (dots per inch) value. Used to calculate the output width (in |
| 413 |
#' inches) of the images. This will be their actual width in pixels, divided |
| 414 |
#' by \code{dpi}. If not provided, the chunk option \code{dpi} is used; if |
| 415 |
#' \code{NA}, the output width will not be calculated. |
| 416 |
#' @param rel_path Whether to automatically convert absolute paths to relative |
| 417 |
#' paths. If you know for sure that absolute paths work, you may set this |
| 418 |
#' argument or the global option \code{knitr.graphics.rel_path} to |
| 419 |
#' \code{FALSE}. |
| 420 |
#' @param error Whether to signal an error if any files specified in the |
| 421 |
#' \code{path} argument do not exist and are not web resources. |
| 422 |
#' @note This function is supposed to be used in R code chunks or inline R code |
| 423 |
#' expressions. For local images, you are recommended to use relative paths |
| 424 |
#' with forward slashes instead of backslashes (e.g., \file{images/fig1.png} |
| 425 |
#' instead of \file{/Users/me/code/images/fig1.png}). |
| 426 |
#' |
| 427 |
#' The automatic calculation of the output width requires the \pkg{png} |
| 428 |
#' package (for PNG images) or the \pkg{jpeg} package (for JPEG images). The |
| 429 |
#' width will not be calculated if the chunk option \code{out.width} is |
| 430 |
#' already provided or \code{dpi = NA}. |
| 431 |
#' @return The same as the input character vector \code{path} but it is marked |
| 432 |
#' with special internal S3 classes so that \pkg{knitr} will convert the file |
| 433 |
#' paths to proper output code according to the output format. |
| 434 |
#' @export |
| 435 |
include_graphics = function( |
| 436 |
path, auto_pdf = getOption('knitr.graphics.auto_pdf', FALSE), dpi = NULL, |
| 437 |
rel_path = getOption('knitr.graphics.rel_path', TRUE), |
| 438 |
error = getOption('knitr.graphics.error', TRUE) |
| 439 |
) { |
| 440 |
path = native_encode(path) # https://d.cosx.org/d/420524 |
| 441 |
if (any(i <- xfun::is_abs_path(path)) && rel_path && !is.null(d <- opts_knit$get('output.dir'))) { |
| 442 |
path[i] = xfun::relative_path(path[i], d, error = FALSE) |
| 443 |
if (any(j <- xfun::is_abs_path(path[i]))) warning( |
| 444 |
'It is highly recommended to use relative paths for images. ', |
| 445 |
'You had absolute paths: ', quote_vec(path[i][j]) |
| 446 |
) |
| 447 |
} |
| 448 |
path = path.expand(path) # https://github.com/rstudio/rmarkdown/issues/1053 |
| 449 |
if (auto_pdf && is_latex_output()) { |
| 450 |
path2 = with_ext(path, 'pdf') |
| 451 |
i = file.exists(path2) |
| 452 |
path[i] = path2[i] |
| 453 |
} |
| 454 |
# relative paths can be tricky in child documents, so don't error (#1957) |
| 455 |
if (child_mode()) error = FALSE |
| 456 |
if (error && length(p <- path[!xfun::is_web_path(path) & !file.exists(path)])) stop( |
| 457 |
'Cannot find the file(s): ', quote_vec(p) |
| 458 |
) |
| 459 |
structure(path, class = c('knit_image_paths', 'knit_asis'), dpi = dpi) |
| 460 |
} |
| 461 |
|
| 462 |
#' Download an image from the web and include it in a document |
| 463 |
#' |
| 464 |
#' When including images in non-HTML output formats such as LaTeX/PDF, URLs will |
| 465 |
#' not work as image paths. In this case, we have to download the images. This |
| 466 |
#' function is a wrapper of \code{xfun::\link[xfun]{download_file}()} and |
| 467 |
#' \code{\link{include_graphics}()}. |
| 468 |
#' @param url The URL of an image. |
| 469 |
#' @param path The download path (inferred from the URL by default). If the file |
| 470 |
#' exists, it will not be downloaded (downloading can take time and requires |
| 471 |
#' Internet connection). If you are sure the file needs to be downloaded |
| 472 |
#' again, delete it beforehand. |
| 473 |
#' @param use_file Whether to use the URL or the download path to include the |
| 474 |
#' image. By default, the URL is used for HTML output formats, and the file |
| 475 |
#' path is used for other output formats. |
| 476 |
#' @param ... Other arguments to be passed to \code{\link{include_graphics}()}. |
| 477 |
#' @export |
| 478 |
#' @examplesIf interactive() |
| 479 |
#' knitr::download_image('https://www.r-project.org/Rlogo.png') |
| 480 |
download_image = function(url, path = xfun::url_filename(url), use_file = !pandoc_to('html'), ...) { |
| 481 |
if (!file.exists(path) && use_file) xfun::download_file(url, path) |
| 482 |
include_graphics(if (use_file) path else url, ...) |
| 483 |
} |
| 484 |
|
| 485 |
# calculate the width in inches for PNG/JPEG images given a DPI |
| 486 |
raster_dpi_width = function(path, dpi) { |
| 487 |
if (!file.exists(path) || is.na(dpi)) return() |
| 488 |
is_png = grepl('[.]png$', path, ignore.case = TRUE) |
| 489 |
is_jpg = grepl('[.]jpe?g$', path, ignore.case = TRUE) |
| 490 |
if (!is_png && !is_jpg) return() |
| 491 |
if (is_png) { |
| 492 |
if (!loadable('png')) return() |
| 493 |
meta = attr(png::readPNG(path, native = TRUE, info = TRUE), 'info') |
| 494 |
w = meta$dim[1] |
| 495 |
if (!is.numeric(dpi)) dpi = meta$dpi[1] |
| 496 |
if (!is.numeric(dpi)) return() # cannot calculate the desired width |
| 497 |
} else if (is_jpg) { |
| 498 |
if (!loadable('jpeg')) return() |
| 499 |
if (!is.numeric(dpi)) return() # there is no dpi info in JPEG |
| 500 |
w = ncol(jpeg::readJPEG(path, native = TRUE)) |
| 501 |
} |
| 502 |
if (is_latex_output()) { |
| 503 |
xfun::decimal_dot(paste0(round(w / dpi, 2), 'in')) |
| 504 |
} else if (is_html_output()) { |
| 505 |
round(w / (dpi / 96)) |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
#' Embed a URL as an HTML iframe or a screenshot in \pkg{knitr} documents |
| 510 |
#' |
| 511 |
#' When the output format is HTML, \code{include_url()} inserts an iframe in the |
| 512 |
#' output; otherwise it takes a screenshot of the URL and insert the image in |
| 513 |
#' the output. \code{include_app()} takes the URL of a Shiny app and adds |
| 514 |
#' \samp{?showcase=0} to it (to disable the showcase mode), then passes the URL |
| 515 |
#' to \code{include_url()}. |
| 516 |
#' @param url A character vector of URLs. |
| 517 |
#' @param height A character vector to specify the height of iframes. |
| 518 |
#' @return An R object with a special class that \pkg{knitr} recognizes |
| 519 |
#' internally to generate the iframes or screenshots. |
| 520 |
#' @seealso \code{\link{include_graphics}} |
| 521 |
#' @export |
| 522 |
include_url = function(url, height = '400px') { |
| 523 |
include_url2(url, height) |
| 524 |
} |
| 525 |
|
| 526 |
include_url2 = function(url, height = '400px', orig = url) { |
| 527 |
structure( |
| 528 |
list(url = url, height = height, url.orig = orig), |
| 529 |
class = c('knit_embed_url', 'knit_asis_url') |
| 530 |
) |
| 531 |
} |
| 532 |
|
| 533 |
#' @rdname include_url |
| 534 |
#' @export |
| 535 |
include_app = function(url, height = '400px') { |
| 536 |
orig = url # store the original URL |
| 537 |
i = !grepl('?', url, fixed = TRUE) |
| 538 |
url[i] = paste0(url[i], '?showcase=0') |
| 539 |
include_url2(url, height, orig) |
| 540 |
} |
| 541 |
|
| 542 |
need_screenshot = function(x, ...) { |
| 543 |
options = list(...)[['options']] |
| 544 |
# if users specify screenshot.force = FALSE, skip screenshot and render HTML |
| 545 |
if (isFALSE(options$screenshot.force)) return(FALSE) |
| 546 |
# force screenshotting even if the output format support HTML |
| 547 |
force = is.list(options) && isTRUE(options$screenshot.force) |
| 548 |
fmt = pandoc_to() |
| 549 |
i1 = inherits(x, 'htmlwidget') |
| 550 |
i2 = inherits(x, 'shiny.appobj') |
| 551 |
i3 = inherits(x, 'knit_embed_url') |
| 552 |
# not R Markdown v2, always screenshot htmlwidgets and shiny apps |
| 553 |
if (length(fmt) == 0 || force) return(i1 || i2 || i3) |
| 554 |
html_format = fmt %in% c('html', 'html4', 'html5', 'revealjs', 's5', 'slideous', 'slidy') |
| 555 |
res = ((i1 || i3) && !html_format) || (i2 && !(html_format && runtime_shiny())) |
| 556 |
res && any(webshot_available()) |
| 557 |
} |
| 558 |
|
| 559 |
runtime_shiny = function() { |
| 560 |
identical(opts_knit$get('rmarkdown.runtime'), 'shiny') |
| 561 |
} |
| 562 |
|
| 563 |
webshot_available = local({ |
| 564 |
res = NULL # cache the availability of webshot2/Chrome and webshot/PhantomJS |
| 565 |
test = function(pkg, fun, pkg2 = pkg) { |
| 566 |
loadable(pkg) && tryCatch( |
| 567 |
file.exists(getFromNamespace(fun, pkg2)()), |
| 568 |
error = function(e) FALSE |
| 569 |
) |
| 570 |
} |
| 571 |
function() { |
| 572 |
if (is.null(res)) res <<- c( |
| 573 |
webshot2 = test('webshot2', 'find_chrome', 'chromote'), |
| 574 |
webshot = test('webshot', 'find_phantom') |
| 575 |
) |
| 576 |
res |
| 577 |
} |
| 578 |
}) |
| 579 |
|
| 580 |
html_screenshot = function(x, options = opts_current$get(), ...) { |
| 581 |
i1 = inherits(x, 'htmlwidget') |
| 582 |
i2 = inherits(x, 'shiny.appobj') |
| 583 |
i3 = inherits(x, 'knit_embed_url') |
| 584 |
if (!(i1 || i2 || i3)) |
| 585 |
stop('Screenshotting for the class ', class(x)[1], ' is not supported.') |
| 586 |
|
| 587 |
# if user has specified the screenshot image, just use it |
| 588 |
if (!is.null(shots <- options$screenshot.alt)) { |
| 589 |
i = shot_counter() |
| 590 |
if (length(shots) < i) stop('Not enough number of screenshots provided') |
| 591 |
return(structure(list(file = shots[i]), class = 'html_screenshot')) |
| 592 |
} |
| 593 |
|
| 594 |
ext = if (length(options$dev)) { |
| 595 |
switch(options$dev[1], pdf = '.pdf', jpeg = '.jpeg', '.png') |
| 596 |
} else '.png' |
| 597 |
wargs = options$screenshot.opts %n% list() |
| 598 |
if (is.null(wargs$vwidth) && !grepl("%$", W <- options$out.width.px)) wargs$vwidth = W |
| 599 |
if (is.null(wargs$vheight) && !grepl("%$", H <- options$out.height.px)) wargs$vheight = H |
| 600 |
if (is.null(wargs$delay)) wargs$delay = if (i1) 0.2 else 1 |
| 601 |
d = tempfile(tmpdir = getOption( |
| 602 |
'knitr.html_screenshot.tmpdir', if (file.access('.', 2) == 0) '.' else tempdir() |
| 603 |
)) |
| 604 |
dir.create(d); on.exit(unlink(d, recursive = TRUE), add = TRUE) |
| 605 |
w = webshot_available() |
| 606 |
webshot = c(options$webshot, names(w)[w]) |
| 607 |
webshot = if (length(webshot) == 0) 'webshot' else webshot[[1L]] |
| 608 |
if (webshot == 'webshot2' && ext == 'pdf' && getOption('knitr.warn.webshot2', TRUE)) warning( |
| 609 |
"webshot2 may take the PDF screenshot with the wrong size. You are recommended ", |
| 610 |
"to use the 'png' format instead (i.e., set the chunk option '", |
| 611 |
if (is_quarto()) "fig-format" else "dev", "' to 'png'). ", |
| 612 |
"See https://github.com/yihui/knitr/issues/2276 for more information." |
| 613 |
) |
| 614 |
# set quiet opions for webshot2::webshot() |
| 615 |
local_options(list(webshot.quiet = getOption('webshot.quiet', TRUE))) |
| 616 |
f = in_dir(d, { |
| 617 |
if (i1 || i3) { |
| 618 |
if (i1) { |
| 619 |
f1 = wd_tempfile('widget', '.html') |
| 620 |
htmlwidgets::saveWidget(x, f1, FALSE, knitrOptions = options) |
| 621 |
} else f1 = x$url |
| 622 |
f2 = wd_tempfile('webshot', ext) |
| 623 |
f3 = do.call(getFromNamespace('webshot', webshot), c(list(f1, f2), wargs)) |
| 624 |
normalizePath(f3) |
| 625 |
} else if (i2) { |
| 626 |
f1 = wd_tempfile('webshot', ext) |
| 627 |
f2 = do.call(getFromNamespace('appshot', webshot), c(list(x, f1), wargs)) |
| 628 |
normalizePath(f2) |
| 629 |
} |
| 630 |
}) |
| 631 |
lapply(f, function(filename) { |
| 632 |
res = xfun::read_bin(filename) |
| 633 |
structure( |
| 634 |
list(image = res, extension = ext, url = if (i3) x$url.orig[filename == f]), |
| 635 |
class = 'html_screenshot' |
| 636 |
) |
| 637 |
}) |
| 638 |
} |