Merck / r2rtf

Easily Create Production-Ready Rich Text Format (RTF) Table and Figure
https://merck.github.io/r2rtf
GNU General Public License v3.0
76 stars 19 forks source link

Isolate side effects in graphics functions #228

Closed nanxstats closed 1 day ago

nanxstats commented 4 months ago

Fixes #227

This PR introduces safe_par() and safe_strwidth() as alternatives to their original graphics functions. These wrappers will be evaluated in a temporary BMP device, to avoid generating Rplots.pdf when running r2rtf code under certain context - such as clicking the test buttons in RStudio environments, even for third-party packages.

@yihui I'm not sure if this is the optimal solution so I'm open to suggestions.

Using these wrappers can be be 10x slower than calling the graphics functions directly:

microbenchmark::microbenchmark(
  r2rtf:::safe_strwidth("Hello world!", units = "inches", cex = 1, font = 1, family = "sans"),
  graphics::strwidth("Hello world!", units = "inches", cex = 1, font = 1, family = "sans"),
  times = 5000
)

#>    min     lq      mean median     uq      max neval cld
#> 44.526 46.945 53.097288 47.806 49.692 4399.300  5000   a
#>  2.747  2.952  3.199353  3.198  3.362   16.482  5000   b