Debian Codegraph @

pyvista/plotting/theme_registry.py

raw
1 """Registry for named pyvista themes."""
2
3 from __future__ import annotations
4
5 from collections.abc import Mapping
6 from importlib import import_module
7 from importlib.metadata import EntryPoint
8 from importlib.metadata import entry_points
9 from typing import TYPE_CHECKING
10 from typing import Literal
11 from typing import NamedTuple
12 from typing import TypedDict
13
14 from pyvista._warn_external import warn_external
15 from pyvista.core.utilities._registry_helpers import handler_source
16
17 if TYPE_CHECKING:
18 from .themes import Theme
19
20
21 THEME_ENTRY_POINT_GROUP = 'pyvista.themes'
22
23
24 class ThemeRegistration(NamedTuple):
25 """Describe how a theme name became registered.
26
27 Returned by :func:`~pyvista.registered_themes`. ``kind`` distinguishes
28 the registration path: a :class:`~pyvista.plotting.themes.Theme`
29 subclass with a class-level ``_default_name`` (``'subclass'``), a
30 ``pyvista.themes`` entry point from an installed plugin
31 (``'entry_point'``), or a built-in legacy alias such as ``'default'``
32 or ``'vtk'`` (``'alias'``).
33
34 Attributes
35 ----------
36 name : str
37 The registered (normalized) theme name.
38 kind : {'subclass', 'entry_point', 'alias'}
39 How the name was registered.
40 source : str
41 Human-readable origin (e.g. ``'my_package.theme.MyTheme'``).
42
43 Examples
44 --------
45 Inspect how a name became registered.
46
47 >>> import pyvista as pv
48 >>> next(r for r in pv.registered_themes() if r.name == 'dark')
49 ThemeRegistration(name='dark', kind='subclass', source='pyvista.plotting.themes.DarkTheme')
50
51 """
52
53 name: str
54 kind: Literal['subclass', 'entry_point', 'alias']
55 source: str
56
57
58 class _ThemeRegistryState(TypedDict):
59 """Stored registry state used by tests."""
60
61 classes: dict[str, type[Theme]]
62 classes_sources: dict[str, str]
63 aliases: set[str]
64 discovered: dict[str, type[Theme] | Theme]
65 discovered_sources: dict[str, str]
66 pending: dict[str, list[EntryPoint]]
67 loaded: bool
68
69
70 _registered_theme_classes: dict[str, type[Theme]] = {}
71 _registered_theme_classes_sources: dict[str, str] = {}
72 _registered_theme_aliases: set[str] = set()
73 _discovered_entry_point_themes: dict[str, type[Theme] | Theme] = {}
74 _discovered_entry_point_sources: dict[str, str] = {}
75 # Entry-point metadata, populated by ``_ensure_entry_points``. Maps each
76 # theme name to the list of ``EntryPoint`` records that declared it. The
77 # plugin module itself is *not* imported until that name is actually
78 # requested via :func:`_resolve_theme`, keeping ``set_plot_theme`` calls
79 # for built-in themes free of third-party plugin import cost.
80 _pending_ep_themes: dict[str, list[EntryPoint]] = {}
81 _entry_points_loaded: bool = False
82
83
84 def _normalize_theme_name(name: str) -> str:
85 """Normalize a theme name."""
86 return name.strip().lower()
87
88
89 def _save_registry_state() -> _ThemeRegistryState:
90 """Snapshot the current registry state for later restoration."""
91 return {
92 'classes': _registered_theme_classes.copy(),
93 'classes_sources': _registered_theme_classes_sources.copy(),
94 'aliases': _registered_theme_aliases.copy(),
95 'discovered': _discovered_entry_point_themes.copy(),
96 'discovered_sources': _discovered_entry_point_sources.copy(),
97 'pending': {k: list(v) for k, v in _pending_ep_themes.items()},
98 'loaded': _entry_points_loaded,
99 }
100
101
102 def _restore_registry_state(state: _ThemeRegistryState) -> None:
103 """Restore registry state from a snapshot."""
104 global _entry_points_loaded # noqa: PLW0603
105 _registered_theme_classes.clear()
106 _registered_theme_classes.update(state['classes'])
107 _registered_theme_classes_sources.clear()
108 _registered_theme_classes_sources.update(state['classes_sources'])
109 _registered_theme_aliases.clear()
110 _registered_theme_aliases.update(state['aliases'])
111 _discovered_entry_point_themes.clear()
112 _discovered_entry_point_themes.update(state['discovered'])
113 _discovered_entry_point_sources.clear()
114 _discovered_entry_point_sources.update(state['discovered_sources'])
115 _pending_ep_themes.clear()
116 _pending_ep_themes.update({k: list(v) for k, v in state['pending'].items()})
117 _entry_points_loaded = state['loaded']
118
119
120 def _register_theme_class(name: str, cls: type[Theme], *, source: str) -> None:
121 """Register a ``Theme`` subclass. Called from ``Theme.__init_subclass__``.
122
123 Collisions warn (do not raise) so that a subclass definition at
124 import time cannot crash the interpreter. Last wins, mirroring the
125 behavior of every other PyVista plugin registry.
126 """
127 normalized = _normalize_theme_name(name)
128 if not normalized:
129 warn_external(
130 f'Theme class {source} declared an empty ``_default_name``; skipped.',
131 )
132 return
133 if normalized in _registered_theme_classes:
134 existing = _registered_theme_classes_sources.get(normalized, '<unknown>')
135 warn_external(
136 f'Registering theme "{normalized}" from {source} replaces an '
137 f'existing registration from {existing}.',
138 )
139 _registered_theme_classes[normalized] = cls
140 _registered_theme_classes_sources[normalized] = source
141
142
143 def _register_alias(name: str, cls: type[Theme]) -> None:
144 """Register a built-in name alias (e.g. ``'default' → DocumentTheme``).
145
146 Bypasses collision detection so built-in aliases can coexist with
147 auto-registered subclasses without warning.
148 """
149 normalized = _normalize_theme_name(name)
150 _registered_theme_classes[normalized] = cls
151 _registered_theme_classes_sources[normalized] = handler_source(cls)
152 _registered_theme_aliases.add(normalized)
153
154
155 def _lookup_explicit(normalized: str) -> Theme | None:
156 """Look up a normalized name in the explicit subclass registry.
157
158 Classes are instantiated fresh every call so callers never share a
159 registered instance with the global theme.
160 """
161 cls = _registered_theme_classes.get(normalized)
162 if cls is not None:
163 return cls()
164 return None
165
166
167 def _lookup_discovered(normalized: str) -> Theme | None:
168 """Look up a normalized name in the loaded entry-point registry."""
169 discovered = _discovered_entry_point_themes.get(normalized)
170 if isinstance(discovered, type):
171 return discovered()
172 return discovered
173
174
175 def _resolve_theme(name: str) -> Theme | None:
176 """Look up a theme by name and return a usable ``Theme`` instance.
177
178 Explicit subclass registrations win over entry-point discoveries.
179 Entry-point plugins are imported lazily — only the plugin claiming
180 *name* loads, sibling plugins stay pending.
181 """
182 normalized = _normalize_theme_name(name)
183
184 resolved = _lookup_explicit(normalized)
185 if resolved is not None:
186 return resolved
187
188 _ensure_entry_points()
189
190 # Fast path: load the plugin claiming this exact name.
191 if normalized in _pending_ep_themes:
192 _resolve_pending_theme(normalized)
193
194 # Loading an entry point's module may have triggered __init_subclass__
195 # on a Theme subclass, which populates the explicit registry. Re-check
196 # before falling back to the discovered registry.
197 resolved = _lookup_explicit(normalized)
198 if resolved is not None:
199 return resolved
200 resolved = _lookup_discovered(normalized)
201 if resolved is not None:
202 return resolved
203
204 # Final fallback: a Mapping-style entry point may expose names that
205 # differ from its ``ep.name``. The fast path above only matches by
206 # ``ep.name``, so resolve any remaining pending EPs as a last resort.
207 for pending_name in list(_pending_ep_themes):
208 _resolve_pending_theme(pending_name)
209 resolved = _lookup_explicit(normalized)
210 if resolved is not None:
211 return resolved
212 resolved = _lookup_discovered(normalized)
213 if resolved is not None:
214 return resolved
215 return None
216
217
218 def _available_theme_names() -> tuple[str, ...]:
219 """Return all currently registered theme names.
220
221 Pending entry-point names appear in the result without triggering
222 plugin imports — only metadata is consulted.
223 """
224 _ensure_entry_points()
225 names = (
226 set(_registered_theme_classes)
227 | set(_discovered_entry_point_themes)
228 | set(_pending_ep_themes)
229 )
230 return tuple(sorted(names))
231
232
233 def registered_themes() -> tuple[ThemeRegistration, ...]:
234 """Return all registered themes.
235
236 Use this to discover which names can be passed to
237 :func:`~pyvista.set_plot_theme` or the ``PYVISTA_PLOT_THEME``
238 environment variable. Entry-point plugins are loaded on the first
239 call so they appear in the result.
240
241 Returns
242 -------
243 tuple[pyvista.ThemeRegistration, ...]
244 One record per registered theme, sorted by name. Each record
245 exposes ``name``, ``kind``, and ``source``.
246
247 Examples
248 --------
249 List available theme names.
250
251 >>> import pyvista as pv
252 >>> for record in pv.registered_themes():
253 ... print(record.name)
254 dark
255 default
256 document
257 document_build
258 document_pro
259 paraview
260 testing
261 vtk
262
263 Inspect how a name became registered.
264
265 >>> next(r for r in pv.registered_themes() if r.name == 'dark').kind
266 'subclass'
267
268 """
269 _ensure_entry_points()
270 # Force every pending plugin to load so the result reflects every
271 # theme visible to PyVista. A plugin that fails to import emits a
272 # ``UserWarning`` and is skipped; the rest still appear.
273 for pending_name in list(_pending_ep_themes):
274 _resolve_pending_theme(pending_name)
275 records: list[ThemeRegistration] = []
276 for name, cls in _registered_theme_classes.items():
277 kind: Literal['subclass', 'alias'] = (
278 'alias' if name in _registered_theme_aliases else 'subclass'
279 )
280 source = _registered_theme_classes_sources.get(name, handler_source(cls))
281 records.append(ThemeRegistration(name=name, kind=kind, source=source))
282 seen = {r.name for r in records}
283 for name in _discovered_entry_point_themes:
284 if name in seen:
285 # Explicit registrations always win over entry-point providers.
286 continue
287 records.append(
288 ThemeRegistration(
289 name=name,
290 kind='entry_point',
291 source=_discovered_entry_point_sources.get(name, '<unknown>'),
292 )
293 )
294 return tuple(sorted(records, key=lambda r: r.name))
295
296
297 def _resolve_dotted_path(spec: str) -> type[Theme]:
298 """Resolve a ``'package.module:ClassName'`` spec to a ``Theme`` subclass."""
299 from .themes import Theme # local import breaks circular dependency # noqa: PLC0415
300
301 if ':' not in spec:
302 msg = f'Theme spec "{spec}" must use "package.module:ClassName" form.'
303 raise ValueError(msg)
304 module_path, _, class_name = spec.partition(':')
305 if not module_path or not class_name:
306 msg = f'Invalid theme spec "{spec}".'
307 raise ValueError(msg)
308 try:
309 module = import_module(module_path)
310 except ImportError as exc:
311 msg = f'Cannot import "{module_path}" from theme spec "{spec}": {exc}'
312 raise ValueError(msg) from exc
313 cls = getattr(module, class_name, None)
314 if cls is None:
315 msg = f'"{class_name}" not found in module "{module_path}".'
316 raise ValueError(msg)
317 if not (isinstance(cls, type) and issubclass(cls, Theme)):
318 # ValueError (not TypeError) keeps parity with the other dotted-path
319 # failure modes and lets _set_plot_theme_from_env catch it uniformly.
320 msg = f'"{spec}" does not resolve to a pyvista Theme subclass.'
321 raise ValueError(msg) # noqa: TRY004
322 return cls
323
324
325 def _ensure_entry_points() -> None:
326 """Scan ``pyvista.themes`` entry-point metadata once.
327
328 Populates :data:`_pending_ep_themes` with every name declared by an
329 installed plugin. The plugin modules themselves are **not** imported
330 here; the cost is one ``importlib.metadata.entry_points`` call.
331 Plugin imports are deferred to :func:`_resolve_pending_theme`, which
332 runs only when a theme with that specific name is actually requested.
333 """
334 global _entry_points_loaded # noqa: PLW0603
335 if _entry_points_loaded:
336 return
337 _entry_points_loaded = True
338
339 for ep in entry_points(group=THEME_ENTRY_POINT_GROUP):
340 normalized = _normalize_theme_name(ep.name)
341 if not normalized:
342 warn_external(
343 f'Ignoring {THEME_ENTRY_POINT_GROUP} entry point from '
344 f'{ep.value}: theme name must not be empty.',
345 )
346 continue
347 if normalized in _registered_theme_classes:
348 # Explicit registration wins silently — user-owned registrations
349 # shouldn't be shouted at just because a plugin also defines it.
350 continue
351 _pending_ep_themes.setdefault(normalized, []).append(ep)
352
353
354 def _resolve_pending_theme(name: str) -> bool:
355 """Import the plugin claiming *name*, if any.
356
357 Returns
358 -------
359 bool
360 ``True`` if a plugin loaded successfully and contributed at least
361 one registration. ``False`` if no pending plugin matches, or if
362 the plugin failed to import.
363
364 Notes
365 -----
366 A plugin that fails to import emits a ``UserWarning`` and is dropped
367 from the pending list, so subsequent lookups of the same name fall
368 straight through without re-triggering the import or re-emitting the
369 warning.
370
371 """
372 eps = _pending_ep_themes.pop(name, None)
373 if not eps:
374 return False
375 winner = eps[0]
376 source = winner.value
377 try:
378 # ep.load() runs third-party import machinery — it can raise
379 # literally anything. Convert to a warning so one broken plugin
380 # cannot take down every theme lookup.
381 loaded = winner.load()
382 except Exception as exc: # noqa: BLE001
383 warn_external(
384 f'Failed to load {THEME_ENTRY_POINT_GROUP} entry point '
385 f'"{winner.name}" from {source}: {exc}',
386 )
387 return False
388
389 if isinstance(loaded, Mapping):
390 for theme_name, theme_obj in loaded.items():
391 if not isinstance(theme_name, str):
392 warn_external(
393 f'Ignoring {THEME_ENTRY_POINT_GROUP} entry point from '
394 f'{source}: theme names must be strings.',
395 )
396 continue
397 _register_discovered_theme(theme_name, theme_obj, source=source)
398 else:
399 _register_discovered_theme(winner.name, loaded, source=source)
400
401 if len(eps) > 1:
402 providers = ', '.join(ep.value for ep in eps)
403 warn_external(
404 f'Multiple {THEME_ENTRY_POINT_GROUP} providers registered for '
405 f'"{name}": {providers}. Using {source}.',
406 )
407 return name in _registered_theme_classes or name in _discovered_entry_point_themes
408
409
410 def _register_discovered_theme(name: str, obj: object, *, source: str) -> None:
411 """Register an entry-point-discovered theme."""
412 from .themes import Theme # local import breaks circular dependency # noqa: PLC0415
413
414 normalized = _normalize_theme_name(name)
415 if not normalized:
416 warn_external(
417 f'Ignoring {THEME_ENTRY_POINT_GROUP} entry point from '
418 f'{source}: theme name must not be empty.',
419 )
420 return
421
422 if normalized in _registered_theme_classes:
423 # Explicit registration wins silently — user-owned registrations
424 # shouldn't be shouted at just because a plugin also defines it.
425 return
426
427 if normalized in _discovered_entry_point_themes:
428 existing = _discovered_entry_point_sources[normalized]
429 warn_external(
430 f'Multiple {THEME_ENTRY_POINT_GROUP} providers registered for '
431 f'"{normalized}": {existing}, {source}. Using {existing}.',
432 )
433 return
434
435 is_class = isinstance(obj, type) and issubclass(obj, Theme)
436 is_instance = isinstance(obj, Theme)
437 if not (is_class or is_instance):
438 warn_external(
439 f'Ignoring {THEME_ENTRY_POINT_GROUP} entry point "{normalized}" '
440 f'from {source}: value is not a pyvista Theme subclass or instance.',
441 )
442 return
443
444 # ``obj`` was just narrowed to ``type[Theme] | Theme`` by the
445 # ``is_class or is_instance`` check, but mypy can't see through the
446 # boolean union. Safe to assign.
447 _discovered_entry_point_themes[normalized] = obj # type: ignore[assignment]
448 _discovered_entry_point_sources[normalized] = source