forked from adafruit/Adafruit_CircuitPython_Display_Text
-
Notifications
You must be signed in to change notification settings - Fork 0
/
label.py
180 lines (155 loc) · 6.9 KB
/
label.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# The MIT License (MIT)
#
# Copyright (c) 2019 Scott Shawcroft for Adafruit Industries LLC
#
# 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.
"""
`adafruit_display_text.label`
====================================================
Displays text labels using CircuitPython's displayio.
* Author(s): Scott Shawcroft
Implementation Notes
--------------------
**Hardware:**
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
import displayio
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Display_Text.git"
class Label(displayio.Group):
"""A label displaying a string of text. The origin point set by ``x`` and ``y``
properties will be the left edge of the bounding box, and in the center of a M
glyph (if its one line), or the (number of lines * linespacing + M)/2. That is,
it will try to have it be center-left as close as possible.
:param Font font: A font class that has ``get_bounding_box`` and ``get_glyph``.
Must include a capital M for measuring character size.
:param str text: Text to display
:param int max_glyphs: The largest quantity of glyphs we will display
:param int color: Color of all text in RGB hex
:param str align: Set vertical alignment to "top" or "center"
:param double line_spacing: Line spacing of text to display"""
def __init__(self, font, *, text=None, max_glyphs=None, color=0xffffff, align=None,
line_spacing=1.25, **kwargs):
if not max_glyphs and not text:
raise RuntimeError("Please provide a max size, or initial text")
if not max_glyphs:
max_glyphs = len(text)
super().__init__(max_size=max_glyphs, **kwargs)
self.width = max_glyphs
self.font = font
self._text = None
self.palette = displayio.Palette(2)
self.palette.make_transparent(0)
self.palette[1] = color
bounds = self.font.get_bounding_box()
self.height = bounds[1]
self._align = align
self._line_spacing = line_spacing
self._boundingbox = None
if text:
self._update_text(text)
def _update_text(self, new_text): # pylint: disable=too-many-locals
x = 0
y = 0
i = 0
old_c = 0
if self._align == 'center'
y_offset = int((self.font.get_glyph(ord('M')).height -
new_text.count('\n') * self.height * self.line_spacing) / 2)
else:
y_offset = 0
#print("y offset from baseline", y_offset)
left = right = top = bottom = 0
for character in new_text:
if character == '\n':
y += int(self.height * self._line_spacing)
x = 0
continue
glyph = self.font.get_glyph(ord(character))
if not glyph:
continue
right = max(right, x+glyph.width)
if y == 0: # first line, find the Ascender height
top = min(top, -glyph.height+y_offset)
bottom = max(bottom, y-glyph.dy+y_offset)
position_y = y - glyph.height - glyph.dy + y_offset
position_x = x + glyph.dx
if not self._text or old_c >= len(self._text) or character != self._text[old_c]:
try:
face = displayio.TileGrid(glyph.bitmap, pixel_shader=self.palette,
default_tile=glyph.tile_index,
tile_width=glyph.width, tile_height=glyph.height,
position=(position_x, position_y))
except TypeError:
face = displayio.TileGrid(glyph.bitmap, pixel_shader=self.palette,
default_tile=glyph.tile_index,
tile_width=glyph.width, tile_height=glyph.height,
x=position_x, y=position_y)
if i < len(self):
self[i] = face
else:
self.append(face)
elif self._text and character == self._text[old_c]:
try:
self[i].position = (position_x, position_y)
except AttributeError:
self[i].x = position_x
self[i].y = position_y
x += glyph.shift_x
# TODO skip this for control sequences or non-printables.
i += 1
old_c += 1
# skip all non-prinables in the old string
while (self._text and old_c < len(self._text) and
(self._text[old_c] == '\n' or not self.font.get_glyph(ord(self._text[old_c])))):
old_c += 1
# Remove the rest
while len(self) > i:
self.pop()
self._text = new_text
self._boundingbox = (left, top, left+right, bottom-top)
@property
def bounding_box(self):
"""An (x, y, w, h) tuple that completely covers all glyphs. The
first two numbers are offset from the x, y origin of this group"""
return tuple(self._boundingbox)
@property
def line_spacing(self):
"""The amount of space between lines of text, in multiples of the font's
bounding-box height. (E.g. 1.0 is the bounding-box height)"""
return self._line_spacing
@line_spacing.setter
def line_spacing(self, spacing):
self._line_spacing = spacing
@property
def color(self):
"""Color of the text as an RGB hex number."""
return self.palette[1]
@color.setter
def color(self, new_color):
self.palette[1] = new_color
@property
def text(self):
"""Text to display."""
return self._text
@text.setter
def text(self, new_text):
self._update_text(new_text)