dynamic-icon-engine 1.0.0__py3-none-any.whl
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.
- dynamic_icon_engine/__init__.py +37 -0
- dynamic_icon_engine/_version.py +1 -0
- dynamic_icon_engine/animation.py +247 -0
- dynamic_icon_engine/appearance.py +77 -0
- dynamic_icon_engine/controller.py +266 -0
- dynamic_icon_engine/errors.py +34 -0
- dynamic_icon_engine/graphic_set.py +436 -0
- dynamic_icon_engine/renderer.py +228 -0
- dynamic_icon_engine/resources/__init__.py +0 -0
- dynamic_icon_engine/resources/default/manifest.json +84 -0
- dynamic_icon_engine/resources/default/symbol.png +0 -0
- dynamic_icon_engine/resources/default/symbol_16.png +0 -0
- dynamic_icon_engine/resources/default/symbol_20.png +0 -0
- dynamic_icon_engine/resources/default/symbol_24.png +0 -0
- dynamic_icon_engine/resources/default/symbol_32.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_16.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_20.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_24.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_32.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_clearance.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_clearance_16.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_clearance_20.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_clearance_24.png +0 -0
- dynamic_icon_engine/resources/default/symbol_ext_clearance_32.png +0 -0
- dynamic_icon_engine/testlab/__init__.py +4 -0
- dynamic_icon_engine/testlab/__main__.py +87 -0
- dynamic_icon_engine/testlab/palette.py +96 -0
- dynamic_icon_engine/testlab/window.py +417 -0
- dynamic_icon_engine-1.0.0.dist-info/METADATA +176 -0
- dynamic_icon_engine-1.0.0.dist-info/RECORD +35 -0
- dynamic_icon_engine-1.0.0.dist-info/WHEEL +5 -0
- dynamic_icon_engine-1.0.0.dist-info/entry_points.txt +2 -0
- dynamic_icon_engine-1.0.0.dist-info/licenses/LICENSE +21 -0
- dynamic_icon_engine-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"""Exchangeable graphic sets: neutral alpha masks for ``symbol`` and ``symbol_ext``.
|
|
2
|
+
|
|
3
|
+
A graphic set consists of alpha masks only - colours are applied by the
|
|
4
|
+
renderer. Layers:
|
|
5
|
+
|
|
6
|
+
``symbol``
|
|
7
|
+
Main symbol (required).
|
|
8
|
+
``symbol_ext``
|
|
9
|
+
Optional additional layer, drawn in the symbol colour when
|
|
10
|
+
``IconAppearance.symbol_ext`` is true.
|
|
11
|
+
``symbol_ext_clearance``
|
|
12
|
+
Optional mask that is cut out of ``symbol`` while ``symbol_ext`` is shown,
|
|
13
|
+
so both shapes stay separable although they share one colour.
|
|
14
|
+
|
|
15
|
+
All master masks of a set must have identical pixel dimensions. Symbol and
|
|
16
|
+
extension are scaled together, based on their *common* alpha bounding box,
|
|
17
|
+
proportionally and centred into the icon square minus a safety margin. The
|
|
18
|
+
background is never part of a graphic set; the renderer generates it.
|
|
19
|
+
|
|
20
|
+
Optionally a set provides hand-tuned masks for exact pixel sizes (``sizes`` in
|
|
21
|
+
the manifest). Such masks are used unchanged and must already contain the
|
|
22
|
+
final placement inside the ``size x size`` square.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
from collections import OrderedDict
|
|
31
|
+
from importlib import resources
|
|
32
|
+
from pathlib import Path, PurePosixPath
|
|
33
|
+
from typing import Any, Mapping, Protocol
|
|
34
|
+
|
|
35
|
+
from PySide6.QtCore import QPoint, QRect, Qt
|
|
36
|
+
from PySide6.QtGui import QColor, QImage, QPainter
|
|
37
|
+
|
|
38
|
+
from .errors import GraphicSetError
|
|
39
|
+
|
|
40
|
+
LAYER_SYMBOL = "symbol"
|
|
41
|
+
LAYER_SYMBOL_EXT = "symbol_ext"
|
|
42
|
+
LAYER_SYMBOL_EXT_CLEARANCE = "symbol_ext_clearance"
|
|
43
|
+
LAYERS = (LAYER_SYMBOL, LAYER_SYMBOL_EXT, LAYER_SYMBOL_EXT_CLEARANCE)
|
|
44
|
+
|
|
45
|
+
MANIFEST_FILE = "manifest.json"
|
|
46
|
+
MANIFEST_FORMAT = "dynamic-icon-engine.graphic-set"
|
|
47
|
+
MANIFEST_FORMAT_VERSION = 1
|
|
48
|
+
|
|
49
|
+
#: Safety margin per side as fraction of the icon size (1 px at 16 px).
|
|
50
|
+
DEFAULT_SAFETY_MARGIN = 1.0 / 16.0
|
|
51
|
+
MAX_SAFETY_MARGIN = 0.25
|
|
52
|
+
|
|
53
|
+
_MASK_FORMAT = QImage.Format.Format_ARGB32_Premultiplied
|
|
54
|
+
_MASK_CACHE_LIMIT = 64
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _Readable(Protocol): # pathlib.Path and importlib.resources Traversable
|
|
58
|
+
def joinpath(self, *parts: str) -> Any: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def safety_margin_px(size: int, safety_margin: float) -> int:
|
|
62
|
+
"""Margin in whole pixels per side for an icon of ``size`` pixels."""
|
|
63
|
+
if safety_margin <= 0:
|
|
64
|
+
return 0
|
|
65
|
+
return max(1, int(size * safety_margin + 0.5))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def alpha_bounds(image: QImage) -> QRect | None:
|
|
69
|
+
"""Bounding box of all pixels with alpha > 0 (``None`` if fully transparent)."""
|
|
70
|
+
alpha = image.convertToFormat(QImage.Format.Format_Alpha8)
|
|
71
|
+
width, height, bpl = alpha.width(), alpha.height(), alpha.bytesPerLine()
|
|
72
|
+
data = bytes(alpha.constBits())
|
|
73
|
+
top = bottom = -1
|
|
74
|
+
left, right = width, -1
|
|
75
|
+
for y in range(height):
|
|
76
|
+
row = data[y * bpl: y * bpl + width]
|
|
77
|
+
stripped_left = row.lstrip(b"\x00")
|
|
78
|
+
if not stripped_left:
|
|
79
|
+
continue
|
|
80
|
+
if top < 0:
|
|
81
|
+
top = y
|
|
82
|
+
bottom = y
|
|
83
|
+
left = min(left, width - len(stripped_left))
|
|
84
|
+
right = max(right, len(row.rstrip(b"\x00")) - 1)
|
|
85
|
+
if top < 0:
|
|
86
|
+
return None
|
|
87
|
+
return QRect(left, top, right - left + 1, bottom - top + 1)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def alpha_values(image: QImage) -> bytes:
|
|
91
|
+
"""Row-major alpha bytes (``width * height``) of ``image``."""
|
|
92
|
+
alpha = image.convertToFormat(QImage.Format.Format_Alpha8)
|
|
93
|
+
width, bpl = alpha.width(), alpha.bytesPerLine()
|
|
94
|
+
data = bytes(alpha.constBits())
|
|
95
|
+
return b"".join(data[y * bpl: y * bpl + width] for y in range(alpha.height()))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _to_mask(image: QImage, label: str) -> QImage:
|
|
99
|
+
"""Copy of ``image`` reduced to its alpha channel (white, premultiplied)."""
|
|
100
|
+
if not isinstance(image, QImage):
|
|
101
|
+
raise GraphicSetError(f"{label}: QImage erwartet, erhalten: {type(image).__name__}")
|
|
102
|
+
if image.isNull():
|
|
103
|
+
raise GraphicSetError(f"{label}: Bild ist leer oder konnte nicht dekodiert werden")
|
|
104
|
+
if not image.hasAlphaChannel():
|
|
105
|
+
raise GraphicSetError(f"{label}: Bild hat keinen Alphakanal (benötigt wird eine Alpha-Maske)")
|
|
106
|
+
mask = QImage(image.size(), _MASK_FORMAT)
|
|
107
|
+
if mask.isNull():
|
|
108
|
+
raise GraphicSetError(f"{label}: Maske konnte nicht angelegt werden")
|
|
109
|
+
mask.fill(QColor(255, 255, 255, 255))
|
|
110
|
+
painter = QPainter(mask)
|
|
111
|
+
try:
|
|
112
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
|
|
113
|
+
painter.drawImage(0, 0, image)
|
|
114
|
+
finally:
|
|
115
|
+
painter.end()
|
|
116
|
+
return mask
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _square_crop(mask: QImage, bounds: QRect) -> QImage:
|
|
120
|
+
"""Square image (side = max(bounds w, h)) with ``bounds`` centred in it."""
|
|
121
|
+
side = max(bounds.width(), bounds.height())
|
|
122
|
+
x0 = bounds.x() + (bounds.width() - side) // 2
|
|
123
|
+
y0 = bounds.y() + (bounds.height() - side) // 2
|
|
124
|
+
square = QImage(side, side, _MASK_FORMAT)
|
|
125
|
+
if square.isNull():
|
|
126
|
+
raise GraphicSetError("Quadratischer Maskenzuschnitt konnte nicht angelegt werden")
|
|
127
|
+
square.fill(Qt.GlobalColor.transparent)
|
|
128
|
+
painter = QPainter(square)
|
|
129
|
+
try:
|
|
130
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source)
|
|
131
|
+
painter.drawImage(QPoint(-x0, -y0), mask)
|
|
132
|
+
finally:
|
|
133
|
+
painter.end()
|
|
134
|
+
return square
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def place_mask(normalized: QImage, size: int, safety_margin: float) -> QImage:
|
|
138
|
+
"""Scale a normalized square mask once into a ``size x size`` icon mask."""
|
|
139
|
+
margin = safety_margin_px(size, safety_margin)
|
|
140
|
+
content = size - 2 * margin
|
|
141
|
+
if content < 1:
|
|
142
|
+
raise GraphicSetError(f"Icongröße {size} px ist für den Sicherheitsabstand zu klein")
|
|
143
|
+
scaled = normalized.scaled(
|
|
144
|
+
content, content,
|
|
145
|
+
Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation,
|
|
146
|
+
).convertToFormat(_MASK_FORMAT)
|
|
147
|
+
if scaled.isNull():
|
|
148
|
+
raise GraphicSetError(f"Maske für {size} px konnte nicht skaliert werden")
|
|
149
|
+
result = QImage(size, size, _MASK_FORMAT)
|
|
150
|
+
if result.isNull():
|
|
151
|
+
raise GraphicSetError(f"Maske für {size} px konnte nicht angelegt werden")
|
|
152
|
+
result.fill(Qt.GlobalColor.transparent)
|
|
153
|
+
painter = QPainter(result)
|
|
154
|
+
try:
|
|
155
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source)
|
|
156
|
+
painter.drawImage(margin, margin, scaled)
|
|
157
|
+
finally:
|
|
158
|
+
painter.end()
|
|
159
|
+
return result
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class GraphicSet:
|
|
163
|
+
"""Validated, renderer-ready set of alpha masks.
|
|
164
|
+
|
|
165
|
+
Construct it from :class:`QImage` objects (masks with alpha channel) or via
|
|
166
|
+
:meth:`load` / :meth:`load_default`. Instances are immutable from the
|
|
167
|
+
outside; computed per-size masks are cached (bounded).
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(
|
|
171
|
+
self,
|
|
172
|
+
symbol: QImage,
|
|
173
|
+
symbol_ext: QImage | None = None,
|
|
174
|
+
symbol_ext_clearance: QImage | None = None,
|
|
175
|
+
*,
|
|
176
|
+
name: str = "custom",
|
|
177
|
+
safety_margin: float = DEFAULT_SAFETY_MARGIN,
|
|
178
|
+
size_masks: Mapping[str, Mapping[int, QImage]] | None = None,
|
|
179
|
+
description: str = "",
|
|
180
|
+
) -> None:
|
|
181
|
+
if not isinstance(safety_margin, (int, float)) or isinstance(safety_margin, bool) \
|
|
182
|
+
or not math.isfinite(safety_margin) or not 0 <= safety_margin < MAX_SAFETY_MARGIN:
|
|
183
|
+
raise GraphicSetError(
|
|
184
|
+
f"safety_margin muss eine Zahl in [0, {MAX_SAFETY_MARGIN}) sein, erhalten: {safety_margin!r}"
|
|
185
|
+
)
|
|
186
|
+
if symbol_ext_clearance is not None and symbol_ext is None:
|
|
187
|
+
raise GraphicSetError("symbol_ext_clearance ist nur zusammen mit symbol_ext erlaubt")
|
|
188
|
+
if symbol is None:
|
|
189
|
+
raise GraphicSetError("Ebene 'symbol': QImage erwartet, erhalten: NoneType")
|
|
190
|
+
self._name = str(name)
|
|
191
|
+
self._description = str(description)
|
|
192
|
+
self._safety_margin = float(safety_margin)
|
|
193
|
+
|
|
194
|
+
raw = {LAYER_SYMBOL: symbol, LAYER_SYMBOL_EXT: symbol_ext,
|
|
195
|
+
LAYER_SYMBOL_EXT_CLEARANCE: symbol_ext_clearance}
|
|
196
|
+
masks = {layer: _to_mask(img, f"Ebene '{layer}'") for layer, img in raw.items() if img is not None}
|
|
197
|
+
source_size = masks[LAYER_SYMBOL].size()
|
|
198
|
+
for layer, mask in masks.items():
|
|
199
|
+
if mask.size() != source_size:
|
|
200
|
+
raise GraphicSetError(
|
|
201
|
+
f"Ebene '{layer}' hat {mask.width()}x{mask.height()} px, erwartet "
|
|
202
|
+
f"{source_size.width()}x{source_size.height()} px wie 'symbol'"
|
|
203
|
+
)
|
|
204
|
+
symbol_bounds = alpha_bounds(masks[LAYER_SYMBOL])
|
|
205
|
+
if symbol_bounds is None:
|
|
206
|
+
raise GraphicSetError("Ebene 'symbol' ist vollständig transparent")
|
|
207
|
+
union = QRect(symbol_bounds)
|
|
208
|
+
if LAYER_SYMBOL_EXT in masks:
|
|
209
|
+
ext_bounds = alpha_bounds(masks[LAYER_SYMBOL_EXT])
|
|
210
|
+
if ext_bounds is None:
|
|
211
|
+
raise GraphicSetError("Ebene 'symbol_ext' ist vollständig transparent")
|
|
212
|
+
union = union.united(ext_bounds)
|
|
213
|
+
# Clearance is a cut-out helper; it does not influence the geometry.
|
|
214
|
+
self._source_size = (source_size.width(), source_size.height())
|
|
215
|
+
self._content_bounds = (union.x(), union.y(), union.width(), union.height())
|
|
216
|
+
self._normalized = {layer: _square_crop(mask, union) for layer, mask in masks.items()}
|
|
217
|
+
|
|
218
|
+
self._size_masks: dict[tuple[str, int], QImage] = {}
|
|
219
|
+
for layer, by_size in (size_masks or {}).items():
|
|
220
|
+
if layer not in self._normalized:
|
|
221
|
+
raise GraphicSetError(f"Größenspezifische Maske für unbekannte/fehlende Ebene '{layer}'")
|
|
222
|
+
for size, image in by_size.items():
|
|
223
|
+
if not isinstance(size, int) or isinstance(size, bool) or size < 1:
|
|
224
|
+
raise GraphicSetError(f"Ungültige Maskengröße {size!r} für Ebene '{layer}'")
|
|
225
|
+
mask = _to_mask(image, f"Ebene '{layer}' ({size} px)")
|
|
226
|
+
if mask.width() != size or mask.height() != size:
|
|
227
|
+
raise GraphicSetError(
|
|
228
|
+
f"Maske für Ebene '{layer}' ({size} px) hat {mask.width()}x{mask.height()} px"
|
|
229
|
+
)
|
|
230
|
+
self._size_masks[(layer, size)] = mask
|
|
231
|
+
self._cache: OrderedDict[tuple[str, int, bool], QImage] = OrderedDict()
|
|
232
|
+
|
|
233
|
+
# -- properties -------------------------------------------------------
|
|
234
|
+
@property
|
|
235
|
+
def name(self) -> str:
|
|
236
|
+
return self._name
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def description(self) -> str:
|
|
240
|
+
return self._description
|
|
241
|
+
|
|
242
|
+
@property
|
|
243
|
+
def has_symbol_ext(self) -> bool:
|
|
244
|
+
return LAYER_SYMBOL_EXT in self._normalized
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def has_symbol_ext_clearance(self) -> bool:
|
|
248
|
+
return LAYER_SYMBOL_EXT_CLEARANCE in self._normalized
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def safety_margin(self) -> float:
|
|
252
|
+
return self._safety_margin
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def source_size(self) -> tuple[int, int]:
|
|
256
|
+
"""Pixel size of the master masks."""
|
|
257
|
+
return self._source_size
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def content_bounds(self) -> tuple[int, int, int, int]:
|
|
261
|
+
"""Common alpha bounding box ``(x, y, w, h)`` of symbol and extension in the masters."""
|
|
262
|
+
return self._content_bounds
|
|
263
|
+
|
|
264
|
+
def tuned_sizes(self, layer: str = LAYER_SYMBOL) -> tuple[int, ...]:
|
|
265
|
+
"""Pixel sizes for which the set provides hand-tuned masks of ``layer``."""
|
|
266
|
+
return tuple(sorted(size for (name, size) in self._size_masks if name == layer))
|
|
267
|
+
|
|
268
|
+
# -- masks ------------------------------------------------------------
|
|
269
|
+
def _remember(self, key: tuple[str, int, bool], image: QImage) -> QImage:
|
|
270
|
+
self._cache[key] = image
|
|
271
|
+
self._cache.move_to_end(key)
|
|
272
|
+
while len(self._cache) > _MASK_CACHE_LIMIT:
|
|
273
|
+
self._cache.popitem(last=False)
|
|
274
|
+
return image
|
|
275
|
+
|
|
276
|
+
def layer_mask(self, layer: str, size: int) -> QImage:
|
|
277
|
+
"""Alpha mask of one layer at ``size x size`` px (ARGB32 premultiplied, white)."""
|
|
278
|
+
if layer not in self._normalized:
|
|
279
|
+
raise GraphicSetError(f"Grafikset '{self._name}' enthält keine Ebene '{layer}'")
|
|
280
|
+
if not isinstance(size, int) or isinstance(size, bool) or size < 1:
|
|
281
|
+
raise GraphicSetError(f"Ungültige Icongröße: {size!r}")
|
|
282
|
+
key = (layer, size, False)
|
|
283
|
+
cached = self._cache.get(key)
|
|
284
|
+
if cached is not None:
|
|
285
|
+
self._cache.move_to_end(key)
|
|
286
|
+
return cached
|
|
287
|
+
tuned = self._size_masks.get((layer, size))
|
|
288
|
+
mask = tuned if tuned is not None else place_mask(self._normalized[layer], size, self._safety_margin)
|
|
289
|
+
return self._remember(key, mask)
|
|
290
|
+
|
|
291
|
+
def foreground_mask(self, size: int, symbol_ext: bool) -> QImage:
|
|
292
|
+
"""Combined alpha mask of everything drawn in the symbol colour.
|
|
293
|
+
|
|
294
|
+
Without extension this is the symbol mask. With extension the clearance
|
|
295
|
+
mask is cut out of the symbol and the extension is added on top.
|
|
296
|
+
"""
|
|
297
|
+
if symbol_ext and not self.has_symbol_ext:
|
|
298
|
+
raise GraphicSetError(f"Grafikset '{self._name}' enthält keine Ebene 'symbol_ext'")
|
|
299
|
+
if not symbol_ext:
|
|
300
|
+
return self.layer_mask(LAYER_SYMBOL, size)
|
|
301
|
+
key = ("<foreground>", size, True)
|
|
302
|
+
cached = self._cache.get(key)
|
|
303
|
+
if cached is not None:
|
|
304
|
+
self._cache.move_to_end(key)
|
|
305
|
+
return cached
|
|
306
|
+
combined = self.layer_mask(LAYER_SYMBOL, size).copy()
|
|
307
|
+
if combined.isNull():
|
|
308
|
+
raise GraphicSetError(f"Vordergrundmaske für {size} px konnte nicht angelegt werden")
|
|
309
|
+
clearance = self.layer_mask(LAYER_SYMBOL_EXT_CLEARANCE, size) if self.has_symbol_ext_clearance else None
|
|
310
|
+
extension = self.layer_mask(LAYER_SYMBOL_EXT, size)
|
|
311
|
+
painter = QPainter(combined)
|
|
312
|
+
try:
|
|
313
|
+
if clearance is not None:
|
|
314
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationOut)
|
|
315
|
+
painter.drawImage(0, 0, clearance)
|
|
316
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
|
|
317
|
+
painter.drawImage(0, 0, extension)
|
|
318
|
+
finally:
|
|
319
|
+
painter.end()
|
|
320
|
+
return self._remember(key, combined)
|
|
321
|
+
|
|
322
|
+
# -- loading ----------------------------------------------------------
|
|
323
|
+
@classmethod
|
|
324
|
+
def load(cls, location: str | os.PathLike[str] | _Readable) -> "GraphicSet":
|
|
325
|
+
"""Load a graphic set from a directory containing ``manifest.json``.
|
|
326
|
+
|
|
327
|
+
``location`` may be a path or an :mod:`importlib.resources` traversable
|
|
328
|
+
(works inside wheels, zip imports and frozen applications). Raises
|
|
329
|
+
:class:`GraphicSetError` with a readable message on any problem.
|
|
330
|
+
"""
|
|
331
|
+
base = Path(location) if isinstance(location, (str, os.PathLike)) else location
|
|
332
|
+
manifest = _read_manifest(base)
|
|
333
|
+
layers = manifest["layers"]
|
|
334
|
+
images: dict[str, QImage] = {}
|
|
335
|
+
size_masks: dict[str, dict[int, QImage]] = {}
|
|
336
|
+
for layer, spec in layers.items():
|
|
337
|
+
images[layer] = _read_image(base, spec["file"], f"Ebene '{layer}'")
|
|
338
|
+
for size_text, file_name in spec.get("sizes", {}).items():
|
|
339
|
+
size = _size_from_key(size_text, f"layers.{layer}.sizes")
|
|
340
|
+
size_masks.setdefault(layer, {})[size] = _read_image(
|
|
341
|
+
base, file_name, f"Ebene '{layer}' ({size} px)"
|
|
342
|
+
)
|
|
343
|
+
return cls(
|
|
344
|
+
images[LAYER_SYMBOL],
|
|
345
|
+
images.get(LAYER_SYMBOL_EXT),
|
|
346
|
+
images.get(LAYER_SYMBOL_EXT_CLEARANCE),
|
|
347
|
+
name=manifest.get("name", "unnamed"),
|
|
348
|
+
safety_margin=manifest.get("safety_margin", DEFAULT_SAFETY_MARGIN),
|
|
349
|
+
size_masks=size_masks,
|
|
350
|
+
description=manifest.get("description", ""),
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
@classmethod
|
|
354
|
+
def load_default(cls) -> "GraphicSet":
|
|
355
|
+
"""Load the bundled neutral default set (``resources/default``)."""
|
|
356
|
+
return cls.load(default_graphic_set_location())
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def default_graphic_set_location() -> Any:
|
|
360
|
+
"""Traversable of the bundled default graphic set directory."""
|
|
361
|
+
return resources.files("dynamic_icon_engine").joinpath("resources", "default")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _describe(base: Any, name: str) -> str:
|
|
365
|
+
return str(base.joinpath(name))
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _size_from_key(size_text: object, field: str) -> int:
|
|
369
|
+
"""Parse an ASCII-decimal size key; reject Unicode digits as GraphicSetError."""
|
|
370
|
+
if not isinstance(size_text, str) or not size_text.isascii() or not size_text.isdigit() \
|
|
371
|
+
or int(size_text) < 1:
|
|
372
|
+
raise GraphicSetError(f"Grafikset-Manifest: ungültige Größe {size_text!r} in {field}")
|
|
373
|
+
return int(size_text)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _safe_name(name: object, field: str) -> str:
|
|
377
|
+
if not isinstance(name, str) or not name:
|
|
378
|
+
raise GraphicSetError(f"Manifest: {field} muss ein Dateiname sein, erhalten: {name!r}")
|
|
379
|
+
pure = PurePosixPath(name.replace("\\", "/"))
|
|
380
|
+
if pure.is_absolute() or ".." in pure.parts or ":" in name or len(pure.parts) != 1:
|
|
381
|
+
raise GraphicSetError(f"Manifest: {field} muss ein einfacher relativer Dateiname sein: {name!r}")
|
|
382
|
+
return name
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _read_bytes(base: Any, name: str, label: str) -> bytes:
|
|
386
|
+
try:
|
|
387
|
+
return base.joinpath(name).read_bytes()
|
|
388
|
+
except FileNotFoundError:
|
|
389
|
+
raise GraphicSetError(f"{label}: Datei nicht gefunden: {_describe(base, name)}") from None
|
|
390
|
+
except OSError as exc:
|
|
391
|
+
raise GraphicSetError(f"{label}: Datei nicht lesbar: {_describe(base, name)} ({exc})") from None
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _read_image(base: Any, name: str, label: str) -> QImage:
|
|
395
|
+
data = _read_bytes(base, name, label)
|
|
396
|
+
image = QImage.fromData(data)
|
|
397
|
+
if image.isNull():
|
|
398
|
+
raise GraphicSetError(f"{label}: Bild defekt oder kein unterstütztes Format: {_describe(base, name)}")
|
|
399
|
+
return image
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _read_manifest(base: Any) -> dict[str, Any]:
|
|
403
|
+
data = _read_bytes(base, MANIFEST_FILE, "Grafikset-Manifest")
|
|
404
|
+
try:
|
|
405
|
+
manifest = json.loads(data.decode("utf-8"))
|
|
406
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
407
|
+
raise GraphicSetError(
|
|
408
|
+
f"Grafikset-Manifest ist kein gültiges JSON: {_describe(base, MANIFEST_FILE)} ({exc})"
|
|
409
|
+
) from None
|
|
410
|
+
if not isinstance(manifest, dict):
|
|
411
|
+
raise GraphicSetError("Grafikset-Manifest: oberste Ebene muss ein JSON-Objekt sein")
|
|
412
|
+
if manifest.get("format") != MANIFEST_FORMAT:
|
|
413
|
+
raise GraphicSetError(f"Grafikset-Manifest: 'format' muss {MANIFEST_FORMAT!r} sein")
|
|
414
|
+
if manifest.get("format_version") != MANIFEST_FORMAT_VERSION:
|
|
415
|
+
raise GraphicSetError(
|
|
416
|
+
f"Grafikset-Manifest: nicht unterstützte format_version {manifest.get('format_version')!r} "
|
|
417
|
+
f"(unterstützt: {MANIFEST_FORMAT_VERSION})"
|
|
418
|
+
)
|
|
419
|
+
layers = manifest.get("layers")
|
|
420
|
+
if not isinstance(layers, dict) or LAYER_SYMBOL not in layers:
|
|
421
|
+
raise GraphicSetError("Grafikset-Manifest: 'layers' mit mindestens der Ebene 'symbol' fehlt")
|
|
422
|
+
for layer, spec in layers.items():
|
|
423
|
+
if layer not in LAYERS:
|
|
424
|
+
raise GraphicSetError(
|
|
425
|
+
f"Grafikset-Manifest: unbekannte Ebene {layer!r} (erlaubt: {', '.join(LAYERS)})"
|
|
426
|
+
)
|
|
427
|
+
if not isinstance(spec, dict):
|
|
428
|
+
raise GraphicSetError(f"Grafikset-Manifest: Ebene {layer!r} muss ein Objekt sein")
|
|
429
|
+
_safe_name(spec.get("file"), f"layers.{layer}.file")
|
|
430
|
+
sizes = spec.get("sizes", {})
|
|
431
|
+
if not isinstance(sizes, dict):
|
|
432
|
+
raise GraphicSetError(f"Grafikset-Manifest: layers.{layer}.sizes muss ein Objekt sein")
|
|
433
|
+
for size_text, file_name in sizes.items():
|
|
434
|
+
_size_from_key(size_text, f"layers.{layer}.sizes")
|
|
435
|
+
_safe_name(file_name, f"layers.{layer}.sizes.{size_text}")
|
|
436
|
+
return manifest
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Static rendering: appearance + background opacity -> QImage / QIcon.
|
|
2
|
+
|
|
3
|
+
The default background is a full square. The optional circle profile draws
|
|
4
|
+
only a coloured disk and a fixed outline. Only the fill opacity is variable.
|
|
5
|
+
In the default profile the foreground is the graphic set's alpha mask
|
|
6
|
+
filled with the symbol colour and composed with premultiplied source-over, so
|
|
7
|
+
fully opaque symbol pixels stay exactly the symbol colour at 100 % alpha.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from collections import OrderedDict
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Iterable
|
|
16
|
+
|
|
17
|
+
from PySide6.QtCore import Qt, QThread
|
|
18
|
+
from PySide6.QtGui import QColor, QGuiApplication, QIcon, QImage, QPainter, QPen, QPixmap
|
|
19
|
+
|
|
20
|
+
from .appearance import IconAppearance, hex_to_rgb, normalize_appearance_colors, normalize_hex_color
|
|
21
|
+
from .errors import InvalidAppearanceError
|
|
22
|
+
from .graphic_set import GraphicSet
|
|
23
|
+
|
|
24
|
+
#: Pixel sizes contained in every rendered QIcon.
|
|
25
|
+
DEFAULT_SIZES: tuple[int, ...] = (16, 20, 24, 32, 48, 64, 128, 256)
|
|
26
|
+
DEFAULT_MAX_CACHED_ICONS = 64
|
|
27
|
+
_LAYER_CACHE_LIMIT = 96
|
|
28
|
+
_IMAGE_FORMAT = QImage.Format.Format_ARGB32_Premultiplied
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def opacity_to_alpha(opacity: float) -> int:
|
|
32
|
+
"""Map a background opacity in ``[0, 1]`` to the 8-bit alpha actually rendered."""
|
|
33
|
+
return int(round(opacity * 255.0))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class CircleProfile:
|
|
38
|
+
"""Standalone disk on transparency, with an optional fixed-width outline.
|
|
39
|
+
|
|
40
|
+
The inset scales with icon size. Outline width is in pixels at each
|
|
41
|
+
rendered size and outline opacity is independent of the fill.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
border_color: str | None = None
|
|
45
|
+
border_width: int = 1
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
if self.border_color is not None:
|
|
49
|
+
object.__setattr__(self, "border_color", normalize_hex_color(self.border_color))
|
|
50
|
+
if type(self.border_width) is not int or self.border_width < 1:
|
|
51
|
+
raise ValueError("border_width muss eine positive Ganzzahl sein")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class IconRenderer:
|
|
55
|
+
"""Renders icons of one graphic set. Use only from the GUI thread.
|
|
56
|
+
|
|
57
|
+
``render_icon`` needs a ``QGuiApplication`` and its GUI thread (QPixmap).
|
|
58
|
+
``render_image`` works with QImage only, without an application. Use a
|
|
59
|
+
separate renderer per thread. Rendered QIcons are kept in a bounded LRU cache
|
|
60
|
+
(``max_cached_icons`` entries); coloured foreground layers in a second
|
|
61
|
+
bounded cache. No file I/O and no high-resolution scaling happen here once
|
|
62
|
+
a size has been prepared by the graphic set.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, graphic_set: GraphicSet | None = None, *,
|
|
66
|
+
sizes: Iterable[int] = DEFAULT_SIZES,
|
|
67
|
+
max_cached_icons: int = DEFAULT_MAX_CACHED_ICONS,
|
|
68
|
+
profile: CircleProfile | None = None) -> None:
|
|
69
|
+
if profile is not None and not isinstance(profile, CircleProfile):
|
|
70
|
+
raise TypeError("profile muss ein CircleProfile sein")
|
|
71
|
+
if profile is not None and graphic_set is not None:
|
|
72
|
+
raise ValueError("CircleProfile benötigt kein Grafikset")
|
|
73
|
+
if graphic_set is not None and not isinstance(graphic_set, GraphicSet):
|
|
74
|
+
raise TypeError("graphic_set muss ein GraphicSet sein")
|
|
75
|
+
self._profile = profile
|
|
76
|
+
self._graphic_set = (graphic_set or GraphicSet.load_default()) if profile is None else None
|
|
77
|
+
size_list = tuple(sorted(set(sizes)))
|
|
78
|
+
if not size_list or any(not isinstance(s, int) or isinstance(s, bool) or s < 1 for s in size_list):
|
|
79
|
+
raise ValueError(f"sizes muss positive Ganzzahlen enthalten, erhalten: {sizes!r}")
|
|
80
|
+
if isinstance(max_cached_icons, bool) or not isinstance(max_cached_icons, int) or max_cached_icons < 0:
|
|
81
|
+
raise ValueError("max_cached_icons muss eine Ganzzahl >= 0 sein (bool ist nicht zulässig)")
|
|
82
|
+
self._sizes = size_list
|
|
83
|
+
self._max_cached_icons = max_cached_icons
|
|
84
|
+
self._icons: OrderedDict[tuple, QIcon] = OrderedDict()
|
|
85
|
+
self._layers: OrderedDict[tuple, QImage] = OrderedDict()
|
|
86
|
+
# Prepare all masks once, so later frames never scale masters.
|
|
87
|
+
if self._graphic_set is not None:
|
|
88
|
+
for size in self._sizes:
|
|
89
|
+
self._graphic_set.foreground_mask(size, False)
|
|
90
|
+
if self._graphic_set.has_symbol_ext:
|
|
91
|
+
self._graphic_set.foreground_mask(size, True)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def graphic_set(self) -> GraphicSet | None:
|
|
95
|
+
return self._graphic_set
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def sizes(self) -> tuple[int, ...]:
|
|
99
|
+
return self._sizes
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def max_cached_icons(self) -> int:
|
|
103
|
+
return self._max_cached_icons
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def cached_icon_count(self) -> int:
|
|
107
|
+
return len(self._icons)
|
|
108
|
+
|
|
109
|
+
def clear_cache(self) -> None:
|
|
110
|
+
self._icons.clear()
|
|
111
|
+
self._layers.clear()
|
|
112
|
+
|
|
113
|
+
def validate(self, appearance: IconAppearance) -> IconAppearance:
|
|
114
|
+
"""Normalized copy of ``appearance``; raises :class:`InvalidAppearanceError`.
|
|
115
|
+
|
|
116
|
+
Checks colours, ``symbol_ext`` type and that the graphic set has an
|
|
117
|
+
extension layer when ``symbol_ext`` is true. The animation name is not
|
|
118
|
+
interpreted by the renderer.
|
|
119
|
+
"""
|
|
120
|
+
normalized = normalize_appearance_colors(appearance)
|
|
121
|
+
if self._graphic_set is None:
|
|
122
|
+
if normalized.symbol_ext:
|
|
123
|
+
raise InvalidAppearanceError("CircleProfile hat keine Ebene 'symbol_ext'")
|
|
124
|
+
return normalized
|
|
125
|
+
if normalized.symbol_ext and not self._graphic_set.has_symbol_ext:
|
|
126
|
+
raise InvalidAppearanceError(
|
|
127
|
+
f"symbol_ext=True, aber Grafikset '{self._graphic_set.name}' hat keine Ebene 'symbol_ext'"
|
|
128
|
+
)
|
|
129
|
+
return normalized
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _check_opacity(opacity: float) -> float:
|
|
133
|
+
if not isinstance(opacity, (int, float)) or isinstance(opacity, bool) \
|
|
134
|
+
or not math.isfinite(opacity) or not 0.0 <= opacity <= 1.0:
|
|
135
|
+
raise ValueError(f"background_opacity muss in [0, 1] liegen, erhalten: {opacity!r}")
|
|
136
|
+
return float(opacity)
|
|
137
|
+
|
|
138
|
+
def _foreground(self, symbol_color: str, symbol_ext: bool, size: int) -> QImage:
|
|
139
|
+
assert self._graphic_set is not None
|
|
140
|
+
key = (symbol_color, symbol_ext, size)
|
|
141
|
+
layer = self._layers.get(key)
|
|
142
|
+
if layer is not None:
|
|
143
|
+
self._layers.move_to_end(key)
|
|
144
|
+
return layer
|
|
145
|
+
mask = self._graphic_set.foreground_mask(size, symbol_ext)
|
|
146
|
+
layer = QImage(size, size, _IMAGE_FORMAT)
|
|
147
|
+
if layer.isNull():
|
|
148
|
+
raise ValueError(f"size {size!r}: QImage konnte nicht angelegt werden")
|
|
149
|
+
layer.fill(QColor(*hex_to_rgb(symbol_color)))
|
|
150
|
+
painter = QPainter(layer)
|
|
151
|
+
try:
|
|
152
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
|
|
153
|
+
painter.drawImage(0, 0, mask)
|
|
154
|
+
finally:
|
|
155
|
+
painter.end()
|
|
156
|
+
self._layers[key] = layer
|
|
157
|
+
while len(self._layers) > _LAYER_CACHE_LIMIT:
|
|
158
|
+
self._layers.popitem(last=False)
|
|
159
|
+
return layer
|
|
160
|
+
|
|
161
|
+
def _compose(self, a: IconAppearance, size: int, alpha: int) -> QImage:
|
|
162
|
+
image = QImage(size, size, _IMAGE_FORMAT)
|
|
163
|
+
if image.isNull():
|
|
164
|
+
raise ValueError(f"size {size!r}: QImage konnte nicht angelegt werden")
|
|
165
|
+
if self._profile is not None:
|
|
166
|
+
image.fill(Qt.GlobalColor.transparent)
|
|
167
|
+
painter = QPainter(image)
|
|
168
|
+
try:
|
|
169
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
170
|
+
border = self._profile.border_color
|
|
171
|
+
painter.setPen(Qt.PenStyle.NoPen if border is None
|
|
172
|
+
else QPen(QColor(border), self._profile.border_width))
|
|
173
|
+
painter.setBrush(QColor(*hex_to_rgb(a.background_color), alpha))
|
|
174
|
+
margin = min(max(2, size // 8), (size - 1) // 2)
|
|
175
|
+
diameter = size - 2 * margin
|
|
176
|
+
painter.drawEllipse(margin, margin, diameter, diameter)
|
|
177
|
+
finally:
|
|
178
|
+
painter.end()
|
|
179
|
+
return image
|
|
180
|
+
image.fill(QColor(*hex_to_rgb(a.background_color), alpha))
|
|
181
|
+
# Resolve the foreground *before* opening the painter: a GraphicSetError
|
|
182
|
+
# must never escape while a paint device is still active (Qt aborts).
|
|
183
|
+
foreground = self._foreground(a.symbol_color, a.symbol_ext, size)
|
|
184
|
+
painter = QPainter(image)
|
|
185
|
+
try:
|
|
186
|
+
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
|
|
187
|
+
painter.drawImage(0, 0, foreground)
|
|
188
|
+
finally:
|
|
189
|
+
painter.end()
|
|
190
|
+
return image
|
|
191
|
+
|
|
192
|
+
def render_image(self, appearance: IconAppearance, size: int, *,
|
|
193
|
+
background_opacity: float = 1.0) -> QImage:
|
|
194
|
+
"""Render one ``size x size`` image (``Format_ARGB32_Premultiplied``)."""
|
|
195
|
+
a = self.validate(appearance)
|
|
196
|
+
alpha = opacity_to_alpha(self._check_opacity(background_opacity))
|
|
197
|
+
if not isinstance(size, int) or isinstance(size, bool) or size < 1:
|
|
198
|
+
raise ValueError(f"size muss eine positive Ganzzahl sein, erhalten: {size!r}")
|
|
199
|
+
return self._compose(a, size, alpha)
|
|
200
|
+
|
|
201
|
+
def render_icon(self, appearance: IconAppearance, *, background_opacity: float = 1.0,
|
|
202
|
+
cache: bool = True) -> QIcon:
|
|
203
|
+
"""Render a QIcon with one pixmap per configured size.
|
|
204
|
+
|
|
205
|
+
Requires a ``QGuiApplication`` and its GUI thread. With ``cache=True`` the icon is stored in
|
|
206
|
+
the bounded LRU cache keyed by colours, ``symbol_ext`` and the rendered
|
|
207
|
+
8-bit background alpha.
|
|
208
|
+
"""
|
|
209
|
+
app = QGuiApplication.instance()
|
|
210
|
+
if not isinstance(app, QGuiApplication):
|
|
211
|
+
raise RuntimeError("render_icon benötigt eine bestehende QGuiApplication/QApplication")
|
|
212
|
+
if QThread.currentThread() is not app.thread():
|
|
213
|
+
raise RuntimeError("render_icon darf nur im GUI-Thread verwendet werden")
|
|
214
|
+
a = self.validate(appearance)
|
|
215
|
+
alpha = opacity_to_alpha(self._check_opacity(background_opacity))
|
|
216
|
+
key = (a.background_color, a.symbol_color, a.symbol_ext, alpha)
|
|
217
|
+
icon = self._icons.get(key)
|
|
218
|
+
if icon is not None:
|
|
219
|
+
self._icons.move_to_end(key)
|
|
220
|
+
return QIcon(icon)
|
|
221
|
+
icon = QIcon()
|
|
222
|
+
for size in self._sizes:
|
|
223
|
+
icon.addPixmap(QPixmap.fromImage(self._compose(a, size, alpha)))
|
|
224
|
+
if cache and self._max_cached_icons > 0:
|
|
225
|
+
self._icons[key] = icon
|
|
226
|
+
while len(self._icons) > self._max_cached_icons:
|
|
227
|
+
self._icons.popitem(last=False)
|
|
228
|
+
return QIcon(icon)
|
|
File without changes
|