diff --git a/LICENSES/OFL-1.1.txt b/LICENSES/OFL-1.1.txt new file mode 100644 index 0000000..84a3934 --- /dev/null +++ b/LICENSES/OFL-1.1.txt @@ -0,0 +1,90 @@ +The SIL Open Font License version 1.1 is copied below, and is also +available with a FAQ at http://scripts.sil.org/OFL. + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/adafruit_bitmap_font/bitmap_font.py b/adafruit_bitmap_font/bitmap_font.py index 842cd2e..7a67ef8 100644 --- a/adafruit_bitmap_font/bitmap_font.py +++ b/adafruit_bitmap_font/bitmap_font.py @@ -27,7 +27,7 @@ from displayio import Bitmap - from . import bdf, pcf, ttf + from . import bdf, lvfontbin, pcf, ttf except ImportError: pass @@ -35,7 +35,14 @@ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git" -def load_font(filename: str, bitmap: Optional[Bitmap] = None) -> Union[bdf.BDF, pcf.PCF, ttf.TTF]: +# The LVGL file starts with the size of the 'head' section. It hasn't changed in five years so +# we can treat it like a magic number. +LVGL_HEADER_SIZE = b"\x30\x00\x00\x00" + + +def load_font( + filename: str, bitmap: Optional[Bitmap] = None +) -> Union[bdf.BDF, lvfontbin.LVGLFont, pcf.PCF, ttf.TTF]: """Loads a font file. Returns None if unsupported.""" if not bitmap: import displayio @@ -56,4 +63,11 @@ def load_font(filename: str, bitmap: Optional[Bitmap] = None) -> Union[bdf.BDF, return ttf.TTF(font_file, bitmap) + if ( + filename.endswith("bin") or filename.endswith("lvfontbin") + ) and first_four == LVGL_HEADER_SIZE: + from . import lvfontbin + + return lvfontbin.LVGLFont(font_file, bitmap) + raise ValueError("Unknown magic number %r" % first_four) diff --git a/adafruit_bitmap_font/lvfontbin.py b/adafruit_bitmap_font/lvfontbin.py new file mode 100644 index 0000000..13075da --- /dev/null +++ b/adafruit_bitmap_font/lvfontbin.py @@ -0,0 +1,228 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +""" +`adafruit_bitmap_font.lvfontbin` +==================================================== + +Loads binary LVGL format fonts. + +* Author(s): Scott Shawcroft + +Implementation Notes +-------------------- + +**Hardware:** + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" + +import struct + +try: + from io import FileIO + from typing import Iterable, Union +except ImportError: + pass + +from fontio import Glyph + +from .glyph_cache import GlyphCache + + +class LVGLFont(GlyphCache): + """Loads glyphs from a LVGL binary font file in the given bitmap_class. + + There is an in-browser converter here: https://lvgl.io/tools/fontconverter + + The format is documented here: https://github.com/lvgl/lv_font_conv/tree/master/doc + + """ + + def __init__(self, f: FileIO, bitmap_class=None): + super().__init__() + f.seek(0) + self.file = f + self.bitmap_class = bitmap_class + # Initialize default values for bounding box + self._width = None + self._height = None + self._x_offset = 0 + self._y_offset = 0 + + # For reading bits + self._byte = 0 + self._remaining_bits = 0 + + while True: + buffer = f.read(4) + if len(buffer) < 4: + break + section_size = struct.unpack(" int: + """The number of pixels above the baseline of a typical ascender""" + return self._ascent + + @property + def descent(self) -> int: + """The number of pixels below the baseline of a typical descender""" + return self._descent + + def get_bounding_box(self) -> tuple[int, int, int, int]: + """Return the maximum glyph size as a 4-tuple of: width, height, x_offset, y_offset""" + return (self._width, self._height, self._x_offset, self._y_offset) + + def _seek(self, offset): + self.file.seek(offset) + self._byte = 0 + self._remaining_bits = 0 + + def _read_bits(self, num_bits): + result = 0 + needed_bits = num_bits + while needed_bits > 0: + if self._remaining_bits == 0: + self._byte = self.file.read(1)[0] + self._remaining_bits = 8 + available_bits = min(needed_bits, self._remaining_bits) + result = (result << available_bits) | (self._byte >> (8 - available_bits)) + self._byte <<= available_bits + self._byte &= 0xFF + self._remaining_bits -= available_bits + needed_bits -= available_bits + return result + + def load_glyphs(self, code_points: Union[int, str, Iterable[int]]) -> None: + # pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals + if isinstance(code_points, int): + code_points = (code_points,) + elif isinstance(code_points, str): + code_points = [ord(c) for c in code_points] + + # Only load glyphs that aren't already cached + code_points = sorted(c for c in code_points if self._glyphs.get(c, None) is None) + if not code_points: + return + + for code_point in code_points: + # Find character ID in the cmap table + cid = None + for start, end, offset in self._cmap_tiny: + if start <= code_point < end: + cid = offset + (code_point - start) + break + + if cid is None or cid >= self._max_cid: + self._glyphs[code_point] = None + continue + + offset_length = 4 if self._index_to_loc_format == 1 else 2 + + # Get the glyph offset from the location table + self._seek(self._loca_start + cid * offset_length) + glyph_offset = struct.unpack( + " 0: # Convert any non-zero value to 1 + bitmap[x, y] = 1 + + # Create and cache the glyph + self._glyphs[code_point] = Glyph( + bitmap, 0, bbox_w, bbox_h, bbox_x, bbox_y, glyph_advance, 0 + ) diff --git a/examples/fonts/unifont-16.0.02-ascii-emoji.bin b/examples/fonts/unifont-16.0.02-ascii-emoji.bin new file mode 100644 index 0000000..71ba9b4 Binary files /dev/null and b/examples/fonts/unifont-16.0.02-ascii-emoji.bin differ diff --git a/examples/fonts/unifont-16.0.02-ascii-emoji.bin.license b/examples/fonts/unifont-16.0.02-ascii-emoji.bin.license new file mode 100644 index 0000000..18b43d8 --- /dev/null +++ b/examples/fonts/unifont-16.0.02-ascii-emoji.bin.license @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2024 GNU Unifont Contributors +# +# SPDX-License-Identifier: OFL-1.1 + +# Unifont version 16.0.02 is licensed under the SIL Open Font License 1.1 (OFL-1.1). + +# Original Unifont converted to LVGL binary format for use with CircuitPython.