Debian Codegraph @

pyvista/plotting/interactor_style_registry.py

raw
1 """Registry for named interactor styles."""
2
3 from __future__ import annotations
4
5 from collections.abc import Mapping
6 from importlib.metadata import entry_points
7 from typing import TYPE_CHECKING
8 from typing import TypedDict
9
10 from pyvista._warn_external import warn_external
11 from pyvista.core.utilities._registry_helpers import handler_source
12
13 if TYPE_CHECKING:
14 from collections.abc import Callable
15 from typing import Any
16
17 InteractorStyleHandler = Callable[..., Any]
18
19
20 class _InteractorStyleRegistryState(TypedDict):
21 """Stored registry state used by tests."""
22
23 custom: dict[str, InteractorStyleHandler]
24 custom_sources: dict[str, str]
25 discovered: dict[str, InteractorStyleHandler]
26 discovered_sources: dict[str, str]
27 loaded: bool
28
29
30 INTERACTOR_STYLE_ENTRY_POINT_GROUP = 'pyvista.interactor_styles'
31
32 _BUILTIN_INTERACTOR_STYLE_METHODS = {
33 '2d_style': 'enable_2d_style',
34 'custom_trackball_style': 'enable_custom_trackball_style',
35 'image_style': 'enable_image_style',
36 'joystick_actor_style': 'enable_joystick_actor_style',
37 'joystick_style': 'enable_joystick_style',
38 'rubber_band_2d_style': 'enable_rubber_band_2d_style',
39 'rubber_band_style': 'enable_rubber_band_style',
40 'terrain_style': 'enable_terrain_style',
41 'trackball_actor_style': 'enable_trackball_actor_style',
42 'trackball_style': 'enable_trackball_style',
43 'zoom_style': 'enable_zoom_style',
44 }
45
46 _custom_interactor_styles: dict[str, InteractorStyleHandler] = {}
47 _custom_interactor_style_sources: dict[str, str] = {}
48 _discovered_entry_point_styles: dict[str, InteractorStyleHandler] = {}
49 _discovered_entry_point_sources: dict[str, str] = {}
50 _entry_points_loaded: bool = False
51
52
53 def _normalize_interactor_style_name(name: str) -> str:
54 """Normalize an interactor style name."""
55 return name.strip().lower()
56
57
58 def _save_registry_state() -> _InteractorStyleRegistryState:
59 """Snapshot the current registry state for later restoration."""
60 return {
61 'custom': _custom_interactor_styles.copy(),
62 'custom_sources': _custom_interactor_style_sources.copy(),
63 'discovered': _discovered_entry_point_styles.copy(),
64 'discovered_sources': _discovered_entry_point_sources.copy(),
65 'loaded': _entry_points_loaded,
66 }
67
68
69 def _restore_registry_state(state: _InteractorStyleRegistryState) -> None:
70 """Restore registry state from a snapshot."""
71 global _entry_points_loaded # noqa: PLW0603
72 _custom_interactor_styles.clear()
73 _custom_interactor_styles.update(state['custom'])
74 _custom_interactor_style_sources.clear()
75 _custom_interactor_style_sources.update(state['custom_sources'])
76 _discovered_entry_point_styles.clear()
77 _discovered_entry_point_styles.update(state['discovered'])
78 _discovered_entry_point_sources.clear()
79 _discovered_entry_point_sources.update(state['discovered_sources'])
80 _entry_points_loaded = state['loaded']
81
82
83 def register_interactor_style(
84 name: str,
85 handler: InteractorStyleHandler,
86 *,
87 override: bool = False,
88 ) -> None:
89 """Register a custom interactor style.
90
91 Parameters
92 ----------
93 name : str
94 Name of the interactor style. Built-in PyVista styles use names
95 that mirror the public ``enable_*_style`` API, such as
96 ``'terrain_style'``.
97
98 handler : callable
99 Handler for the interactor style. This can be a
100 :vtk:`vtkInteractorStyle` subclass (instantiated automatically)
101 or any callable with signature ``handler(interactor)`` that
102 returns an interactor style instance.
103
104 override : bool, default: False
105 If ``True``, allow registering a name that collides with a
106 built-in interactor style. Also silences the warning emitted
107 when replacing an existing custom registration.
108
109 Raises
110 ------
111 ValueError
112 If ``name`` is empty, or collides with a built-in PyVista
113 interactor style and ``override`` is ``False``.
114
115 Warns
116 -----
117 UserWarning
118 If ``name`` already refers to a registered custom interactor
119 style. The new registration replaces the old one (last wins);
120 pass ``override=True`` to silence the warning.
121
122 Examples
123 --------
124 Register a :vtk:`vtkInteractorStyle` subclass directly and use
125 it from a theme.
126
127 >>> import pyvista as pv
128 >>> from vtkmodules.vtkInteractionStyle import (
129 ... vtkInteractorStyleFlight,
130 ... )
131 >>> pv.register_interactor_style(
132 ... 'flight_style', vtkInteractorStyleFlight
133 ... ) # doctest: +SKIP
134 >>> pv.global_theme.interactor_style = 'flight_style' # doctest: +SKIP
135
136 A callable that takes the interactor as an argument can also be
137 registered.
138
139 >>> def custom_style(interactor): ...
140 >>> pv.register_interactor_style(
141 ... 'custom_style', custom_style
142 ... ) # doctest: +SKIP
143
144 """
145 normalized_name = _normalize_interactor_style_name(name)
146 if not normalized_name:
147 msg = 'Interactor style name must not be empty.'
148 raise ValueError(msg)
149 if not override and normalized_name in _BUILTIN_INTERACTOR_STYLE_METHODS:
150 msg = (
151 f'Cannot register custom interactor style "{normalized_name}": '
152 'collides with a built-in interactor style. '
153 'Use override=True to replace it.'
154 )
155 raise ValueError(msg)
156 if not override and normalized_name in _custom_interactor_styles:
157 existing_source = _custom_interactor_style_sources.get(normalized_name, '<unknown>')
158 warn_external(
159 f'Registering interactor style "{normalized_name}" replaces an '
160 f'existing custom registration from {existing_source}.',
161 )
162
163 _custom_interactor_styles[normalized_name] = handler
164 _custom_interactor_style_sources[normalized_name] = handler_source(handler)
165
166
167 def _get_interactor_style_handler(name: str) -> str | InteractorStyleHandler | None:
168 """Look up a registered interactor style by name."""
169 normalized_name = _normalize_interactor_style_name(name)
170 handler = _custom_interactor_styles.get(normalized_name)
171 if handler is not None:
172 return handler
173
174 builtin_method = _BUILTIN_INTERACTOR_STYLE_METHODS.get(normalized_name)
175 if builtin_method is not None:
176 return builtin_method
177
178 _ensure_entry_points()
179 return _discovered_entry_point_styles.get(normalized_name)
180
181
182 def _available_interactor_style_names() -> tuple[str, ...]:
183 """Return all currently available interactor style names."""
184 _ensure_entry_points()
185 names = (
186 set(_BUILTIN_INTERACTOR_STYLE_METHODS)
187 | set(_custom_interactor_styles)
188 | set(_discovered_entry_point_styles)
189 )
190 return tuple(sorted(names))
191
192
193 def _has_interactor_style(name: str) -> bool:
194 """Return ``True`` when an interactor style name is available."""
195 normalized_name = _normalize_interactor_style_name(name)
196 if normalized_name in _custom_interactor_styles:
197 return True
198 if normalized_name in _BUILTIN_INTERACTOR_STYLE_METHODS:
199 return True
200
201 _ensure_entry_points()
202 return normalized_name in _discovered_entry_point_styles
203
204
205 def _validate_interactor_style(name: object) -> str:
206 """Validate and normalize an interactor style name."""
207 if not isinstance(name, str):
208 msg = f'Interactor style must be a string, not {type(name).__name__}.'
209 raise TypeError(msg)
210
211 normalized_name = _normalize_interactor_style_name(name)
212 if _has_interactor_style(normalized_name):
213 return normalized_name
214
215 available_styles = ', '.join(f'"{item}"' for item in _available_interactor_style_names())
216 msg = f'Invalid interactor style "{name}".\nUse one of the following:\n{available_styles}'
217 raise ValueError(msg)
218
219
220 def _ensure_entry_points() -> None:
221 """Discover ``pyvista.interactor_styles`` entry points once."""
222 global _entry_points_loaded # noqa: PLW0603
223 if _entry_points_loaded:
224 return
225
226 _entry_points_loaded = True
227 for interactor_style_entry_point in entry_points(group=INTERACTOR_STYLE_ENTRY_POINT_GROUP):
228 source = interactor_style_entry_point.value
229 try:
230 loaded_handler = interactor_style_entry_point.load()
231 except Exception as exc: # noqa: BLE001
232 msg = (
233 f'Failed to load {INTERACTOR_STYLE_ENTRY_POINT_GROUP} entry point '
234 f'"{interactor_style_entry_point.name}" from {source}: {exc}'
235 )
236 warn_external(msg)
237 continue
238
239 if isinstance(loaded_handler, Mapping):
240 for style_name, style_handler in loaded_handler.items():
241 if not isinstance(style_name, str):
242 msg = (
243 f'Ignoring {INTERACTOR_STYLE_ENTRY_POINT_GROUP} entry point from '
244 f'{source}: style names must be strings.'
245 )
246 warn_external(msg)
247 continue
248 _register_discovered_interactor_style(
249 style_name,
250 style_handler,
251 source=source,
252 )
253 continue
254
255 _register_discovered_interactor_style(
256 interactor_style_entry_point.name,
257 loaded_handler,
258 source=source,
259 )
260
261
262 def _register_discovered_interactor_style(
263 name: str,
264 handler: object,
265 *,
266 source: str,
267 ) -> None:
268 """Register a discovered interactor style handler from an entry point."""
269 normalized_name = _normalize_interactor_style_name(name)
270 if not normalized_name:
271 msg = (
272 f'Ignoring {INTERACTOR_STYLE_ENTRY_POINT_GROUP} entry point from '
273 f'{source}: style name must not be empty.'
274 )
275 warn_external(msg)
276 return
277
278 if normalized_name in _BUILTIN_INTERACTOR_STYLE_METHODS:
279 msg = (
280 f'Ignoring {INTERACTOR_STYLE_ENTRY_POINT_GROUP} entry point '
281 f'"{normalized_name}" from {source}: collides with a built-in interactor style.'
282 )
283 warn_external(msg)
284 return
285
286 if normalized_name in _custom_interactor_styles:
287 return
288
289 if normalized_name in _discovered_entry_point_styles:
290 existing_source = _discovered_entry_point_sources[normalized_name]
291 msg = (
292 f'Multiple {INTERACTOR_STYLE_ENTRY_POINT_GROUP} providers registered for '
293 f'"{normalized_name}": {existing_source}, {source}. Using {existing_source}.'
294 )
295 warn_external(msg)
296 return
297
298 if not callable(handler):
299 msg = (
300 f'Ignoring {INTERACTOR_STYLE_ENTRY_POINT_GROUP} entry point '
301 f'"{normalized_name}" from {source}: handler is not callable.'
302 )
303 warn_external(msg)
304 return
305
306 _discovered_entry_point_styles[normalized_name] = handler
307 _discovered_entry_point_sources[normalized_name] = source