Debian Codegraph @

R/hooks-html.R

raw
1 #' @rdname hook_plot
2 #' @export
3 hook_plot_html = function(x, options) {
4 # pull out all the relevant plot options
5 fig.num = options$fig.num = options$fig.num %n% 1L
6 fig.cur = options$fig.cur %n% 1L
7
8 if (options$fig.show == 'animate') {
9 # Don't print out intermediate plots if we're animating
10 return(if (fig.cur < fig.num) '' else hook_animation(options)(x, options))
11 }
12 ai = options$fig.show == 'asis'
13 plot1 = ai || fig.cur <= 1L; plot2 = ai || fig.cur == fig.num
14 d1 = if (plot1) paste0(if (out_format('html')) '</div>',
15 sprintf('<div class="rimage %s">', options$fig.align))
16 d2 = if (plot2) paste0('</div>', if (out_format('html')) '<div class="rcode">')
17 paste0(
18 d1, .img.tag(
19 x, options$out.width, options$out.height, .img.cap(options),
20 paste(c(options$out.extra, 'class="plot"'), collapse = ' ')
21 ), d2, '\n'
22 )
23 }
24
25 hook_animation = function(options) {
26 if (is.function(fun <- options$animation.hook)) return(fun)
27 if (is.character(fun)) return(switch(
28 fun, ffmpeg = hook_ffmpeg_html, gifski = hook_gifski,
29 scianimator = hook_scianimator, r2swf = hook_r2swf,
30 stop2('Invalid value for the chunk option animation.hook: ', fun)
31 ))
32 if (is.function(fun <- opts_knit$get('animation.fun'))) return(fun)
33 hook_ffmpeg_html
34 }
35
36 .img.attr = function(w, h, extra) {
37 paste(c(sprintf('width="%s"', w), sprintf('height="%s"', h), extra), collapse = ' ')
38 }
39
40 .img.tag = function(src, w, h, caption, extra) {
41 ext = tolower(file_ext(src))
42 tag = 'img'; extra2 = NULL; att = 'src'
43 if (ext == 'pdf') {
44 extra2 = 'type="application/pdf"'; tag = 'embed'
45 } else if (ext == 'svg' && getOption('knitr.svg.object', FALSE)) {
46 extra2 = 'type="image/svg+xml"'; tag = 'object'; att = 'data'
47 }
48 if (length(caption) != 1 || is.na(caption) || (tag != 'img' && caption == ''))
49 caption = NULL
50 res = paste0(c(
51 paste0('<', tag),
52 sprintf('%s="%s%s"', att, opts_knit$get('base.url') %n% '', .upload.url(src)),
53 sprintf('%s="%s"', if (tag == 'img') 'alt' else 'title', caption),
54 .img.attr(w, h, c(extra, extra2))
55 ), collapse = ' ')
56 paste0(res, if (tag == 'object') '></object>' else ' />')
57 }
58
59 .img.cap = function(options, alt = FALSE, escape = FALSE) {
60 cap = options$fig.cap %n% {
61 if (is.null(pandoc_to())) sprintf('plot of chunk %s', options$label) else ''
62 }
63 if (length(cap) == 0 || is.na(cap)) cap = ''
64 if (alt) {
65 alt = options$fig.alt %n% cap
66 return(if (escape) html_escape(alt) else alt)
67 }
68 if (is_blank(cap)) return(cap)
69 paste0(create_label(
70 options$fig.lp, options$label,
71 if (options$fig.num > 1L && options$fig.show == 'asis') c('-', options$fig.cur)
72 ), cap)
73 }
74
75 # a wrapper to upload an image and return the URL
76 .upload.url = function(x) {
77 opts_knit$get('upload.fun')(x)
78 }
79
80 .chunk.hook.html = function(x, options) {
81 if (output_asis(x, options)) return(x)
82 x = sprintf('<div class="chunk" id="%s"><div class="rcode">%s</div></div>',
83 options$label, x)
84 x = gsub('<div class="rcode">\\s*</div>', '', x) # rm empty rcode layers
85 if (options$split) {
86 name = fig_path('.html', options, NULL)
87 if (!file.exists(dirname(name)))
88 dir.create(dirname(name))
89 write_utf8(x, name)
90 sprintf('<iframe src="%s" class="knitr" width="100%%"></iframe>', name)
91 } else x
92 }
93
94 #' Hooks to create animations in HTML output
95 #'
96 #' \code{hook_ffmpeg_html()} uses FFmpeg to convert images to a video;
97 #' \code{hook_gifski()} uses the \pkg{gifski} to convert images to a GIF
98 #' animation; \code{hook_scianimator()} uses the JavaScript library SciAnimator
99 #' to create animations; \code{hook_r2swf()} uses the \pkg{R2SWF} package.
100 #'
101 #' These hooks are mainly for the package option \code{animation.fun}, e.g. you
102 #' can set \code{opts_knit$set(animation.fun = hook_scianimator)}.
103 #' @inheritParams hook_plot_tex
104 #' @rdname hook_animation
105 #' @export
106 hook_ffmpeg_html = function(x, options) {
107 hook_ffmpeg(x, options, options$ffmpeg.format %n% 'webm')
108 }
109
110 hook_ffmpeg = function(x, options, format = 'webm') {
111 x = c(sans_ext(x), file_ext(x))
112 fig.num = options$fig.num
113 format = sub('^[.]', '', format)
114 # set up the ffmpeg run
115 base = sub(paste0(fig.num, '$'), '', x[1])
116 fig.fname = paste0(base, '%d', '.', x[2])
117 mov.fname = paste0(sub('-$', '', base), '.', format)
118
119 extra = switch(
120 format,
121 webm = paste('-b:v', options$ffmpeg.bitrate %n% '1M', '-crf 10'),
122 mp4 = '-pix_fmt yuv420p' # enables Safari support of .mp4
123 )
124 ffmpeg.cmd = paste(
125 'ffmpeg', '-y', '-r', 1 / options$interval, '-i', fig.fname, extra, mov.fname
126 )
127
128 if (Sys.which('ffmpeg') == '') stop2(
129 'Could not find ffmpeg command. You should either change the animation.fun ',
130 'hook option or install ffmpeg with libvpx enabled.'
131 )
132 message('executing: ', ffmpeg.cmd)
133 system(ffmpeg.cmd, ignore.stdout = TRUE)
134
135 # use a normal plot hook if the output is GIF
136 if (format == 'gif') {
137 options$fig.show = 'hold'
138 return((if (out_format('markdown')) hook_plot_md else hook_plot_html)(mov.fname, options))
139 }
140
141 # controls,loop --> controls loop
142 opts = paste(sc_split(options$aniopts), collapse = ' ')
143 opts = paste(
144 sprintf('width="%s"', options$out.width),
145 sprintf('height="%s"', options$out.height), opts
146 )
147 cap = .img.cap(options, alt = TRUE, escape = TRUE)
148 if (cap != '') cap = sprintf('<p>%s</p>', cap)
149 sprintf(
150 '<video %s><source src="%s" />%s</video>', trimws(opts),
151 paste0(opts_knit$get('base.url'), mov.fname), cap
152 )
153 }
154
155 # use gifski to create gif's
156 #' @rdname hook_animation
157 #' @export
158 hook_gifski = function(x, options) {
159 x = c(sans_ext(x), file_ext(x))
160 if (tolower(x[2]) != 'png') stop(
161 "To use hook_gifski(), the code chunk must generate 'png' images instead of '", x[2], "'."
162 )
163 fig.num = options$fig.num
164 base = sub(paste0(fig.num, '$'), '', x[1])
165 frames = paste0(base, format(seq_len(fig.num), trim = TRUE), '.', x[2])
166 gif = paste0(base, '.gif')
167 dpi = options$dpi
168 gifski::gifski(
169 frames, gif, width = options$fig.width * dpi, height = options$fig.height * dpi,
170 delay = options$interval, loop = isTRUE(grepl('\\bloop\\b', options$aniopts)),
171 progress = opts_knit$get('progress')
172 )
173 unlink(frames)
174 # pretend it is a single image (gif) generated from the code chunk
175 options$fig.show = 'asis'; options$fig.cur = 1; options$fig.num = 1
176 knit_hooks$get('plot')(gif, options)
177 }
178
179
180 # use SciAnimator to create animations
181 #' @rdname hook_animation
182 #' @export
183 hook_scianimator = function(x, options) {
184 x = c(sans_ext(x), file_ext(x))
185 fig.num = options$fig.num
186 base = opts_knit$get('base.url') %n% ''
187
188 # write the div and js code here
189 id = gsub('[^[:alnum:]]', '_', options$label)
190 sprintf('
191 <div class="scianimator">
192 <div id="%s" style="display: inline-block;">
193 </div>
194 </div>
195 <script type="text/javascript">
196 (function($) {
197 $(document).ready(function() {
198 var imgs = Array(%s);
199 for (i = 0; ; i++) {
200 if (i == imgs.length) break;
201 imgs[i] = "%s%s" + (i + 1) + ".%s";
202 }
203 $("#%s").scianimator({
204 "images": imgs,
205 "delay": %s,
206 "controls": ["first", "previous", "play", "next", "last", "loop", "speed"],
207 });
208 $("#%s").scianimator("play");
209 });
210 })(jQuery);
211 </script>
212 ',
213 id, fig.num, base, sub(paste0(fig.num, '$'), '', x[1]), x[2], id,
214 options$interval * 1000, id)
215 }
216
217
218 # use the R2SWF package to create Flash animations
219 #' @rdname hook_animation
220 #' @export
221 hook_r2swf = function(x, options) {
222 x = c(sans_ext(x), file_ext(x))
223 fig.num = options$fig.num
224 # set up the R2SWF run
225 fig.name = paste0(sub(paste0(fig.num, '$'), '', x[1]), 1:fig.num, '.', x[2])
226 swf.name = fig_path('.swf', options, NULL)
227
228 w = options$out.width %n% (options$fig.width * options$dpi)
229 h = options$out.height %n% (options$fig.height * options$dpi)
230
231 swf2html = getFromNamespace('swf2html', 'R2SWF')
232 file2swf = getFromNamespace('file2swf', 'R2SWF')
233 swfhtml = swf2html(file2swf(files = fig.name, swf.name, interval = options$interval),
234 output = FALSE, fragment = TRUE, width = w, height = h)
235 if (options$fig.align == 'default') return(swfhtml)
236 sprintf(paste('<div align = "%s">\n', swfhtml, '\n</div>'), options$fig.align)
237 }
238
239 #' @rdname output_hooks
240 #' @export
241 render_html = function() {
242 set_html_dev()
243 opts_knit$set(out.format = 'html')
244 h = opts_knit$get('header')
245 if (!nzchar(h['highlight'])) set_header(highlight = .header.hi.html)
246 knit_hooks$set(hooks_html())
247 }
248
249 #' @rdname output_hooks
250 #' @export
251 hooks_html = function() {
252 # use div with different classes
253 hook = function(name) {
254 force(name)
255 function(x, options) {
256 if (name == 'output' && output_asis(x, options)) return(x)
257 x = if (name == 'source') {
258 c(hilight_source(x, 'html', options), '')
259 } else html_escape(x)
260 x = one_string(x)
261 sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', name, tolower(options$engine), x)
262 }
263 }
264 list(
265 source = hook('source'), output = hook('output'), warning = hook('warning'),
266 message = hook('message'), error = hook('error'), plot = hook_plot_html,
267 chunk = .chunk.hook.html, inline = function(x) sprintf(
268 if (inherits(x, 'AsIs')) '%s' else '<code class="knitr inline">%s</code>',
269 .inline.hook(format_sci(x, 'html'))
270 )
271 )
272 }