Skip to content

data

chromatic.data

VGA437 = userfonts[_ROOT_FONT_KEY] module-attribute

userfonts = mappingproxy(_userfonts) module-attribute

DEFAULT_FONT module-attribute

UserFont dataclass

Source code in chromatic/data/userfont.py
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
@dataclass(frozen=True, slots=True, repr=False)
class UserFont:
    font: str
    size: int = field(default=24, kw_only=True)
    index: int = field(default=0, kw_only=True)
    encoding: str = field(default="", kw_only=True)
    is_default: bool = field(default=False, kw_only=True, compare=False)
    _base_dir: Path = field(init=False, compare=False)

    def __post_init__(self):
        font_path = Path(self.font)
        if not font_path.is_absolute():
            raise ValueError
        if not font_path.is_file():
            raise FileNotFoundError(f"{font_path}")
        object.__setattr__(self, "font", font_path.name)
        object.__setattr__(self, "_base_dir", font_path.parent)
        if self.is_default:
            global _DEFAULT_FONT
            _DEFAULT_FONT = self

    def __hash__(self):
        return hash((type(self), self.font, self.size, self.index, self.encoding))

    def __fspath__(self):
        return os.fspath(self._base_dir.joinpath(self.font).resolve(strict=True))

    def to_truetype(self):
        from PIL.ImageFont import truetype

        return truetype(self, self.size, self.index, self.encoding)

font instance-attribute

size = field(default=24, kw_only=True) class-attribute instance-attribute

index = field(default=0, kw_only=True) class-attribute instance-attribute

encoding = field(default='', kw_only=True) class-attribute instance-attribute

is_default = field(default=False, kw_only=True, compare=False) class-attribute instance-attribute

__post_init__()

Source code in chromatic/data/userfont.py
39
40
41
42
43
44
45
46
47
48
49
def __post_init__(self):
    font_path = Path(self.font)
    if not font_path.is_absolute():
        raise ValueError
    if not font_path.is_file():
        raise FileNotFoundError(f"{font_path}")
    object.__setattr__(self, "font", font_path.name)
    object.__setattr__(self, "_base_dir", font_path.parent)
    if self.is_default:
        global _DEFAULT_FONT
        _DEFAULT_FONT = self

__hash__()

Source code in chromatic/data/userfont.py
51
52
def __hash__(self):
    return hash((type(self), self.font, self.size, self.index, self.encoding))

__fspath__()

Source code in chromatic/data/userfont.py
54
55
def __fspath__(self):
    return os.fspath(self._base_dir.joinpath(self.font).resolve(strict=True))

to_truetype()

Source code in chromatic/data/userfont.py
57
58
59
60
def to_truetype(self):
    from PIL.ImageFont import truetype

    return truetype(self, self.size, self.index, self.encoding)

__init__(font, *, size=24, index=0, encoding='', is_default=False)

register_userfont(fp, font_dir=None, **kwargs)

Source code in chromatic/data/userfont.py
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
def register_userfont(
    fp: str | os.PathLike[str],
    font_dir: str | os.PathLike[str] | None = None,
    **kwargs: tp.Unpack[_RegisterUserfontKwargs],
):
    fp = Path(fp)
    if not fp.is_file():
        raise FileNotFoundError(f"{fp}")
    if fp.suffix.lower() not in _TRUETYPE_EXT:
        raise ValueError("not a truetype font file: %r" % str(fp))
    if font_dir is None:
        font_dir = _get_font_dir()
    else:
        font_dir = Path(font_dir)
    font_dir.mkdir(parents=True, exist_ok=True)
    if not font_dir.is_absolute():
        font_dir = Path(os.path.normpath(font_dir.absolute()))
    if font_dir.samefile(_ROOT_FONT_DIR):
        caller_file = Path(sys._getframe(1).f_code.co_filename)
        if not (caller_file.is_file() and caller_file.samefile(__file__)):
            import warnings

            warnings.warn(
                "you are writing to the root font directory. "
                "files added here will likely be deleted "
                "the next time you update this package.",
                UserWarning,
            )
    name = fp.stem
    metadata_fields = {"size": int, "index": int, "encoding": str, "is_default": bool}
    metadata = {}
    symlink = False
    typ_err_msg = (
        "expected {!r} to be {.__name__}, got type {.__class__.__name__!r} instead"
    ).format
    for k, v in kwargs.items():
        if k == "name":
            if not isinstance(v, str):
                err = typ_err_msg(k, str, v)
                raise TypeError(err)
            name = v
        elif k in metadata_fields:
            expected_t = metadata_fields[k]
            if not isinstance(v, expected_t):
                err = typ_err_msg(k, expected_t, v)
                raise TypeError(err)
            metadata[k] = v
        elif k == "symlink":
            symlink = bool(v)
        else:
            raise ValueError(f"unexpected keyword argument: {k!r}")
    if not fp.parent.samefile(font_dir):
        loc = font_dir / fp.name
        if symlink:
            loc.symlink_to(os.path.normpath(fp.absolute()))
        else:
            with fp.open("rb") as rf, loc.open("wb") as wf:
                chunksize = 0xFFFF + 1
                while chunk := rf.read(chunksize):
                    wf.write(chunk)
        fp = loc
    metadata["font"] = os.path.abspath(fp)
    _userfonts[name] = UserFont(**metadata)
    _dump_userfonts({name: metadata | {"font": fp.name}}, font_dir)

butterfly()

Source code in chromatic/data/__init__.py
16
17
def butterfly():
    return _load("butterfly.jpg")

escher()

Source code in chromatic/data/__init__.py
20
21
def escher():
    return _load("escher.png")

goblin_virus()

Source code in chromatic/data/__init__.py
24
25
def goblin_virus():
    return _load("goblin_virus.png")