bdf.py
  1  # The MIT License (MIT)
  2  #
  3  # Copyright (c) 2019 Scott Shawcroft for Adafruit Industries LLC
  4  #
  5  # Permission is hereby granted, free of charge, to any person obtaining a copy
  6  # of this software and associated documentation files (the "Software"), to deal
  7  # in the Software without restriction, including without limitation the rights
  8  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9  # copies of the Software, and to permit persons to whom the Software is
 10  # furnished to do so, subject to the following conditions:
 11  #
 12  # The above copyright notice and this permission notice shall be included in
 13  # all copies or substantial portions of the Software.
 14  #
 15  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 16  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 17  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 18  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 19  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 20  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 21  # THE SOFTWARE.
 22  """
 23  `adafruit_bitmap_font.bdf`
 24  ====================================================
 25  
 26  Loads BDF format fonts.
 27  
 28  * Author(s): Scott Shawcroft
 29  
 30  Implementation Notes
 31  --------------------
 32  
 33  **Hardware:**
 34  
 35  **Software and Dependencies:**
 36  
 37  * Adafruit CircuitPython firmware for the supported boards:
 38    https://github.com/adafruit/circuitpython/releases
 39  
 40  """
 41  
 42  import gc
 43  from fontio import Glyph
 44  from .glyph_cache import GlyphCache
 45  
 46  __version__ = "0.0.0-auto.0"
 47  __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
 48  
 49  
 50  class BDF(GlyphCache):
 51      """Loads glyphs from a BDF file in the given bitmap_class."""
 52  
 53      def __init__(self, f, bitmap_class):
 54          super().__init__()
 55          self.file = f
 56          self.name = f
 57          self.file.seek(0)
 58          self.bitmap_class = bitmap_class
 59          line = self.file.readline()
 60          line = str(line, "utf-8")
 61          if not line or not line.startswith("STARTFONT 2.1"):
 62              raise ValueError("Unsupported file version")
 63          self.point_size = None
 64          self.x_resolution = None
 65          self.y_resolution = None
 66  
 67      def get_bounding_box(self):
 68          """Return the maximum glyph size as a 4-tuple of: width, height, x_offset, y_offset"""
 69          self.file.seek(0)
 70          while True:
 71              line = self.file.readline()
 72              line = str(line, "utf-8")
 73              if not line:
 74                  break
 75  
 76              if line.startswith("FONTBOUNDINGBOX "):
 77                  _, x, y, x_offset, y_offset = line.split()
 78                  return (int(x), int(y), int(x_offset), int(y_offset))
 79          return None
 80  
 81      def load_glyphs(self, code_points):
 82          # pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals
 83          metadata = True
 84          character = False
 85          code_point = None
 86          bytes_per_row = 1
 87          desired_character = False
 88          current_info = {}
 89          current_y = 0
 90          rounded_x = 1
 91          if isinstance(code_points, int):
 92              remaining = set()
 93              remaining.add(code_points)
 94          elif isinstance(code_points, str):
 95              remaining = set(ord(c) for c in code_points)
 96          elif isinstance(code_points, set):
 97              remaining = code_points
 98          else:
 99              remaining = set(code_points)
100          for code_point in remaining:
101              if code_point in self._glyphs and self._glyphs[code_point]:
102                  remaining.remove(code_point)
103          if not remaining:
104              return
105  
106          x, _, _, _ = self.get_bounding_box()
107  
108          self.file.seek(0)
109          while True:
110              line = self.file.readline()
111              if not line:
112                  break
113              if line.startswith(b"CHARS "):
114                  metadata = False
115              elif line.startswith(b"SIZE"):
116                  _, self.point_size, self.x_resolution, self.y_resolution = line.split()
117              elif line.startswith(b"COMMENT"):
118                  pass
119              elif line.startswith(b"STARTCHAR"):
120                  # print(lineno, line.strip())
121                  # _, character_name = line.split()
122                  character = True
123              elif line.startswith(b"ENDCHAR"):
124                  character = False
125                  if desired_character:
126                      bounds = current_info["bounds"]
127                      shift = current_info["shift"]
128                      gc.collect()
129                      self._glyphs[code_point] = Glyph(
130                          current_info["bitmap"],
131                          0,
132                          bounds[0],
133                          bounds[1],
134                          bounds[2],
135                          bounds[3],
136                          shift[0],
137                          shift[1],
138                      )
139                      remaining.remove(code_point)
140                      if not remaining:
141                          return
142                  desired_character = False
143              elif line.startswith(b"BBX"):
144                  if desired_character:
145                      _, x, y, x_offset, y_offset = line.split()
146                      x = int(x)
147                      y = int(y)
148                      x_offset = int(x_offset)
149                      y_offset = int(y_offset)
150                      current_info["bounds"] = (x, y, x_offset, y_offset)
151                      current_info["bitmap"] = self.bitmap_class(x, y, 2)
152              elif line.startswith(b"BITMAP"):
153                  if desired_character:
154                      rounded_x = x // 8
155                      if x % 8 > 0:
156                          rounded_x += 1
157                      bytes_per_row = rounded_x
158                      if bytes_per_row % 4 > 0:
159                          bytes_per_row += 4 - bytes_per_row % 4
160                      current_y = 0
161              elif line.startswith(b"ENCODING"):
162                  _, code_point = line.split()
163                  code_point = int(code_point)
164                  if code_point in remaining:
165                      desired_character = True
166                      current_info = {"bitmap": None, "bounds": None, "shift": None}
167              elif line.startswith(b"DWIDTH"):
168                  if desired_character:
169                      _, shift_x, shift_y = line.split()
170                      shift_x = int(shift_x)
171                      shift_y = int(shift_y)
172                      current_info["shift"] = (shift_x, shift_y)
173              elif line.startswith(b"SWIDTH"):
174                  pass
175              elif character:
176                  if desired_character:
177                      bits = int(line.strip(), 16)
178                      width = current_info["bounds"][0]
179                      start = current_y * width
180                      x = 0
181                      for i in range(rounded_x):
182                          val = (bits >> ((rounded_x - i - 1) * 8)) & 0xFF
183                          for j in range(7, -1, -1):
184                              if x >= width:
185                                  break
186                              bit = 0
187                              if val & (1 << j) != 0:
188                                  bit = 1
189                              current_info["bitmap"][start + x] = bit
190                              x += 1
191                      current_y += 1
192              elif metadata:
193                  # print(lineno, line.strip())
194                  pass