]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - fontio.py
Pin to Python 3.11 because of typing
[hackapet/Adafruit_Blinka_Displayio.git] / fontio.py
1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4
5 """
6 `fontio`
7 ================================================================================
8
9 fontio for Blinka
10
11 **Software and Dependencies:**
12
13 * Adafruit Blinka:
14   https://github.com/adafruit/Adafruit_Blinka/releases
15
16 * Author(s): Melissa LeBlanc-Williams
17
18 """
19
20 import os
21 from typing import Union, Tuple, Optional
22 from PIL import ImageFont
23 from displayio import Bitmap
24
25 try:
26     from typing import Protocol
27 except ImportError:
28     from typing_extensions import Protocol
29
30 __version__ = "0.0.0+auto.0"
31 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
32
33 DEFAULT_FONT = "displayio/resources/ter-u12n.pil"
34
35
36 class FontProtocol(Protocol):
37     """A protocol shared by `BuiltinFont` and classes in ``adafruit_bitmap_font``"""
38
39     def get_bounding_box(self) -> Union[Tuple[int, int], Tuple[int, int, int, int]]:
40         """Retrieve the maximum bounding box of any glyph in the font.
41
42         The four element version is ``(width, height, x_offset, y_offset)``.
43         The two element version is ``(width, height)``, in which
44         ``x_offset`` and ``y_offset`` are assumed to be zero.
45         """
46
47     def get_glyph(self, codepoint: int) -> Optional["Glyph"]:
48         """Retrieve the Glyph for a given code point
49
50         If the code point is not present in the font, `None` is returned.
51         """
52
53
54 class BuiltinFont:
55     """Simulate a font built into CircuitPython"""
56
57     def __init__(self):
58         self._font = ImageFont.load(os.path.dirname(__file__) + "/" + DEFAULT_FONT)
59         self._generate_bitmap(0x20, 0x7E)
60
61     def _generate_bitmap(self, start_range, end_range):
62         char_width, char_height = self.get_bounding_box()
63         self._bitmap = Bitmap(
64             char_width * (end_range - start_range + 1), char_height, 2
65         )
66         for character in range(start_range, end_range + 1):
67             ascii_char = chr(character)
68             ascii_mask = self._font.getmask(ascii_char, mode="1")
69             for y in range(char_height):
70                 for x in range(char_width):
71                     color = ascii_mask.getpixel((x, y))
72                     character_position = character - start_range
73                     self._bitmap[character_position * char_width + x, y] = (
74                         1 if color else 0
75                     )
76
77     def get_bounding_box(self):
78         """Returns the maximum bounds of all glyphs in the font in
79         a tuple of two values: width, height.
80         """
81         return self._font.getbbox("M")[2:4]
82
83     def get_glyph(self, codepoint):
84         """Returns a `fontio.Glyph` for the given codepoint or None if no glyph is available."""
85         if 0x20 <= codepoint <= 0x7E:
86             glyph_index = codepoint - 0x20
87         else:
88             return None
89
90         bounding_box = self._font.getbbox(chr(codepoint))[2:4]
91         width, height = bounding_box
92         return Glyph(
93             bitmap=self._bitmap,
94             tile_index=glyph_index,
95             width=width,
96             height=height,
97             dx=0,
98             dy=0,
99             shift_x=width,
100             shift_y=0,
101         )
102
103     @property
104     def bitmap(self):
105         """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use
106         `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and
107         `terminalio.Terminal`.
108         """
109         return self._bitmap
110
111
112 # pylint: disable=too-few-public-methods, invalid-name, too-many-arguments
113 class Glyph:
114     """Storage of glyph info"""
115
116     def __init__(self, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
117         self.bitmap = bitmap
118         self.width = width
119         self.height = height
120         self.dx = dx
121         self.dy = dy
122         self.shift_x = shift_x
123         self.shift_y = shift_y
124         self.tile_index = tile_index
125
126
127 # pylint: enable=too-few-public-methods, invalid-name, too-many-arguments