]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/_palette.py
More displayio code updates
[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 import circuitpython_typing
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         self._needs_refresh = False
38         self._dither = dither
39
40         self._colors = []
41         for _ in range(color_count):
42             self._colors.append(self._make_color(0))
43
44     def _make_color(self, value, transparent=False):
45         color = ColorStruct(transparent=transparent)
46
47         if isinstance(value, (tuple, list, bytes, bytearray)):
48             value = (value[0] & 0xFF) << 16 | (value[1] & 0xFF) << 8 | value[2] & 0xFF
49         elif isinstance(value, int):
50             if not 0 <= value <= 0xFFFFFF:
51                 raise ValueError("Color must be between 0x000000 and 0xFFFFFF")
52         else:
53             raise TypeError("Color buffer must be a buffer, tuple, list, or int")
54         color.rgb888 = value
55         self._needs_refresh = True
56
57         return color
58
59     def __len__(self) -> int:
60         """Returns the number of colors in a Palette"""
61         return len(self._colors)
62
63     def __setitem__(
64         self,
65         index: int,
66         value: Union[int, circuitpython_typing.ReadableBuffer, Tuple[int, int, int]],
67     ) -> None:
68         """Sets the pixel color at the given index. The index should be
69         an integer in the range 0 to color_count-1.
70
71         The value argument represents a color, and can be from 0x000000 to 0xFFFFFF
72         (to represent an RGB value). Value can be an int, bytes (3 bytes (RGB) or
73         4 bytes (RGB + pad byte)), bytearray, or a tuple or list of 3 integers.
74         """
75         if self._colors[index].rgb888 != value:
76             self._colors[index] = self._make_color(value)
77
78     def __getitem__(self, index: int) -> Optional[int]:
79         if not 0 <= index < len(self._colors):
80             raise ValueError("Palette index out of range")
81         return self._colors[index].rgb888
82
83     def make_transparent(self, palette_index: int) -> None:
84         """Set the palette index to be a transparent color"""
85         self._colors[palette_index].transparent = True
86
87     def make_opaque(self, palette_index: int) -> None:
88         """Set the palette index to be an opaque color"""
89         self._colors[palette_index].transparent = False
90
91     def _get_palette(self):
92         """Generate a palette for use with PIL"""
93         palette = []
94         for color in self._colors:
95             palette += color.rgba()[0:3]
96         return palette
97
98     def _get_alpha_palette(self):
99         """Generate an alpha channel palette with white being
100         opaque and black being transparent"""
101         palette = []
102         for color in self._colors:
103             for _ in range(3):
104                 palette += [0 if color.transparent else 0xFF]
105         return palette
106
107     def _get_color(
108         self,
109         colorspace: Colorspace,
110         input_pixel: InputPixelStruct,
111         output_color: OutputPixelStruct,
112     ):
113         palette_index = input_pixel.pixel
114         if palette_index > len(self._colors) or self._colors[palette_index].transparent:
115             output_color.opaque = False
116             return
117
118         color = self._colors[palette_index]
119         if (
120             not self._dither
121             and color.cached_colorspace == colorspace
122             and color.cached_colorspace_grayscale_bit == colorspace.grayscale_bit
123             and color.cached_colorspace_grayscale == colorspace.grayscale
124         ):
125             output_color.pixel = self._colors[palette_index].cached_color
126             return
127
128         rgb888_pixel = input_pixel
129         ColorConverter._convert_color(  # pylint: disable=protected-access
130             colorspace, self._dither, rgb888_pixel, output_color
131         )
132         if not self._dither:
133             color.cached_colorspace = colorspace
134             color.cached_color = output_color.pixel
135             color.cached_colorspace_grayscale = colorspace.grayscale
136             color.cached_colorspace_grayscale_bit = colorspace.grayscale_bit
137
138     def is_transparent(self, palette_index: int) -> bool:
139         """Returns True if the palette index is transparent. Returns False if opaque."""
140         return self._colors[palette_index].transparent
141
142     @property
143     def dither(self) -> bool:
144         """When true the palette dithers the output by adding
145         random noise when truncating to display bitdepth
146         """
147         return self._dither
148
149     @dither.setter
150     def dither(self, value: bool):
151         if not isinstance(value, bool):
152             raise ValueError("Value should be boolean")
153         self._dither = value