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,37 @@
|
|
|
1
|
+
"""Dynamic Icon Engine - neutral, reusable PySide6 component for dynamic icons.
|
|
2
|
+
|
|
3
|
+
Public API (see README.md):
|
|
4
|
+
|
|
5
|
+
* :class:`IconAppearance` - desired look (background colour, symbol colour,
|
|
6
|
+
optional extension layer, animation name).
|
|
7
|
+
* :class:`AnimationDefinition`, :class:`AnimationRegistry`, :data:`GENERIC_PRESETS`,
|
|
8
|
+
:func:`sample_animation` - the single background-opacity animation mechanism.
|
|
9
|
+
* :class:`GraphicSet` - exchangeable alpha masks (``symbol``, ``symbol_ext``).
|
|
10
|
+
* :class:`IconRenderer` - static rendering to ``QImage``/``QIcon``.
|
|
11
|
+
* :class:`IconController` - stateful controller emitting ``iconChanged(QIcon)``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from ._version import __version__
|
|
15
|
+
from .animation import (
|
|
16
|
+
GENERIC_PRESETS, TRANSITION_SMOOTH, TRANSITION_STEP, AnimationDefinition, AnimationRegistry,
|
|
17
|
+
AnimationSample, next_update_delay_ms, sample_animation, total_duration_ms,
|
|
18
|
+
validate_animation_definition,
|
|
19
|
+
)
|
|
20
|
+
from .appearance import ANIMATION_NONE, IconAppearance, normalize_hex_color
|
|
21
|
+
from .controller import IconController
|
|
22
|
+
from .errors import DynamicIconEngineError, GraphicSetError, InvalidAnimationError, InvalidAppearanceError
|
|
23
|
+
from .graphic_set import (
|
|
24
|
+
LAYER_SYMBOL, LAYER_SYMBOL_EXT, LAYER_SYMBOL_EXT_CLEARANCE, GraphicSet, default_graphic_set_location,
|
|
25
|
+
)
|
|
26
|
+
from .renderer import DEFAULT_SIZES, CircleProfile, IconRenderer, opacity_to_alpha
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"__version__",
|
|
30
|
+
"ANIMATION_NONE", "DEFAULT_SIZES", "GENERIC_PRESETS", "LAYER_SYMBOL", "LAYER_SYMBOL_EXT",
|
|
31
|
+
"LAYER_SYMBOL_EXT_CLEARANCE", "TRANSITION_SMOOTH", "TRANSITION_STEP",
|
|
32
|
+
"AnimationDefinition", "AnimationRegistry", "AnimationSample", "CircleProfile", "DynamicIconEngineError",
|
|
33
|
+
"GraphicSet", "GraphicSetError", "IconAppearance", "IconController", "IconRenderer",
|
|
34
|
+
"InvalidAnimationError", "InvalidAppearanceError",
|
|
35
|
+
"default_graphic_set_location", "next_update_delay_ms", "normalize_hex_color",
|
|
36
|
+
"opacity_to_alpha", "sample_animation", "total_duration_ms", "validate_animation_definition",
|
|
37
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""The single neutral animation mechanism: background opacity over time.
|
|
2
|
+
|
|
3
|
+
An animation only varies the opacity of the background fill. Symbol,
|
|
4
|
+
extension and fixed outlines retain their opacity. All values are computed from
|
|
5
|
+
monotonic elapsed time (never from counted timer ticks), therefore the pure
|
|
6
|
+
functions in this module fully describe what the controller shows.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
from typing import Mapping, NamedTuple
|
|
16
|
+
|
|
17
|
+
from .appearance import ANIMATION_NONE
|
|
18
|
+
from .errors import InvalidAnimationError
|
|
19
|
+
|
|
20
|
+
TRANSITION_SMOOTH = "smooth"
|
|
21
|
+
TRANSITION_STEP = "step"
|
|
22
|
+
TRANSITIONS = (TRANSITION_SMOOTH, TRANSITION_STEP)
|
|
23
|
+
|
|
24
|
+
_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.\-]{0,63}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class AnimationDefinition:
|
|
29
|
+
"""Immutable description of a background opacity animation.
|
|
30
|
+
|
|
31
|
+
``period_ms`` includes ``hold_max_ms``. ``repetitions=None`` means endless.
|
|
32
|
+
The constructor validates all values (see :func:`validate_animation_definition`).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
min_opacity: float = 0.5
|
|
36
|
+
max_opacity: float = 1.0
|
|
37
|
+
period_ms: int = 1000
|
|
38
|
+
transition: str = "smooth"
|
|
39
|
+
repetitions: int | None = None
|
|
40
|
+
hold_max_ms: int = 0
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
validate_animation_definition(self)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _is_real(value: object) -> bool:
|
|
47
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _is_int(value: object) -> bool:
|
|
51
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def validate_animation_definition(definition: object) -> AnimationDefinition:
|
|
55
|
+
"""Check every rule of the animation contract; raise :class:`InvalidAnimationError`.
|
|
56
|
+
|
|
57
|
+
Rules: finite ``0 <= min_opacity <= max_opacity <= 1``; integer
|
|
58
|
+
``period_ms > 0``; integer ``0 <= hold_max_ms < period_ms``; ``transition``
|
|
59
|
+
is ``"smooth"`` or ``"step"``; ``repetitions`` is ``None`` or an integer >= 1.
|
|
60
|
+
"""
|
|
61
|
+
if not isinstance(definition, AnimationDefinition):
|
|
62
|
+
raise InvalidAnimationError(
|
|
63
|
+
f"AnimationDefinition erwartet, erhalten: {type(definition).__name__}"
|
|
64
|
+
)
|
|
65
|
+
d = definition
|
|
66
|
+
for field in ("min_opacity", "max_opacity"):
|
|
67
|
+
value = getattr(d, field)
|
|
68
|
+
if not _is_real(value) or not math.isfinite(value):
|
|
69
|
+
raise InvalidAnimationError(f"{field} muss eine endliche Zahl sein, erhalten: {value!r}")
|
|
70
|
+
if not 0.0 <= d.min_opacity <= d.max_opacity <= 1.0:
|
|
71
|
+
raise InvalidAnimationError(
|
|
72
|
+
"Es muss gelten 0 <= min_opacity <= max_opacity <= 1, erhalten: "
|
|
73
|
+
f"min_opacity={d.min_opacity!r}, max_opacity={d.max_opacity!r}"
|
|
74
|
+
)
|
|
75
|
+
if not _is_int(d.period_ms) or d.period_ms <= 0:
|
|
76
|
+
raise InvalidAnimationError(f"period_ms muss eine positive Ganzzahl sein, erhalten: {d.period_ms!r}")
|
|
77
|
+
if not _is_int(d.hold_max_ms) or not 0 <= d.hold_max_ms < d.period_ms:
|
|
78
|
+
raise InvalidAnimationError(
|
|
79
|
+
"hold_max_ms muss eine Ganzzahl mit 0 <= hold_max_ms < period_ms sein, erhalten: "
|
|
80
|
+
f"hold_max_ms={d.hold_max_ms!r}, period_ms={d.period_ms!r}"
|
|
81
|
+
)
|
|
82
|
+
if d.transition not in TRANSITIONS:
|
|
83
|
+
raise InvalidAnimationError(
|
|
84
|
+
f"transition muss 'smooth' oder 'step' sein, erhalten: {d.transition!r}"
|
|
85
|
+
)
|
|
86
|
+
if d.repetitions is not None and (not _is_int(d.repetitions) or d.repetitions < 1):
|
|
87
|
+
raise InvalidAnimationError(
|
|
88
|
+
f"repetitions muss None (endlos) oder eine Ganzzahl >= 1 sein, erhalten: {d.repetitions!r}"
|
|
89
|
+
)
|
|
90
|
+
return d
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class AnimationSample(NamedTuple):
|
|
94
|
+
"""Background opacity at one point in time."""
|
|
95
|
+
|
|
96
|
+
opacity: float
|
|
97
|
+
finished: bool
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def total_duration_ms(definition: AnimationDefinition) -> int | None:
|
|
101
|
+
"""Total run time of a finite animation, ``None`` for endless animations."""
|
|
102
|
+
if definition.repetitions is None:
|
|
103
|
+
return None
|
|
104
|
+
return definition.repetitions * definition.period_ms
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _opacity_in_cycle(d: AnimationDefinition, t: float) -> float:
|
|
108
|
+
"""Opacity at position ``0 <= t < period_ms`` inside one cycle."""
|
|
109
|
+
if t < d.hold_max_ms:
|
|
110
|
+
return float(d.max_opacity)
|
|
111
|
+
rest = d.period_ms - d.hold_max_ms
|
|
112
|
+
u = t - d.hold_max_ms
|
|
113
|
+
if d.transition == TRANSITION_STEP:
|
|
114
|
+
return float(d.max_opacity) if u < rest / 2.0 else float(d.min_opacity)
|
|
115
|
+
# Smooth: cosine fall over the first half of the rest, cosine rise over the
|
|
116
|
+
# second half. 0.5*(1-cos(2*pi*u/rest)) runs 0 -> 1 -> 0; no hold at the bottom.
|
|
117
|
+
depth = 0.5 * (1.0 - math.cos(2.0 * math.pi * u / rest))
|
|
118
|
+
value = d.max_opacity - (d.max_opacity - d.min_opacity) * depth
|
|
119
|
+
return min(float(d.max_opacity), max(float(d.min_opacity), value))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def sample_animation(definition: AnimationDefinition, elapsed_ms: float) -> AnimationSample:
|
|
123
|
+
"""Background opacity after ``elapsed_ms`` of monotonic time.
|
|
124
|
+
|
|
125
|
+
Each cycle starts at ``max_opacity``. After a finite animation has run for
|
|
126
|
+
exactly ``repetitions * period_ms`` the result is ``(1.0, True)``: a fully
|
|
127
|
+
opaque background, independent of ``max_opacity``.
|
|
128
|
+
"""
|
|
129
|
+
elapsed = max(0.0, float(elapsed_ms))
|
|
130
|
+
total = total_duration_ms(definition)
|
|
131
|
+
if total is not None and elapsed >= total:
|
|
132
|
+
return AnimationSample(1.0, True)
|
|
133
|
+
t = math.fmod(elapsed, definition.period_ms)
|
|
134
|
+
return AnimationSample(_opacity_in_cycle(definition, t), False)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def next_update_delay_ms(
|
|
138
|
+
definition: AnimationDefinition, elapsed_ms: float, frame_interval_ms: int
|
|
139
|
+
) -> float | None:
|
|
140
|
+
"""Delay until the visible opacity can change next (``None`` when finished).
|
|
141
|
+
|
|
142
|
+
Smooth animations are sampled every ``frame_interval_ms`` except during the
|
|
143
|
+
upper hold, step animations are re-evaluated exactly at their edges. The delay never
|
|
144
|
+
overshoots the end of a finite animation.
|
|
145
|
+
"""
|
|
146
|
+
elapsed = max(0.0, float(elapsed_ms))
|
|
147
|
+
total = total_duration_ms(definition)
|
|
148
|
+
if total is not None and elapsed >= total:
|
|
149
|
+
return None
|
|
150
|
+
d = definition
|
|
151
|
+
t = math.fmod(elapsed, d.period_ms)
|
|
152
|
+
if t < d.hold_max_ms:
|
|
153
|
+
delay = d.hold_max_ms - t
|
|
154
|
+
elif d.transition == TRANSITION_STEP:
|
|
155
|
+
edge = d.hold_max_ms + (d.period_ms - d.hold_max_ms) / 2.0
|
|
156
|
+
delay = edge - t if t < edge else d.period_ms - t
|
|
157
|
+
else:
|
|
158
|
+
delay = float(frame_interval_ms)
|
|
159
|
+
if total is not None:
|
|
160
|
+
delay = min(delay, total - elapsed)
|
|
161
|
+
return max(delay, 1.0)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
#: Generic demo/test presets (start values for visual checks only; the engine
|
|
165
|
+
#: does not know what a host uses them for).
|
|
166
|
+
GENERIC_PRESETS: Mapping[str, AnimationDefinition] = MappingProxyType(
|
|
167
|
+
{
|
|
168
|
+
"pulse_slow": AnimationDefinition(
|
|
169
|
+
min_opacity=0.20, max_opacity=1.0, period_ms=2800,
|
|
170
|
+
transition=TRANSITION_SMOOTH, repetitions=None, hold_max_ms=240,
|
|
171
|
+
),
|
|
172
|
+
"blink_fast": AnimationDefinition(
|
|
173
|
+
min_opacity=0.40, max_opacity=1.0, period_ms=600,
|
|
174
|
+
transition=TRANSITION_STEP, repetitions=None, hold_max_ms=0,
|
|
175
|
+
),
|
|
176
|
+
"blink_triple": AnimationDefinition(
|
|
177
|
+
min_opacity=0.25, max_opacity=1.0, period_ms=400,
|
|
178
|
+
transition=TRANSITION_STEP, repetitions=3, hold_max_ms=0,
|
|
179
|
+
),
|
|
180
|
+
}
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class AnimationRegistry:
|
|
185
|
+
"""Neutral name -> :class:`AnimationDefinition` registry.
|
|
186
|
+
|
|
187
|
+
``"none"`` is reserved and always available (static, fully opaque background,
|
|
188
|
+
no timer); it can neither be registered nor removed. Names consist of 1-64
|
|
189
|
+
characters ``A-Z a-z 0-9 _ . -`` and start with a letter or digit.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
def __init__(self, definitions: Mapping[str, AnimationDefinition] | None = None, *,
|
|
193
|
+
include_generic_presets: bool = True) -> None:
|
|
194
|
+
self._definitions: dict[str, AnimationDefinition] = {}
|
|
195
|
+
if include_generic_presets:
|
|
196
|
+
for name, definition in GENERIC_PRESETS.items():
|
|
197
|
+
self.register(name, definition)
|
|
198
|
+
for name, definition in (definitions or {}).items():
|
|
199
|
+
self.register(name, definition, replace=True)
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _check_name(name: object) -> str:
|
|
203
|
+
if not isinstance(name, str) or _NAME.fullmatch(name) is None:
|
|
204
|
+
raise InvalidAnimationError(
|
|
205
|
+
f"Ungültiger Animationsname {name!r} (erlaubt: 1-64 Zeichen A-Z a-z 0-9 _ . -)"
|
|
206
|
+
)
|
|
207
|
+
if name == ANIMATION_NONE:
|
|
208
|
+
raise InvalidAnimationError("Der Name 'none' ist reserviert")
|
|
209
|
+
return name
|
|
210
|
+
|
|
211
|
+
def register(self, name: str, definition: AnimationDefinition, *, replace: bool = False) -> None:
|
|
212
|
+
"""Validate and register ``definition`` under ``name``.
|
|
213
|
+
|
|
214
|
+
Raises :class:`InvalidAnimationError` for invalid names/definitions or
|
|
215
|
+
when ``name`` exists and ``replace`` is false. A replaced definition is
|
|
216
|
+
used for animations started afterwards (new appearance or replay).
|
|
217
|
+
"""
|
|
218
|
+
self._check_name(name)
|
|
219
|
+
validate_animation_definition(definition)
|
|
220
|
+
if name in self._definitions and not replace:
|
|
221
|
+
raise InvalidAnimationError(f"Animation {name!r} ist bereits registriert")
|
|
222
|
+
self._definitions[name] = definition
|
|
223
|
+
|
|
224
|
+
def unregister(self, name: str) -> None:
|
|
225
|
+
"""Remove ``name``; raises :class:`InvalidAnimationError` if unknown or reserved."""
|
|
226
|
+
self._check_name(name)
|
|
227
|
+
if name not in self._definitions:
|
|
228
|
+
raise InvalidAnimationError(f"Animation {name!r} ist nicht registriert")
|
|
229
|
+
del self._definitions[name]
|
|
230
|
+
|
|
231
|
+
def get(self, name: str) -> AnimationDefinition | None:
|
|
232
|
+
"""Definition for ``name``; ``None`` for ``"none"``; error if unknown."""
|
|
233
|
+
if name == ANIMATION_NONE:
|
|
234
|
+
return None
|
|
235
|
+
try:
|
|
236
|
+
return self._definitions[name]
|
|
237
|
+
except (KeyError, TypeError):
|
|
238
|
+
raise InvalidAnimationError(f"Animation {name!r} ist nicht registriert") from None
|
|
239
|
+
|
|
240
|
+
def __contains__(self, name: object) -> bool:
|
|
241
|
+
if not isinstance(name, str):
|
|
242
|
+
return False
|
|
243
|
+
return name == ANIMATION_NONE or name in self._definitions
|
|
244
|
+
|
|
245
|
+
def names(self) -> tuple[str, ...]:
|
|
246
|
+
"""``"none"`` followed by all registered names in registration order."""
|
|
247
|
+
return (ANIMATION_NONE, *self._definitions)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Neutral appearance contract and colour validation.
|
|
2
|
+
|
|
3
|
+
The engine only knows *how an icon looks*: a background colour, a symbol
|
|
4
|
+
colour, whether the optional extension layer is visible and the name of a
|
|
5
|
+
registered animation. It deliberately knows nothing about why a host chooses
|
|
6
|
+
a particular appearance.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, replace
|
|
13
|
+
|
|
14
|
+
from .errors import InvalidAppearanceError
|
|
15
|
+
|
|
16
|
+
#: Reserved animation name: static, fully opaque background, no timer.
|
|
17
|
+
ANIMATION_NONE = "none"
|
|
18
|
+
|
|
19
|
+
_HEX_COLOR = re.compile(r"#[0-9A-Fa-f]{6}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class IconAppearance:
|
|
24
|
+
"""Desired look of the icon (public contract, field names are binding)."""
|
|
25
|
+
|
|
26
|
+
background_color: str
|
|
27
|
+
symbol_color: str
|
|
28
|
+
symbol_ext: bool = False
|
|
29
|
+
animation: str = "none"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def normalize_hex_color(value: object, *, field: str = "color") -> str:
|
|
33
|
+
"""Validate an RGB hex colour and return its canonical form.
|
|
34
|
+
|
|
35
|
+
Accepted is exactly ``#RRGGBB`` (``#`` followed by six hexadecimal digits,
|
|
36
|
+
case-insensitive). The canonical form is upper case, e.g. ``"#103c85"`` ->
|
|
37
|
+
``"#103C85"``. Everything else - short forms (``#RGB``), alpha forms
|
|
38
|
+
(``#AARRGGBB``), colour names, missing ``#``, surrounding whitespace or
|
|
39
|
+
non-string values - raises :class:`InvalidAppearanceError`. There are no
|
|
40
|
+
silent replacement colours.
|
|
41
|
+
"""
|
|
42
|
+
if not isinstance(value, str) or _HEX_COLOR.fullmatch(value) is None:
|
|
43
|
+
raise InvalidAppearanceError(
|
|
44
|
+
f"{field}: ungültige Farbe {value!r} - erwartet wird '#RRGGBB' "
|
|
45
|
+
"(sechs Hexadezimalziffern, z. B. '#103C85')"
|
|
46
|
+
)
|
|
47
|
+
return value.upper()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def hex_to_rgb(value: str) -> tuple[int, int, int]:
|
|
51
|
+
"""Convert a validated ``#RRGGBB`` colour to an ``(r, g, b)`` tuple."""
|
|
52
|
+
canonical = normalize_hex_color(value)
|
|
53
|
+
return int(canonical[1:3], 16), int(canonical[3:5], 16), int(canonical[5:7], 16)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def normalize_appearance_colors(appearance: object) -> IconAppearance:
|
|
57
|
+
"""Validate type, colours and ``symbol_ext`` of an appearance.
|
|
58
|
+
|
|
59
|
+
Returns a copy with canonical colours. The ``animation`` field is only
|
|
60
|
+
type-checked here; whether the name is registered is checked by the
|
|
61
|
+
controller against its :class:`~dynamic_icon_engine.AnimationRegistry`.
|
|
62
|
+
"""
|
|
63
|
+
if not isinstance(appearance, IconAppearance):
|
|
64
|
+
raise InvalidAppearanceError(
|
|
65
|
+
f"IconAppearance erwartet, erhalten: {type(appearance).__name__}"
|
|
66
|
+
)
|
|
67
|
+
background = normalize_hex_color(appearance.background_color, field="background_color")
|
|
68
|
+
symbol = normalize_hex_color(appearance.symbol_color, field="symbol_color")
|
|
69
|
+
if not isinstance(appearance.symbol_ext, bool):
|
|
70
|
+
raise InvalidAppearanceError(
|
|
71
|
+
f"symbol_ext muss bool sein, erhalten: {appearance.symbol_ext!r}"
|
|
72
|
+
)
|
|
73
|
+
if not isinstance(appearance.animation, str) or not appearance.animation:
|
|
74
|
+
raise InvalidAppearanceError(
|
|
75
|
+
f"animation muss ein nicht-leerer Name sein, erhalten: {appearance.animation!r}"
|
|
76
|
+
)
|
|
77
|
+
return replace(appearance, background_color=background, symbol_color=symbol)
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Stateful icon controller: appearance in, QIcon out via Qt signal.
|
|
2
|
+
|
|
3
|
+
Exactly one ``QTimer`` per controller drives the background opacity
|
|
4
|
+
animation. Every frame is computed from monotonic elapsed time; the timer only
|
|
5
|
+
decides *when* to look again. All methods must be called from the GUI thread.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import time
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
from PySide6.QtCore import QObject, QThread, QTimer, Qt, Signal
|
|
15
|
+
from PySide6.QtGui import QGuiApplication, QIcon
|
|
16
|
+
|
|
17
|
+
from .animation import (
|
|
18
|
+
TRANSITION_STEP, AnimationDefinition, AnimationRegistry, next_update_delay_ms, sample_animation,
|
|
19
|
+
)
|
|
20
|
+
from .appearance import IconAppearance
|
|
21
|
+
from .errors import InvalidAnimationError, InvalidAppearanceError
|
|
22
|
+
from .graphic_set import GraphicSet
|
|
23
|
+
from .renderer import IconRenderer, opacity_to_alpha
|
|
24
|
+
|
|
25
|
+
DEFAULT_FRAME_INTERVAL_MS = 33
|
|
26
|
+
MIN_FRAME_INTERVAL_MS = 10
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _monotonic_ms() -> float:
|
|
30
|
+
return time.monotonic_ns() / 1_000_000.0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class IconController(QObject):
|
|
34
|
+
"""Holds the current :class:`IconAppearance` and publishes rendered icons.
|
|
35
|
+
|
|
36
|
+
Signals:
|
|
37
|
+
``iconChanged(QIcon)`` - emitted synchronously whenever the visible icon
|
|
38
|
+
changes (new appearance, animation frame, end of a finite animation).
|
|
39
|
+
``animationFinished()`` - a finite animation completed all repetitions.
|
|
40
|
+
|
|
41
|
+
Lifecycle: create after ``QGuiApplication`` exists, in the GUI thread; call
|
|
42
|
+
:meth:`dispose` before dropping it. After ``dispose`` no timer runs and no
|
|
43
|
+
signal is emitted; further calls are ignored and return ``False``. The
|
|
44
|
+
controller never owns or controls the host window or the application.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
iconChanged = Signal(QIcon)
|
|
48
|
+
animationFinished = Signal()
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
graphic_set: GraphicSet | None = None,
|
|
53
|
+
*,
|
|
54
|
+
renderer: IconRenderer | None = None,
|
|
55
|
+
registry: AnimationRegistry | None = None,
|
|
56
|
+
frame_interval_ms: int = DEFAULT_FRAME_INTERVAL_MS,
|
|
57
|
+
clock: Callable[[], float] | None = None,
|
|
58
|
+
parent: QObject | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
app = QGuiApplication.instance()
|
|
61
|
+
if not isinstance(app, QGuiApplication):
|
|
62
|
+
raise RuntimeError("IconController benötigt eine bestehende QGuiApplication/QApplication")
|
|
63
|
+
if QThread.currentThread() is not app.thread():
|
|
64
|
+
raise RuntimeError("IconController muss im GUI-Thread erzeugt werden")
|
|
65
|
+
super().__init__(parent)
|
|
66
|
+
if renderer is not None and graphic_set is not None and renderer.graphic_set is not graphic_set:
|
|
67
|
+
raise ValueError("graphic_set und renderer.graphic_set widersprechen sich")
|
|
68
|
+
if not isinstance(frame_interval_ms, int) or frame_interval_ms < MIN_FRAME_INTERVAL_MS:
|
|
69
|
+
raise ValueError(f"frame_interval_ms muss eine Ganzzahl >= {MIN_FRAME_INTERVAL_MS} sein")
|
|
70
|
+
self._renderer = renderer if renderer is not None else IconRenderer(graphic_set)
|
|
71
|
+
self._registry = registry if registry is not None else AnimationRegistry()
|
|
72
|
+
self._frame_interval_ms = frame_interval_ms
|
|
73
|
+
self._clock = clock if clock is not None else _monotonic_ms
|
|
74
|
+
|
|
75
|
+
self._timer = QTimer(self)
|
|
76
|
+
self._timer.setSingleShot(True)
|
|
77
|
+
self._timer.setTimerType(Qt.TimerType.PreciseTimer)
|
|
78
|
+
self._timer.timeout.connect(self._on_timeout)
|
|
79
|
+
|
|
80
|
+
self._appearance: IconAppearance | None = None
|
|
81
|
+
self._definition: AnimationDefinition | None = None
|
|
82
|
+
self._start_ms = 0.0
|
|
83
|
+
self._animating = False
|
|
84
|
+
self._generation = 0
|
|
85
|
+
self._opacity = 1.0
|
|
86
|
+
self._shown_key: tuple | None = None
|
|
87
|
+
self._icon = QIcon()
|
|
88
|
+
self._disposed = False
|
|
89
|
+
|
|
90
|
+
# -- read-only state --------------------------------------------------
|
|
91
|
+
@property
|
|
92
|
+
def renderer(self) -> IconRenderer:
|
|
93
|
+
return self._renderer
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def registry(self) -> AnimationRegistry:
|
|
97
|
+
return self._registry
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def appearance(self) -> IconAppearance | None:
|
|
101
|
+
"""Last valid (normalized) appearance, ``None`` before the first one."""
|
|
102
|
+
return self._appearance
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def background_opacity(self) -> float:
|
|
106
|
+
"""Background opacity of the icon currently shown."""
|
|
107
|
+
return self._opacity
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def is_animating(self) -> bool:
|
|
111
|
+
"""``True`` while an animation runs (and the timer is armed)."""
|
|
112
|
+
return self._animating
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def is_disposed(self) -> bool:
|
|
116
|
+
return self._disposed
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def active_definition(self) -> AnimationDefinition | None:
|
|
120
|
+
"""Definition snapshot used by the current/last animation (``None`` for ``none``)."""
|
|
121
|
+
return self._definition
|
|
122
|
+
|
|
123
|
+
def icon(self) -> QIcon:
|
|
124
|
+
"""Icon currently shown (null ``QIcon`` before the first appearance)."""
|
|
125
|
+
return QIcon(self._icon)
|
|
126
|
+
|
|
127
|
+
# -- commands ---------------------------------------------------------
|
|
128
|
+
def set_appearance(self, appearance: IconAppearance) -> bool:
|
|
129
|
+
"""Apply ``appearance``.
|
|
130
|
+
|
|
131
|
+
Returns ``True`` if the state changed, ``False`` for an identical
|
|
132
|
+
(normalized) appearance - a running or already finished animation is
|
|
133
|
+
then neither restarted nor re-emitted - and after :meth:`dispose`.
|
|
134
|
+
Raises :class:`InvalidAppearanceError` for invalid input; the last valid
|
|
135
|
+
state stays untouched. A change stops the previous animation at once and
|
|
136
|
+
emits the first frame of the new state synchronously.
|
|
137
|
+
"""
|
|
138
|
+
if self._disposed:
|
|
139
|
+
return False
|
|
140
|
+
self._ensure_gui_thread()
|
|
141
|
+
normalized = self._renderer.validate(appearance)
|
|
142
|
+
# Idempotent update first: an unchanged state must not require the
|
|
143
|
+
# animation name to still be registered. The running animation keeps
|
|
144
|
+
# its definition snapshot and is neither restarted nor re-emitted.
|
|
145
|
+
if normalized == self._appearance:
|
|
146
|
+
return False
|
|
147
|
+
if normalized.animation not in self._registry:
|
|
148
|
+
raise InvalidAppearanceError(
|
|
149
|
+
f"animation: {normalized.animation!r} ist nicht registriert "
|
|
150
|
+
f"(verfügbar: {', '.join(self._registry.names())})"
|
|
151
|
+
)
|
|
152
|
+
definition = self._registry.get(normalized.animation)
|
|
153
|
+
self._timer.stop()
|
|
154
|
+
self._appearance = normalized
|
|
155
|
+
self._start(definition)
|
|
156
|
+
return True
|
|
157
|
+
|
|
158
|
+
def replay(self) -> bool:
|
|
159
|
+
"""Restart the animation of the current appearance from its beginning.
|
|
160
|
+
|
|
161
|
+
Intended for deliberately re-triggered finite animations; also picks up
|
|
162
|
+
a definition re-registered under the same name. Returns ``False`` for
|
|
163
|
+
``none``, without appearance or after dispose.
|
|
164
|
+
"""
|
|
165
|
+
if self._disposed or self._appearance is None:
|
|
166
|
+
return False
|
|
167
|
+
self._ensure_gui_thread()
|
|
168
|
+
try:
|
|
169
|
+
definition = self._registry.get(self._appearance.animation)
|
|
170
|
+
except InvalidAnimationError:
|
|
171
|
+
raise InvalidAnimationError(
|
|
172
|
+
f"Animation {self._appearance.animation!r} ist nicht mehr registriert"
|
|
173
|
+
) from None
|
|
174
|
+
if definition is None:
|
|
175
|
+
return False
|
|
176
|
+
self._timer.stop()
|
|
177
|
+
self._start(definition)
|
|
178
|
+
return True
|
|
179
|
+
|
|
180
|
+
def stop_animation(self) -> bool:
|
|
181
|
+
"""Stop a running animation and show a fully opaque background.
|
|
182
|
+
|
|
183
|
+
The appearance is kept (setting it again is idempotent). Returns
|
|
184
|
+
``True`` if an animation was running.
|
|
185
|
+
"""
|
|
186
|
+
if self._disposed:
|
|
187
|
+
return False
|
|
188
|
+
self._ensure_gui_thread()
|
|
189
|
+
# Also invalidate pending completion during a synchronous final frame.
|
|
190
|
+
self._generation += 1
|
|
191
|
+
if not self._animating:
|
|
192
|
+
return False
|
|
193
|
+
self._timer.stop()
|
|
194
|
+
self._animating = False
|
|
195
|
+
self._show(1.0)
|
|
196
|
+
return True
|
|
197
|
+
|
|
198
|
+
def dispose(self) -> None:
|
|
199
|
+
"""Stop the timer and silence all signals permanently (idempotent)."""
|
|
200
|
+
if self._disposed:
|
|
201
|
+
return
|
|
202
|
+
self._ensure_gui_thread()
|
|
203
|
+
self._generation += 1
|
|
204
|
+
self._disposed = True
|
|
205
|
+
self._animating = False
|
|
206
|
+
self._timer.stop()
|
|
207
|
+
self.blockSignals(True)
|
|
208
|
+
self._renderer.clear_cache()
|
|
209
|
+
|
|
210
|
+
# -- internals ----------------------------------------------------------
|
|
211
|
+
@staticmethod
|
|
212
|
+
def _ensure_gui_thread() -> None:
|
|
213
|
+
app = QGuiApplication.instance()
|
|
214
|
+
if app is None or QThread.currentThread() is not app.thread():
|
|
215
|
+
raise RuntimeError("IconController darf nur im GUI-Thread verwendet werden")
|
|
216
|
+
|
|
217
|
+
def _start(self, definition: AnimationDefinition | None) -> None:
|
|
218
|
+
self._generation += 1
|
|
219
|
+
generation = self._generation
|
|
220
|
+
self._definition = definition
|
|
221
|
+
if definition is None:
|
|
222
|
+
self._animating = False
|
|
223
|
+
self._show(1.0)
|
|
224
|
+
return
|
|
225
|
+
self._animating = True
|
|
226
|
+
self._start_ms = float(self._clock())
|
|
227
|
+
self._show(sample_animation(definition, 0.0).opacity)
|
|
228
|
+
if generation == self._generation:
|
|
229
|
+
self._schedule()
|
|
230
|
+
|
|
231
|
+
def _schedule(self) -> None:
|
|
232
|
+
assert self._definition is not None
|
|
233
|
+
elapsed_ms = float(self._clock()) - self._start_ms
|
|
234
|
+
delay = next_update_delay_ms(self._definition, elapsed_ms, self._frame_interval_ms)
|
|
235
|
+
self._timer.start(0 if delay is None else int(math.ceil(delay)))
|
|
236
|
+
|
|
237
|
+
def _on_timeout(self) -> None:
|
|
238
|
+
if self._disposed or not self._animating or self._definition is None:
|
|
239
|
+
return
|
|
240
|
+
generation = self._generation
|
|
241
|
+
elapsed = float(self._clock()) - self._start_ms
|
|
242
|
+
sample = sample_animation(self._definition, elapsed)
|
|
243
|
+
if sample.finished:
|
|
244
|
+
self._animating = False
|
|
245
|
+
self._timer.stop()
|
|
246
|
+
self._show(1.0)
|
|
247
|
+
if generation == self._generation:
|
|
248
|
+
self.animationFinished.emit()
|
|
249
|
+
return
|
|
250
|
+
self._show(sample.opacity)
|
|
251
|
+
if generation == self._generation:
|
|
252
|
+
self._schedule()
|
|
253
|
+
|
|
254
|
+
def _show(self, opacity: float) -> None:
|
|
255
|
+
assert self._appearance is not None
|
|
256
|
+
alpha = opacity_to_alpha(opacity)
|
|
257
|
+
key = (self._appearance, alpha)
|
|
258
|
+
self._opacity = opacity
|
|
259
|
+
if key == self._shown_key:
|
|
260
|
+
return
|
|
261
|
+
definition = self._definition
|
|
262
|
+
cache = alpha == 255 or definition is None or definition.transition == TRANSITION_STEP \
|
|
263
|
+
or alpha in (opacity_to_alpha(definition.min_opacity), opacity_to_alpha(definition.max_opacity))
|
|
264
|
+
self._icon = self._renderer.render_icon(self._appearance, background_opacity=opacity, cache=cache)
|
|
265
|
+
self._shown_key = key
|
|
266
|
+
self.iconChanged.emit(QIcon(self._icon))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Exception hierarchy of the dynamic icon engine.
|
|
2
|
+
|
|
3
|
+
:class:`DynamicIconEngineError` is the base class of the engine-specific
|
|
4
|
+
*domain* errors below. Validation errors of this hierarchy additionally derive
|
|
5
|
+
from :class:`ValueError`.
|
|
6
|
+
|
|
7
|
+
Not every deliberate error derives from this hierarchy: programming and
|
|
8
|
+
environment errors (wrong argument types, invalid constructor values, missing
|
|
9
|
+
``QGuiApplication``, use outside the GUI thread) are raised as the built-in
|
|
10
|
+
:class:`ValueError`, :class:`TypeError` or :class:`RuntimeError`. The exact
|
|
11
|
+
list is documented in ``docs/reference/errors.md``; hosts should treat those as
|
|
12
|
+
programming errors and catch :class:`DynamicIconEngineError` for runtime input.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DynamicIconEngineError(Exception):
|
|
19
|
+
"""Base class of all engine specific errors."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InvalidAppearanceError(DynamicIconEngineError, ValueError):
|
|
23
|
+
"""An :class:`~dynamic_icon_engine.IconAppearance` (or one of its fields) is invalid.
|
|
24
|
+
|
|
25
|
+
The controller keeps its last valid state when this error is raised.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InvalidAnimationError(DynamicIconEngineError, ValueError):
|
|
30
|
+
"""An :class:`~dynamic_icon_engine.AnimationDefinition` or animation name is invalid."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GraphicSetError(DynamicIconEngineError):
|
|
34
|
+
"""A graphic set could not be loaded (missing file, broken manifest, unusable image)."""
|