Coverage for gws-app/gws/lib/font/__init__.py: 100%
16 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-05 13:35 +0200
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-05 13:35 +0200
1"""Fonts for server-side rendering.
3This package installs custom fonts on the server and loads fonts for drawing.
4Fonts are configured in the ``fonts`` option of the application. On configuration,
5all files from the given directory are copied to the system font directory
6``/usr/local/share/fonts`` and the font cache is rebuilt with ``fc-cache``.
7Installed fonts can then be loaded by name with ``from_name``, for example, to draw SVG labels.
9Example::
11 fonts {
12 dir "/data/fonts"
13 }
14"""
16import PIL.ImageFont
18import gws
19import gws.lib.osx
22class Config(gws.Config):
23 """Custom fonts, installed on the server for rendering."""
25 dir: gws.DirPath
26 """Directory with font files to install."""
29def configure(cfg: Config):
30 """Install fonts according to the configuration.
32 Args:
33 cfg: Font configuration. If ``dir`` is not set, nothing is done.
34 """
35 if cfg.dir:
36 install_fonts(cfg.dir)
39def install_fonts(source_dir):
40 """Copy font files to the system font directory and rebuild the font cache.
42 Args:
43 source_dir: Directory with font files. Files in subdirectories are also copied.
44 """
45 target_dir = '/usr/local/share/fonts'
46 gws.lib.osx.run(['mkdir', '-p', target_dir], echo=True)
47 for p in gws.lib.osx.find_files(source_dir):
48 gws.lib.osx.run(['cp', '-v', p, target_dir], echo=True)
50 gws.lib.osx.run(['fc-cache', '-fv'], echo=True)
53def from_name(name: str, size: int):
54 """Load a TrueType or OpenType font.
56 Args:
57 name: Font file name or path, as understood by ``PIL.ImageFont.truetype``.
58 size: Font size in points.
60 Returns:
61 A ``PIL.ImageFont.FreeTypeFont`` object.
62 """
63 return PIL.ImageFont.truetype(font=name, size=size)