File: fonts.R

package info (click to toggle)
r-cran-gdtools 0.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 436 kB
  • sloc: cpp: 467; sh: 14; ansic: 5; makefile: 2
file content (279 lines) | stat: -rw-r--r-- 9,080 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#' @importFrom htmltools htmlDependency
#' @importFrom utils packageVersion
#' @export
#' @title 'Google Font' HTML dependency
#' @description Create an HTML dependency ready
#' to be used in 'Shiny' or 'R Markdown'.
#' @details
#' It allows users to use fonts from 'Google Fonts' in an HTML page generated by 'shiny' or 'R Markdown'.
#' At the first request, the font files will be downloaded and stored in a cache on the
#' user's machine, thus avoiding many useless downloads or allowing to work with
#' these fonts afterwards without an Internet connection, in a docker image for example.
#' See [fonts_cache_dir()].
#'
#' The server delivering the font files should not be too busy. That's
#' why a one second pause is added after each download to respect the server's
#' limits. This time can be set with the option `GFONTS_DOWNLOAD_SLEEPTIME` which
#' must be a number of seconds.
#' @param family family name of a 'Google Fonts', for example, "Open Sans", "Roboto",
#' "Fira Code" or "Fira Sans Condensed". Complete list is available with the
#' following command:
#'
#' ```
#' gfonts::get_all_fonts()$family |>
#'   unlist() |>
#'   unique() |>
#'   sort()
#' ```
#' @param subset font subset, a character vector, it defaults to only "latin" and
#' "latin-ext" and can contains values such as "greek", "emoji", "chinese-traditional",
#'
#' Run the following code to get a complete list:
#' ```
#' gfonts::get_all_fonts()$subsets |> unlist() |> unique() |> sort()
#' ```
#'
#' @family functions for font management
#' @return an object defined with [htmltools::htmlDependency()].
#' @examples
#' \dontrun{
#' if (check_gfonts()) {
#'   dummy_setup()
#'   gfontHtmlDependency(family = "Open Sans")
#' }
#' }
gfontHtmlDependency <- function(family = "Open Sans", subset = c("latin", "latin-ext")) {
  pkg_version <- packageVersion("gdtools")
  pkg_version_str <- format(pkg_version)

  font_id <- get_font_id(family)
  register_gfont(family = family, subset = subset)

  htmlDependency(
    all_files = TRUE,
    name = font_id,
    version = pkg_version_str,
    src = file.path(fonts_cache_dir(), font_id),
    stylesheet = paste0("css/", font_id, ".css")
  )
}

#' @export
#' @importFrom htmltools tags attachDependencies
#' @title Use a font in Shiny or Markdown
#' @description Add an empty HTML element attached
#' to an 'HTML Dependency' containing
#' the css and the font files so that the font is available
#' in the HTML page. Multiple families are supported.
#'
#' The htmlDependency is defined with function [gfontHtmlDependency()].
#' @inherit gfontHtmlDependency params details
#' @return an HTML object
#' @family functions for font management
#' @examples
#' \dontrun{
#' if (check_gfonts()) {
#'   dummy_setup()
#'   addGFontHtmlDependency(family = "Open Sans")
#' }
#' }
addGFontHtmlDependency <- function(family = "Open Sans", subset = c("latin", "latin-ext")) {
  attachDependencies(
    x = tags$style(""),
    lapply(family, gfontHtmlDependency, subset = subset)
  )
}

get_font_id <- function(family) {
  x <- gfonts_summary()

  if (!family %in% x$family) {
    stop("Font family ", shQuote(family), " has not been found.",
      call. = FALSE
    )
  }
  x[x$family %in% family, ]$id
}

#' @importFrom systemfonts register_font
#' @export
#' @title Register a 'Google Fonts'
#' @description Register a font from 'Google Fonts' so that it can be used
#' with devices using the 'systemfonts' package, i.e. the 'flextable'
#' package and graphic outputs generated with the 'ragg', 'svglite'
#' and 'ggiraph' packages.
#' @inherit gfontHtmlDependency params details
#' @return TRUE if the operation went ok.
#' @family functions for font management
#' @examples
#' \dontrun{
#' if (check_gfonts()) {
#'   dummy_setup()
#'   register_gfont(family = "Roboto")
#' }
#' }
register_gfont <- function(family = "Open Sans", subset = c("latin", "latin-ext")) {
  font_id <- get_font_id(family)
  x <- gfonts_summary()
  faces <- reduce_faces(x[x$id %in% font_id, ]$variants[[1]])

  font_to_cache(family = family, faces = faces, subset = subset)

  files <- lapply(faces, function(face) {
    list.files(
      path = font_dir(font_id),
      pattern = paste0(font_id, "(.*)-", face, "\\.ttf"),
      full.names = TRUE
    )
  })

  if (!font_family_exists(family)) {
    files[["name"]] <- family
    do.call(register_font, files)
  }

  font_family_exists(family)
}

#' @export
#' @title Shell command to install a font from 'Google Fonts'
#' @description Create a string containing a system command to execute
#' so that the font from 'Google Fonts' is installed on the system.
#' Its execution may require root permissions, in dockerfile for example.
#' @inherit gfontHtmlDependency params details
#' @param platform "debian" and "windows" and "macos" are supported.
#' @param file script file to generate, optional. If the parameter is
#' specified, a file will be generated ready for execution. If the
#' platform is Windows, administration rights are required to run
#' the script.
#' @return the 'shell' or 'PowerShell' command as a string
#' @family functions for font management
#' @examples
#' \dontrun{
#' if (check_gfonts()) {
#'   dummy_setup()
#'   install_gfont_script(family = "Roboto", platform = "macos")
#' }
#' }
install_gfont_script <- function(family = "Open Sans",
                                 subset = c("latin", "latin-ext"),
                                 platform = c("debian", "windows", "macos"),
                                 file = NULL) {
  platform <- match.arg(platform)
  font_id <- get_font_id(family)
  x <- gfonts_summary()
  faces <- reduce_faces(x[x$id %in% font_id, ]$variants[[1]])

  font_to_cache(family = family, faces = faces, subset = subset)

  if ("debian" %in% platform) {
    str <- debian_sysinstall_command(font_id, dir = "custom-fonts")
  } else if ("windows" %in% platform) {
    str <- windows_sysinstall_command(font_id)
  } else {
    str <- macos_sysinstall_command(font_id, dir = if (user_cache_exists()) "~/Library/Fonts" else "/Library/Fonts")
  }

  if (!is.null(file)) {
    writeLines(str, file, useBytes = TRUE)
    Sys.chmod(file, mode = "755")
  }

  invisible(str)
}

#' @export
#' @title List installed 'Google Fonts'
#' @description List installed 'Google Fonts' that can be
#' found in the user cache directory.
#' @return families names as a character vector
#' @family functions for font management
#' @examples
#' \dontrun{
#' if (check_gfonts()) {
#'   dummy_setup()
#'   register_gfont(family = "Roboto")
#'   installed_gfonts()
#' }
#' }
installed_gfonts <- function() {
  x <- gfonts_summary()
  fonts_ids <- basename(list.dirs(fonts_cache_dir(), recursive = FALSE))
  x$family[x$id %in% fonts_ids]
}

#' @export
#' @title Checks the operability of 'gfonts'
#' @description Checks that 'gfonts' is installed and can be used.
#' Packages 'curl' and 'gfonts' must be installed and internet
#' connectivity must be active.
#' @param errors if TRUE, function is triggering errors if a condition
#' is not satisfied.
#' @return TRUE or FALSE
#' @keywords internal
check_gfonts <- function(errors = FALSE) {
  has_curl <- requireNamespace("curl", quietly = TRUE)
  has_gfonts <- requireNamespace("gfonts", quietly = TRUE)

  if (!has_curl && errors) {
    stop("package 'curl' is required to download fonts from 'fonts.google'.")
  }
  if (!has_curl) {
    return(FALSE)
  }

  if (!has_gfonts && errors) {
    stop("package 'gfonts' is required to download fonts from 'fonts.google'.")
  }
  if (!has_gfonts) {
    return(FALSE)
  }

  has_connectivity <- curl::has_internet()
  if (!has_connectivity && errors) {
    stop("an internet connection is required to download the font files.")
  }
  if (!has_connectivity) {
    return(FALSE)
  }

  TRUE
}


# utils ----
windows_sysinstall_command <- function(font_id) {
  # https://www.jordanmalcolm.com/deploying-windows-10-fonts-at-scale/
  id_dir <- font_dir(font_id)
  install_cmd <- c(
    sprintf("$FontFolder = \"%s\"", id_dir),
    "$FontItem = Get-Item -Path $FontFolder",
    "$FontList = Get-ChildItem -Path \"$FontItem\\*\" -Include ('*.otf','*.ttc','*.ttf')",
    "",
    "foreach ($Font in $FontList) {",
    "  Copy-Item $Font \"C:\\Windows\\Fonts\"",
    "  New-ItemProperty -Name $Font.BaseName -Path \"HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" -PropertyType string -Value $Font.name",
    "}", ""
  )
  install_cmd <- paste0(install_cmd, collapse = "\n")
  install_cmd
}


debian_sysinstall_command <- function(font_id, dir = "custom-fonts") {
  id_dir <- font_dir(font_id)
  create_dir <- sprintf("mkdir -p /usr/share/fonts/truetype/%s", dir)
  id_dir <- font_dir(font_id)
  install_cmd <- sprintf(
    "find %s -name \"*.ttf\" -exec install -m644 {} /usr/share/fonts/truetype/%s/ \\; || return 1",
    gsub(" ", "\\ ", id_dir, fixed = TRUE), dir
  )

  paste(create_dir, install_cmd, "fc-cache -f", sep = ";")
}


macos_sysinstall_command <- function(font_id, dir = "~/Library/Fonts") {
  id_dir <- font_dir(font_id)
  sprintf("cp %s/* %s", gsub(" ", "\\ ", id_dir, fixed = TRUE), dir)
}