Skip to content

Commit ab11a45

Browse files
committed
Fixup example and lint.
1 parent f79585f commit ab11a45

File tree

3 files changed

+154
-35
lines changed

3 files changed

+154
-35
lines changed

adafruit_bitmap_font/bdf.py

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,53 @@
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+
142
import gc
2-
from .glyph_cache import GlyphCache
343
from displayio 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"
448

549
class BDF(GlyphCache):
50+
"""Loads glyphs from a BDF file in the given bitmap_class."""
651
def __init__(self, f, bitmap_class):
752
super().__init__()
853
self.file = f
@@ -13,8 +58,12 @@ def __init__(self, f, bitmap_class):
1358
line = str(line, "utf-8")
1459
if not line or not line.startswith("STARTFONT 2.1"):
1560
raise ValueError("Unsupported file version")
61+
self.point_size = None
62+
self.x_resolution = None
63+
self.y_resolution = None
1664

1765
def get_bounding_box(self):
66+
"""Return the maximum glyph size as a 4-tuple of: width, height, x_offset, y_offset"""
1867
self.file.seek(0)
1968
while True:
2069
line = self.file.readline()
@@ -23,17 +72,18 @@ def get_bounding_box(self):
2372
break
2473

2574
if line.startswith("FONTBOUNDINGBOX "):
26-
_, x, y, dx, dy = line.split()
27-
return (int(x), int(y), int(dx), int(dy))
75+
_, x, y, x_offset, y_offset = line.split()
76+
return (int(x), int(y), int(x_offset), int(y_offset))
2877
return None
2978

3079
def load_glyphs(self, code_points):
80+
# pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals
3181
metadata = True
3282
character = False
3383
code_point = None
3484
bytes_per_row = 1
3585
desired_character = False
36-
current_info = None
86+
current_info = {}
3787
current_y = 0
3888
rounded_x = 1
3989
total_remaining = len(code_points)
@@ -74,12 +124,12 @@ def load_glyphs(self, code_points):
74124
desired_character = False
75125
elif line.startswith(b"BBX"):
76126
if desired_character:
77-
_, x, y, dx, dy = line.split()
127+
_, x, y, x_offset, y_offset = line.split()
78128
x = int(x)
79129
y = int(y)
80-
dx = int(dx)
81-
dy = int(dy)
82-
current_info["bounds"] = (x, y, dx, dy)
130+
x_offset = int(x_offset)
131+
y_offset = int(y_offset)
132+
current_info["bounds"] = (x, y, x_offset, y_offset)
83133
current_info["bitmap"] = self.bitmap_class(x, y, 2)
84134
elif line.startswith(b"BITMAP"):
85135
if desired_character:
@@ -114,7 +164,7 @@ def load_glyphs(self, code_points):
114164
x = 0
115165
for i in range(rounded_x):
116166
val = (bits >> ((rounded_x-i-1)*8)) & 0xFF
117-
for j in range(7,-1,-1):
167+
for j in range(7, -1, -1):
118168
if x >= width:
119169
break
120170
bit = 0

adafruit_bitmap_font/bitmap_font.py

Lines changed: 72 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,90 @@
1-
import sys
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.bitmap_font`
24+
====================================================
25+
26+
Loads bitmap glyphs from a variety of font.
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+
__version__ = "0.0.0-auto.0"
43+
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Bitmap_Font.git"
44+
245

346
def load_font(filename, bitmap=None):
47+
"""Loads a font file. Returns None if unsupported."""
448
if not bitmap:
549
import displayio
650
bitmap = displayio.Bitmap
7-
f = open(filename, "rb")
8-
first_four = f.read(4)
51+
font_file = open(filename, "rb")
52+
first_four = font_file.read(4)
953
#print(first_four)
1054
if filename.endswith("bdf") and first_four == b"STAR":
1155
from . import bdf
12-
return bdf.BDF(f, bitmap)
13-
elif filename.endswith("pcf") and first_four == b"\x01fcp":
56+
return bdf.BDF(font_file, bitmap)
57+
if filename.endswith("pcf") and first_four == b"\x01fcp":
1458
import pcf
15-
return pcf.PCF(f)
16-
elif filename.endswith("ttf") and first_four == b"\x00\x01\x00\x00":
59+
return pcf.PCF(font_file)
60+
if filename.endswith("ttf") and first_four == b"\x00\x01\x00\x00":
1761
import ttf
18-
return ttf.TTF(f)
19-
20-
62+
return ttf.TTF(font_file)
63+
return None
2164

2265
if __name__ == "__main__":
66+
#pylint: disable=invalid-name
67+
import os
68+
import sys
69+
sys.path.append(os.path.join(sys.path[0], "test"))
2370
font = load_font(sys.argv[1])
24-
for c in "Adafruit CircuitPython":
25-
o = ord(c)
26-
if o not in f.characters:
27-
continue
28-
glyph = f.characters[o]
29-
print(glyph)
30-
for i in range(10):
71+
72+
_, height, _, dy = font.get_bounding_box()
73+
for y in range(height):
3174
for c in "Adafruit CircuitPython":
32-
o = ord(c)
33-
if o not in f.characters:
75+
glyph = font.get_glyph(ord(c))
76+
if not glyph:
3477
continue
35-
glyph = f.characters[o]
36-
# print(glyph)
37-
shifted_i = i + (glyph["bounds"][1] - 8) + glyph["bounds"][3]
38-
if 0 <= shifted_i < len(glyph["bitmap"]):
39-
pixels = glyph["bitmap"][shifted_i]
78+
glyph_y = y + (glyph.height - (height + dy)) + glyph.dy
79+
pixels = []
80+
if 0 <= glyph_y < glyph.height:
81+
for i in range(glyph.width):
82+
value = glyph.bitmap[i, glyph_y]
83+
pixel = " "
84+
if value > 0:
85+
pixel = "#"
86+
pixels.append(pixel)
4087
else:
4188
pixels = ""
42-
print(pixels + " " * (glyph["shift"][0] - len(pixels)), end="")
89+
print("".join(pixels) + " " * (glyph.shift_x - len(pixels)), end="")
4390
print()

test/displayio.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,24 @@
1+
import collections
2+
13
class Bitmap:
2-
pass
4+
def __init__(self, width, height, color_count):
5+
self.width = width
6+
self.height = height
7+
if color_count > 255:
8+
raise ValueError("Cannot support that many colors")
9+
self.values = bytearray(width * height)
10+
11+
def __setitem__(self, index, value):
12+
if isinstance(index, tuple):
13+
index = index[0] + index[1] * self.width
14+
self.values[index] = value
15+
16+
def __getitem__(self, index):
17+
if isinstance(index, tuple):
18+
index = index[0] + index[1] * self.width
19+
return self.values[index]
20+
21+
def __len__(self):
22+
return self.width * self.height
23+
24+
Glyph = collections.namedtuple("Glyph", ["bitmap", "tile_index", "width", "height", "dx", "dy", "shift_x", "shift_y"])

0 commit comments

Comments
 (0)