|
| 1 | +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +""" |
| 6 | +`adafruit_bitmap_font.lvfontbin` |
| 7 | +==================================================== |
| 8 | +
|
| 9 | +Loads binary LVGL format fonts. |
| 10 | +
|
| 11 | +* Author(s): Scott Shawcroft |
| 12 | +
|
| 13 | +Implementation Notes |
| 14 | +-------------------- |
| 15 | +
|
| 16 | +**Hardware:** |
| 17 | +
|
| 18 | +**Software and Dependencies:** |
| 19 | +
|
| 20 | +* Adafruit CircuitPython firmware for the supported boards: |
| 21 | + https://github.com/adafruit/circuitpython/releases |
| 22 | +
|
| 23 | +""" |
| 24 | + |
| 25 | +import struct |
| 26 | + |
| 27 | +try: |
| 28 | + from io import FileIO |
| 29 | + from typing import Iterable, Union |
| 30 | +except ImportError: |
| 31 | + pass |
| 32 | + |
| 33 | +from fontio import Glyph |
| 34 | + |
| 35 | +from .glyph_cache import GlyphCache |
| 36 | + |
| 37 | + |
| 38 | +class LVGLFont(GlyphCache): |
| 39 | + """Loads glyphs from a LVGL binary font file in the given bitmap_class. |
| 40 | +
|
| 41 | + There is an in-browser converter here: https://lvgl.io/tools/fontconverter |
| 42 | +
|
| 43 | + The format is documented here: https://github.com/lvgl/lv_font_conv/tree/master/doc |
| 44 | +
|
| 45 | + """ |
| 46 | + |
| 47 | + def __init__(self, f: FileIO, bitmap_class=None): |
| 48 | + super().__init__() |
| 49 | + f.seek(0) |
| 50 | + self.file = f |
| 51 | + self.bitmap_class = bitmap_class |
| 52 | + # Initialize default values for bounding box |
| 53 | + self._width = None |
| 54 | + self._height = None |
| 55 | + self._x_offset = 0 |
| 56 | + self._y_offset = 0 |
| 57 | + |
| 58 | + # For reading bits |
| 59 | + self._byte = 0 |
| 60 | + self._remaining_bits = 0 |
| 61 | + |
| 62 | + while True: |
| 63 | + buffer = f.read(4) |
| 64 | + if len(buffer) < 4: |
| 65 | + break |
| 66 | + section_size = struct.unpack("<I", buffer)[0] |
| 67 | + if section_size == 0: |
| 68 | + break |
| 69 | + table_marker = f.read(4) |
| 70 | + section_start = f.tell() |
| 71 | + remaining_section = f.read(section_size - 8) |
| 72 | + if table_marker == b"head": |
| 73 | + self._load_head(remaining_section) |
| 74 | + # Set bounding box based on font metrics from head section |
| 75 | + self._width = self._default_advance_width |
| 76 | + self._height = self._font_size |
| 77 | + self._x_offset = 0 |
| 78 | + self._y_offset = self._descent |
| 79 | + elif table_marker == b"cmap": |
| 80 | + self._load_cmap(remaining_section) |
| 81 | + elif table_marker == b"loca": |
| 82 | + self._max_cid = struct.unpack("<I", remaining_section[0:4])[0] |
| 83 | + self._loca_start = section_start + 4 |
| 84 | + elif table_marker == b"glyf": |
| 85 | + self._glyf_start = section_start - 8 |
| 86 | + |
| 87 | + def _load_head(self, data): |
| 88 | + self._version = struct.unpack("<I", data[0:4])[0] |
| 89 | + ( |
| 90 | + self._font_size, |
| 91 | + self._ascent, |
| 92 | + self._descent, |
| 93 | + self._typo_ascent, |
| 94 | + self._typo_descent, |
| 95 | + self._line_gap, |
| 96 | + self._min_y, |
| 97 | + self._max_y, |
| 98 | + self._default_advance_width, |
| 99 | + self._kerning_scale, |
| 100 | + ) = struct.unpack("<HHhHhHHHHH", data[6:26]) |
| 101 | + self._index_to_loc_format = data[26] |
| 102 | + self._glyph_id_format = data[27] |
| 103 | + self._advance_format = data[28] |
| 104 | + self._bits_per_pixel = data[29] |
| 105 | + self._glyph_bbox_xy_bits = data[30] |
| 106 | + self._glyph_bbox_wh_bits = data[31] |
| 107 | + self._glyph_advance_bits = data[32] |
| 108 | + self._glyph_header_bits = ( |
| 109 | + self._glyph_advance_bits + 2 * self._glyph_bbox_xy_bits + 2 * self._glyph_bbox_wh_bits |
| 110 | + ) |
| 111 | + self._glyph_header_bytes = (self._glyph_header_bits + 7) // 8 |
| 112 | + self._compression_alg = data[33] |
| 113 | + self._subpixel_rendering = data[34] |
| 114 | + |
| 115 | + def _load_cmap(self, data): |
| 116 | + data = memoryview(data) |
| 117 | + subtable_count = struct.unpack("<I", data[0:4])[0] |
| 118 | + self._cmap_tiny = [] |
| 119 | + for i in range(subtable_count): |
| 120 | + subtable_header = data[4 + 16 * i : 4 + 16 * (i + 1)] |
| 121 | + (_, range_start, range_length, glyph_offset, _) = struct.unpack( |
| 122 | + "<IIHHH", subtable_header[:14] |
| 123 | + ) |
| 124 | + format_type = subtable_header[14] |
| 125 | + |
| 126 | + if format_type != 2: |
| 127 | + raise RuntimeError(f"Unsupported cmap format {format_type}") |
| 128 | + |
| 129 | + self._cmap_tiny.append((range_start, range_start + range_length, glyph_offset)) |
| 130 | + |
| 131 | + @property |
| 132 | + def ascent(self) -> int: |
| 133 | + """The number of pixels above the baseline of a typical ascender""" |
| 134 | + return self._ascent |
| 135 | + |
| 136 | + @property |
| 137 | + def descent(self) -> int: |
| 138 | + """The number of pixels below the baseline of a typical descender""" |
| 139 | + return self._descent |
| 140 | + |
| 141 | + def get_bounding_box(self) -> tuple[int, int, int, int]: |
| 142 | + """Return the maximum glyph size as a 4-tuple of: width, height, x_offset, y_offset""" |
| 143 | + return (self._width, self._height, self._x_offset, self._y_offset) |
| 144 | + |
| 145 | + def _seek(self, offset): |
| 146 | + self.file.seek(offset) |
| 147 | + self._byte = 0 |
| 148 | + self._remaining_bits = 0 |
| 149 | + |
| 150 | + def _read_bits(self, num_bits): |
| 151 | + result = 0 |
| 152 | + needed_bits = num_bits |
| 153 | + while needed_bits > 0: |
| 154 | + if self._remaining_bits == 0: |
| 155 | + self._byte = self.file.read(1)[0] |
| 156 | + self._remaining_bits = 8 |
| 157 | + available_bits = min(needed_bits, self._remaining_bits) |
| 158 | + result = (result << available_bits) | (self._byte >> (8 - available_bits)) |
| 159 | + self._byte <<= available_bits |
| 160 | + self._byte &= 0xFF |
| 161 | + self._remaining_bits -= available_bits |
| 162 | + needed_bits -= available_bits |
| 163 | + return result |
| 164 | + |
| 165 | + def load_glyphs(self, code_points: Union[int, str, Iterable[int]]) -> None: |
| 166 | + # pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals |
| 167 | + if isinstance(code_points, int): |
| 168 | + code_points = (code_points,) |
| 169 | + elif isinstance(code_points, str): |
| 170 | + code_points = [ord(c) for c in code_points] |
| 171 | + |
| 172 | + # Only load glyphs that aren't already cached |
| 173 | + code_points = sorted(c for c in code_points if self._glyphs.get(c, None) is None) |
| 174 | + if not code_points: |
| 175 | + return |
| 176 | + |
| 177 | + for code_point in code_points: |
| 178 | + # Find character ID in the cmap table |
| 179 | + cid = None |
| 180 | + for start, end, offset in self._cmap_tiny: |
| 181 | + if start <= code_point < end: |
| 182 | + cid = offset + (code_point - start) |
| 183 | + break |
| 184 | + |
| 185 | + if cid is None or cid >= self._max_cid: |
| 186 | + self._glyphs[code_point] = None |
| 187 | + continue |
| 188 | + |
| 189 | + offset_length = 4 if self._index_to_loc_format == 1 else 2 |
| 190 | + |
| 191 | + # Get the glyph offset from the location table |
| 192 | + self._seek(self._loca_start + cid * offset_length) |
| 193 | + glyph_offset = struct.unpack( |
| 194 | + "<I" if offset_length == 4 else "<H", self.file.read(offset_length) |
| 195 | + )[0] |
| 196 | + |
| 197 | + # Read glyph header data |
| 198 | + self._seek(self._glyf_start + glyph_offset) |
| 199 | + glyph_advance = self._read_bits(self._glyph_advance_bits) |
| 200 | + |
| 201 | + # Read and convert signed bbox_x and bbox_y |
| 202 | + bbox_x = self._read_bits(self._glyph_bbox_xy_bits) |
| 203 | + # Convert to signed value if needed (using two's complement) |
| 204 | + if bbox_x & (1 << (self._glyph_bbox_xy_bits - 1)): |
| 205 | + bbox_x = bbox_x - (1 << self._glyph_bbox_xy_bits) |
| 206 | + |
| 207 | + bbox_y = self._read_bits(self._glyph_bbox_xy_bits) |
| 208 | + # Convert to signed value if needed (using two's complement) |
| 209 | + if bbox_y & (1 << (self._glyph_bbox_xy_bits - 1)): |
| 210 | + bbox_y = bbox_y - (1 << self._glyph_bbox_xy_bits) |
| 211 | + |
| 212 | + bbox_w = self._read_bits(self._glyph_bbox_wh_bits) |
| 213 | + bbox_h = self._read_bits(self._glyph_bbox_wh_bits) |
| 214 | + |
| 215 | + # Create bitmap for the glyph |
| 216 | + bitmap = self.bitmap_class(bbox_w, bbox_h, 2) |
| 217 | + |
| 218 | + # Read bitmap data (starting from the current bit position) |
| 219 | + for y in range(bbox_h): |
| 220 | + for x in range(bbox_w): |
| 221 | + pixel_value = self._read_bits(self._bits_per_pixel) |
| 222 | + if pixel_value > 0: # Convert any non-zero value to 1 |
| 223 | + bitmap[x, y] = 1 |
| 224 | + |
| 225 | + # Create and cache the glyph |
| 226 | + self._glyphs[code_point] = Glyph( |
| 227 | + bitmap, 0, bbox_w, bbox_h, bbox_x, bbox_y, glyph_advance, 0 |
| 228 | + ) |
0 commit comments