omnipython-palettes 0.0.1__tar.gz → 0.0.16.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. omnipython_palettes-0.0.16.dev3/LICENSE +21 -0
  2. omnipython_palettes-0.0.16.dev3/PKG-INFO +62 -0
  3. omnipython_palettes-0.0.16.dev3/README.md +49 -0
  4. omnipython_palettes-0.0.16.dev3/VERSION +1 -0
  5. omnipython_palettes-0.0.16.dev3/lib/omnipython_palettes.egg-info/PKG-INFO +62 -0
  6. omnipython_palettes-0.0.16.dev3/lib/omnipython_palettes.egg-info/SOURCES.txt +28 -0
  7. omnipython_palettes-0.0.16.dev3/lib/omnipython_palettes.egg-info/top_level.txt +1 -0
  8. omnipython_palettes-0.0.16.dev3/lib/palettes/__init__.py +358 -0
  9. omnipython_palettes-0.0.16.dev3/lib/palettes/__init__.pyi +50 -0
  10. omnipython_palettes-0.0.16.dev3/lib/palettes/_cube125.py +135 -0
  11. omnipython_palettes-0.0.16.dev3/lib/palettes/_cube27.py +39 -0
  12. omnipython_palettes-0.0.16.dev3/lib/palettes/_cube64.py +74 -0
  13. omnipython_palettes-0.0.16.dev3/lib/palettes/_cube8.py +16 -0
  14. omnipython_palettes-0.0.16.dev3/lib/palettes/_material_design.py +333 -0
  15. omnipython_palettes-0.0.16.dev3/lib/palettes/ansi.py +135 -0
  16. omnipython_palettes-0.0.16.dev3/lib/palettes/ansi.pyi +26 -0
  17. omnipython_palettes-0.0.16.dev3/lib/palettes/cube.py +76 -0
  18. omnipython_palettes-0.0.16.dev3/lib/palettes/cube.pyi +18 -0
  19. omnipython_palettes-0.0.16.dev3/lib/palettes/material_design.py +95 -0
  20. omnipython_palettes-0.0.16.dev3/lib/palettes/material_design.pyi +21 -0
  21. omnipython_palettes-0.0.16.dev3/lib/palettes/py.typed +0 -0
  22. omnipython_palettes-0.0.16.dev3/lib/palettes/wheel.py +134 -0
  23. omnipython_palettes-0.0.16.dev3/lib/palettes/wheel.pyi +20 -0
  24. omnipython_palettes-0.0.16.dev3/pyproject.toml +26 -0
  25. omnipython_palettes-0.0.16.dev3/tests/test_ansi.py +78 -0
  26. omnipython_palettes-0.0.16.dev3/tests/test_color_depth.py +79 -0
  27. omnipython_palettes-0.0.16.dev3/tests/test_import.py +38 -0
  28. omnipython_palettes-0.0.16.dev3/tests/test_name_order.py +83 -0
  29. omnipython_palettes-0.0.1/PKG-INFO +0 -19
  30. omnipython_palettes-0.0.1/README.md +0 -9
  31. omnipython_palettes-0.0.1/omnipython_palettes.egg-info/PKG-INFO +0 -19
  32. omnipython_palettes-0.0.1/omnipython_palettes.egg-info/SOURCES.txt +0 -6
  33. omnipython_palettes-0.0.1/omnipython_palettes.egg-info/top_level.txt +0 -1
  34. omnipython_palettes-0.0.1/pyproject.toml +0 -18
  35. {omnipython_palettes-0.0.1 → omnipython_palettes-0.0.16.dev3/lib}/omnipython_palettes.egg-info/dependency_links.txt +0 -0
  36. {omnipython_palettes-0.0.1 → omnipython_palettes-0.0.16.dev3}/setup.cfg +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Brad Barnett
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: omnipython-palettes
3
+ Version: 0.0.16.dev3
4
+ Summary: Pure-Python color palette toolkit for OmniPython
5
+ Author: Brad Barnett
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/PyDevices/omnipython/tree/main/palettes
8
+ Project-URL: Issues, https://github.com/PyDevices/omnipython/issues
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ ![A color wheel above the sixteen Windows colors and ten shades of Material amber](docs/images/palettes.png)
15
+
16
+ # palettes
17
+
18
+ palettes is the part of OmniPython that turns a palette index into a color a
19
+ display, LED or terminal can use: wheels, cubes, Material Design swatches and
20
+ the sixteen Windows names, with the same code on MicroPython-compatible boards,
21
+ CircuitPython-compatible boards and CPython. It has no dependencies.
22
+
23
+ ```bash
24
+ pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ omnipython-palettes
25
+ ```
26
+
27
+ ```python
28
+ import omip
29
+ omip.install("palettes")
30
+ ```
31
+
32
+ `omip` comes with OmniPython firmware. On other MicroPython firmware, run
33
+ `mip.install("github:PyDevices/omnipython/lib/omip.py")` once to put it on the board.
34
+
35
+ ```python
36
+ from palettes import get_palette
37
+
38
+ # A 360-step color wheel, ready to write to an RGB565 display
39
+ wheel = get_palette(name="wheel", length=360, color_depth=16)
40
+ print("red, green, blue as RGB565: 0x%04X 0x%04X 0x%04X" % (wheel[0], wheel[120], wheel[240]))
41
+
42
+ # Named colors, by attribute
43
+ win16 = get_palette(name="default", color_depth=24)
44
+ print("RED is 0x%06X, and its name back again is %r" % (win16.RED, win16.color_name(12)))
45
+
46
+ # Material Design, 0xRRGGBB
47
+ md = get_palette(name="material_design", color_depth=24)
48
+ print("Amber 500 is 0x%06X" % md.AMBER_S500)
49
+ ```
50
+
51
+ ```text
52
+ red, green, blue as RGB565: 0xF800 0x07E0 0x001F
53
+ RED is 0xFF0000, and its name back again is 'Red'
54
+ Amber 500 is 0xFFC107
55
+ ```
56
+
57
+ The picture at the top of this page is those three palettes drawn as bands: the
58
+ wheel, the sixteen Windows names and the Amber ramp.
59
+
60
+ [Docs](https://docs.omnipython.org/en/latest/palettes/) · [Examples](https://gallery.omnipython.org/pyscript/) · [Roadmap](ROADMAP.md)
61
+
62
+ OmniPython is made by [PyDevices](https://pydevices.com).
@@ -0,0 +1,49 @@
1
+ ![A color wheel above the sixteen Windows colors and ten shades of Material amber](docs/images/palettes.png)
2
+
3
+ # palettes
4
+
5
+ palettes is the part of OmniPython that turns a palette index into a color a
6
+ display, LED or terminal can use: wheels, cubes, Material Design swatches and
7
+ the sixteen Windows names, with the same code on MicroPython-compatible boards,
8
+ CircuitPython-compatible boards and CPython. It has no dependencies.
9
+
10
+ ```bash
11
+ pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ omnipython-palettes
12
+ ```
13
+
14
+ ```python
15
+ import omip
16
+ omip.install("palettes")
17
+ ```
18
+
19
+ `omip` comes with OmniPython firmware. On other MicroPython firmware, run
20
+ `mip.install("github:PyDevices/omnipython/lib/omip.py")` once to put it on the board.
21
+
22
+ ```python
23
+ from palettes import get_palette
24
+
25
+ # A 360-step color wheel, ready to write to an RGB565 display
26
+ wheel = get_palette(name="wheel", length=360, color_depth=16)
27
+ print("red, green, blue as RGB565: 0x%04X 0x%04X 0x%04X" % (wheel[0], wheel[120], wheel[240]))
28
+
29
+ # Named colors, by attribute
30
+ win16 = get_palette(name="default", color_depth=24)
31
+ print("RED is 0x%06X, and its name back again is %r" % (win16.RED, win16.color_name(12)))
32
+
33
+ # Material Design, 0xRRGGBB
34
+ md = get_palette(name="material_design", color_depth=24)
35
+ print("Amber 500 is 0x%06X" % md.AMBER_S500)
36
+ ```
37
+
38
+ ```text
39
+ red, green, blue as RGB565: 0xF800 0x07E0 0x001F
40
+ RED is 0xFF0000, and its name back again is 'Red'
41
+ Amber 500 is 0xFFC107
42
+ ```
43
+
44
+ The picture at the top of this page is those three palettes drawn as bands: the
45
+ wheel, the sixteen Windows names and the Amber ramp.
46
+
47
+ [Docs](https://docs.omnipython.org/en/latest/palettes/) · [Examples](https://gallery.omnipython.org/pyscript/) · [Roadmap](ROADMAP.md)
48
+
49
+ OmniPython is made by [PyDevices](https://pydevices.com).
@@ -0,0 +1 @@
1
+ 0.0.16.dev3
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: omnipython-palettes
3
+ Version: 0.0.16.dev3
4
+ Summary: Pure-Python color palette toolkit for OmniPython
5
+ Author: Brad Barnett
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/PyDevices/omnipython/tree/main/palettes
8
+ Project-URL: Issues, https://github.com/PyDevices/omnipython/issues
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ ![A color wheel above the sixteen Windows colors and ten shades of Material amber](docs/images/palettes.png)
15
+
16
+ # palettes
17
+
18
+ palettes is the part of OmniPython that turns a palette index into a color a
19
+ display, LED or terminal can use: wheels, cubes, Material Design swatches and
20
+ the sixteen Windows names, with the same code on MicroPython-compatible boards,
21
+ CircuitPython-compatible boards and CPython. It has no dependencies.
22
+
23
+ ```bash
24
+ pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ omnipython-palettes
25
+ ```
26
+
27
+ ```python
28
+ import omip
29
+ omip.install("palettes")
30
+ ```
31
+
32
+ `omip` comes with OmniPython firmware. On other MicroPython firmware, run
33
+ `mip.install("github:PyDevices/omnipython/lib/omip.py")` once to put it on the board.
34
+
35
+ ```python
36
+ from palettes import get_palette
37
+
38
+ # A 360-step color wheel, ready to write to an RGB565 display
39
+ wheel = get_palette(name="wheel", length=360, color_depth=16)
40
+ print("red, green, blue as RGB565: 0x%04X 0x%04X 0x%04X" % (wheel[0], wheel[120], wheel[240]))
41
+
42
+ # Named colors, by attribute
43
+ win16 = get_palette(name="default", color_depth=24)
44
+ print("RED is 0x%06X, and its name back again is %r" % (win16.RED, win16.color_name(12)))
45
+
46
+ # Material Design, 0xRRGGBB
47
+ md = get_palette(name="material_design", color_depth=24)
48
+ print("Amber 500 is 0x%06X" % md.AMBER_S500)
49
+ ```
50
+
51
+ ```text
52
+ red, green, blue as RGB565: 0xF800 0x07E0 0x001F
53
+ RED is 0xFF0000, and its name back again is 'Red'
54
+ Amber 500 is 0xFFC107
55
+ ```
56
+
57
+ The picture at the top of this page is those three palettes drawn as bands: the
58
+ wheel, the sixteen Windows names and the Amber ramp.
59
+
60
+ [Docs](https://docs.omnipython.org/en/latest/palettes/) · [Examples](https://gallery.omnipython.org/pyscript/) · [Roadmap](ROADMAP.md)
61
+
62
+ OmniPython is made by [PyDevices](https://pydevices.com).
@@ -0,0 +1,28 @@
1
+ LICENSE
2
+ README.md
3
+ VERSION
4
+ pyproject.toml
5
+ lib/omnipython_palettes.egg-info/PKG-INFO
6
+ lib/omnipython_palettes.egg-info/SOURCES.txt
7
+ lib/omnipython_palettes.egg-info/dependency_links.txt
8
+ lib/omnipython_palettes.egg-info/top_level.txt
9
+ lib/palettes/__init__.py
10
+ lib/palettes/__init__.pyi
11
+ lib/palettes/_cube125.py
12
+ lib/palettes/_cube27.py
13
+ lib/palettes/_cube64.py
14
+ lib/palettes/_cube8.py
15
+ lib/palettes/_material_design.py
16
+ lib/palettes/ansi.py
17
+ lib/palettes/ansi.pyi
18
+ lib/palettes/cube.py
19
+ lib/palettes/cube.pyi
20
+ lib/palettes/material_design.py
21
+ lib/palettes/material_design.pyi
22
+ lib/palettes/py.typed
23
+ lib/palettes/wheel.py
24
+ lib/palettes/wheel.pyi
25
+ tests/test_ansi.py
26
+ tests/test_color_depth.py
27
+ tests/test_import.py
28
+ tests/test_name_order.py
@@ -0,0 +1,358 @@
1
+ # SPDX-FileCopyrightText: 2024 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Color palette toolkit for PyDevices.
5
+
6
+ Use this package when a UI or graphics routine needs a predictable set of
7
+ colors rather than hard-coded values. The public API is small: call
8
+ `get_palette <palettes.get_palette>` to create a palette, then index it to get display-ready
9
+ colors for fills, gradients, labels, progress bars, and other visual states.
10
+
11
+ A common pattern is to create one palette per display or scene and reuse it
12
+ across multiple draw calls. For example, a 16-bit RGB565 display will usually
13
+ want ``color_depth=16`` and may also need ``swapped=True`` when the driver
14
+ expects byte-swapped colors.
15
+
16
+ Example:
17
+ >>> from palettes import get_palette
18
+ >>> palette = get_palette(name="wheel", length=256, saturation=1.0)
19
+ >>> palette[0]
20
+ >>> palette.color_name(0)
21
+
22
+ Attributes:
23
+ WIN16: Ordered ``(0xRRGGBB, name)`` pairs for the Windows 16 colors, the
24
+ default name table for `Palette <palettes.Palette>` and
25
+ `WheelPalette <palettes.wheel.WheelPalette>`. A pair's position is its palette
26
+ index. This is a tuple rather than a dict on purpose: MicroPython and
27
+ CircuitPython do not preserve dict insertion order, so a dict would
28
+ give a different index order on each interpreter.
29
+ """
30
+
31
+ __all__ = ["WIN16", "get_palette", "Palette", "MappedPalette"]
32
+
33
+ WIN16 = (
34
+ (0x000000, "Black"),
35
+ (0x000080, "Navy"),
36
+ (0x0000FF, "Blue"),
37
+ (0x008000, "Green"),
38
+ (0x008080, "Teal"),
39
+ (0x00FF00, "Lime"),
40
+ (0x00FFFF, "Cyan"),
41
+ (0x800000, "Maroon"),
42
+ (0x800080, "Purple"),
43
+ (0x808000, "Olive"),
44
+ (0x808080, "Grey"),
45
+ (0xC0C0C0, "Silver"),
46
+ (0xFF0000, "Red"),
47
+ (0xFF00FF, "Magenta"),
48
+ (0xFFFF00, "Yellow"),
49
+ (0xFFFFFF, "White"),
50
+ )
51
+
52
+
53
+ def get_palette(name="default", **kwargs):
54
+ """Construct a palette by logical name.
55
+
56
+ This is the easiest entry point for most applications. Select a palette
57
+ family once, then reuse the returned object as a color source across the
58
+ rest of the UI.
59
+
60
+ Args:
61
+ name (str): Palette type. One of ``"default"`` (Windows 16-color),
62
+ ``"wheel"``, ``"cube"``, ``"material_design"`` or ``"ansi"``. Unknown names
63
+ fall back to `Palette <palettes.Palette>`.
64
+ **kwargs (Any): Forwarded to the palette constructor (for example
65
+ ``color_depth``, ``length``, ``size``, ``saturation``, and
66
+ ``swapped``).
67
+
68
+ Returns:
69
+ Palette: A `Palette <palettes.Palette>` subclass instance.
70
+
71
+ Example:
72
+ >>> pal = get_palette(name="cube", size=3, color_depth=16)
73
+ >>> color = pal[12]
74
+ """
75
+ if name == "wheel":
76
+ from .wheel import WheelPalette as MyPalette
77
+ elif name == "material_design":
78
+ from .material_design import MDPalette as MyPalette
79
+ elif name == "cube":
80
+ from .cube import CubePalette as MyPalette
81
+ elif name == "ansi":
82
+ from .ansi import AnsiPalette as MyPalette
83
+ else:
84
+ MyPalette = Palette
85
+ return MyPalette(name, **kwargs)
86
+
87
+
88
+ class Palette:
89
+ """Indexed color palette with optional named color attributes.
90
+
91
+ Subclasses override `_get_rgb` to define how each index maps to red,
92
+ green, and blue components. The resulting color can then be used for fills,
93
+ gradients, status indicators, and other display operations. A subclass may
94
+ also set ``_names`` to its own ordered sequence of ``(0xRRGGBB, name)``
95
+ pairs before calling ``__init__``; pair position is palette index.
96
+
97
+ In practice, applications usually create one palette for a screen or view and
98
+ then reuse it for many draw calls rather than generating colors inline. Named
99
+ colors from the palette's name table (for example ``palette.RED``) are
100
+ attached as attributes during initialization.
101
+
102
+ Args:
103
+ name (str): Optional label stored in `name`.
104
+ color_depth (int): Output format for `__getitem__`: `4` (the palette
105
+ index itself, for 4-bit indexed/grayscale framebuffers), `8`
106
+ (RGB332), `16` (RGB565), or `24` (`0xRRGGBB`).
107
+ swapped (bool): If ``True``, byte-swap 16-bit colors (little-endian displays).
108
+ cached (bool): If ``True``, memoize computed index colors in an internal dict.
109
+ """
110
+
111
+ def __init__(self, name="", color_depth=16, swapped=False, cached=False):
112
+ """Create a palette from the default Windows 16-color name table.
113
+
114
+ Args:
115
+ name (str): Optional label stored in `name`.
116
+ color_depth (int): Output format for `__getitem__`: ``4``, ``8``,
117
+ ``16``, or ``24``.
118
+ swapped (bool): If ``True``, byte-swap 16-bit colors.
119
+ cached (bool): If ``True``, memoize computed index colors.
120
+ """
121
+ self._name = name
122
+ self._color_depth = color_depth
123
+ self._swapped = swapped
124
+ self._cache = {} if cached else None
125
+
126
+ if not hasattr(self, "_names"):
127
+ self._names = WIN16
128
+ if not hasattr(self, "_length"):
129
+ self._length = len(self._names)
130
+ # Reverse lookup for rgb_name(); index order is still defined by _names.
131
+ self._names_by_value = dict(self._names)
132
+
133
+ self._define_named_colors()
134
+
135
+ def _define_named_colors(self):
136
+ for index, (color, name) in enumerate(self._names):
137
+ if self._color_depth == 16:
138
+ color = self.color565(color)
139
+ elif self._color_depth == 8:
140
+ color = self.color332(color)
141
+ elif self._color_depth == 4:
142
+ color = index
143
+ setattr(self, name.replace(" ", "_").upper(), color)
144
+
145
+ @property
146
+ def name(self):
147
+ """Human-readable palette label."""
148
+ return self._name
149
+
150
+ def __iter__(self):
151
+ """Yield each palette entry in index order."""
152
+ for i in range(len(self)):
153
+ yield self[i]
154
+
155
+ def __len__(self):
156
+ """Number of colors in the palette."""
157
+ return self._length
158
+
159
+ def __getitem__(self, index):
160
+ """Return the color at ``index`` in the configured bit depth.
161
+
162
+ Negative indices and indices beyond the palette length wrap around.
163
+
164
+ Args:
165
+ index (int): Color index (supports negative and out-of-range values).
166
+
167
+ Returns:
168
+ int: Color value (format depends on ``color_depth``).
169
+
170
+ Raises:
171
+ ValueError: If ``color_depth`` is not 4, 8, 16, or 24.
172
+ """
173
+ index = self._normalize(index)
174
+
175
+ # At depth 4 the index *is* the value: a GS4 framebuffer stores a
176
+ # nibble per pixel, and the named attributes have always returned the
177
+ # index (see _define_named_colors). Returning packed RGB here made the
178
+ # two halves of the surface disagree -- and pdwidgets passes a driver's
179
+ # color_depth straight through, so an ssd1327 got a 24-bit value where
180
+ # a nibble belongs.
181
+ if self._color_depth == 4:
182
+ return index
183
+
184
+ if self._cache is not None and index in self._cache:
185
+ return self._cache[index]
186
+
187
+ r, g, b = self._get_rgb(index)
188
+ if self._color_depth == 24:
189
+ return r << 16 | g << 8 | b
190
+ elif self._color_depth == 16:
191
+ return self.color565(r, g, b)
192
+ elif self._color_depth == 8:
193
+ return self.color332(r, g, b)
194
+ raise ValueError("Invalid color depth")
195
+
196
+ def _normalize(self, index):
197
+ while index < 0:
198
+ index += len(self)
199
+ if index >= len(self):
200
+ index %= len(self)
201
+ return index
202
+
203
+ def color565(self, r, g=None, b=None):
204
+ """Convert RGB to a 16-bit RGB565 value.
205
+
206
+ Args:
207
+ r (int): Red component (0–255), a 24-bit ``0xRRGGBB`` integer, or an
208
+ ``(r, g, b)`` sequence.
209
+ g (int): Green component when ``r`` is passed separately.
210
+ b (int): Blue component when ``r`` is passed separately.
211
+
212
+ Returns:
213
+ int: 16-bit color, optionally byte-swapped when ``swapped`` is ``True``.
214
+ """
215
+ if isinstance(r, (tuple, list)):
216
+ # r is a tuple or list
217
+ r, g, b = r
218
+ elif g is None:
219
+ # r is a 24-bit color
220
+ r, g, b = r >> 16 & 0xFF, r >> 8 & 0xFF, r & 0xFF
221
+
222
+ color = (r & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3
223
+ if self._swapped:
224
+ return (color & 0xFF) << 8 | (color & 0xFF00) >> 8
225
+ else:
226
+ return color
227
+
228
+ def color332(self, r, g=None, b=None):
229
+ """Convert RGB to an 8-bit RGB332 value.
230
+
231
+ Args:
232
+ r (int): Red component (0–255), a 24-bit ``0xRRGGBB`` integer, or an
233
+ ``(r, g, b)`` sequence.
234
+ g (int): Green component when ``r`` is passed separately.
235
+ b (int): Blue component when ``r`` is passed separately.
236
+
237
+ Returns:
238
+ int: 8-bit RGB332 color.
239
+ """
240
+ # Convert r, g, b to 8-bit
241
+ if isinstance(r, (tuple, list)):
242
+ # r is a tuple or list
243
+ r, g, b = r
244
+ elif g is None:
245
+ # r is a 24-bit color
246
+ r, g, b = r >> 16 & 0xFF, r >> 8 & 0xFF, r & 0xFF
247
+
248
+ color = (r & 0xE0) | (g & 0xE0) >> 3 | (b & 0xC0) >> 6
249
+ return color
250
+
251
+ def color_rgb(self, color):
252
+ """Expand a packed color to an ``(r, g, b)`` tuple.
253
+
254
+ Args:
255
+ color (int): A 16-bit integer, or a 2- or 3-byte sequence in display
256
+ byte order.
257
+
258
+ Returns:
259
+ tuple: ``(red, green, blue)`` with each component in ``0``–``255``.
260
+ """
261
+ if isinstance(color, int):
262
+ # convert 16-bit int color to 2 bytes
263
+ color = (color & 0xFF, color >> 8)
264
+ if len(color) == 2:
265
+ r = color[1] & 0xF8 | (color[1] >> 5) & 0x7 # 5 bit to 8 bit red
266
+ g = color[1] << 5 & 0xE0 | (color[0] >> 3) & 0x1F # 6 bit to 8 bit green
267
+ b = color[0] << 3 & 0xF8 | (color[0] >> 2) & 0x7 # 5 bit to 8 bit blue
268
+ else:
269
+ r, g, b = color
270
+ return (r, g, b)
271
+
272
+ def color_name(self, index):
273
+ """Return the name of the color at ``index``.
274
+
275
+ Args:
276
+ index (int): Palette index (supports wrapping).
277
+
278
+ Returns:
279
+ str: A name from the palette name table, or a ``"#RRGGBB"`` hex
280
+ string when no name matches.
281
+ """
282
+ return self.rgb_name(self._get_rgb(self._normalize(index)))
283
+
284
+ def rgb_name(self, r, g=None, b=None):
285
+ """Look up a color name from RGB components.
286
+
287
+ Args:
288
+ r (int): Red (0–255), a 24-bit integer, or an ``(r, g, b)`` sequence.
289
+ g (int): Green when ``r`` is passed separately.
290
+ b (int): Blue when ``r`` is passed separately.
291
+
292
+ Returns:
293
+ str: Matching name from `_names`, or ``"#RRGGBB"`` if unknown.
294
+ """
295
+ if isinstance(r, (tuple, list)):
296
+ r, g, b = r
297
+ value = r << 16 | g << 8 | b
298
+ return self._names_by_value.get(value, f"#{r:02X}{g:02X}{b:02X}")
299
+
300
+ def luminance(self, index):
301
+ """Perceived brightness of the color at ``index`` (ITU-R BT.601).
302
+
303
+ Args:
304
+ index (int): Palette index.
305
+
306
+ Returns:
307
+ float: Luminance in ``0.0``–``255.0``.
308
+ """
309
+ r, g, b = self._get_rgb(index)
310
+ return 0.299 * r + 0.587 * g + 0.114 * b
311
+
312
+ def brightness(self, index):
313
+ """Average channel brightness of the color at ``index``.
314
+
315
+ Args:
316
+ index (int): Palette index.
317
+
318
+ Returns:
319
+ float: Normalized brightness in ``0.0``–``1.0``.
320
+ """
321
+ r, g, b = self._get_rgb(index)
322
+ return (r + g + b) / 3 / 255
323
+
324
+ def _get_rgb(self, index):
325
+ color = self._names[index][0]
326
+ return color >> 16 & 0xFF, color >> 8 & 0xFF, color & 0xFF
327
+
328
+
329
+ class MappedPalette(Palette):
330
+ """Palette backed by a flat RGB byte map.
331
+
332
+ Each color occupies three consecutive bytes ``(r, g, b)`` in
333
+ ``color_map``. Subclasses such as `MDPalette <palettes.material_design.MDPalette>`
334
+ supply a pre-built map and named-color attributes.
335
+
336
+ Args:
337
+ name (str): Optional label stored in `name`.
338
+ color_depth (int): Output format for `Palette.__getitem__`.
339
+ swapped (bool): Byte-swap 16-bit colors when ``True``.
340
+ color_map (bytes): ``bytes`` or buffer of RGB triplets, length ``3 * n_colors``.
341
+ """
342
+
343
+ def __init__(self, name, color_depth, swapped, color_map):
344
+ """Create a palette from a flat RGB byte map.
345
+
346
+ Args:
347
+ name (str): Optional label stored in `name`.
348
+ color_depth (int): Output format for `Palette.__getitem__`.
349
+ swapped (bool): Byte-swap 16-bit colors when ``True``.
350
+ color_map (bytes): ``bytes`` or buffer of RGB triplets.
351
+ """
352
+ self._color_map = color_map
353
+ self._length = len(color_map) // 3
354
+ super().__init__(name, color_depth, swapped)
355
+
356
+ def _get_rgb(self, index):
357
+ r, g, b = self._color_map[index * 3 : index * 3 + 3]
358
+ return r, g, b
@@ -0,0 +1,50 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Color palette toolkit for PyDevices."""
5
+
6
+ from collections.abc import Iterator, Sequence
7
+ from typing import Any
8
+
9
+ __all__ = ["WIN16", "get_palette", "Palette", "MappedPalette"]
10
+
11
+ WIN16: tuple[tuple[int, str], ...]
12
+
13
+ def get_palette(name: str = "default", **kwargs: Any) -> Palette:
14
+ """Construct a palette by name: `default`, `wheel`, `cube`, `material_design` or `ansi`."""
15
+
16
+ class Palette:
17
+ """Indexed color palette with optional named color attributes."""
18
+
19
+ def __init__(
20
+ self, name: str = "", color_depth: int = 16, swapped: bool = False, cached: bool = False
21
+ ) -> None: ...
22
+ @property
23
+ def name(self) -> str: ...
24
+ def __iter__(self) -> Iterator[int]: ...
25
+ def __len__(self) -> int: ...
26
+ def __getitem__(self, index: int) -> int: ...
27
+ def color565(
28
+ self, r: int | Sequence[int], g: int | None = None, b: int | None = None
29
+ ) -> int: ...
30
+ def color332(
31
+ self, r: int | Sequence[int], g: int | None = None, b: int | None = None
32
+ ) -> int: ...
33
+ def color_rgb(self, color: int | bytes | bytearray | Sequence[int]) -> tuple[int, int, int]: ...
34
+ def color_name(self, index: int) -> str: ...
35
+ def rgb_name(
36
+ self, r: int | Sequence[int], g: int | None = None, b: int | None = None
37
+ ) -> str: ...
38
+ def luminance(self, index: int) -> float: ...
39
+ def brightness(self, index: int) -> float: ...
40
+
41
+ class MappedPalette(Palette):
42
+ """Palette backed by a flat RGB byte map."""
43
+
44
+ def __init__(
45
+ self,
46
+ name: str,
47
+ color_depth: int,
48
+ swapped: bool,
49
+ color_map: bytes | bytearray | memoryview,
50
+ ) -> None: ...