]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blobdiff - fontio.py
fix: use original self._reset.switch_to_output(value=True) from main branch
[hackapet/Adafruit_Blinka_Displayio.git] / fontio.py
index f66dc188273a972b5a9fd121b551f709d3a71a87..2eddfa47b21826ece12944951c773cf94ae17d02 100644 (file)
--- a/fontio.py
+++ b/fontio.py
@@ -1,24 +1,7 @@
-# The MIT License (MIT)
+# SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
 #
-# Copyright (c) 2020 Melissa LeBlanc-Williams for Adafruit Industries
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
+# SPDX-License-Identifier: MIT
+
 """
 `fontio`
 ================================================================================
@@ -34,58 +17,103 @@ fontio for Blinka
 
 """
 
-from displayio import Bitmap
+import os
+from typing import Union, Tuple, Optional
 from PIL import ImageFont
+from displayio import Bitmap
 
-__version__ = "0.0.0-auto.0"
+try:
+    from typing import Protocol
+except ImportError:
+    from typing_extensions import Protocol
+
+__version__ = "0.0.0+auto.0"
 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
 
+DEFAULT_FONT = "displayio/resources/ter-u12n.pil"
+
+
+class FontProtocol(Protocol):
+    """A protocol shared by `BuiltinFont` and classes in ``adafruit_bitmap_font``"""
+
+    def get_bounding_box(self) -> Union[Tuple[int, int], Tuple[int, int, int, int]]:
+        """Retrieve the maximum bounding box of any glyph in the font.
+
+        The four element version is ``(width, height, x_offset, y_offset)``.
+        The two element version is ``(width, height)``, in which
+        ``x_offset`` and ``y_offset`` are assumed to be zero.
+        """
+
+    def get_glyph(self, codepoint: int) -> Optional["Glyph"]:
+        """Retrieve the Glyph for a given code point
+
+        If the code point is not present in the font, `None` is returned.
+        """
+
 
 class BuiltinFont:
+    """Simulate a font built into CircuitPython"""
+
     def __init__(self):
-        self._font = ImageFont.load_default()
-        ascii = ""
-        for character in range(0x20, 0x7F):
-            ascii += chr(character)
-        self._font.getmask(ascii)
-        bmp_size = self._font.getsize(ascii)
-        self._bitmap = Bitmap(bmp_size[0], bmp_size[1], 2)
-        ascii_mask = self._font.getmask(ascii, mode="1")
-        for x in range(bmp_size[0]):
-            for y in range(bmp_size[1]):
-                self._bitmap[x, y] = 1 if ascii_mask.getpixel((x, y)) else 0
-
-    def _get_glyph_index(self, charcode):
-        if 0x20 <= charcode <= 0x7E:
-            return charcode - 0x20
+        self._font = ImageFont.load(os.path.dirname(__file__) + "/" + DEFAULT_FONT)
+        self._generate_bitmap(0x20, 0x7E)
+
+    def _generate_bitmap(self, start_range, end_range):
+        char_width, char_height = self.get_bounding_box()
+        self._bitmap = Bitmap(
+            char_width * (end_range - start_range + 1), char_height, 2
+        )
+        for character in range(start_range, end_range + 1):
+            ascii_char = chr(character)
+            ascii_mask = self._font.getmask(ascii_char, mode="1")
+            for y in range(char_height):
+                for x in range(char_width):
+                    color = ascii_mask.getpixel((x, y))
+                    character_position = character - start_range
+                    self._bitmap[character_position * char_width + x, y] = (
+                        1 if color else 0
+                    )
 
     def get_bounding_box(self):
-        """Returns the maximum bounds of all glyphs in the font in a tuple of two values: width, height."""
-        return self._font.getsize("M")
+        """Returns the maximum bounds of all glyphs in the font in
+        a tuple of two values: width, height.
+        """
+        return self._font.getbbox("M")[2:4]
 
     def get_glyph(self, codepoint):
         """Returns a `fontio.Glyph` for the given codepoint or None if no glyph is available."""
-        bounding_box = self._font.getsize(chr(codepoint))
+        if 0x20 <= codepoint <= 0x7E:
+            glyph_index = codepoint - 0x20
+        else:
+            return None
+
+        bounding_box = self._font.getbbox(chr(codepoint))[2:4]
+        width, height = bounding_box
         return Glyph(
             bitmap=self._bitmap,
-            tile_index=self._get_glyph_index(codepoint),
-            width=bounding_box[0],
-            height=bounding_box[1],
+            tile_index=glyph_index,
+            width=width,
+            height=height,
             dx=0,
             dy=0,
-            shift_x=0,
+            shift_x=width,
             shift_y=0,
         )
 
     @property
     def bitmap(self):
-        """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and `terminalio.Terminal`.
+        """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use
+        `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and
+        `terminalio.Terminal`.
         """
         return self._bitmap
 
 
+# pylint: disable=too-few-public-methods, invalid-name, too-many-arguments
 class Glyph:
-    def __init__(self, *, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
+    """Storage of glyph info"""
+
+    def __init__(self, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
         self.bitmap = bitmap
         self.width = width
         self.height = height
@@ -94,3 +122,6 @@ class Glyph:
         self.shift_x = shift_x
         self.shift_y = shift_y
         self.tile_index = tile_index
+
+
+# pylint: enable=too-few-public-methods, invalid-name, too-many-arguments