]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/_palette.py
Update to pyproject.toml
[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
23 __version__ = "0.0.0+auto.0"
24 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
25
26
27 class Palette:
28     """Map a pixel palette_index to a full color. Colors are transformed to the display’s
29     format internally to save memory.
30     """
31
32     def __init__(self, color_count: int):
33         """Create a Palette object to store a set number of colors."""
34         self._needs_refresh = False
35
36         self._colors = []
37         for _ in range(color_count):
38             self._colors.append(self._make_color(0))
39             self._update_rgba(len(self._colors) - 1)
40
41     def _update_rgba(self, index):
42         color = self._colors[index]["rgb888"]
43         transparent = self._colors[index]["transparent"]
44         self._colors[index]["rgba"] = (
45             color >> 16,
46             (color >> 8) & 0xFF,
47             color & 0xFF,
48             0 if transparent else 0xFF,
49         )
50
51     def _make_color(self, value, transparent=False):
52         color = {
53             "transparent": transparent,
54             "rgb888": 0,
55             "rgba": (0, 0, 0, 255),
56         }
57         if isinstance(value, (tuple, list, bytes, bytearray)):
58             value = (value[0] & 0xFF) << 16 | (value[1] & 0xFF) << 8 | value[2] & 0xFF
59         elif isinstance(value, int):
60             if not 0 <= value <= 0xFFFFFF:
61                 raise ValueError("Color must be between 0x000000 and 0xFFFFFF")
62         else:
63             raise TypeError("Color buffer must be a buffer, tuple, list, or int")
64         color["rgb888"] = value
65         self._needs_refresh = True
66
67         return color
68
69     def __len__(self) -> int:
70         """Returns the number of colors in a Palette"""
71         return len(self._colors)
72
73     def __setitem__(
74         self,
75         index: int,
76         value: Union[int, circuitpython_typing.ReadableBuffer, Tuple[int, int, int]],
77     ) -> None:
78         """Sets the pixel color at the given index. The index should be
79         an integer in the range 0 to color_count-1.
80
81         The value argument represents a color, and can be from 0x000000 to 0xFFFFFF
82         (to represent an RGB value). Value can be an int, bytes (3 bytes (RGB) or
83         4 bytes (RGB + pad byte)), bytearray, or a tuple or list of 3 integers.
84         """
85         if self._colors[index]["rgb888"] != value:
86             self._colors[index] = self._make_color(value)
87             self._update_rgba(index)
88
89     def __getitem__(self, index: int) -> Optional[int]:
90         if not 0 <= index < len(self._colors):
91             raise ValueError("Palette index out of range")
92         return self._colors[index]["rgb888"]
93
94     def make_transparent(self, palette_index: int) -> None:
95         """Set the palette index to be a transparent color"""
96         self._colors[palette_index]["transparent"] = True
97         self._update_rgba(palette_index)
98
99     def make_opaque(self, palette_index: int) -> None:
100         """Set the palette index to be an opaque color"""
101         self._colors[palette_index]["transparent"] = False
102         self._update_rgba(palette_index)
103
104     def _get_palette(self):
105         """Generate a palette for use with PIL"""
106         palette = []
107         for color in self._colors:
108             palette += color["rgba"][0:3]
109         return palette
110
111     def _get_alpha_palette(self):
112         """Generate an alpha channel palette with white being
113         opaque and black being transparent"""
114         palette = []
115         for color in self._colors:
116             for _ in range(3):
117                 palette += [0 if color["transparent"] else 255]
118         return palette
119
120     def is_transparent(self, palette_index: int) -> bool:
121         """Returns True if the palette index is transparent. Returns False if opaque."""
122         return self._colors[palette_index]["transparent"]