]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/_palette.py
Added missing stuff, fixed group layer order issue
[hackapet/Adafruit_Blinka_Displayio.git] / displayio / _palette.py
1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4
5 """
6 `displayio.palette`
7 ================================================================================
8
9 displayio for Blinka
10
11 **Software and Dependencies:**
12
13 * Adafruit Blinka:
14   https://github.com/adafruit/Adafruit_Blinka/releases
15
16 * Author(s): Melissa LeBlanc-Williams
17
18 """
19
20 from typing import Optional, Union, Tuple
21 from circuitpython_typing import ReadableBuffer
22 from ._colorconverter import ColorConverter
23 from ._colorspace import Colorspace
24 from ._structs import InputPixelStruct, OutputPixelStruct, ColorStruct
25
26 __version__ = "0.0.0+auto.0"
27 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
28
29
30 class Palette:
31     """Map a pixel palette_index to a full color. Colors are transformed to the display's
32     format internally to save memory.
33     """
34
35     def __init__(self, color_count: int, *, dither: bool = False):
36         """Create a Palette object to store a set number of colors.
37
38         :param int color_count: The number of colors in the Palette
39         :param bool dither: When true, dither the RGB color before converting to the
40                             display's color space
41         """
42         self._needs_refresh = False
43         self._dither = dither
44
45         self._colors = []
46         for _ in range(color_count):
47             self._colors.append(self._make_color(0))
48
49     @staticmethod
50     def _make_color(value, transparent=False):
51         color = ColorStruct(transparent=transparent)
52
53         if isinstance(value, (tuple, list, bytes, bytearray)):
54             value = (value[0] & 0xFF) << 16 | (value[1] & 0xFF) << 8 | value[2] & 0xFF
55         elif isinstance(value, int):
56             if not 0 <= value <= 0xFFFFFF:
57                 raise ValueError("Color must be between 0x000000 and 0xFFFFFF")
58         else:
59             raise TypeError("Color buffer must be a buffer, tuple, list, or int")
60         color.rgb888 = value
61
62         return color
63
64     def __len__(self) -> int:
65         """Returns the number of colors in a Palette"""
66         return len(self._colors)
67
68     def __setitem__(
69         self,
70         index: int,
71         value: Union[int, ReadableBuffer, Tuple[int, int, int]],
72     ) -> None:
73         """Sets the pixel color at the given index. The index should be
74         an integer in the range 0 to color_count-1.
75
76         The value argument represents a color, and can be from 0x000000 to 0xFFFFFF
77         (to represent an RGB value). Value can be an int, bytes (3 bytes (RGB) or
78         4 bytes (RGB + pad byte)), bytearray, or a tuple or list of 3 integers.
79         """
80         if self._colors[index].rgb888 == value:
81             return
82         self._colors[index] = self._make_color(value)
83         self._colors[index].cached_colorspace = None
84         self._needs_refresh = True
85
86     def __getitem__(self, index: int) -> Optional[int]:
87         if not 0 <= index < len(self._colors):
88             raise ValueError("Palette index out of range")
89         return self._colors[index].rgb888
90
91     def make_transparent(self, palette_index: int) -> None:
92         """Set the palette index to be a transparent color"""
93         self._colors[palette_index].transparent = True
94         self._needs_refresh = True
95
96     def make_opaque(self, palette_index: int) -> None:
97         """Set the palette index to be an opaque color"""
98         self._colors[palette_index].transparent = False
99         self._needs_refresh = True
100
101     def _get_palette(self):
102         """Generate a palette for use with PIL"""
103         palette = []
104         for color in self._colors:
105             palette += color.rgba()[0:3]
106         return palette
107
108     def _get_alpha_palette(self):
109         """Generate an alpha channel palette with white being
110         opaque and black being transparent"""
111         palette = []
112         for color in self._colors:
113             for _ in range(3):
114                 palette += [0 if color.transparent else 0xFF]
115         return palette
116
117     def _get_color(
118         self,
119         colorspace: Colorspace,
120         input_pixel: InputPixelStruct,
121         output_color: OutputPixelStruct,
122     ):
123         palette_index = input_pixel.pixel
124         if palette_index > len(self._colors) or self._colors[palette_index].transparent:
125             output_color.opaque = False
126             return
127
128         color = self._colors[palette_index]
129         if (
130             not self._dither
131             and color.cached_colorspace == colorspace
132             and color.cached_colorspace_grayscale_bit == colorspace.grayscale_bit
133             and color.cached_colorspace_grayscale == colorspace.grayscale
134         ):
135             output_color.pixel = self._colors[palette_index].cached_color
136             return
137
138         rgb888_pixel = input_pixel
139         rgb888_pixel.pixel = self._colors[palette_index].rgb888
140         ColorConverter._convert_color(  # pylint: disable=protected-access
141             colorspace, self._dither, rgb888_pixel, output_color
142         )
143         if not self._dither:
144             color.cached_colorspace = colorspace
145             color.cached_color = output_color.pixel
146             color.cached_colorspace_grayscale = colorspace.grayscale
147             color.cached_colorspace_grayscale_bit = colorspace.grayscale_bit
148
149     def is_transparent(self, palette_index: int) -> bool:
150         """Returns True if the palette index is transparent. Returns False if opaque."""
151         return self._colors[palette_index].transparent
152
153     def _finish_refresh(self):
154         self._needs_refresh = False
155
156     @property
157     def dither(self) -> bool:
158         """When true the palette dithers the output by adding
159         random noise when truncating to display bitdepth
160         """
161         return self._dither
162
163     @dither.setter
164     def dither(self, value: bool):
165         if not isinstance(value, bool):
166             raise ValueError("Value should be boolean")
167         self._dither = value