]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/_displaycore.py
More bug fixes
[hackapet/Adafruit_Blinka_Displayio.git] / displayio / _displaycore.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 # SPDX-FileCopyrightText: 2021 James Carr
3 #
4 # SPDX-License-Identifier: MIT
5
6 """
7 `displayio._displaycore`
8 ================================================================================
9
10 Super class of the display classes
11
12 **Software and Dependencies:**
13
14 * Adafruit Blinka:
15   https://github.com/adafruit/Adafruit_Blinka/releases
16
17 * Author(s): James Carr, Melissa LeBlanc-Williams
18
19 """
20
21 __version__ = "0.0.0+auto.0"
22 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_Displayio.git"
23
24
25 import time
26 import struct
27 from circuitpython_typing import WriteableBuffer, ReadableBuffer
28 from paralleldisplay import ParallelBus
29 from ._fourwire import FourWire
30 from ._group import Group
31 from ._i2cdisplay import I2CDisplay
32 from ._structs import ColorspaceStruct, TransformStruct
33 from ._area import Area
34 from ._displaybus import _DisplayBus
35 from ._helpers import bswap16
36 from ._constants import (
37     CHIP_SELECT_UNTOUCHED,
38     CHIP_SELECT_TOGGLE_EVERY_BYTE,
39     DISPLAY_COMMAND,
40     DISPLAY_DATA,
41     NO_COMMAND,
42 )
43
44
45 class _DisplayCore:
46     # pylint: disable=too-many-arguments, too-many-instance-attributes, too-many-locals, too-many-branches, too-many-statements
47
48     def __init__(
49         self,
50         bus,
51         width: int,
52         height: int,
53         ram_width: int,
54         ram_height: int,
55         colstart: int,
56         rowstart: int,
57         rotation: int,
58         color_depth: int,
59         grayscale: bool,
60         pixels_in_byte_share_row: bool,
61         bytes_per_cell: int,
62         reverse_pixels_in_byte: bool,
63         reverse_bytes_in_word: bool,
64         column_command: int,
65         row_command: int,
66         set_current_column_command: int,
67         set_current_row_command: int,
68         data_as_commands: bool,
69         always_toggle_chip_select: bool,
70         sh1107_addressing: bool,
71         address_little_endian: bool,
72     ):
73         self.colorspace = ColorspaceStruct(
74             depth=color_depth,
75             grayscale=grayscale,
76             grayscale_bit=8 - color_depth,
77             pixels_in_byte_share_row=pixels_in_byte_share_row,
78             bytes_per_cell=bytes_per_cell,
79             reverse_pixels_in_byte=reverse_pixels_in_byte,
80             reverse_bytes_in_word=reverse_bytes_in_word,
81             dither=False,
82         )
83         self.current_group = None
84         self.colstart = colstart
85         self.rowstart = rowstart
86         self.last_refresh = 0
87
88         self.column_command = column_command
89         self.row_command = row_command
90         self.set_current_column_command = set_current_column_command
91         self.set_current_row_command = set_current_row_command
92         self.data_as_commands = data_as_commands
93         self.always_toggle_chip_select = always_toggle_chip_select
94         self.sh1107_addressing = sh1107_addressing
95         self.address_little_endian = address_little_endian
96
97         self.refresh_in_progress = False
98         self.full_refresh = False
99         self.last_refresh = 0
100
101         if bus:
102             if isinstance(bus, (FourWire, I2CDisplay, ParallelBus)):
103                 self._bus_reset = bus.reset
104                 self._begin_transaction = bus._begin_transaction
105                 self._send = bus._send
106                 self._end_transaction = bus._end_transaction
107             else:
108                 raise ValueError("Unsupported display bus type")
109
110         self._bus = bus
111         self.area = Area(0, 0, width, height)
112
113         self.width = width
114         self.height = height
115         self.ram_width = ram_width
116         self.ram_height = ram_height
117         self.rotation = rotation
118         self.transform = TransformStruct()
119
120     def set_rotation(self, rotation: int) -> None:
121         """
122         Sets the rotation of the display as an int in degrees.
123         """
124         # pylint: disable=protected-access, too-many-branches
125         transposed = self.rotation in (90, 270)
126         will_be_transposed = rotation in (90, 270)
127         if transposed != will_be_transposed:
128             self.width, self.height = self.height, self.width
129
130         height = self.height
131         width = self.width
132
133         rotation %= 360
134         self.rotation = rotation
135         self.transform.x = 0
136         self.transform.y = 0
137         self.transform.scale = 1
138         self.transform.mirror_x = False
139         self.transform.mirror_y = False
140         self.transform.transpose_xy = False
141
142         if rotation in (0, 180):
143             if rotation == 180:
144                 self.transform.mirror_x = True
145                 self.transform.mirror_y = True
146         else:
147             self.transform.transpose_xy = True
148             if rotation == 270:
149                 self.transform.mirror_y = True
150             else:
151                 self.transform.mirror_x = True
152
153         self.area.x1 = 0
154         self.area.y1 = 0
155         self.area.next = None
156
157         self.transform.dx = 1
158         self.transform.dy = 1
159         if self.transform.transpose_xy:
160             self.area.x2 = height
161             self.area.y2 = width
162             if self.transform.mirror_x:
163                 self.transform.x = height
164                 self.transform.dx = -1
165             if self.transform.mirror_y:
166                 self.transform.y = width
167                 self.transform.dy = -1
168         else:
169             self.area.x2 = width
170             self.area.y2 = height
171             if self.transform.mirror_x:
172                 self.transform.x = width
173                 self.transform.dx = -1
174             if self.transform.mirror_y:
175                 self.transform.y = height
176                 self.transform.dy = -1
177
178         if self.current_group is not None:
179             self.current_group._update_transform(self.transform)
180
181     def set_root_group(self, root_group: Group) -> bool:
182         """
183         Switches to displaying the given group of layers. When group is `None`, the
184         default CircuitPython terminal will be shown.
185
186         :param Optional[displayio.Group] root_group: The group to show.
187         """
188         # pylint: disable=protected-access
189
190         if root_group == self.current_group:
191             return True
192
193         if root_group is not None and root_group._in_group:
194             return False
195
196         if self.current_group is not None:
197             self.current_group._in_group = False
198
199         if root_group is not None:
200             root_group._update_transform(self.transform)
201             root_group._in_group = True
202
203         self.current_group = root_group
204         self.full_refresh = True
205
206         return True
207
208     def start_refresh(self) -> bool:
209         # pylint: disable=protected-access
210         """Mark the display core as currently being refreshed"""
211
212         if self.refresh_in_progress:
213             return False
214
215         self.refresh_in_progress = True
216         self.last_refresh = time.monotonic() * 1000
217         return True
218
219     def finish_refresh(self) -> None:
220         # pylint: disable=protected-access
221         """Unmark the display core as currently being refreshed"""
222
223         if self.current_group is not None:
224             self.current_group._finish_refresh()
225
226         self.full_refresh = False
227         self.refresh_in_progress = False
228         self.last_refresh = time.monotonic() * 1000
229
230     def release_display_core(self) -> None:
231         """Release the display from the current group"""
232         # pylint: disable=protected-access
233
234         if self.current_group is not None:
235             self.current_group._in_group = False
236
237     def fill_area(
238         self,
239         area: Area,
240         mask: WriteableBuffer,
241         buffer: WriteableBuffer,
242     ) -> bool:
243         """Call the current group's fill area function"""
244         if self.current_group is not None:
245             return self.current_group._fill_area(  # pylint: disable=protected-access
246                 self.colorspace, area, mask, buffer
247             )
248         return False
249
250     def clip_area(self, area: Area, clipped: Area) -> bool:
251         """Shrink the area to the region shared by the two areas"""
252
253         overlaps = self.area.compute_overlap(area, clipped)
254         if not overlaps:
255             return False
256
257         # Expand the area if we have multiple pixels per byte and we need to byte align the bounds
258         if self.colorspace.depth < 8:
259             pixels_per_byte = (
260                 8 // self.colorspace.depth * self.colorspace.bytes_per_cell
261             )
262             if self.colorspace.pixels_in_byte_share_row:
263                 if clipped.x1 % pixels_per_byte != 0:
264                     clipped.x1 -= clipped.x1 % pixels_per_byte
265                 if clipped.x2 % pixels_per_byte != 0:
266                     clipped.x2 += pixels_per_byte - clipped.x2 % pixels_per_byte
267             else:
268                 if clipped.y1 % pixels_per_byte != 0:
269                     clipped.y1 -= clipped.y1 % pixels_per_byte
270                 if clipped.y2 % pixels_per_byte != 0:
271                     clipped.y2 += pixels_per_byte - clipped.y2 % pixels_per_byte
272
273         return True
274
275     def set_region_to_update(self, area: Area) -> None:
276         """Set the region to update"""
277         region_x1 = area.x1 + self.colstart
278         region_x2 = area.x2 + self.colstart
279         region_y1 = area.y1 + self.rowstart
280         region_y2 = area.y2 + self.rowstart
281
282         if self.colorspace.depth < 8:
283             pixels_per_byte = 8 // self.colorspace.depth
284             if self.colorspace.pixels_in_byte_share_row:
285                 region_x1 //= pixels_per_byte * self.colorspace.bytes_per_cell
286                 region_x2 //= pixels_per_byte * self.colorspace.bytes_per_cell
287             else:
288                 region_y1 //= pixels_per_byte * self.colorspace.bytes_per_cell
289                 region_y2 //= pixels_per_byte * self.colorspace.bytes_per_cell
290
291         region_x2 -= 1
292         region_y2 -= 1
293
294         chip_select = CHIP_SELECT_UNTOUCHED
295         if self.always_toggle_chip_select or self.data_as_commands:
296             chip_select = CHIP_SELECT_TOGGLE_EVERY_BYTE
297
298         # Set column
299         self.begin_transaction()
300         data_type = DISPLAY_DATA
301         if not self.data_as_commands:
302             self.send(
303                 DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, bytes([self.column_command])
304             )
305         else:
306             data_type = DISPLAY_COMMAND
307
308         if self.ram_width < 0x100:  # Single Byte Bounds
309             data = struct.pack(">BB", region_x1, region_x2)
310         else:
311             if self.address_little_endian:
312                 region_x1 = bswap16(region_x1)
313                 region_x2 = bswap16(region_x2)
314             data = struct.pack(">HH", region_x1, region_x2)
315
316         # Quirk for SH1107 "SH1107_addressing"
317         #     Column lower command = 0x00, Column upper command = 0x10
318         if self.sh1107_addressing:
319             data = struct.pack(
320                 ">BB",
321                 ((region_x1 >> 4) & 0xF0) | 0x10,  # 0x10 to 0x17
322                 region_x1 & 0x0F,  # 0x00 to 0x0F
323             )
324
325         self.send(data_type, chip_select, data)
326         self.end_transaction()
327
328         if self.set_current_column_command != NO_COMMAND:
329             self.begin_transaction()
330             self.send(
331                 DISPLAY_COMMAND, chip_select, bytes([self.set_current_column_command])
332             )
333             # Only send the first half of data because it is the first coordinate.
334             self.send(DISPLAY_DATA, chip_select, data[: len(data) // 2])
335             self.end_transaction()
336
337         # Set row
338         self.begin_transaction()
339
340         if not self.data_as_commands:
341             self.send(DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, bytes([self.row_command]))
342
343         if self.ram_width < 0x100:  # Single Byte Bounds
344             data = struct.pack(">BB", region_y1, region_y2)
345         else:
346             if self.address_little_endian:
347                 region_y1 = bswap16(region_y1)
348                 region_y2 = bswap16(region_y2)
349             data = struct.pack(">HH", region_y1, region_y2)
350
351         # Quirk for SH1107 "SH1107_addressing"
352         #     Page address command = 0xB0
353         if self.sh1107_addressing:
354             data = struct.pack(">B", 0xB0 | region_y1)
355
356         self.send(data_type, chip_select, data)
357         self.end_transaction()
358
359         if self.set_current_row_command != NO_COMMAND:
360             self.begin_transaction()
361             self.send(
362                 DISPLAY_COMMAND, chip_select, bytes([self.set_current_row_command])
363             )
364             # Only send the first half of data because it is the first coordinate.
365             self.send(DISPLAY_DATA, chip_select, data[: len(data) // 2])
366             self.end_transaction()
367
368         """
369         img = self._buffer.convert("RGB").crop(astuple(area))
370         img = img.rotate(360 - self._core.rotation, expand=True)
371
372         display_area = self._apply_rotation(area)
373
374         img = img.crop(astuple(display_area))
375
376         data = numpy.array(img).astype("uint16")
377         color = (
378             ((data[:, :, 0] & 0xF8) << 8)
379             | ((data[:, :, 1] & 0xFC) << 3)
380             | (data[:, :, 2] >> 3)
381         )
382
383         pixels = bytes(
384             numpy.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()
385         )
386         """
387
388     def send(
389         self,
390         data_type: int,
391         chip_select: int,
392         data: ReadableBuffer,
393     ) -> None:
394         """
395         Send the data to the current bus
396         """
397         self._send(data_type, chip_select, data)
398
399     def begin_transaction(self) -> None:
400         """
401         Begin Bus Transaction
402         """
403         self._begin_transaction()
404
405     def end_transaction(self) -> None:
406         """
407         End Bus Transaction
408         """
409         self._end_transaction()
410
411     def get_width(self) -> int:
412         """
413         Gets the width of the display in pixels.
414         """
415         return self.width
416
417     def get_height(self) -> int:
418         """
419         Gets the height of the display in pixels.
420         """
421         return self.height
422
423     def get_rotation(self) -> int:
424         """
425         Gets the rotation of the display as an int in degrees.
426         """
427         return self.rotation
428
429     def get_bus(self) -> _DisplayBus:
430         """
431         The bus being used by the display. [readonly]
432         """
433         return self._bus