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