Commit7b596a53Recorded9 Nov 2026Repositorysigil-fontconfig

Add isolated Fontconfig inventories and fallback ordering

Changed
 README.md                  |  93 +++++++++++++++++++++++++++++++++++++++++++++++++----
 manifest.scm               |   5 +--
 package.sgl                |  15 +++++----
 scripts/ci-test.sgl        |  45 ++++++++++++++++++++++++++
 sigil.lock                 |  73 ++++++++++++++++++++++++++++++++++++++++++
 src/sigil/fontconfig.sgl   | 291 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
 test/test-00-isolation.sgl |  53 ++++++++++++++++++++++++++++++
 test/test-context.sgl      | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 8 files changed, 669 insertions(+), 50 deletions(-)
Diff
README.mdmodified
@@ -1,7 +1,7 @@
1
# sigil-fontconfig
2
3
Font discovery for Sigil through pure dynamic FFI. The system must supply
−4
`libfontconfig`; no C extension or external font lookup process is used.
+4
`libfontconfig` 2.12.5 or later; no C extension or external font lookup process is used.
5
6
```scheme
7
(import (sigil fontconfig))
@@ -23,13 +23,92 @@ uses exact property matching without fallback. Results expose `fc-font-file`,
23
data; native patterns and sets are destroyed before returning. File and index
24
can be passed directly to `ft-new-face` from sigil-freetype.
25
−26
The package uses the process's default Fontconfig configuration. It initializes
−27
Fontconfig lazily and leaves its shared caches available to other library users.
+26
These two legacy functions use the process default and initialize it lazily.
+27
They leave its shared caches available to other library users. Legacy listing
+28
rejects a native set larger than 65536 records before copying its entries.
+29
+30
For UI discovery independent of a page renderer, use an owned inventory:
+31
+32
```scheme
+33
(define context
+34
(make-fc-context
+35
files: '("fonts/JetBrainsMono-Regular.ttf" "fonts/JetBrainsMono-Bold.ttf")
+36
directories: '("/usr/share/fonts/truetype/jetbrains-mono")
+37
cache-directory: "/absolute/private/ui-font-cache"
+38
max-fonts: 4096))
+39
(dynamic-wind
+40
(lambda () #f)
+41
(lambda ()
+42
(fc-context-match context (fc-pattern family: "JetBrains Mono" style: "Regular"))
+43
(fc-context-sort context (fc-pattern family: "JetBrains Mono"))
+44
(fc-context-list context))
+45
(lambda () (fc-context-close! context)))
+46
```
+47
+48
The context starts empty and scans only explicit files/directories. It loads no
+49
system or user configuration, inherits no cache directories or sysroot, and
+50
disables its own automatic rescans. It never replaces the process default or
+51
changes environment variables. Directory scanning is synchronous; select
+52
specific font roots, not broad filesystem roots. `max-fonts:` bounds the
+53
completed inventory and returned copies (default 4096, positive exact integer
+54
below 1000000); it is not a native scan-memory or time limit. The bound counts
+55
font patterns, including named instances in variable-font files.
+56
Directory inventories require an explicit absolute `cache-directory:`;
+57
create a private writable directory before calling. Only that cache path is
+58
loaded into the context. File-only inventories need no disk cache.
+59
+60
Owned matching/sorting applies normal weight, roman slant, normal width and
+61
the standard numeric/boolean matching defaults directly. Unspecified point
+62
size uses 12 points at 75 DPI. Name languages come from the first selected
+63
locale, normalized without a default configuration, with a weak English fallback.
+64
The legacy system API still calls Fontconfig's default-substitution function.
+65
The owned path never calls it, including on Fontconfig 2.17 and later where
+66
that function initializes the process default.
+67
+68
`fc-context-match` returns one copied record or `#f`.
+69
`fc-context-list` optionally accepts one pattern.
+70
`fc-context-sort` returns copied candidates in Fontconfig preference order;
+71
its default `trim?: #t` removes candidates adding no character coverage.
+72
Use `trim?: #f` to retain all candidates. Consumers should check actual glyph
+73
coverage in their face loader. No native patterns or charsets escape. Results
+74
survive later calls and closing their context.
+75
+76
Close is idempotent; subsequent discovery calls raise an error.
+77
`fc-context-closed?` exposes this state. Pointer finalization also covers
+78
abandoned contexts, while explicit close clears that finalizer before release.
79
Missing libraries, invalid arguments and native allocation failures raise errors.
−29
No native pointers escape the API.
+80
Static compilation tools may import the module without a dynamic loader;
+81
an attempted native operation then reports the saved load failure.
+82
+83
The implementation follows the upstream
+84
[Fontconfig developer reference](https://fontconfig.pages.freedesktop.org/fontconfig/fontconfig-devel/)
+85
for explicit configurations, application font inventories and sorted sets.
+86
+87
Use `guix shell -m manifest.scm` for Fontconfig, its native test compiler,
+88
JetBrains Mono and Noto Sans/Serif,
+89
then `sigil deps install`, `sigil build` and `sigil scripts/ci-test.sgl`.
+90
Or run the ordered gate directly:
+91
+92
```text
+93
guix shell -m manifest.scm -- sigil scripts/ci-test.sgl
+94
```
+95
+96
The shipped driver copies just the four test faces into a temporary inventory
+97
and supplies private process-default configuration and cache directories.
+98
To supply fixtures without the manifest, set `SIGIL_FONTCONFIG_TEST_DIRECTORY`
+99
to an absolute owned directory containing `JetBrainsMono-Regular.ttf`,
+100
`JetBrainsMono-Bold.ttf`, `NotoSans.ttf` and `NotoSerif.ttf`.
+101
`SIGIL_FONTCONFIG_TEST_CACHE` optionally selects an absolute private writable
+102
cache directory for the owned-directory tests; otherwise the driver creates
+103
one temporarily. These variables are required when running individual test
+104
files without the driver. No desktop font configuration is needed.
105
−31
Use `guix shell -m manifest.scm` for Fontconfig and the deterministic test font,
−32
then `sigil deps install`, `sigil build` and `sigil test`. Dependencies follow the
−33
same conventions as sigil-freetype, sigil-harfbuzz and sigil-cairo.
+106
The driver runs `test/test-00-isolation.sgl` alone in a fresh process before
+107
the other two suites. Its sentinel cache must remain empty after owned
+108
matching, sorting and listing, then become nonempty when `FcConfigGetCurrent`
+109
explicitly initializes that default. This positive control makes prior default
+110
initialization fail the test. Plain `sigil test` is not the ordered gate: file
+111
discovery order is unspecified. The separate default pointer-identity control
+112
checks preservation after initialization.
113
114
BSD-3-Clause.
manifest.scmmodified
@@ -1,2 +1,3 @@
−1
;; Native runtime dependency plus a deterministic test font.
−2
(specifications->manifest (list "fontconfig" "font-jetbrains-mono"))
+1
;; Native runtime and the four faces selected by the isolated test driver.
+2
(specifications->manifest
+3
(list "fontconfig" "gcc-toolchain" "font-jetbrains-mono" "font-google-noto"))
package.sglmodified
@@ -1,10 +1,10 @@
1
;;; Font discovery through the system Fontconfig library.
2
(package
3
name: "sigil-fontconfig"
−4
version: "0.8.1"
−5
sigil: "0.20"
+4
version: "0.9.0"
+5
sigil: "0.24.5"
6
description: "Fontconfig font discovery bindings for Sigil"
−7
url: "https://codeberg.org/sigil/sigil-fontconfig"
+7
url: "https://git.usesigil.org/sigil/sigil-fontconfig"
8
license: "BSD-3-Clause"
9
authors: (list "David Wilson <david@daviwil.com>")
10
@@ -13,12 +13,13 @@
13
(config name: 'release output-dir: "build/release" debug?: #f optimize: 2))
14
15
dependencies: (list
−16
(from-git url: "codeberg:sigil/sigil" package: "sigil-stdlib" version: ">=0.21")
−17
(from-git url: "codeberg:sigil/sigil-ffi" version: "^0.16"))
+16
(from-pkg name: "sigil/sigil-lib" version: "^0.24.5")
+17
(from-pkg name: "sigil/sigil-stdlib" version: "^0.24.5")
+18
(from-pkg name: "sigil/sigil-ffi" version: "^0.16.4"))
19
20
dev-dependencies: (list
−20
(from-git url: "codeberg:sigil/sigil" package: "sigil-test" version: ">=0.21")
−21
(from-git url: "codeberg:sigil/sigil" package: "sigil-test-runner" version: ">=0.21"))
+21
(from-pkg name: "sigil/sigil-test" version: "^0.24.5")
+22
(from-pkg name: "sigil/sigil-test-runner" version: "^0.24.5"))
23
24
tasks: (list
25
(task name: 'build description: "Compile sigil-fontconfig modules"
scripts/ci-test.sgladded
@@ -0,0 +1,45 @@
+1
;;; Run isolation in a fresh process, then the suites that initialize defaults.
+2
(import (sigil shell prelude) (sigil fs))
+3
(requires (tools sigil))
+4
(define root (dirname (script-dir)))
+5
(define profile (getenv "GUIX_ENVIRONMENT"))
+6
(define (xml text)
+7
(string-replace (string-replace (string-replace text "&" "&amp;") "<" "&lt;") ">" "&gt;"))
+8
(define (profile-face names)
+9
(unless profile
+10
(error "Use guix shell -m manifest.scm or set SIGIL_FONTCONFIG_TEST_DIRECTORY"))
+11
(let find ((remaining names))
+12
(when (null? remaining) (error "The manifest lacks a required test face" names))
+13
(let ((candidate (path profile "share/fonts/truetype" (car remaining))))
+14
(if (file? candidate) candidate (find (cdr remaining))))))
+15
+16
(with-temp-dir work
+17
(define inventory (or (getenv "SIGIL_FONTCONFIG_TEST_DIRECTORY") (path work "fonts")))
+18
(unless (getenv "SIGIL_FONTCONFIG_TEST_DIRECTORY")
+19
(ensure-directory inventory)
+20
(each entry '(("JetBrainsMono-Regular.ttf" "JetBrainsMono-Regular.ttf")
+21
("JetBrainsMono-Bold.ttf" "JetBrainsMono-Bold.ttf")
+22
("NotoSans.ttf" "NotoSans[wdth,wght].ttf" "NotoSans-Regular.ttf" "NotoSans.ttf")
+23
("NotoSerif.ttf" "NotoSerif[wdth,wght].ttf" "NotoSerif-Regular.ttf" "NotoSerif.ttf"))
+24
(copy-file (profile-face (cdr entry)) (path inventory (car entry)))))
+25
(each name '("JetBrainsMono-Regular.ttf" "JetBrainsMono-Bold.ttf" "NotoSans.ttf" "NotoSerif.ttf")
+26
(unless (file? (path inventory name)) (error "Missing owned test face" name)))
+27
(define context-cache (or (getenv "SIGIL_FONTCONFIG_TEST_CACHE") (path work "context-cache")))
+28
(define default-cache (path work "default-cache"))
+29
(define configuration (path work "fonts.conf"))
+30
(ensure-directory context-cache)
+31
(ensure-directory default-cache)
+32
(write-text configuration
+33
(str "<fontconfig><dir>" (xml inventory) "</dir><cachedir>"
+34
(xml default-cache) "</cachedir></fontconfig>"))
+35
(setenv! "SIGIL_FONTCONFIG_TEST_DIRECTORY" inventory)
+36
(setenv! "SIGIL_FONTCONFIG_TEST_CACHE" context-cache)
+37
(setenv! "FONTCONFIG_FILE" configuration)
+38
(setenv! "FONTCONFIG_PATH" work)
+39
(setenv! "FONTCONFIG_SYSROOT" #f)
+40
(setenv! "XDG_CACHE_HOME" default-cache)
+41
(when profile (setenv! "LD_LIBRARY_PATH" (path profile "lib")))
+42
(println "Fontconfig CI: fresh-process isolation first")
+43
($ sigil test test/test-00-isolation.sgl cwd: ,root timeout: 900)
+44
(println "Fontconfig CI: legacy and owned-context suites")
+45
($ sigil test test/test-fontconfig.sgl test/test-context.sgl cwd: ,root timeout: 900))
sigil.lockadded
@@ -0,0 +1,73 @@
+1
;; Auto-generated by sigil deps install. Do not edit.
+2
(lock
+3
(package name: "sigil/sigil-lib"
+4
source: pkg
+5
integrity: "sha256:77dda5bb21f033675e3109b04de00a9c5bc766ddd8f169f3a6e92a699381daae"
+6
version: "0.24.5"
+7
dependencies: ())
+8
(package name: "sigil/sigil-stdlib"
+9
source: pkg
+10
integrity: "sha256:5a6afce5dcd9f045dd59fc3e79afdc83da4dcac9579778b73297fa7c5691519e"
+11
version: "0.24.5"
+12
dependencies: ())
+13
(package name: "sigil/sigil-ffi"
+14
source: pkg
+15
integrity: "sha256:eb28deece197b5ac0f8321c25e2d438180f1a97dc13bbc641a13491221dc2447"
+16
version: "0.16.4"
+17
dependencies: ())
+18
(package name: "sigil/sigil-test"
+19
source: pkg
+20
integrity: "sha256:9ec38070d55089546a63b1523a81cd0d8870b9125157399fe32741e543a9cab4"
+21
version: "0.24.5"
+22
dependencies: ())
+23
(package name: "sigil/sigil-test-runner"
+24
source: pkg
+25
integrity: "sha256:4f7f6d96cb49ac097196433db841aef3c70a39370fe07d9d33ebb19bf66b4392"
+26
version: "0.24.5"
+27
dependencies: ((from-pkg name: "sigil/sigil-test" version: "=0.24.5") (from-pkg name: "sigil/sigil-package" version: "=0.24.5") (from-pkg name: "sigil/sigil-build" version: "=0.24.5") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.5") (from-pkg name: "sigil/sigil-json" version: "^0.16.0")))
+28
(package name: "sigil/sigil-package"
+29
source: pkg
+30
integrity: "sha256:e7a7207b0e92a8dce3993e60b43178b7dbb68c42b426393c74a567ff074aebb0"
+31
version: "0.24.5"
+32
dependencies: ())
+33
(package name: "sigil/sigil-build"
+34
source: pkg
+35
integrity: "sha256:651c03091da73fa4e7c441f26b1ef9e89f5cb6e42a28237dd51de570c1ec9b85"
+36
version: "0.24.5"
+37
dependencies: ((from-pkg name: "sigil/sigil-shell" version: "=0.24.5") (from-pkg name: "sigil/sigil-json" version: "^0.16.0") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.5") (from-pkg name: "sigil/sigil-store" version: "=0.24.5") (from-pkg name: "sigil/sigil-package" version: "=0.24.5") (from-pkg name: "sigil/sigil-deps" version: "=0.24.5")))
+38
(package name: "sigil/sigil-json"
+39
source: pkg
+40
integrity: "sha256:5e04c7409a0009bfd0d2be31b2ecb5c61b1536aca92b03fb17044213deb52692"
+41
version: "0.16.2"
+42
dependencies: ())
+43
(package name: "sigil/sigil-shell"
+44
source: pkg
+45
integrity: "sha256:7c96207ce868722f7bdbfca5374cbe4b793584e3e30ba8fcbe247c792fb3ae22"
+46
version: "0.24.5"
+47
dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.5") (from-pkg name: "sigil/sigil-json" version: "^0.16.0")))
+48
(package name: "sigil/sigil-store"
+49
source: pkg
+50
integrity: "sha256:ddaf5a84dfd6414a0492d24af8ba98a843e16c3791e5beff1d6af484e1a8b9ae"
+51
version: "0.24.5"
+52
dependencies: ((from-pkg name: "sigil/sigil-shell" version: "=0.24.5") (from-pkg name: "sigil/sigil-crypto" version: "^0.19.1") (from-pkg name: "sigil/sigil-sqlite" version: "^0.16.0")))
+53
(package name: "sigil/sigil-deps"
+54
source: pkg
+55
integrity: "sha256:ec668f0d12cd4e22ea17d90c94aa151ac985add294aa706fd8c7fb7eafe53729"
+56
version: "0.24.5"
+57
dependencies: ((from-pkg name: "sigil/sigil-git" version: "=0.24.5") (from-pkg name: "sigil/sigil-stdlib" version: "=0.24.5") (from-pkg name: "sigil/sigil-package" version: "=0.24.5")))
+58
(package name: "sigil/sigil-crypto"
+59
source: pkg
+60
integrity: "sha256:fc2620e9ce36aa121173628a059a3a4fd1be57f4d18286628590f8e3c549ef56"
+61
version: "0.19.2"
+62
dependencies: ((from-pkg name: "sigil/sigil-lib" version: ">=0.24")))
+63
(package name: "sigil/sigil-sqlite"
+64
source: pkg
+65
integrity: "sha256:ae319b42069c3e00408f03923b0eacbef58369b2e6e76dfb24b0b833d39ff618"
+66
version: "0.16.4"
+67
dependencies: ())
+68
(package name: "sigil/sigil-git"
+69
source: pkg
+70
integrity: "sha256:f3be509b189a52e7dc83be7c70539aba2a52410d90f48053914d2aea58467a04"
+71
version: "0.24.5"
+72
dependencies: ((from-pkg name: "sigil/sigil-stdlib" version: "=0.24.5")))
+73
)
src/sigil/fontconfig.sglmodified
@@ -2,53 +2,107 @@
2
;;; native patterns and font sets are released before a call returns.
3
(define-library (sigil fontconfig)
4
(import (sigil ffi)
+5
(only (sigil process) getenv)
+6
(only (sigil string) string-split string-ci=?)
7
(sigil struct))
8
(export fc-pattern fc-pattern? fc-pattern-family fc-pattern-style fc-pattern-size
9
fc-font-match fc-font-list
+10
make-fc-context fc-context? fc-context-closed? fc-context-close!
+11
fc-context-match fc-context-list fc-context-sort
12
fc-font? fc-font-file fc-font-index fc-font-family fc-font-style)
13
(begin
14
(define-struct fc-pattern
15
(family default: #f) (style default: #f) (size default: #f))
16
(define-struct fc-font (file) (index) (family) (style))
+17
(define-struct fc-context (handle mutable: #t) (max-fonts))
18
−14
(define library (c-library "libfontconfig"))
−15
(define init (c-function library "FcInit" '() ffi/int))
+19
;; Static compilation tools may import layouts without a dynamic loader.
+20
;; Preserve the load failure and report it only on a native operation.
+21
(define library-failure #f)
+22
(define library
+23
(guard (failure (#t (set! library-failure failure) #f))
+24
(c-library "libfontconfig")))
+25
(define (native-function name arguments result)
+26
(if library
+27
(c-function library name arguments result)
+28
(lambda ignored
+29
(error (string-append "Fontconfig is unavailable: " (exception-message library-failure))
+30
name library-failure))))
+31
(define init (native-function "FcInit" '() ffi/int))
+32
(define config-create (native-function "FcConfigCreate" '() ffi/pointer))
+33
(define config-destroy
+34
(native-function "FcConfigDestroy" (list ffi/pointer) ffi/void))
+35
(define config-destroy-pointer (and library (c-symbol library "FcConfigDestroy")))
+36
(define config-set-sysroot
+37
(native-function "FcConfigSetSysRoot" (list ffi/pointer ffi/pointer) ffi/void))
+38
(define config-set-rescan
+39
(native-function "FcConfigSetRescanInterval" (list ffi/pointer ffi/int) ffi/int))
+40
(define config-parse-memory
+41
(native-function "FcConfigParseAndLoadFromMemory"
+42
(list ffi/pointer ffi/string ffi/int) ffi/int))
+43
(define config-get-fonts
+44
(native-function "FcConfigGetFonts" (list ffi/pointer ffi/int) ffi/pointer))
+45
(define config-build-fonts
+46
(native-function "FcConfigBuildFonts" (list ffi/pointer) ffi/int))
+47
(define config-add-file
+48
(native-function "FcConfigAppFontAddFile" (list ffi/pointer ffi/string) ffi/int))
+49
(define config-add-directory
+50
(native-function "FcConfigAppFontAddDir" (list ffi/pointer ffi/string) ffi/int))
51
(define pattern-create
−17
(c-function library "FcPatternCreate" '() ffi/pointer))
+52
(native-function "FcPatternCreate" '() ffi/pointer))
53
(define pattern-destroy
−19
(c-function library "FcPatternDestroy" (list ffi/pointer) ffi/void))
+54
(native-function "FcPatternDestroy" (list ffi/pointer) ffi/void))
55
(define pattern-add-string
−21
(c-function library "FcPatternAddString"
+56
(native-function "FcPatternAddString"
57
(list ffi/pointer ffi/string ffi/string) ffi/int))
+58
;; FcValue's union holds a pointer, double or integer. Integer storage
+59
;; preserves the union's size/alignment and its integer ABI classification.
+60
(define value-layout (c-struct-layout type: ffi/int value: ffi/uint64))
+61
(define pattern-add-weak
+62
(native-function "FcPatternAddWeak"
+63
(list ffi/pointer ffi/string value-layout ffi/int) ffi/int))
64
(define pattern-add-double
−24
(c-function library "FcPatternAddDouble"
+65
(native-function "FcPatternAddDouble"
66
(list ffi/pointer ffi/string ffi/double) ffi/int))
+67
(define pattern-add-integer
+68
(native-function "FcPatternAddInteger"
+69
(list ffi/pointer ffi/string ffi/int) ffi/int))
+70
(define pattern-add-bool
+71
(native-function "FcPatternAddBool"
+72
(list ffi/pointer ffi/string ffi/int) ffi/int))
+73
(define normalize-language
+74
(native-function "FcLangNormalize" (list ffi/string) ffi/pointer))
+75
(define free-string
+76
(native-function "FcStrFree" (list ffi/pointer) ffi/void))
77
(define config-substitute
−27
(c-function library "FcConfigSubstitute"
+78
(native-function "FcConfigSubstitute"
79
(list ffi/pointer ffi/pointer ffi/int) ffi/int))
80
(define default-substitute
−30
(c-function library "FcDefaultSubstitute" (list ffi/pointer) ffi/void))
+81
(native-function "FcDefaultSubstitute" (list ffi/pointer) ffi/void))
82
(define font-match
−32
(c-function library "FcFontMatch"
+83
(native-function "FcFontMatch"
84
(list ffi/pointer ffi/pointer ffi/pointer) ffi/pointer))
+85
(define font-sort
+86
(native-function "FcFontSort"
+87
(list ffi/pointer ffi/pointer ffi/int ffi/pointer ffi/pointer) ffi/pointer))
88
(define pattern-get-string
−35
(c-function library "FcPatternGetString"
+89
(native-function "FcPatternGetString"
90
(list ffi/pointer ffi/string ffi/int ffi/pointer) ffi/int))
91
(define pattern-get-integer
−38
(c-function library "FcPatternGetInteger"
+92
(native-function "FcPatternGetInteger"
93
(list ffi/pointer ffi/string ffi/int ffi/pointer) ffi/int))
94
(define object-set-create
−41
(c-function library "FcObjectSetCreate" '() ffi/pointer))
+95
(native-function "FcObjectSetCreate" '() ffi/pointer))
96
(define object-set-add
−43
(c-function library "FcObjectSetAdd"
+97
(native-function "FcObjectSetAdd"
98
(list ffi/pointer ffi/string) ffi/int))
99
(define object-set-destroy
−46
(c-function library "FcObjectSetDestroy" (list ffi/pointer) ffi/void))
+100
(native-function "FcObjectSetDestroy" (list ffi/pointer) ffi/void))
101
(define font-list
−48
(c-function library "FcFontList"
+102
(native-function "FcFontList"
103
(list ffi/pointer ffi/pointer ffi/pointer) ffi/pointer))
104
(define font-set-destroy
−51
(c-function library "FcFontSetDestroy" (list ffi/pointer) ffi/void))
+105
(native-function "FcFontSetDestroy" (list ffi/pointer) ffi/void))
106
(define font-set-layout
107
(c-struct-layout count: ffi/int capacity: ffi/int fonts: ffi/pointer))
108
@@ -69,6 +123,112 @@
123
(and (not (= (char->integer (string-ref value i)) 0))
124
(loop (+ i 1))))))))
125
+126
;;; An immutable font inventory in an owned, initially empty FcConfig.
+127
;;; No system config is loaded and the process default is never replaced.
+128
;;; Only explicit files/directories are scanned. No implicit config,
+129
;;; system root, rescan or cache directory is inherited from the process.
+130
;;; Directory scanning requires an explicit private cache location.
+131
(define (make-fc-context
+132
(keys: (files '()) (directories '()) (cache-directory #f) (max-fonts 4096)))
+133
(define (valid-paths? paths)
+134
(and (list? paths)
+135
(let visit ((rest paths))
+136
(or (null? rest)
+137
(and (string? (car rest)) (valid-name? (car rest))
+138
(visit (cdr rest)))))))
+139
(unless (and (valid-paths? files) (valid-paths? directories))
+140
(error "files and directories must be lists of nonempty paths without NUL"))
+141
(unless (and (exact-integer? max-fonts) (< 0 max-fonts 1000000))
+142
(error "max-fonts must be a positive exact integer below 1000000"))
+143
(unless (or (not cache-directory)
+144
(and (string? cache-directory) (valid-name? cache-directory)
+145
(char=? (string-ref cache-directory 0) #\/)))
+146
(error "cache-directory must be an absolute path without NUL, or #f"))
+147
(when (and (pair? directories) (not cache-directory))
+148
(error "Directory inventories require an explicit private cache-directory"))
+149
(let ((native (config-create)))
+150
(check-native native "FcConfigCreate")
+151
(set-pointer-finalizer! native config-destroy-pointer)
+152
(let ((context (fc-context handle: native max-fonts: max-fonts)))
+153
(guard (failure (#t (fc-context-close! context) (raise failure)))
+154
;; FcConfigCreate reads FONTCONFIG_SYSROOT. Clear that value on
+155
;; this explicit config, without changing the process environment.
+156
(config-set-sysroot native #f)
+157
(check-native (config-set-rescan native 0) "FcConfigSetRescanInterval")
+158
(when cache-directory
+159
(let ((escaped
+160
(apply string-append
+161
(map (lambda (character)
+162
(case character
+163
((#\&) "&amp;") ((#\<) "&lt;") ((#\>) "&gt;")
+164
(else (string character))))
+165
(string->list cache-directory)))))
+166
(check-native
+167
(config-parse-memory native
+168
(string-append "<fontconfig><cachedir>" escaped "</cachedir></fontconfig>") 1)
+169
"FcConfigParseAndLoadFromMemory")))
+170
(check-native (config-build-fonts native) "FcConfigBuildFonts")
+171
(for-each (lambda (directory)
+172
(check-native (config-add-directory native directory) "FcConfigAppFontAddDir")
+173
(check-font-count (config-get-fonts native 1) max-fonts)) directories)
+174
(for-each (lambda (file)
+175
(check-native (config-add-file native file) "FcConfigAppFontAddFile")
+176
(check-font-count (config-get-fonts native 1) max-fonts)) files)
+177
context))))
+178
+179
(define (fc-context-closed? context)
+180
(unless (fc-context? context) (error "expected an fc-context" context))
+181
(not (fc-context-handle context)))
+182
+183
;;; Safe to close repeatedly. The pointer finalizer covers abandoned
+184
;;; contexts; explicit close clears it before releasing the same handle.
+185
(define (fc-context-close! context)
+186
(unless (fc-context? context) (error "expected an fc-context" context))
+187
(let ((native (fc-context-handle context)))
+188
(when native
+189
(set-fc-context-handle! context #f)
+190
(set-pointer-finalizer! native #f)
+191
(config-destroy native))))
+192
+193
(define (context-native context)
+194
(when (fc-context-closed? context) (error "font context is closed"))
+195
(fc-context-handle context))
+196
+197
(define (fc-context-match context specification)
+198
(match-in-context (context-native context) specification))
+199
+200
(define (fc-context-list context . options)
+201
(when (> (length options) 1) (error "fc-context-list takes at most one pattern"))
+202
(list-in-context (context-native context)
+203
(if (pair? options) (car options) (fc-pattern))
+204
(fc-context-max-fonts context)))
+205
+206
;;; Ordered fallback candidates. All returned records are owned copies;
+207
;;; neither the shared native patterns nor their charset are retained.
+208
(define (fc-context-sort context specification (keys: (trim? #t)))
+209
(unless (boolean? trim?) (error "trim? must be a boolean"))
+210
(let ((native (context-native context)))
+211
(with-pattern native specification
+212
(lambda (pattern)
+213
(check-native (config-substitute native pattern 0) "FcConfigSubstitute")
+214
(context-defaults pattern specification)
+215
(let ((result (c-alloc (c-sizeof ffi/int))) (fonts #f))
+216
(dynamic-wind (lambda () #t)
+217
(lambda ()
+218
(set! fonts (font-sort native pattern (if trim? 1 0) #f result))
+219
(cond
+220
(fonts
+221
(unless (or (= (pointer-ref result ffi/int 0) 0)
+222
(and (= (pointer-ref result ffi/int 0) 1)
+223
(= 0 (check-font-count fonts (fc-context-max-fonts context)))))
+224
(error "FcFontSort returned a failed result"))
+225
(copy-font-set fonts (fc-context-max-fonts context)))
+226
((= (pointer-ref result ffi/int 0) 1) '())
+227
(else (error "FcFontSort failed"))))
+228
(lambda ()
+229
(when fonts (font-set-destroy fonts))
+230
(c-free result))))))))
+231
232
(define (validate specification)
233
(unless (fc-pattern? specification)
234
(error "expected an fc-pattern" specification))
@@ -79,9 +239,58 @@
239
(unless (or (not size) (and (real? size) (> size 0) (< size 1000000)))
240
(error "font point size must be positive and finite, or #f" size))))
241
−82
(define (with-pattern specification body)
+242
;; The context has no substitution rules beyond its private cache path.
+243
;; Apply public matching defaults directly: FcDefaultSubstitute on 2.17+
+244
;; references the process default config even when every field is present.
+245
(define (context-defaults pattern specification)
+246
(for-each (lambda (entry)
+247
(check-native (pattern-add-integer pattern (car entry) (cdr entry))
+248
"FcPatternAddInteger"))
+249
'(("weight" . 80) ("slant" . 0) ("width" . 100)
+250
("fontversion" . 2147483647) ("hintstyle" . 3) ("order" . 0)))
+251
(for-each (lambda (entry)
+252
(check-native (pattern-add-bool pattern (car entry) (cdr entry))
+253
"FcPatternAddBool"))
+254
'(("hinting" . 1) ("verticallayout" . 0) ("autohint" . 0)
+255
("globaladvance" . 1) ("embeddedbitmap" . 1) ("decorative" . 0)
+256
("symbol" . 0) ("variable" . 0)))
+257
(let ((size (or (fc-pattern-size specification) 12)))
+258
(unless (fc-pattern-size specification)
+259
(check-native (pattern-add-double pattern "size" size) "FcPatternAddDouble"))
+260
(for-each (lambda (entry)
+261
(check-native (pattern-add-double pattern (car entry) (cdr entry))
+262
"FcPatternAddDouble"))
+263
(list (cons "scale" 1) (cons "dpi" 75) (cons "pixelsize" (* size (/ 75 72))))))
+264
;; Normalize locale text without consulting a default FcConfig.
+265
(let* ((available
+266
(lambda (name)
+267
(let ((value (getenv name)))
+268
(and value (> (string-length value) 0) value))))
+269
(locale (or (available "FC_LANG") (available "LC_ALL")
+270
(let ((ctype (available "LC_CTYPE")))
+271
(and ctype (not (string-ci=? ctype "UTF-8")) ctype))
+272
(available "LANG") "en"))
+273
(normalized (normalize-language (car (string-split locale ":")))))
+274
(dynamic-wind (lambda () #t)
+275
(lambda ()
+276
(let ((language (if normalized (pointer->string normalized) "en")))
+277
(for-each (lambda (name)
+278
(check-native (pattern-add-string pattern name language) "FcPatternAddString"))
+279
'("namelang" "familylang" "stylelang" "fullnamelang"))
+280
(let ((fallback (string->pointer "en-us")))
+281
(dynamic-wind (lambda () #t)
+282
(lambda ()
+283
(for-each (lambda (name)
+284
(check-native (pattern-add-weak pattern name
+285
(dict type: 3 value: (pointer-address fallback)) 1)
+286
"FcPatternAddWeak"))
+287
'("familylang" "stylelang" "fullnamelang")))
+288
(lambda () (c-free fallback))))))
+289
(lambda () (when normalized (free-string normalized))))))
+290
+291
(define (with-pattern native specification body)
292
(validate specification)
−84
(unless initialized?
+293
(unless (or native initialized?)
294
(check-native (init) "FcInit")
295
(set! initialized? #t))
296
(let ((pattern (pattern-create)))
@@ -134,16 +343,19 @@
343
;; family may resolve to a fallback; inspect fc-font-family if needed.
344
;; Returns #f if Fontconfig reports no matching font.
345
(define (fc-font-match specification)
−137
(with-pattern specification
+346
(match-in-context #f specification))
+347
+348
(define (match-in-context native specification)
+349
(with-pattern native specification
350
(lambda (pattern)
−139
(check-native (config-substitute #f pattern 0) "FcConfigSubstitute")
−140
(default-substitute pattern)
+351
(check-native (config-substitute native pattern 0) "FcConfigSubstitute")
+352
(if native (context-defaults pattern specification) (default-substitute pattern))
353
(let ((result (c-alloc (c-sizeof ffi/int)))
354
(matched #f))
355
(dynamic-wind
356
(lambda () #t)
357
(lambda ()
−146
(set! matched (font-match #f pattern result))
+358
(set! matched (font-match native pattern result))
359
(and matched
360
(begin
361
(unless (= (pointer-ref result ffi/int 0) 0)
@@ -157,7 +369,27 @@
369
;; all installed fonts; a pattern limits family/style/size properties.
370
(define (fc-font-list . options)
371
(when (> (length options) 1) (error "fc-font-list takes at most one pattern"))
−160
(with-pattern (if (pair? options) (car options) (fc-pattern))
+372
(list-in-context #f (if (pair? options) (car options) (fc-pattern))))
+373
+374
(define (check-font-count fonts limit)
+375
(let ((count (if fonts (c-struct-ref fonts font-set-layout count:) 0)))
+376
(unless (and (exact-integer? count) (<= 0 count limit))
+377
(error "Font inventory exceeds its copy limit" count limit))
+378
count))
+379
+380
(define (copy-font-set fonts limit)
+381
(let ((count (check-font-count fonts limit))
+382
(items (and fonts (c-struct-ref fonts font-set-layout fonts:))))
+383
(when (and (> count 0) (not items)) (error "Font set contains no item array"))
+384
(let loop ((i 0) (copied '()))
+385
(if (= i count) (reverse copied)
+386
(loop (+ i 1)
+387
(cons (copy-font (pointer-ref items ffi/pointer (* i (c-sizeof ffi/pointer))))
+388
copied))))))
+389
+390
(define (list-in-context native specification . options)
+391
(define limit (if (pair? options) (car options) 65536))
+392
(with-pattern native specification
393
(lambda (pattern)
394
(let ((objects (object-set-create))
395
(fonts #f))
@@ -169,18 +401,9 @@
401
(lambda (name)
402
(check-native (object-set-add objects name) "FcObjectSetAdd"))
403
'("file" "index" "family" "style"))
−172
(set! fonts (font-list #f pattern objects))
+404
(set! fonts (font-list native pattern objects))
405
(check-native fonts "FcFontList")
−174
(let ((count (c-struct-ref fonts font-set-layout count:))
−175
(items (c-struct-ref fonts font-set-layout fonts:)))
−176
(let loop ((i 0) (copied '()))
−177
(if (= i count)
−178
(reverse copied)
−179
(loop (+ i 1)
−180
(cons (copy-font
−181
(pointer-ref items ffi/pointer
−182
(* i (c-sizeof ffi/pointer))))
−183
copied))))))
+406
(copy-font-set fonts limit))
407
(lambda ()
408
(when fonts (font-set-destroy fonts))
409
(object-set-destroy objects)))))))))
test/test-00-isolation.sgladded
@@ -0,0 +1,53 @@
+1
;;; Run this file alone in a fresh native process before either legacy suite.
+2
(import (sigil test) (sigil fontconfig) (sigil ffi) (sigil fs) (sigil string)
+3
(sigil process) (sigil path))
+4
+5
(define inventory
+6
(or (getenv "SIGIL_FONTCONFIG_TEST_DIRECTORY") (error "Select the owned font inventory")))
+7
(test "fresh isolated queries never initialize the process default config"
+8
(define work (or (make-temp-directory) (error "Cannot create the sentinel fixture")))
+9
(define sentinel-cache (path-join work "default-cache"))
+10
(define sentinel-file (path-join work "sentinel-default-config.conf"))
+11
(define (xml text)
+12
(string-replace (string-replace (string-replace text "&" "&amp;") "<" "&lt;") ">" "&gt;"))
+13
(ensure-directory sentinel-cache)
+14
(write-file-string sentinel-file
+15
(string-append "<fontconfig><dir>" (xml inventory) "</dir><cachedir>"
+16
(xml sentinel-cache) "</cachedir></fontconfig>"))
+17
(define previous
+18
(map (lambda (name) (cons name (getenv name)))
+19
'("FONTCONFIG_FILE" "FONTCONFIG_PATH" "XDG_CACHE_HOME")))
+20
(assert-equal '() (directory-list sentinel-cache))
+21
(dynamic-wind
+22
(lambda ()
+23
(setenv! "FONTCONFIG_FILE" sentinel-file)
+24
(setenv! "FONTCONFIG_PATH" (path-dirname sentinel-file))
+25
(setenv! "XDG_CACHE_HOME" sentinel-cache))
+26
(lambda ()
+27
;; FcGetVersion reports the loaded library without touching FcConfig.
+28
(let* ((library (c-library "libfontconfig"))
+29
(version (c-function library "FcGetVersion" '() ffi/int)))
+30
(display "ISOLATION_FONTCONFIG_VERSION=") (display (version)) (newline))
+31
(let ((context
+32
(make-fc-context files:
+33
(list (path-join inventory "JetBrainsMono-Regular.ttf")
+34
(path-join inventory "JetBrainsMono-Bold.ttf")))))
+35
(dynamic-wind (lambda () #f)
+36
(lambda ()
+37
(assert-equal "Regular" (fc-font-style
+38
(fc-context-match context (fc-pattern family: "JetBrains Mono"))))
+39
(assert-equal "Bold" (fc-font-style
+40
(fc-context-match context (fc-pattern family: "JetBrains Mono" style: "Bold" size: 16))))
+41
(assert-true (pair? (fc-context-sort context (fc-pattern family: "JetBrains Mono"))))
+42
(assert-equal 2 (length (fc-context-list context))))
+43
(lambda () (fc-context-close! context))))
+44
(assert-equal '() (directory-list sentinel-cache))
+45
;; This must initialize the sentinel default now. If another test already
+46
;; initialized it, the new cache stays empty and this test must fail.
+47
(display "ISOLATION_DEFAULT_CONTROL_BEGIN\n")
+48
(let* ((library (c-library "libfontconfig"))
+49
(current (c-function library "FcConfigGetCurrent" '() ffi/pointer)))
+50
(assert-true (pointer? (current))))
+51
(assert-true (pair? (directory-list sentinel-cache))))
+52
(lambda ()
+53
(for-each (lambda (entry) (setenv! (car entry) (cdr entry))) previous))))
test/test-context.sgladded
@@ -0,0 +1,144 @@
+1
(import (sigil test) (sigil fs) (sigil process) (sigil list) (sigil path) (sigil ffi)
+2
(sigil fontconfig))
+3
+4
(define inventory
+5
(or (getenv "SIGIL_FONTCONFIG_TEST_DIRECTORY")
+6
(error "Select the owned font inventory")))
+7
(define regular (path-join inventory "JetBrainsMono-Regular.ttf"))
+8
(define bold (path-join inventory "JetBrainsMono-Bold.ttf"))
+9
(define sans (path-join inventory "NotoSans.ttf"))
+10
(define serif (path-join inventory "NotoSerif.ttf"))
+11
(define context-cache
+12
(or (getenv "SIGIL_FONTCONFIG_TEST_CACHE") (error "Select an owned context cache")))
+13
(define regular-pattern (fc-pattern family: "JetBrains Mono" style: "Regular"))
+14
(define test-library (c-library "libfontconfig"))
+15
(define current-config
+16
(c-function test-library "FcConfigGetCurrent" '() ffi/pointer))
+17
+18
(define (with-context files body)
+19
(let ((context (make-fc-context files: files)))
+20
(dynamic-wind (lambda () #f)
+21
(lambda () (body context))
+22
(lambda () (fc-context-close! context)))))
+23
+24
(test-group "isolated fontconfig"
+25
(test "an empty context never borrows the process font inventory"
+26
(with-context '()
+27
(lambda (context)
+28
(assert-equal '() (fc-context-list context))
+29
(assert-false (fc-context-match context regular-pattern))
+30
(assert-equal '() (fc-context-sort context regular-pattern)))))
+31
+32
(test "explicit files select Regular and Bold within their own inventory"
+33
(with-context (list regular bold)
+34
(lambda (context)
+35
(assert-equal 2 (length (fc-context-list context)))
+36
(assert-equal regular (fc-font-file (fc-context-match context regular-pattern)))
+37
(assert-equal bold
+38
(fc-font-file (fc-context-match context
+39
(fc-pattern family: "JetBrains Mono" style: "Bold")))))))
+40
+41
(test "an explicit directory supplies copied ordered fallback candidates"
+42
(let ((context (make-fc-context directories: (list inventory) cache-directory: context-cache)))
+43
(dynamic-wind (lambda () #f)
+44
(lambda ()
+45
(let ((fonts (fc-context-sort context regular-pattern trim?: #f)))
+46
;; Variable fonts can expose several named instances per file.
+47
(assert-true (>= (length fonts) 4))
+48
(for-each
+49
(lambda (file) (assert-true (member file (map fc-font-file fonts))))
+50
(list regular bold sans serif))
+51
(assert-equal regular (fc-font-file (car fonts)))
+52
(assert-true (member sans (map fc-font-file fonts)))
+53
(assert-true (member serif (map fc-font-file fonts)))
+54
(for-each
+55
(lambda (font)
+56
(assert-true (file-exists? (fc-font-file font)))
+57
(assert-true (member (fc-font-file font) (list regular bold sans serif)))
+58
(assert-true (exact-integer? (fc-font-index font))))
+59
fonts)))
+60
(lambda () (fc-context-close! context)))))
+61
+62
(test "coverage trimming retains the primary and adds only useful candidates"
+63
(let ((context (make-fc-context directories: (list inventory) cache-directory: context-cache)))
+64
(dynamic-wind (lambda () #f)
+65
(lambda ()
+66
(let ((all (fc-context-sort context regular-pattern trim?: #f))
+67
(trimmed (fc-context-sort context regular-pattern)))
+68
(assert-equal regular (fc-font-file (car trimmed)))
+69
(assert-true (<= 1 (length trimmed) (length all)))
+70
(for-each
+71
(lambda (font) (assert-true (member (fc-font-file font) (map fc-font-file all))))
+72
trimmed)))
+73
(lambda () (fc-context-close! context)))))
+74
+75
(test "independent contexts do not replace the initialized process default"
+76
(let* ((before (fc-font-file (fc-font-match regular-pattern)))
+77
(names '("FONTCONFIG_FILE" "FONTCONFIG_PATH" "FONTCONFIG_SYSROOT" "XDG_CACHE_HOME"))
+78
(environment (map getenv names)))
+79
(with-context (list sans)
+80
(lambda (context)
+81
(assert-equal sans (fc-font-file (fc-context-match context regular-pattern)))
+82
(with-context (list regular)
+83
(lambda (other)
+84
(assert-equal regular (fc-font-file (fc-context-match other regular-pattern)))))
+85
(assert-equal sans (fc-font-file (fc-context-match context regular-pattern)))))
+86
(assert-equal before (fc-font-file (fc-font-match regular-pattern)))
+87
(assert-equal environment (map getenv names))))
+88
+89
(test "a process sysroot does not redirect explicit context inputs"
+90
(let ((previous (getenv "FONTCONFIG_SYSROOT")))
+91
(dynamic-wind
+92
(lambda () (setenv! "FONTCONFIG_SYSROOT" inventory))
+93
(lambda ()
+94
(with-context (list regular)
+95
(lambda (context)
+96
(assert-equal regular (fc-font-file (fc-context-match context regular-pattern)))
+97
(assert-equal inventory (getenv "FONTCONFIG_SYSROOT")))))
+98
(lambda () (setenv! "FONTCONFIG_SYSROOT" previous)))))
+99
+100
(test "copied sort and list results survive later calls and context close"
+101
(let* ((context (make-fc-context files: (list regular bold sans)))
+102
(sorted (fc-context-sort context regular-pattern trim?: #f))
+103
(listed (fc-context-list context)))
+104
(fc-context-match context (fc-pattern family: "Noto Sans"))
+105
(fc-context-close! context)
+106
(assert-equal regular (fc-font-file (car sorted)))
+107
(for-each
+108
(lambda (font) (assert-true (file-exists? (fc-font-file font))))
+109
(append sorted listed))))
+110
+111
(test "closing is idempotent and all subsequent context operations fail"
+112
(let ((context (make-fc-context files: (list regular))))
+113
(assert-false (fc-context-closed? context))
+114
(fc-context-close! context)
+115
(fc-context-close! context)
+116
(assert-true (fc-context-closed? context))
+117
(assert-error (fc-context-list context))
+118
(assert-error (fc-context-match context regular-pattern))
+119
(assert-error (fc-context-sort context regular-pattern))))
+120
+121
(test "inventory bounds and invalid inputs fail with owned cleanup"
+122
(assert-error (make-fc-context files: (list regular bold) max-fonts: 1))
+123
(assert-error (make-fc-context max-fonts: 0))
+124
(assert-error (make-fc-context max-fonts: 1.5))
+125
(assert-error (make-fc-context files: regular))
+126
(assert-error (make-fc-context directories: '(3)))
+127
(assert-error (make-fc-context directories: (list inventory)))
+128
(assert-error (make-fc-context cache-directory: "relative-cache"))
+129
(assert-error (make-fc-context files: (list "")))
+130
(assert-error (make-fc-context files: (list (string #\A (integer->char 0)))))
+131
(assert-error (make-fc-context files: (list (path-join inventory "missing.ttf"))))
+132
(with-context (list regular)
+133
(lambda (context)
+134
(assert-error (fc-context-sort context "sans"))
+135
(assert-error (fc-context-sort context regular-pattern trim?: 1))
+136
(assert-error (fc-context-list context (fc-pattern) (fc-pattern))))))
+137
+138
(test "context creation and destruction preserve the actual default config pointer"
+139
(let ((before (pointer-address (current-config))))
+140
(with-context (list sans serif)
+141
(lambda (context)
+142
(fc-context-sort context (fc-pattern family: "Noto Sans"))
+143
(assert-equal before (pointer-address (current-config)))))
+144
(assert-equal before (pointer-address (current-config))))))