-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathweb_fonts.R
More file actions
702 lines (654 loc) · 19.8 KB
/
Copy pathweb_fonts.R
File metadata and controls
702 lines (654 loc) · 19.8 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#' Search font repositories for a font based on family name
#'
#' While it is often advisable to visit the webpage for a font repository when
#' looking for a font, in order to see examples etc, `search_web_fonts()`
#' provide a quick lookup based on family name in the repositories supported by
#' systemfonts (currently [Google Fonts](https://fonts.google.com) and
#' [Font Squirrel](https://fontsquirrel.com) - [Bunny Fonts](https://fonts.bunny.net/)
#' provide the same fonts as Google Fonts but doesn't have a search API). The
#' lookup is based on fuzzy matching provided by [utils::adist()] and the
#' matching parameters can be controlled through `...`
#'
#' @param family The font family name to look for
#' @param n_max The maximum number of matches to return
#' @inheritDotParams utils::adist -x -y
#'
#' @return A data.frame with the columns `family`, giving the family name of the
#' matched font, and `repository` giving the repository it was found in.
#'
#' @export
#'
#' @examples
#' # Requires an internet connection
#'
#' # search_web_fonts("Spectral")
#'
search_web_fonts <- function(family, n_max = 10, ...) {
gf <- unique(get_google_fonts_registry()$family)
fs <- unique(get_font_squirrel_registry()$family)
all <- data.frame(
family = c(gf, fs),
repository = c(rep(
c("Google Fonts/Bunny Fonts", "Font Squirrel"),
c(length(gf), length(fs))
))
)
all[
order(utils::adist(
x = tolower(family),
y = tolower(all$family),
...
))[seq_len(min(n_max, nrow(all)))],
]
}
#' Download and add web font
#'
#' In order to use a font in R it must first be made available locally. These
#' functions facilitate the download and registration of fonts from online
#' repositories.
#'
#' @param family The font family to download (case insensitive)
#' @param dir Where to download the font to. The default places it in your user
#' local font folder so that the font will be available automatically in new R
#' sessions. Set to `tempdir()` to only keep the font for the session.
#' @param woff2 Should the font be downloaded in the woff2 format (smaller and
#' more optimized)? Defaults to FALSE as the format is not supported on all
#' systems
#'
#' @return A logical invisibly indicating whether a font was found and
#' downloaded or not
#'
#' @name web-fonts
#' @rdname web-fonts
#'
NULL
#' @rdname web-fonts
#' @export
#'
get_from_google_fonts <- function(family, dir = "~/fonts", woff2 = FALSE) {
fonts <- get_google_fonts_registry(woff2)
match <- which(tolower(fonts$family) == tolower(family))
if (length(match) == 0) {
return(invisible(FALSE))
}
if (!dir.exists(dir)) dir.create(dir, recursive = TRUE)
files <- fonts$url[match]
download_name <- file.path(dir, fonts$file[match])
success <- try(
{
if (capabilities("libcurl")) {
utils::download.file(
files,
download_name,
method = "libcurl",
quiet = TRUE,
mode = "wb"
)
} else {
mapply(
utils::download.file,
url = files,
destfile = download_name,
quiet = TRUE,
mode = "wb"
)
}
},
silent = TRUE
)
if (inherits(success, "try-error")) {
return(invisible(FALSE))
}
add_fonts(download_name)
invisible(TRUE)
}
#' @rdname web-fonts
#' @export
#'
get_from_font_squirrel <- function(family, dir = "~/fonts") {
fonts <- get_font_squirrel_registry()
match <- which(tolower(fonts$family) == tolower(family))
if (length(match) == 0) {
return(invisible(FALSE))
}
if (!dir.exists(dir)) dir.create(dir, recursive = TRUE)
files <- fonts$url[match]
download_name <- file.path(
tempdir(check = TRUE),
paste0(basename(fonts$url[match]), ".zip")
)
success <- try(
{
if (capabilities("libcurl")) {
utils::download.file(
files,
download_name,
method = "libcurl",
quiet = TRUE
)
} else {
mapply(
utils::download.file,
url = files,
destfile = download_name,
quiet = TRUE
)
}
},
silent = TRUE
)
if (inherits(success, "try-error")) {
return(invisible(FALSE))
}
new_fonts <- unlist(mapply(
utils::unzip,
zipfile = download_name,
MoreArgs = list(exdir = dir)
))
is_font <- grepl("\\.(?:ttf|ttc|otf|otc|woff|woff2)$", tolower(new_fonts))
unlink(new_fonts[!is_font])
add_fonts(new_fonts[is_font])
return(invisible(TRUE))
}
get_from_font_library <- function(family, dir = "~/fonts") {
url <- import_from_font_library(family)
if (length(url) == 0) {
return(invisible(FALSE))
}
url <- readLines(url)
urls <- grep("url\\(.*?\\)", url, value = TRUE)
urls <- sub(".*url\\((.*?)\\).*", "\\1", urls)
urls <- paste0("https://fontlibrary.org", gsub("'|\"", "", urls))
if (!dir.exists(dir)) dir.create(dir, recursive = TRUE)
download_name <- file.path(dir, basename(urls))
success <- try(
{
if (capabilities("libcurl")) {
utils::download.file(
urls,
download_name,
method = "libcurl",
quiet = TRUE
)
} else {
mapply(
utils::download.file,
url = urls,
destfile = download_name,
quiet = TRUE
)
}
},
silent = TRUE
)
if (inherits(success, "try-error")) {
return(invisible(FALSE))
}
add_fonts(download_name)
return(invisible(TRUE))
}
#' Ensure font availability in a script
#'
#' When running a script on a different machine you are not always in control of
#' which fonts are installed on the system and thus how graphics created by the
#' script ends up looking. `require_font()` is a way to specify your font
#' requirements for a script. It will look at the available fonts and if the
#' required font family is not present it will attempt to fetch it from one of
#' the given repositories (in the order given). If that fails, it will either
#' throw an error or, if `fallback` is given, provide an alias for the fallback
#' so it maps to the required font.
#'
#' @param family The font family to require
#' @param fallback An available font to fall back to if `family` cannot be found
#' or downloaded
#' @param dir The location to put the font file downloaded from repositories
#' @param repositories The repositories to search for the font in case it is not
#' available on the system. They will be tried in the order given. Currently
#' `"Google Fonts"`, `"Font Squirrel"`, and `"Font Library"` is available.
#' @param error Should the function throw an error if unsuccessful?
#' @param verbose Should status messages be emitted?
#'
#' @return Invisibly `TRUE` if the font is available or `FALSE` if not (this can
#' only be returned if `error = FALSE`)
#'
#' @export
#'
#' @examples
#' # Should always work
#' require_font("sans")
#'
require_font <- function(
family,
fallback = NULL,
dir = tempdir(),
repositories = c("Google Fonts", "Font Squirrel", "Font Library"),
error = TRUE,
verbose = TRUE
) {
if (tolower(family) %in% c("sans", "serif", "mono", "symbol"))
return(invisible(TRUE))
if (!is.character(family) || length(family) != 1) {
stop("`family` must be a string")
}
if (
!is.null(fallback) && (!is.character(fallback) || length(fallback) != 1)
) {
stop("`family` must be a string")
}
fonts <- system_fonts()
available <- which(tolower(fonts$family) == tolower(family))
if (length(available) != 0) {
if (verbose) {
message(
"`",
family,
"` available at ",
paste0(unique(dirname(fonts$path[available])), collapse = ", ")
)
}
return(invisible(TRUE))
}
success <- FALSE
has_internet <- !inherits(
suppressWarnings(try(
readLines("https://8.8.8.8", n = 1L),
silent = TRUE
)),
"try-error"
)
if (!has_internet) {
if (verbose) {
message("No internet connection. Can't search online repositories")
}
} else {
for (repo in repositories) {
if (verbose) message("Trying ", repo, "...", appendLF = FALSE)
success <- switch(
tolower(repo),
"google fonts" = get_from_google_fonts(family, dir),
"font squirrel" = get_from_font_squirrel(family, dir),
"font library" = get_from_font_library(family, dir),
FALSE
)
if (verbose) {
if (success) {
message(" Found! Downloading font to ", dir)
} else {
message("Not found.")
}
}
if (success) break
}
}
if (!success) {
if (is.null(fallback)) {
if (error)
stop(paste0(
"Required font: ",
family,
", is not available on the system"
))
} else {
message(
"Required font: `",
family,
"`, is not available on the system. Adding alias to `",
fallback,
"`"
)
register_variant(family, fallback)
success <- TRUE
}
}
invisible(success)
}
#' Create import specifications for web content
#'
#' If you create content in a text-based format such as HTML or SVG you need to
#' make sure that the font is available on the computer where it is viewed. This
#' can be achieved through the use of stylesheets that can either be added with
#' a `<link>` tag or inserted with an `@import` statement. This function
#' facilitates the creation of either of these (or the bare URL to the
#' stylesheet). It can rely on the Bunny Fonts, Google Fonts and/or Font Library
#' repositories for serving the fonts. If the requested font is not found it can
#' optionally hard code the data into the stylesheet.
#'
#' @inheritParams match_fonts
#' @param ... Additional arguments passed on to the specific functions for the
#' repositories. Currently:
#' * **Google Fonts and Bunny Fonts:**
#' - `text` A piece of text containing the glyphs required. Using this can
#' severely cut down on the size of the required download
#' - `display` One of `"auto"`, `"block"`, `"swap"`, `"fallback"`, or
#' `"optional"`. Controls how the text is displayed while the font is
#' downloading.
#' @param type The type of return value. `"url"` returns the bare url pointing
#' to the style sheet. `"import"` returns the stylesheet as an import statement
#' (`@import url(<url>)`). `"link"` returns the stylesheet as a link tag
#' (`<link rel="stylesheet" href="<url>"/>`)
#' @param may_embed Logical. Should fonts that can't be found in the provided
#' repositories be embedded as data-URLs. This is only possible if the font is
#' available locally and in a `woff2`, `woff`, `otf`, or `ttf` file.
#' @param repositories The repositories to try looking for the font. Currently
#' `"Bunny Fonts"`, `"Google Fonts"`, and `"Font Library"` are supported. Set
#' this to `NULL` together with `may_embed = TRUE` to force embedding of the
#' font data.
#'
#' @return A character vector with stylesheet specifications according to `type`
#' @export
#'
fonts_as_import <- function(
family,
italic = NULL,
weight = NULL,
width = NULL,
...,
type = c("url", "import", "link"),
may_embed = TRUE,
repositories = c("Bunny Fonts", "Google Fonts", "Font Library")
) {
import <- character(0)
type <- match.arg(type)
if (may_embed) repositories <- c(repositories, "local")
all_families <- family
for (repo in repositories) {
fonts <- switch(
tolower(repo),
"bunny fonts" = import_from_bunny_fonts(
family,
italic = italic,
weight = weight,
width = width,
...
),
"google fonts" = import_from_google_fonts(
family,
italic = italic,
weight = weight,
width = width,
...
),
"font library" = import_from_font_library(family, ...),
"local" = import_embedded(
family,
italic = italic,
weight = weight,
width = width,
...
),
NULL
)
if (!is.null(fonts)) {
import <- c(import, fonts)
missing <- attr(fonts, "no_match")
family <- family[missing]
if (!is.null(italic)) italic <- italic[missing]
if (!is.null(width)) width <- width[missing]
if (!is.null(weight)) weight <- weight[missing]
}
if (length(family) == 0) break
}
if (length(family) != 0) {
warning("No import found for ", paste(family, collapse = ", "))
}
imported <- unique(setdiff(all_families, family))
for (f in imported) {
success <- require_font(imported, error = FALSE, verbose = FALSE)
if (!success) {
warning(
"An import URL for ",
f,
" could be made but the font could not be made avialable on the system"
)
}
}
switch(
type,
import = paste0("@import url('", import, "');"),
link = paste0('<link rel="stylesheet" href="', import, '"/>'),
url = import
)
}
import_from_google_fonts <- function(
family,
italic = NULL,
weight = NULL,
width = NULL,
...,
text = NULL,
display = "swap"
) {
n_fonts <- max(length(family), length(italic), length(weight), length(width))
family <- rep_len(family, n_fonts)
if (!is.null(italic)) italic <- rep_len_default(as.integer(italic), n_fonts, 0L)
if (!is.null(weight))
weight <- rep_len_default(systemfonts::as_font_weight(weight), n_fonts, 400)
if (!is.null(width))
width <- rep_len_default(systemfonts::as_font_width(width), n_fonts, 0)
clusters <- split(seq_along(family), family)
possible_fonts <- unique(get_google_fonts_registry()$family)
fonts <- lapply(clusters, function(i) {
fam <- family[i[1]]
fam <- match(tolower(fam), tolower(possible_fonts))
if (is.na(fam)) return()
fam <- possible_fonts[fam]
fam <- paste0("family=", gsub(" ", "+", family[i[1]]))
spec <- list()
spec$ital <- if (!is.null(italic)) as.character(unique(range(italic[i])))
if (isTRUE(spec$ital == 0L)) spec$ital <- NULL
spec$wdth <- if (!is.null(width))
paste0(unique(range(width[i])), collapse = "..")
spec$wght <- if (!is.null(weight))
paste0(unique(range(weight[i])), collapse = "..")
spec <- spec[lengths(spec) != 0]
if (length(spec) != 0) {
n_specs <- max(lengths(spec))
spec <- lapply(spec, rep_len, n_specs)
val <- paste0(
vapply(
seq_len(n_specs),
function(i) {
paste0(vapply(spec, `[[`, character(1), i), collapse = ",")
},
character(1)
),
collapse = ";"
)
spec <- paste0(names(spec), collapse = ",")
fam <- paste0(fam, ":", spec, "@", val)
}
fam
})
missing <- unlist(clusters[lengths(fonts) == 0]) %||% integer()
fonts <- paste0(unlist(fonts), collapse = "&")
display <- match.arg(
display,
c("auto", "block", "swap", "fallback", "optional")
)
url <- paste0("https://fonts.googleapis.com/css2?", fonts)
if (display != "auto") {
url <- paste0(url, "&display=", display)
}
if (!is.null(text)) {
url <- paste0(url, "&text=", utils::URLencode(text))
}
success <- try(suppressWarnings(readLines(url, n = 1)), silent = TRUE)
if (inherits(success, "try-error")) {
url <- character(0)
missing <- seq_along(family)
}
structure(url %||% character(), no_match = missing)
}
import_from_bunny_fonts <- function(
family,
italic = NULL,
weight = NULL,
width = NULL,
...,
text = NULL,
display = "swap"
) {
url <- import_from_google_fonts(
family = family,
italic = italic,
weight = weight,
width = width,
...,
text = text,
display = display
)
success <- try(suppressWarnings(readLines(url, n = 1)), silent = TRUE)
if (
inherits(success, "try-error") || any(grepl("Error: API Error", success))
) {
return(structure(character(), no_match = seq_along(family)))
}
structure(
sub(
"https://fonts.googleapis.com/css2?",
"https://fonts.bunny.net/css2?",
url,
fixed = TRUE
),
no_match = attr(url, "no_match")
)
}
import_from_font_library <- function(family, ...) {
family <- gsub(" ", "-", tolower(family))
u_fam <- unique(family)
names(u_fam) <- u_fam
fonts <- lapply(u_fam, function(name) {
url <- paste0("https://fontlibrary.org/face/", name)
if (length(readLines(url, n = 1)) != 0) {
url
} else {
NULL
}
})
missing <- which(family %in% names(fonts[lengths(fonts) == 0]))
fonts <- unlist(fonts)
structure(fonts %||% character(), no_match = missing, names = NULL)
}
import_embedded <- function(
family,
italic = NULL,
weight = NULL,
width = NULL,
...
) {
fonts <- match_fonts(
family,
italic = italic %||% FALSE,
weight = weight %||% "normal",
width = width %||% "undefined"
)
fonts <- lapply(seq_along(family), function(i) {
found <- font_info(path = fonts$path[i], index = fonts$index[i])
if (tolower(family[i]) != tolower(found$family)) return()
ext <- tools::file_ext(fonts$path[i])
if (!ext %in% c("woff2", "woff", "otf", "ttf")) {
warning(ext, "-files cannot be embedded (", family[i], ")")
return()
}
format <- switch(
ext,
woff2 = 'format("woff2")',
woff = 'format("woff")',
otf = 'format("opentype")',
ttf = 'format("truetype")'
)
src <- paste0(
"url(data:font/",
ext,
";charset=utf-8;base64,",
base64enc::base64encode(fonts$path[i]),
") ",
format
)
features <- paste0(
'"',
fonts$features[[i]][[1]],
'" ',
fonts$features[[i]][[2]],
collapse = ", "
)
# fmt: skip
x <- paste0(
'@font-face {\n',
' font-family: "', found$family, '";\n',
' src: ', src, ';\n',
if (length(fonts$features[[i]]) != 0) paste0(
' font-feature-settings: ', features, ';\n'),
if (!is.na(found$width)) paste0(
' font-stretch: ', sub("(ra|mi)", "\\1-", found$width), ';\n'),
if (!is.na(found$weight)) paste0(
' font-weight: ', as_font_weight(found$weight), ';\n'),
' font-style: ', if (found$italic) "italic" else "normal", ';\n',
'}'
)
paste0("data:text/css,", utils::URLencode(x))
})
missing <- which(lengths(fonts) == 0)
fonts <- unlist(fonts)
structure(fonts %||% character(), no_match = missing)
}
# REGISTRIES -------------------------------------------------------------------
google_fonts_registry <- new.env(parent = emptyenv())
get_google_fonts_registry <- function(woff2 = FALSE) {
loc <- if (woff2) "woff2" else "ttf"
if (is.null(google_fonts_registry[[loc]])) {
url <- "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBkOYsZREsyZWvbSR_d03SI5XX30cIapYo&sort=popularity"
if (woff2) {
url <- paste0(url, "&capability=WOFF2")
}
fonts <- jsonlite::read_json(url)$items
google_fonts_registry[[loc]] <- do.call(
rbind,
lapply(fonts, function(x) {
x <- data.frame(
family = x$family,
variant = unlist(x$variants),
url = unlist(x$files),
file = NA_character_,
version = x$version,
modified = x$lastModified,
category = I(rep(list(x$category), length(x$variants)))
)
x$file <- paste0(
x$family,
"-",
x$variant,
sub("^.*(\\.\\w+)$", "\\1", x$url)
)
attr(x, "row.names") <- .set_row_names(nrow(x))
x
})
)
}
google_fonts_registry[[loc]]
}
font_squirrel_registry <- new.env(parent = emptyenv())
get_font_squirrel_registry <- function() {
if (is.null(font_squirrel_registry$fonts)) {
fonts <- jsonlite::read_json(
"https://www.fontsquirrel.com/api/fontlist/all"
)
font_squirrel_registry$fonts <- do.call(
rbind,
lapply(fonts, function(x) {
x <- data.frame(
family = x$family_name,
n_variants = x$family_count,
url = paste0(
"https://www.fontsquirrel.com/fonts/download/",
x$family_urlname
),
category = I(list(x$classification))
)
attr(x, "row.names") <- .set_row_names(nrow(x))
x
})
)
}
font_squirrel_registry$fonts
}