---
title: "systemfonts C interface"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{systemfonts C interface}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(systemfonts)
```

Most of the functionality in systemfonts is intended to be used from compiled
code to help e.g. graphic devices to resolve font specifications to a font file
prior to rendering. systemfonts provide key functionality to get called at the 
C level using the `R_getCCallable()` function. The systemfonts namespace must
be loaded for this to work, so be sure to import e.g. `match_font()` in the
package namespace. For more information about this interface see 
[*Registering native routines*](https://cran.r-project.org/doc/manuals/R-exts.html#Registering-native-routines)
in *Writing R Extensions*.

## Font matching
The C equivalent of the `match_font()` R function is `locate_font()` with the
following signature:

```C
int locate_font(const char *family, int italic, int bold, char *path, int max_path_length)
```

It takes a UTF-8 encoded string with the font family name, an int setting both
italic and bold styles along with a char pointer to be filled with the located
path and the maximum length it can hold. The return value is an int giving the
index of the font in the font file.

The best way to use the function in a package is to wrap it in a function to
avoid fetching it multiple times, e.g.

```C
static int locate_font(const char *family, int italic, int bold, char *path, int max_path_length) {
  static int (*p_locate_font)(const char *family, int italic, int bold, char *path, int max_path_length) = NULL;
  if (p_locate_font == NULL) {
    p_locate_font = (int(*)(const char *, int, int, char *, int)) R_GetCCallable("systemfonts", "locate_font");
  }
  return p_locate_font(family, italic, bold, path, max_path_length);
}
```
