]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/palette.py
ae3d27c47b3c1128df8ff1d7c4b71121a5c2d959
[hackapet/Adafruit_Blinka_Displayio.git] / displayio / palette.py
1 # The MIT License (MIT)
2 #
3 # Copyright (c) 2020 Melissa LeBlanc-Williams for Adafruit Industries
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.
22
23 """
24 `displayio.palette`
25 ================================================================================
26
27 displayio for Blinka
28
29 **Software and Dependencies:**
30
31 * Adafruit Blinka:
32   https://github.com/adafruit/Adafruit_Blinka/releases
33
34 * Author(s): Melissa LeBlanc-Williams
35
36 """
37
38 __version__ = "0.0.0-auto.0"
39 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
40
41
42 class Palette:
43     """Map a pixel palette_index to a full color. Colors are transformed to the display’s
44     format internally to save memory.
45     """
46
47     def __init__(self, color_count):
48         """Create a Palette object to store a set number of colors."""
49         self._needs_refresh = False
50
51         self._colors = []
52         for _ in range(color_count):
53             self._colors.append(self._make_color(0))
54             self._update_rgba(len(self._colors) - 1)
55
56     def _update_rgba(self, index):
57         color = self._colors[index]["rgb888"]
58         transparent = self._colors[index]["transparent"]
59         self._colors[index]["rgba"] = (
60             color >> 16,
61             (color >> 8) & 0xFF,
62             color & 0xFF,
63             0 if transparent else 0xFF,
64         )
65
66     def _make_color(self, value, transparent=False):
67         color = {
68             "transparent": transparent,
69             "rgb888": 0,
70             "rgba": (0, 0, 0, 255),
71         }
72         if isinstance(value, (tuple, list, bytes, bytearray)):
73             value = (value[0] & 0xFF) << 16 | (value[1] & 0xFF) << 8 | value[2] & 0xFF
74         elif isinstance(value, int):
75             if not 0 <= value <= 0xFFFFFF:
76                 raise ValueError("Color must be between 0x000000 and 0xFFFFFF")
77         else:
78             raise TypeError("Color buffer must be a buffer, tuple, list, or int")
79         color["rgb888"] = value
80         self._needs_refresh = True
81
82         return color
83
84     def __len__(self):
85         """Returns the number of colors in a Palette"""
86         return len(self._colors)
87
88     def __setitem__(self, index, value):
89         """Sets the pixel color at the given index. The index should be
90         an integer in the range 0 to color_count-1.
91
92         The value argument represents a color, and can be from 0x000000 to 0xFFFFFF
93         (to represent an RGB value). Value can be an int, bytes (3 bytes (RGB) or
94         4 bytes (RGB + pad byte)), bytearray, or a tuple or list of 3 integers.
95         """
96         if self._colors[index]["rgb888"] != value:
97             self._colors[index] = self._make_color(value)
98             self._update_rgba(index)
99
100     def __getitem__(self, index):
101         if not 0 <= index < len(self._colors):
102             raise ValueError("Palette index out of range")
103         return self._colors[index]
104
105     def make_transparent(self, palette_index):
106         """Set the palette index to be a transparent color"""
107         self._colors[palette_index]["transparent"] = True
108         self._update_rgba(palette_index)
109
110     def make_opaque(self, palette_index):
111         """Set the palette index to be an opaque color"""
112         self._colors[palette_index]["transparent"] = False
113         self._update_rgba(palette_index)
114
115     def _get_palette(self):
116         """Generate a palette for use with PIL"""
117         palette = []
118         for color in self._colors:
119             palette += color["rgba"][0:3]
120         return palette
121
122     def _get_alpha_palette(self):
123         """Generate an alpha channel palette with white being
124         opaque and black being transparent"""
125         palette = []
126         for color in self._colors:
127             for _ in range(3):
128                 palette += [0 if color["transparent"] else 255]
129         return palette