Debian Codegraph @

pyvista/plotting/render_window_interactor.py

raw
1 """Wrap :vtk:`vtkRenderWindowInteractor`."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from contextlib import contextmanager
7 from functools import partial
8 from inspect import signature
9 import logging
10 import time
11 from typing import TYPE_CHECKING
12 from typing import Literal
13 import weakref
14
15 import numpy as np
16
17 import pyvista as pv
18 from pyvista import _vtk
19 from pyvista import vtk_version_info
20 from pyvista._deprecate_positional_args import _deprecate_positional_args
21 from pyvista._warn_external import warn_external
22 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
23 from pyvista.core.utilities.misc import _NoNewAttrMixin
24 from pyvista.core.utilities.misc import abstract_class
25 from pyvista.core.utilities.misc import try_callback
26
27 from .errors import MismatchedInteractorError
28 from .interactor_style_registry import _get_interactor_style_handler
29 from .interactor_style_registry import _validate_interactor_style
30 from .opts import PickerType
31
32 if TYPE_CHECKING:
33 from .interactor_style_registry import InteractorStyleHandler
34
35 log = logging.getLogger(__name__)
36 log.setLevel('CRITICAL')
37 log.addHandler(logging.StreamHandler())
38
39
40 class Timer(_NoNewAttrMixin):
41 """Timer class.
42
43 Parameters
44 ----------
45 max_steps : int
46 Maximum number of steps to allow for the timer before destroying it.
47
48 callback : callable
49 A callable that takes one argument. It will be passed `step`,
50 which is the number of times the timer event has occurred.
51
52 """
53
54 def __init__(self, max_steps, callback):
55 """Initialize."""
56 self.step = 0
57 self.max_steps = max_steps
58 self.id = None
59 self.callback = callback
60
61 def execute(self, obj, _event): # pragma: no cover # numpydoc ignore=PR01,RT01
62 """Execute Timer."""
63 # https://github.com/pyvista/pyvista/pull/5618
64 iren = obj
65
66 if self.step < self.max_steps:
67 self.callback(self.step)
68 iren.GetRenderWindow().Render()
69 self.step += 1
70 elif self.id:
71 iren.DestroyTimer(self.id)
72
73
74 class RenderWindowInteractor(_NoNewAttrMixin):
75 """Wrap :vtk:`vtkRenderWindowInteractor`.
76
77 This class has been added for the purpose of making some methods
78 we add to the RenderWindowInteractor more python, like certain
79 testing methods.
80
81 Parameters
82 ----------
83 plotter : pyvista.Plotter
84 Plotter object upon which the initialization of
85 RenderWindowInteractor is based.
86
87 desired_update_rate : float, default: 30
88 The desired update rate of the interactor.
89
90 light_follow_camera : bool, default: True
91 If set to ``True``, the light follows the camera.
92
93 interactor : :vtk:`vtkRenderWindowInteractor`, default: None
94 The render window interactor. If set to ``None``, a new
95 :vtk:`vtkRenderWindowInteractor` instance will be created.
96
97 """
98
99 @_deprecate_positional_args(allowed=['plotter'])
100 def __init__( # noqa: PLR0917
101 self,
102 plotter,
103 desired_update_rate=30,
104 light_follow_camera=True, # noqa: FBT002
105 interactor=None,
106 ):
107 """Initialize."""
108 if interactor is None:
109 interactor = _vtk.vtkRenderWindowInteractor()
110 self.interactor = interactor
111 self.interactor.SetDesiredUpdateRate(desired_update_rate)
112 if not light_follow_camera:
113 self.interactor.LightFollowCameraOff()
114
115 # Map of observers to events
116 self._observers = {}
117 self._last_key: str | None = None
118 self._key_press_event_callbacks = defaultdict(list)
119 self._click_event_callbacks = { # type: ignore[var-annotated]
120 event: {(double, v): [] for double in (False, True) for v in (False, True)}
121 for event in ('LeftButtonPressEvent', 'RightButtonPressEvent')
122 }
123 self._timer = None
124 self._timer_event = None
125 self._click_time = 0
126 self._MAX_CLICK_DELAY = 0.8 # seconds
127 self._MAX_CLICK_DELTA = 40 # squared => ~6 pixels
128
129 # Set default style
130 self._style_class: _vtk.vtkInteractorStyle | None = None
131 self._style: Literal['Interactor', 'Context'] | None = 'Interactor'
132 self._prev_style_class: _vtk.vtkInteractorStyle | None = self._style_class
133 self._prev_style: Literal['Interactor', 'Context'] | None = self._style
134 self.style = InteractorStyleRubberBandPick(self)
135 self.__plotter = weakref.ref(plotter)
136
137 # Toggle interaction style when clicked on a visible chart (to
138 # enable interaction with visible charts)
139 self._context_style = _vtk.vtkContextInteractorStyle()
140 self.track_click_position(
141 self._toggle_chart_interaction,
142 side='left',
143 double=True,
144 viewport=True,
145 )
146
147 self.reset_picker()
148 self.picker = PickerType.POINT
149
150 @property
151 def _plotter(self):
152 """Return the plotter."""
153 return self.__plotter()
154
155 def add_key_event(self, key, callback):
156 """Add a function to callback when the given key is pressed.
157
158 These are non-unique - thus a key could map to many callback
159 functions. The callback function must not have any arguments.
160
161 Parameters
162 ----------
163 key : str
164 The key to trigger the event.
165
166 callback : callable
167 A callable that takes no arguments (keyword arguments are allowed).
168
169 """
170 if not callable(callback):
171 msg = 'callback must be callable.'
172 raise TypeError(msg)
173 for param in signature(callback).parameters.values():
174 if param.default is param.empty:
175 msg = '`callback` must not have any arguments without default values.'
176 raise TypeError(msg)
177 self._key_press_event_callbacks[key].append(callback)
178
179 def add_timer_event(self, max_steps, duration, callback):
180 """Add a function to callback as timer event.
181
182 Parameters
183 ----------
184 max_steps : int
185 Maximum number of steps for integrating a timer.
186
187 duration : int
188 Time (in milliseconds) before the timer emits a TimerEvent and
189 ``callback`` is called.
190
191 callback : callable
192 A callable that takes one argument. It will be passed
193 `step`, which is the number of times the timer event has occurred.
194
195 See Also
196 --------
197 :ref:`animation_example`
198
199 Examples
200 --------
201 Add a timer to a Plotter to move a sphere across a scene.
202
203 >>> import pyvista as pv
204 >>> sphere = pv.Sphere()
205 >>> pl = pv.Plotter()
206 >>> actor = pl.add_mesh(sphere)
207 >>> def callback(step):
208 ... actor.position = [step / 100.0, step / 100.0, 0]
209 >>> pl.add_timer_event(max_steps=200, duration=500, callback=callback)
210
211 """
212 self._timer = Timer(max_steps, callback)
213 self.add_observer('TimerEvent', self._timer.execute)
214 self._timer.id = self.create_timer(duration)
215
216 @staticmethod
217 def _get_event_str(event):
218 if isinstance(event, str):
219 # Make sure we pass it at least once through these functions, such that
220 # invalid event names are mapped to "NoEvent".
221 event = _vtk.vtkCommand.GetEventIdFromString(event)
222 return _vtk.vtkCommand.GetStringFromEventId(event)
223
224 @_deprecate_positional_args(allowed=['event', 'call'])
225 def add_observer(self, event, call, interactor_style_fallback=True): # noqa: FBT002
226 """Add an observer for the given event.
227
228 Parameters
229 ----------
230 event : str | int
231 The event to observe. Either the name of this event (string) or
232 a VTK event identifier (int).
233
234 call : callable
235 Callback to be called when the event is invoked.
236
237 interactor_style_fallback : bool
238 If ``True``, the observer will be added to the interactor style
239 in cases known to be problematic.
240
241 Returns
242 -------
243 int
244 The identifier of the added observer.
245
246 Examples
247 --------
248 Add a custom observer.
249
250 >>> import pyvista as pv
251 >>> pl = pv.Plotter()
252 >>> obs_enter = pl.iren.add_observer('EnterEvent', lambda *_: print('Enter!'))
253
254 """
255 call = partial(try_callback, call)
256 event = self._get_event_str(event)
257
258 if (
259 isinstance(self.style, InteractorStyleCaptureMixin)
260 and interactor_style_fallback
261 and event
262 in [
263 'LeftButtonReleaseEvent',
264 'RightButtonReleaseEvent',
265 ]
266 ):
267 # Release events are swallowed by the interactor, but registering
268 # on the interactor style seems to work.
269 # See https://github.com/pyvista/pyvista/issues/4976
270 observer = self.style.add_observer(event, call)
271 else:
272 observer = self.interactor.AddObserver(event, call)
273 self._observers[observer] = event
274 return observer
275
276 def remove_observer(self, observer):
277 """Remove an observer.
278
279 Parameters
280 ----------
281 observer : int
282 The identifier of the observer to remove.
283
284 Examples
285 --------
286 Add an observer and immediately remove it.
287
288 >>> import pyvista as pv
289 >>> pl = pv.Plotter()
290 >>> obs_enter = pl.iren.add_observer('EnterEvent', lambda *_: print('Enter!'))
291 >>> pl.iren.remove_observer(obs_enter)
292
293 """
294 if observer in self._observers:
295 self.interactor.RemoveObserver(observer)
296 del self._observers[observer]
297
298 def remove_observers(self, event=None):
299 """Remove all observers.
300
301 Parameters
302 ----------
303 event : str | int, optional
304 If provided, only removes observers of the given event. Otherwise,
305 if it is ``None``, removes all observers.
306
307 Examples
308 --------
309 Add two observers and immediately remove them.
310
311 >>> import pyvista as pv
312 >>> pl = pv.Plotter()
313 >>> obs_enter = pl.iren.add_observer('EnterEvent', lambda *_: print('Enter!'))
314 >>> obs_leave = pl.iren.add_observer('LeaveEvent', lambda *_: print('Leave!'))
315 >>> pl.iren.remove_observers()
316
317 """
318 if event is None:
319 observers = list(self._observers.keys())
320 else:
321 event = self._get_event_str(event)
322 observers = [obs for obs, ev in self._observers.items() if event == ev]
323 for observer in observers:
324 self.remove_observer(observer)
325
326 @_deprecate_positional_args(allowed=['key'])
327 def clear_events_for_key(self, key, raise_on_missing=False): # noqa: FBT002
328 """Remove the callbacks associated to the key.
329
330 Parameters
331 ----------
332 key : str
333 Key to clear events for.
334
335 raise_on_missing : bool, default: False
336 Whether to raise a :class:`ValueError` if there are no events
337 registered for the given key.
338
339 """
340 try:
341 self._key_press_event_callbacks.pop(key)
342 except KeyError:
343 if raise_on_missing:
344 msg = f'No events found for key {key!r}.'
345 raise ValueError(msg) from None
346
347 def track_mouse_position(self, callback):
348 """Keep track of the mouse position.
349
350 This will potentially slow down the interactor. No callbacks supported
351 here - use :func:`pyvista.Plotter.track_click_position` instead.
352
353 Parameters
354 ----------
355 callback : callable
356 A function to call back when the mouse moves. This function will be
357 passed the current mouse position.
358
359 """
360 self.add_observer(_vtk.vtkCommand.MouseMoveEvent, callback)
361
362 def untrack_mouse_position(self):
363 """Stop tracking the mouse position."""
364 self.remove_observers(_vtk.vtkCommand.MouseMoveEvent)
365
366 @staticmethod
367 def _get_click_event(side) -> str:
368 side = str(side).lower()
369 if side in ['right', 'r']:
370 return 'RightButtonPressEvent'
371 elif side in ['left', 'l']:
372 return 'LeftButtonPressEvent'
373 else:
374 msg = f'Side ({side}) not supported. Try `left` or `right`.'
375 raise TypeError(msg)
376
377 def _click_event(self, _obj, event):
378 t = time.time()
379 dt = t - self._click_time
380 last_pos = self._plotter.click_position or (0, 0)
381
382 self._plotter.store_click_position()
383 dp = (self._plotter.click_position[0] - last_pos[0]) ** 2
384 dp += (self._plotter.click_position[1] - last_pos[1]) ** 2
385 double = dp < self._MAX_CLICK_DELTA and dt < self._MAX_CLICK_DELAY
386 # Reset click time in case of a double click, otherwise a subsequent third click
387 # is considered to be a double click as well.
388 self._click_time = 0 if double else t # type: ignore[assignment]
389
390 for callback in self._click_event_callbacks[event][double, False]:
391 callback(self._plotter.pick_click_position())
392 for callback in self._click_event_callbacks[event][double, True]:
393 callback(self._plotter.click_position)
394
395 @_deprecate_positional_args(allowed=['callback', 'side'])
396 def track_click_position( # noqa: PLR0917,
397 self,
398 callback=None,
399 side='right',
400 double=False, # noqa: FBT002
401 viewport=False, # noqa: FBT002
402 ):
403 """Keep track of the click position.
404
405 By default, it only tracks right clicks.
406
407 Parameters
408 ----------
409 callback : callable, optional
410 A callable method that will use the click position. Passes
411 the click position as a length two tuple.
412
413 side : str, default: "right"
414 The mouse button to track (either ``'left'`` or ``'right'``).
415 Also accepts ``'r'`` or ``'l'``.
416
417 double : bool, default: False
418 Track single clicks if ``False``, double clicks if ``True``.
419 Defaults to single clicks.
420
421 viewport : bool, default: False
422 If ``True``, uses the normalized viewport coordinate
423 system (values between 0.0 and 1.0 and support for HiDPI)
424 when passing the click position to the callback.
425
426 """
427 event = self._get_click_event(side)
428 add_observer = all(len(cbs) == 0 for cbs in self._click_event_callbacks[event].values())
429 if callback is None and add_observer:
430 # No observers for this event yet and custom callback not given
431 # insert dummy callback
432 callback = lambda _, __: None
433 if callable(callback):
434 self._click_event_callbacks[event][double, viewport].append(callback)
435 else:
436 msg = 'Invalid callback provided, it should be either ``None`` or a callable.'
437 raise TypeError(msg)
438
439 if add_observer:
440 self.add_observer(event, self._click_event)
441
442 def untrack_click_position(self, side='right'):
443 """Stop tracking the click position.
444
445 Parameters
446 ----------
447 side : str, optional
448 The mouse button to stop tracking (either ``'left'`` or
449 ``'right'``). Default is ``'right'``. Also accepts ``'r'``
450 or ``'l'``.
451
452 """
453 event = self._get_click_event(side)
454 self.remove_observers(event)
455 for cbs in self._click_event_callbacks[event].values():
456 cbs.clear()
457
458 def clear_key_event_callbacks(self):
459 """Clear key event callbacks."""
460 self._key_press_event_callbacks.clear()
461
462 def key_press_event(self, *args): # noqa: ARG002
463 """Listen for key press event."""
464 key = self.interactor.GetKeySym()
465 log.debug(f'Key {key} pressed')
466 self._last_key = key
467 if key in self._key_press_event_callbacks.keys():
468 # Note that defaultdict's will never throw a key error
469 callbacks = self._key_press_event_callbacks[key]
470 for func in callbacks:
471 func()
472
473 def update_style(self):
474 """Update the camera interactor style.
475
476 Called when setting :meth:`style` attribute.
477 """
478 self.interactor.SetInteractorStyle(self.style)
479
480 @property
481 def style(
482 self,
483 ) -> (
484 _vtk.vtkContextInteractorStyle
485 | _vtk.vtkInteractorStyle
486 | InteractorStyleCaptureMixin
487 | None
488 ):
489 """Get/set the current interactor style.
490
491 When set to a string, the name is resolved through the
492 interactor style registry (equivalent to calling
493 :meth:`enable_interactor_style`).
494
495 .. warning::
496
497 Setting an interactor style needs careful control of events handling.
498 See :class:`~plotting.render_window_interactor.InteractorStyleCaptureMixin`
499 and its implementation as an example.
500
501 Returns
502 -------
503 output : :vtk:`vtkInteractorStyle` | :vtk:`vtkContextInteractorStyle` | None
504 The current interactor style.
505
506 Examples
507 --------
508 Set interactor style by name.
509
510 >>> import pyvista as pv
511 >>> pl = pv.Plotter()
512 >>> pl.iren.style = 'terrain_style'
513
514 Set interactor style with a customized vtk interactor.
515
516 >>> from vtkmodules.vtkInteractionStyle import (
517 ... vtkInteractorStyleTrackballCamera,
518 ... )
519
520 >>> class MyCustomInteractorStyle(vtkInteractorStyleTrackballCamera):
521 ... # Implement custom functionality
522 ... def __repr__(self):
523 ... return 'A custom interactor style.'
524
525 >>> pl = pv.Plotter()
526 >>> pl.iren.style = MyCustomInteractorStyle()
527 >>> pl.iren.style
528 A custom interactor style.
529
530 """
531 return self._style_class
532
533 @style.setter
534 def style(self, style: _vtk.vtkInteractorStyle | InteractorStyleCaptureMixin | str | None):
535 if isinstance(style, str):
536 self.enable_interactor_style(style)
537 return
538 self._style = 'Interactor'
539 self._style_class = style
540 self.update_style()
541
542 def _toggle_chart_interaction(self, mouse_pos):
543 """Toggle interaction with indicated charts.
544
545 Parameters
546 ----------
547 mouse_pos : tuple of float
548 Tuple containing the mouse position.
549
550 """
551 # Loop over all renderers to see whether any charts need to be made interactive
552 interactive_scene = None
553 for renderer in self._plotter.renderers:
554 if interactive_scene is None and renderer.IsInViewport(*mouse_pos):
555 # No interactive charts yet and mouse is within this renderer's viewport,
556 # so collect all charts indicated by the mouse (typically only one, except
557 # when there are overlapping charts).
558 origin = renderer.GetOrigin() # Correct for viewport origin (see #3278)
559 charts = renderer._get_charts_by_pos(
560 (mouse_pos[0] - origin[0], mouse_pos[1] - origin[1]),
561 )
562 if charts:
563 # Toggle interaction for indicated charts and determine whether
564 # there are any remaining interactive charts.
565 interactive_charts = renderer.set_chart_interaction(charts, toggle=True)
566 if interactive_charts:
567 # Save a reference to this renderer's scene if there are
568 # remaining interactive charts.
569 interactive_scene = renderer._charts._scene
570 else:
571 # No indicated charts, so disable interaction with all charts
572 # for this renderer.
573 renderer.set_chart_interaction(False)
574 else:
575 # Not in viewport or interactive charts were already found in another
576 # renderer, so disable interaction with all charts for this renderer.
577 renderer.set_chart_interaction(False)
578 # Manually set context_style based on found interactive scene (or stop interaction
579 # with any scene if there are no interactive charts).
580 self._set_context_style(interactive_scene)
581
582 def _set_context_style(self, scene):
583 """Set the context style interactor or switch back to previous interactor style.
584
585 Parameters
586 ----------
587 scene : :vtk:`vtkContextScene`, optional
588 The scene to interact with or ``None`` to stop interaction with any scene.
589
590 """
591 # Set scene to interact with or reset it to stop interaction (otherwise crash)
592 if (
593 vtk_version_info < (9, 3, 0) and scene is not None and len(self._plotter.renderers) > 1
594 ): # pragma: no cover
595 warn_external(
596 'Interaction with charts is not possible when using multiple subplots.'
597 'Upgrade to VTK 9.3 or newer to enable this feature.',
598 )
599 scene = None
600 self._context_style.SetScene(scene)
601 if scene is None and self._style == 'Context':
602 # Switch back to previous interactor style
603 self._style = self._prev_style
604 self.style = self._prev_style_class
605 self._prev_style = None
606 self._prev_style_class = None
607 elif scene is not None and self._style != 'Context':
608 # Enable context interactor style
609 self._prev_style = self._style
610 self._prev_style_class = self.style
611 self._style = 'Context'
612 self._style_class = self._context_style
613 self.update_style()
614
615 def enable_trackball_style(self):
616 """Set the interactive style to Trackball Camera.
617
618 The trackball camera is the default interactor style. Moving
619 the mouse moves the camera around, leaving the scene intact.
620
621 For a 3-button mouse, the left button is for rotation, the
622 right button for zooming, the middle button for panning, and
623 ctrl + left button for spinning the view around the viewing
624 axis of the camera. Alternatively, ctrl + shift + left button
625 or mouse wheel zooms, and shift + left button pans.
626
627 See Also
628 --------
629 pyvista.Plotter.enable_custom_trackball_style
630 A style that can be customized for mouse actions.
631
632 Examples
633 --------
634 Create a simple scene with a plotter that has the Trackball
635 Camera interactive style (which is also the default):
636
637 >>> import pyvista as pv
638 >>> pl = pv.Plotter()
639 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
640 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
641 >>> pl.show_axes()
642 >>> pl.enable_trackball_style()
643 >>> pl.show() # doctest:+SKIP
644
645 """
646 self.style = InteractorStyleTrackballCamera(self)
647
648 @_deprecate_positional_args
649 def enable_custom_trackball_style( # noqa: PLR0917
650 self,
651 left='rotate',
652 shift_left='pan',
653 control_left='spin',
654 middle='pan',
655 shift_middle='pan',
656 control_middle='pan',
657 right='dolly',
658 shift_right='environment_rotate',
659 control_right='dolly',
660 ):
661 """Set the interactive style to a custom style based on Trackball Camera.
662
663 For each choice of button, control-button, and shift-button,
664 the behavior when the mouse is moved can be chosen by passing the
665 following strings:
666
667 * ``"dolly"``
668 * ``"environment_rotate"``
669 * ``"pan"``
670 * ``"rotate"``
671 * ``"spin"``
672
673 ``None`` can also be passed, which also results in the default behavior.
674
675 .. versionadded:: 0.44.0
676
677 Parameters
678 ----------
679 left : str, default: "rotate"
680 Action when the left button is clicked and the mouse is moved.
681
682 shift_left : str, default: "pan"
683 Action when the left button is clicked with the shift key and the mouse is moved.
684
685 control_left : str, default: "spin"
686 Action when the left button is clicked with the control key and mouse moved.
687
688 middle : str, default: "pan"
689 Action when the middle button is clicked and the mouse is moved.
690
691 shift_middle : str, default: "pan"
692 Action when the middle button is clicked with the shift key and the mouse is moved.
693
694 control_middle : str, default: "pan"
695 Action when the middle button is clicked with the control key and mouse moved.
696
697 right : str, default: "dolly"
698 Action when the right button is clicked and the mouse is moved.
699
700 shift_right : str, default: "environment_rotate"
701 Action when the right button is clicked with the shift key and the mouse is moved.
702
703 control_right : str, default: "dolly"
704 Action when the right button is clicked with the control key and the mouse is moved.
705
706 See Also
707 --------
708 pyvista.Plotter.enable_trackball_style
709 Base style.
710
711 Examples
712 --------
713 Create a simple scene with a plotter that has the left button
714 dolly.
715
716 >>> import pyvista as pv
717 >>> pl = pv.Plotter()
718 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
719 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
720 >>> pl.show_axes()
721 >>> pl.enable_custom_trackball_style(left='dolly')
722 >>> pl.show() # doctest:+SKIP
723
724 """
725 self.style = InteractorStyleTrackballCamera(self)
726
727 start_action_map = {
728 'environment_rotate': self.style.StartEnvRotate,
729 'rotate': self.style.StartRotate,
730 'pan': self.style.StartPan,
731 'spin': self.style.StartSpin,
732 'dolly': self.style.StartDolly,
733 }
734
735 end_action_map = {
736 'environment_rotate': self.style.EndEnvRotate,
737 'rotate': self.style.EndRotate,
738 'pan': self.style.EndPan,
739 'spin': self.style.EndSpin,
740 'dolly': self.style.EndDolly,
741 }
742
743 for p in [
744 left,
745 shift_left,
746 control_left,
747 middle,
748 shift_middle,
749 control_middle,
750 right,
751 shift_right,
752 control_right,
753 ]:
754 if p not in start_action_map:
755 msg = f"Action '{p}' not in the allowed {list(start_action_map.keys())}"
756 raise ValueError(msg)
757
758 button_press_map = {
759 'left': self.style.OnLeftButtonDown,
760 'middle': self.style.OnMiddleButtonDown,
761 'right': self.style.OnRightButtonDown,
762 }
763 button_release_map = {
764 'left': self.style.OnLeftButtonUp,
765 'middle': self.style.OnMiddleButtonUp,
766 'right': self.style.OnRightButtonUp,
767 }
768
769 def _setup_callbacks(*, button, click, control, shift):
770 """Return callbacks for press and release events.
771
772 Callbacks are formed for a button and action for a click,
773 control-click, and shift-click.
774
775 """
776 button_press = button_press_map[button]
777 button_release = button_release_map[button]
778
779 click_action = start_action_map[click]
780 control_action = start_action_map[control]
781 shift_action = start_action_map[shift]
782
783 click_release_action = end_action_map[click]
784 control_release_action = end_action_map[control]
785 shift_release_action = end_action_map[shift]
786
787 def _press_callback(_obj, _):
788 if self.interactor.GetControlKey():
789 control_action()
790 elif self.interactor.GetShiftKey():
791 shift_action()
792 else:
793 click_action()
794 button_press()
795
796 def _release_callback(_obj, _):
797 click_release_action()
798 control_release_action()
799 shift_release_action()
800 button_release()
801
802 return partial(try_callback, _press_callback), partial(try_callback, _release_callback)
803
804 _left_button_press_callback, _left_button_release_callback = _setup_callbacks(
805 button='left',
806 click=left,
807 control=control_left,
808 shift=shift_left,
809 )
810 self.style.add_observer('LeftButtonPressEvent', _left_button_press_callback)
811 self.style.add_observer('LeftButtonReleaseEvent', _left_button_release_callback)
812
813 _middle_button_press_callback, _middle_button_release_callback = _setup_callbacks(
814 button='middle',
815 click=middle,
816 control=control_middle,
817 shift=shift_middle,
818 )
819 self.style.add_observer('MiddleButtonPressEvent', _middle_button_press_callback)
820 self.style.add_observer('MiddleButtonReleaseEvent', _middle_button_release_callback)
821
822 _right_button_press_callback, _right_button_release_callback = _setup_callbacks(
823 button='right',
824 click=right,
825 control=control_right,
826 shift=shift_right,
827 )
828 self.style.add_observer('RightButtonPressEvent', _right_button_press_callback)
829 self.style.add_observer('RightButtonReleaseEvent', _right_button_release_callback)
830
831 def enable_2d_style(self):
832 """Set the interactive style to 2D.
833
834 For a 3-button mouse, the left button pans, the
835 right button dollys, the middle button spins, and the wheel
836 dollys.
837 ctrl + left button spins, shift + left button dollys,
838 ctrl + middle button pans, shift + middle button dollys,
839 ctrl + right button rotates in 3D, and shift + right button
840 dollys.
841
842 Recommended to use with
843 :func:`pyvista.Plotter.enable_parallel_projection`.
844
845 See Also
846 --------
847 pyvista.Plotter.enable_parallel_projection
848 Set parallel projection, which is useful for 2D views.
849
850 pyvista.Plotter.enable_custom_trackball_style
851 A style that can be customized for mouse actions.
852
853 Examples
854 --------
855 Create a simple scene with a plotter that has a
856 ParaView-like 2D style:
857
858 >>> import pyvista as pv
859 >>> pl = pv.Plotter()
860 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
861 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
862 >>> pl.show_axes()
863 >>> pl.enable_parallel_projection()
864 >>> pl.enable_2d_style()
865 >>> pl.show() # doctest:+SKIP
866
867 """
868 self.enable_custom_trackball_style(
869 left='pan',
870 shift_left='dolly',
871 control_left='spin',
872 middle='spin',
873 shift_middle='dolly',
874 control_middle='pan',
875 right='dolly',
876 shift_right='dolly',
877 control_right='rotate',
878 )
879
880 def enable_trackball_actor_style(self):
881 """Set the interactive style to Trackball Actor.
882
883 This allows to rotate actors around the scene. The controls
884 are similar to the default Trackball Camera style, but
885 movements transform specific objects under the mouse cursor.
886
887 For a 3-button mouse, the left button is for rotation, the
888 right button for zooming, the middle button for panning, and
889 ctrl + left button for spinning objects around the axis
890 connecting the camera with the their center. Alternatively,
891 shift + left button pans.
892
893 Examples
894 --------
895 Create a simple scene with a plotter that has the Trackball
896 Actor interactive style:
897
898 >>> import pyvista as pv
899 >>> pl = pv.Plotter()
900 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
901 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
902 >>> pl.show_axes()
903 >>> pl.enable_trackball_actor_style()
904 >>> pl.show() # doctest:+SKIP
905
906 """
907 self.style = InteractorStyleTrackballActor(self)
908
909 def enable_image_style(self):
910 """Set the interactive style to Image.
911
912 Controls:
913 - Left Mouse button triggers window level events
914 - CTRL Left Mouse spins the camera around its view plane normal
915 - SHIFT Left Mouse pans the camera
916 - CTRL SHIFT Left Mouse dollies (a positional zoom) the camera
917 - Middle mouse button pans the camera
918 - Right mouse button dollies the camera
919 - SHIFT Right Mouse triggers pick events
920
921 Examples
922 --------
923 Create a simple scene with a plotter that has the Image
924 interactive style:
925
926 >>> import pyvista as pv
927 >>> pl = pv.Plotter()
928 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
929 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
930 >>> pl.show_axes()
931 >>> pl.enable_image_style()
932 >>> pl.show() # doctest:+SKIP
933
934 """
935 self.style = InteractorStyleImage(self)
936
937 def enable_joystick_style(self):
938 """Set the interactive style to Joystick Camera.
939
940 It allows the user to move (rotate, pan, etc.) the camera, the
941 point of view for the scene. The position of the mouse
942 relative to the center of the scene determines the speed at
943 which the camera moves, so the camera continues to move even
944 if the mouse if not moving.
945
946 For a 3-button mouse, the left button is for rotation, the
947 right button for zooming, the middle button for panning, and
948 ctrl + left button for spinning. (With fewer mouse buttons,
949 ctrl + shift + left button is for zooming, and shift + left
950 button is for panning.)
951
952 Examples
953 --------
954 Create a simple scene with a plotter that has the Joystick
955 Camera interactive style:
956
957 >>> import pyvista as pv
958 >>> pl = pv.Plotter()
959 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
960 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
961 >>> pl.show_axes()
962 >>> pl.enable_joystick_style()
963 >>> pl.show() # doctest:+SKIP
964
965 """
966 self.style = InteractorStyleJoystickCamera(self)
967
968 def enable_joystick_actor_style(self):
969 """Set the interactive style to Joystick Actor.
970
971 Similar to the Joystick Camera interaction style, however
972 in case of the Joystick Actor style the objects in the scene
973 rather than the camera can be moved (rotated, panned, etc.).
974 The position of the mouse relative to the center of the object
975 determines the speed at which the object moves, so the object
976 continues to move even if the mouse is not moving.
977
978 For a 3-button mouse, the left button is for rotation, the
979 right button for zooming, the middle button for panning, and
980 ctrl + left button for spinning. (With fewer mouse buttons,
981 ctrl + shift + left button is for zooming, and shift + left
982 button is for panning.)
983
984 Examples
985 --------
986 Create a simple scene with a plotter that has the Joystick
987 Actor interactive style:
988
989 >>> import pyvista as pv
990 >>> pl = pv.Plotter()
991 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
992 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
993 >>> pl.show_axes()
994 >>> pl.enable_joystick_actor_style()
995 >>> pl.show() # doctest:+SKIP
996
997 """
998 self.style = InteractorStyleJoystickActor(self)
999
1000 def enable_zoom_style(self):
1001 """Set the interactive style to Rubber Band Zoom.
1002
1003 This interactor style allows the user to draw a rectangle in
1004 the render window using the left mouse button. When the mouse
1005 button is released, the current camera zooms by an amount
1006 determined from the shorter side of the drawn rectangle.
1007
1008 Examples
1009 --------
1010 Create a simple scene with a plotter that has the Rubber Band
1011 Zoom interactive style:
1012
1013 >>> import pyvista as pv
1014 >>> pl = pv.Plotter()
1015 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
1016 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
1017 >>> pl.show_axes()
1018 >>> pl.enable_zoom_style()
1019 >>> pl.show() # doctest:+SKIP
1020
1021 """
1022 self.style = InteractorStyleZoom(self)
1023
1024 @_deprecate_positional_args
1025 def enable_terrain_style(
1026 self,
1027 mouse_wheel_zooms: bool | float = True, # noqa: FBT001, FBT002
1028 shift_pans: bool = True, # noqa: FBT001, FBT002
1029 ):
1030 """Set the interactive style to Terrain.
1031
1032 Used to manipulate a camera which is viewing a scene with a
1033 natural view up, e.g., terrain. The camera in such a scene is
1034 manipulated by specifying azimuth (angle around the view up
1035 vector) and elevation (the angle from the horizon). Similar to
1036 the default Trackball Camera style and in contrast to the
1037 Joystick Camera style, movements of the mouse translate to
1038 movements of the camera.
1039
1040 Left mouse click rotates the camera around the focal point
1041 using both elevation and azimuth invocations on the camera.
1042 Left mouse motion in the horizontal direction results in
1043 azimuth motion; left mouse motion in the vertical direction
1044 results in elevation motion. Therefore, diagonal motion results
1045 in a combination of azimuth and elevation. (If the shift key is
1046 held during motion, then only one of elevation or azimuth is
1047 invoked, depending on the whether the mouse motion is primarily
1048 horizontal or vertical.) Middle mouse button pans the camera
1049 across the scene (again the shift key has a similar effect on
1050 limiting the motion to the vertical or horizontal direction.
1051 The right mouse is used to dolly towards or away from the focal
1052 point (zoom in or out). Panning and zooming behavior can be
1053 overridden to match the Trackball Camera style.
1054
1055 The class also supports some keypress events. The ``r`` key
1056 resets the camera. The ``e`` key invokes the exit callback
1057 and closes the plotter. The ``f`` key sets a new
1058 camera focal point and flies towards that point. The ``u``
1059 key invokes the user event. The ``3`` key toggles between
1060 stereo and non-stero mode. The ``l`` key toggles on/off
1061 latitude/longitude markers that can be used to estimate/control
1062 position.
1063
1064 .. versionchanged:: 0.45
1065 mouse_wheel_zooms and shift_pans parameters are not True by
1066 default to be more intuitive. We also improved the scroll
1067 zooming factor to be less jumpy.
1068
1069 Parameters
1070 ----------
1071 mouse_wheel_zooms : bool | float, default: True
1072 Whether to use the mouse wheel for zooming. If ``False``,
1073 you can still zoom with right click and drag. Pass a float
1074 value for to control the zoom factor, default is ``1.05``.
1075
1076 shift_pans : bool, default: True
1077 Whether shift + left mouse button pans the scene. If
1078 ``False``, shift + left mouse button rotates the view
1079 restricted to only horizontal or vertical movements, and
1080 panning is done holding down the middle mouse button.
1081
1082 Examples
1083 --------
1084 Create a simple scene with a plotter that has the Terrain
1085 interactive style:
1086
1087 >>> import pyvista as pv
1088 >>> pl = pv.Plotter()
1089 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
1090 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
1091 >>> pl.show_axes()
1092 >>> pl.enable_terrain_style()
1093 >>> pl.show() # doctest:+SKIP
1094
1095 Use controls that are closer to the default style:
1096
1097 >>> pl = pv.Plotter()
1098 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
1099 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
1100 >>> pl.show_axes()
1101 >>> pl.enable_terrain_style(mouse_wheel_zooms=True, shift_pans=True)
1102 >>> pl.show() # doctest:+SKIP
1103
1104 """
1105 self.style = InteractorStyleTerrain(self)
1106
1107 if mouse_wheel_zooms:
1108 factor = 1.05 if isinstance(mouse_wheel_zooms, bool) else mouse_wheel_zooms
1109
1110 def wheel_zoom_callback(_obj, event): # pragma: no cover
1111 """Zoom in or out on mouse wheel roll."""
1112 if event == 'MouseWheelForwardEvent':
1113 # zoom in
1114 zoom_factor = 1.0 / factor
1115 elif event == 'MouseWheelBackwardEvent':
1116 # zoom out
1117 zoom_factor = factor
1118
1119 with self.poked_subplot():
1120 if self._plotter.camera.parallel_projection:
1121 self._plotter.camera.parallel_scale *= zoom_factor
1122 else:
1123 camera_position = np.array(self._plotter.camera.position)
1124 camera_focal_point = np.array(self._plotter.camera.focal_point)
1125 camera_vector = camera_position - camera_focal_point
1126 self._plotter.camera.position = (
1127 camera_focal_point + zoom_factor * camera_vector
1128 )
1129
1130 self._plotter.reset_camera_clipping_range()
1131 self._plotter.render()
1132
1133 callback = partial(try_callback, wheel_zoom_callback)
1134
1135 for event in 'MouseWheelForwardEvent', 'MouseWheelBackwardEvent':
1136 self.style.add_observer(event, callback)
1137
1138 if shift_pans:
1139
1140 def pan_on_shift_callback(_obj, event): # pragma: no cover
1141 """Trigger left mouse panning if shift is pressed."""
1142 if event == 'LeftButtonPressEvent':
1143 if self.interactor.GetShiftKey():
1144 self.style.StartPan() # type: ignore[union-attr]
1145 self.style.OnLeftButtonDown() # type: ignore[union-attr]
1146 elif event == 'LeftButtonReleaseEvent':
1147 # always stop panning on release
1148 self.style.EndPan() # type: ignore[union-attr]
1149 self.style.OnLeftButtonUp() # type: ignore[union-attr]
1150
1151 callback = partial(try_callback, pan_on_shift_callback)
1152
1153 for event in 'LeftButtonPressEvent', 'LeftButtonReleaseEvent':
1154 self.style.add_observer(event, callback)
1155
1156 def enable_rubber_band_style(self):
1157 """Set the interactive style to Rubber Band Picking.
1158
1159 This interactor style allows the user to draw a rectangle in
1160 the render window by hitting ``r`` and then using the left
1161 mouse button. When the mouse button is released, the attached
1162 picker operates on the pixel in the center of the selection
1163 rectangle. If the picker happens to be a :vtk:`vtkAreaPicker`
1164 it will operate on the entire selection rectangle. When the
1165 ``p`` key is hit the above pick operation occurs on a 1x1
1166 rectangle. In other respects it behaves the same as the
1167 Trackball Camera style.
1168
1169 Examples
1170 --------
1171 Create a simple scene with a plotter that has the Rubber Band
1172 Pick interactive style:
1173
1174 >>> import pyvista as pv
1175 >>> pl = pv.Plotter()
1176 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
1177 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
1178 >>> pl.show_axes()
1179 >>> pl.enable_rubber_band_style()
1180 >>> pl.show() # doctest:+SKIP
1181
1182 """
1183 self.style = InteractorStyleRubberBandPick(self)
1184
1185 def enable_rubber_band_2d_style(self):
1186 """Set the interactive style to Rubber Band 2D.
1187
1188 Camera rotation is not enabled with this interactor
1189 style. Zooming affects the camera's parallel scale only, and
1190 assumes that the camera is in parallel projection mode. The
1191 style also allows to draw a rubber band using the left mouse
1192 button. All camera changes invoke ``StartInteractionEvent`` when
1193 the button is pressed, ``InteractionEvent`` when the mouse (or
1194 wheel) is moved, and ``EndInteractionEvent`` when the button is
1195 released. The bindings are as follows:
1196
1197 * Left mouse: Select (invokes a ``SelectionChangedEvent``).
1198 * Right mouse: Zoom.
1199 * Middle mouse: Pan.
1200 * Scroll wheel: Zoom.
1201
1202 Examples
1203 --------
1204 Create a simple scene with a plotter that has the Rubber Band
1205 2D interactive style:
1206
1207 >>> import pyvista as pv
1208 >>> pl = pv.Plotter()
1209 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0)))
1210 >>> _ = pl.add_mesh(pv.Cube(center=(0, 1, 0)))
1211 >>> pl.show_axes()
1212 >>> pl.enable_rubber_band_2d_style()
1213 >>> pl.show() # doctest:+SKIP
1214
1215 """
1216 self.style = InteractorStyleRubberBand2D(self)
1217
1218 def _instantiate_registered_interactor_style(
1219 self, handler: InteractorStyleHandler
1220 ) -> _vtk.vtkInteractorStyle | InteractorStyleCaptureMixin:
1221 """Instantiate a registered interactor style handler."""
1222 if isinstance(handler, type) and issubclass(handler, InteractorStyleCaptureMixin):
1223 style: object = handler(self)
1224 elif isinstance(handler, type) and issubclass(handler, _vtk.vtkInteractorStyle):
1225 style = handler()
1226 else:
1227 # Generic callable — pass the interactor so the factory can
1228 # configure the style. The cast is needed because mypy narrows
1229 # ``Callable[..., Any]`` to a non-callable after two failing
1230 # ``isinstance(handler, type)`` checks.
1231 factory: InteractorStyleHandler = handler
1232 style = factory(self)
1233
1234 if not isinstance(style, (_vtk.vtkInteractorStyle, InteractorStyleCaptureMixin)):
1235 msg = (
1236 'Registered interactor styles must resolve to an instance of `vtkInteractorStyle`.'
1237 )
1238 raise TypeError(msg)
1239
1240 return style
1241
1242 def enable_interactor_style(self, style: str | None = None) -> None:
1243 """Set the interactive style to a built-in or registered mode.
1244
1245 Parameters
1246 ----------
1247 style : str, optional
1248 Name of the interactor style to enable. Built-in styles use
1249 names that mirror the public ``enable_*_style`` methods,
1250 such as ``'terrain_style'``. If ``None``, use the current
1251 plotter theme's :attr:`~pyvista.plotting.themes.Theme.interactor_style`
1252 or the global theme when no plotter is attached.
1253
1254 Raises
1255 ------
1256 TypeError
1257 If the registered handler does not resolve to an interactor
1258 style instance.
1259
1260 ValueError
1261 If the style name is not known.
1262
1263 Examples
1264 --------
1265 Enable a built-in interactor style by name.
1266
1267 >>> import pyvista as pv
1268 >>> pl = pv.Plotter()
1269 >>> pl.enable_interactor_style('terrain_style')
1270
1271 """
1272 if style is None:
1273 if self._plotter is not None:
1274 style = self._plotter.theme.interactor_style
1275 else:
1276 style = pv.global_theme.interactor_style
1277
1278 validated = _validate_interactor_style(style)
1279 handler = _get_interactor_style_handler(validated)
1280
1281 if isinstance(handler, str):
1282 getattr(self, handler)()
1283 elif handler is not None:
1284 self.style = self._instantiate_registered_interactor_style(handler)
1285
1286 def _simulate_keypress(self, key):
1287 """Simulate a keypress."""
1288 if len(key) > 1:
1289 msg = 'Only accepts a single key'
1290 raise ValueError(msg)
1291 self.interactor.SetKeyCode(key)
1292 self.interactor.SetKeySym(key)
1293 self.interactor.CharEvent()
1294
1295 def _control_key_press(self):
1296 """Simulate a control keypress."""
1297 self.interactor.SetControlKey(1)
1298
1299 def _control_key_release(self):
1300 """Simulate a control keypress."""
1301 self.interactor.SetControlKey(0)
1302
1303 def _shift_key_press(self):
1304 """Simulate a shift keypress."""
1305 self.interactor.SetShiftKey(1)
1306
1307 def _shift_key_release(self):
1308 """Simulate a shift keypress."""
1309 self.interactor.SetShiftKey(0)
1310
1311 def _mouse_left_button_press(
1312 self,
1313 x=None,
1314 y=None,
1315 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1316 """Simulate a left mouse button press.
1317
1318 If ``x`` and ``y`` are entered then simulates a movement to
1319 that position.
1320
1321 """
1322 if x is not None and y is not None:
1323 self._mouse_move(x, y)
1324 self.interactor.LeftButtonPressEvent()
1325
1326 def _mouse_left_button_release(
1327 self,
1328 x=None,
1329 y=None,
1330 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1331 """Simulate a left mouse button release."""
1332 if x is not None and y is not None:
1333 self._mouse_move(x, y)
1334 self.interactor.LeftButtonReleaseEvent()
1335
1336 def _mouse_left_button_click(self, x=None, y=None, count=1):
1337 for _ in range(count):
1338 self._mouse_left_button_press(x, y)
1339 self._mouse_left_button_release()
1340
1341 def _mouse_middle_button_press(
1342 self,
1343 x=None,
1344 y=None,
1345 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1346 """Simulate a middle mouse button press.
1347
1348 If ``x`` and ``y`` are entered then simulates a movement to
1349 that position.
1350
1351 """
1352 if x is not None and y is not None:
1353 self._mouse_move(x, y)
1354 self.interactor.MiddleButtonPressEvent()
1355
1356 def _mouse_middle_button_release(
1357 self,
1358 x=None,
1359 y=None,
1360 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1361 """Simulate a middle mouse button release."""
1362 if x is not None and y is not None:
1363 self._mouse_move(x, y)
1364 self.interactor.MiddleButtonReleaseEvent()
1365
1366 def _mouse_middle_button_click(self, x=None, y=None, count=1):
1367 for _ in range(count):
1368 self._mouse_middle_button_press(x, y)
1369 self._mouse_middle_button_release()
1370
1371 def _mouse_right_button_press(
1372 self,
1373 x=None,
1374 y=None,
1375 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1376 """Simulate a right mouse button press.
1377
1378 If ``x`` and ``y`` are entered then simulates a movement to
1379 that position.
1380
1381 """
1382 if x is not None and y is not None:
1383 self._mouse_move(x, y)
1384 self.interactor.RightButtonPressEvent()
1385
1386 def _mouse_right_button_release(
1387 self,
1388 x=None,
1389 y=None,
1390 ): # pragma: no cover # numpydoc ignore=PR01,RT01
1391 """Simulate a right mouse button release."""
1392 if x is not None and y is not None:
1393 self._mouse_move(x, y)
1394 self.interactor.RightButtonReleaseEvent()
1395
1396 def _mouse_right_button_click(self, x=None, y=None, count=1):
1397 for _ in range(count):
1398 self._mouse_right_button_press(x, y)
1399 self._mouse_right_button_release()
1400
1401 def _mouse_move(self, x, y): # pragma:
1402 """Simulate moving the mouse to ``(x, y)`` screen coordinates."""
1403 self.interactor.SetEventPosition(x, y)
1404 self.interactor.MouseMoveEvent()
1405
1406 def get_event_position(self):
1407 """Get the event position.
1408
1409 Returns
1410 -------
1411 tuple
1412 The ``(x, y)`` coordinate position.
1413
1414 """
1415 return self.interactor.GetEventPosition()
1416
1417 def get_poked_renderer(self, x=None, y=None):
1418 """Get poked renderer for last or specific event position.
1419
1420 Parameters
1421 ----------
1422 x : float, default: None
1423 The x-coordinate for a user-defined event position.
1424
1425 y : float, default: None
1426 The y-coordinate for a user-defined event position.
1427
1428 Returns
1429 -------
1430 :vtk:`vtkRenderer`
1431 The poked renderer for given or last event position.
1432
1433 """
1434 if x is None or y is None:
1435 x, y = self.get_event_position()
1436 return self.interactor.FindPokedRenderer(x, y)
1437
1438 def get_event_subplot_loc(self):
1439 """Get the subplot location of the last event.
1440
1441 Returns
1442 -------
1443 tuple
1444 A tuple containing the location of the subplot.
1445
1446 Raises
1447 ------
1448 RuntimeError
1449 If the poked renderer is not found in the Plotter.
1450
1451 """
1452 poked_renderer = self.get_poked_renderer()
1453 for index in range(len(self._plotter.renderers)):
1454 renderer = self._plotter.renderers[index]
1455 if renderer is poked_renderer:
1456 return self._plotter.renderers.index_to_loc(index)
1457 msg = 'Poked renderer not found in Plotter.'
1458 raise RuntimeError(msg)
1459
1460 @contextmanager
1461 def poked_subplot(self):
1462 """Activate the subplot that was last interacted."""
1463 active_renderer_index = self._plotter.renderers._active_index
1464 loc = self.get_event_subplot_loc()
1465 self._plotter.subplot(*loc)
1466 try:
1467 yield
1468 finally:
1469 # Reset to the active renderer.
1470 loc = self._plotter.renderers.index_to_loc(active_renderer_index)
1471 self._plotter.subplot(*loc)
1472
1473 def get_interactor_style(self):
1474 """Get the interactor style.
1475
1476 Returns
1477 -------
1478 :vtk:`vtkInteractorStyle`
1479 VTK interactor style.
1480
1481 """
1482 return self.interactor.GetInteractorStyle()
1483
1484 def get_desired_update_rate(self):
1485 """Get the desired update rate.
1486
1487 Returns
1488 -------
1489 float
1490 Desired update rate.
1491
1492 """
1493 return self.interactor.GetDesiredUpdateRate()
1494
1495 @_deprecate_positional_args(allowed=['duration'])
1496 def create_timer(self, duration, repeating=True): # noqa: FBT002
1497 """Create a timer.
1498
1499 Parameters
1500 ----------
1501 duration : int
1502 Time (in milliseconds) before the timer emits a TimerEvent.
1503
1504 repeating : bool, default: True
1505 When ``False`` a one-shot timer is created, which only fires
1506 once. When ``True`` a repeating timer is created, which
1507 continuously fires (every ``duration`` milliseconds) until
1508 destruction.
1509
1510 Returns
1511 -------
1512 int
1513 Timer ID.
1514
1515 """
1516 if repeating:
1517 timer_id = self.interactor.CreateRepeatingTimer(duration)
1518 else:
1519 timer_id = self.interactor.CreateOneShotTimer(duration)
1520 return timer_id
1521
1522 def destroy_timer(self, timer_id):
1523 """Destroy the given timer.
1524
1525 Parameters
1526 ----------
1527 timer_id : int
1528 The ID of the timer to destroy.
1529
1530 """
1531 self.interactor.DestroyTimer(timer_id)
1532
1533 def start(self):
1534 """Start interactions."""
1535 self.interactor.Start()
1536
1537 def initialize(self):
1538 """Initialize the interactor."""
1539 self.interactor.Initialize()
1540
1541 def set_render_window(self, render_window):
1542 """Set the render window for the interactor.
1543
1544 Parameters
1545 ----------
1546 render_window : :vtk:`vtkRenderWindow`
1547 Render window to set for the interactor.
1548
1549 """
1550 self.interactor.SetRenderWindow(render_window)
1551
1552 def process_events(self):
1553 """Process events."""
1554 if not self.initialized:
1555 msg = 'Render window interactor must be initialized before processing events.'
1556 raise RuntimeError(msg)
1557 rw = self.interactor.GetRenderWindow()
1558 if rw is not None: # pragma: no cover
1559 iren_cls = type(self.interactor).__name__
1560 rw_cls = type(rw).__name__
1561 del rw
1562 if iren_cls == 'vtkXRenderWindowInteractor' and rw_cls != 'vtkXOpenGLRenderWindow':
1563 msg = (
1564 f'Cannot process events: {iren_cls} requires an X-backed render window '
1565 f'but got {rw_cls}. This typically happens on headless Linux where VTK '
1566 f'falls back to EGL for rendering but the interactor still expects X. '
1567 f'Use vtkGenericRenderWindowInteractor for headless/EGL contexts.'
1568 )
1569 raise MismatchedInteractorError(msg)
1570 self.interactor.ProcessEvents()
1571
1572 @property
1573 def initialized(self): # numpydoc ignore=RT01
1574 """Return if the interactor has been initialized."""
1575 return self.interactor.GetInitialized()
1576
1577 @property
1578 def picker(self): # numpydoc ignore=RT01
1579 """Get/set the picker.
1580
1581 Returns
1582 -------
1583 :vtk:`vtkAbstractPicker`
1584 VTK picker.
1585
1586 """
1587 return self.interactor.GetPicker()
1588
1589 @picker.setter
1590 def picker(self, picker):
1591 pickers = {
1592 PickerType.AREA: _vtk.vtkAreaPicker,
1593 PickerType.CELL: _vtk.vtkCellPicker,
1594 PickerType.POINT: _vtk.vtkPointPicker,
1595 PickerType.PROP: _vtk.vtkPropPicker,
1596 PickerType.RENDERED: _vtk.vtkRenderedAreaPicker,
1597 PickerType.RESLICE: _vtk.vtkResliceCursorPicker,
1598 PickerType.SCENE: _vtk.vtkScenePicker,
1599 PickerType.VOLUME: _vtk.vtkVolumePicker,
1600 PickerType.WORLD: _vtk.vtkWorldPointPicker,
1601 }
1602 if _vtk.vtkHardwarePicker is not None:
1603 # Unavailable on VTK < 9.2
1604 pickers[PickerType.HARDWARE] = _vtk.vtkHardwarePicker
1605 if isinstance(picker, (str, int, PickerType)):
1606 picker = PickerType.from_any(picker)
1607 try:
1608 picker = pickers[picker]()
1609 except KeyError:
1610 msg = f'Picker class `{picker}` is unknown.'
1611 raise KeyError(msg)
1612 # Set default tolerance for internal configurations
1613 if hasattr(picker, 'SetTolerance'):
1614 picker.SetTolerance(0.025)
1615 self.interactor.SetPicker(picker)
1616
1617 def add_pick_observer(self, observer):
1618 """Add an observer to call back when pick events end.
1619
1620 Parameters
1621 ----------
1622 observer : callable
1623 The observer function to call when a pick event ends.
1624
1625 """
1626 self.picker.AddObserver(_vtk.vtkCommand.EndPickEvent, observer)
1627
1628 def reset_picker(self):
1629 """Reset the picker."""
1630 # Remove observers
1631 self.picker.RemoveObservers(_vtk.vtkCommand.EndPickEvent)
1632 # Set default picker to vtkWorldPointPicker
1633 self.picker = 'world'
1634
1635 def fly_to(self, renderer, point):
1636 """Fly the interactor to the given point in a renderer.
1637
1638 Parameters
1639 ----------
1640 renderer : :vtk:`vtkRenderer`
1641 The renderer in which the action will take place.
1642
1643 point : list or tuple
1644 The point to fly to.
1645
1646 """
1647 self.interactor.FlyTo(renderer, *point)
1648
1649 def terminate_app(self):
1650 """Terminate the app."""
1651 if self.initialized:
1652 self.interactor.SetDone(True) # See: https://gitlab.kitware.com/vtk/vtk/-/issues/18242
1653 self.interactor.TerminateApp()
1654
1655 def close(self):
1656 """Close out the render window interactor.
1657
1658 This will terminate the render window if it is not already closed.
1659 """
1660 self.remove_observers()
1661 if self.style == self._context_style: # pragma: no cover
1662 self._set_context_style(None) # Disable context interactor style first
1663 if self.style is not None:
1664 if hasattr(self.style, 'remove_observers'):
1665 self.style.remove_observers()
1666 self.style = None
1667
1668 self.terminate_app()
1669 self.interactor = None
1670 self._click_event_callbacks = None # type: ignore[assignment]
1671 self._timer_event = None
1672
1673
1674 @abstract_class
1675 class InteractorStyleCaptureMixin(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkInteractorStyle):
1676 """A mixin for subclasses of vtkInteractorStyle with capturing ability.
1677
1678 Use a custom capturing events because the default ones
1679 swallow the release events. See
1680 https://public.kitware.com/pipermail/vtkusers/2013-December/082315.html.
1681
1682 """
1683
1684 def __init__(self, render_window_interactor: RenderWindowInteractor):
1685 super().__init__()
1686 self._parent = weakref.ref(render_window_interactor)
1687
1688 # An unknown problem with AddObserver not typed to include string despite overload.
1689 # Ignore typing.
1690 self._observers = []
1691 self._observers.append(
1692 self.AddObserver('LeftButtonPressEvent', partial(try_callback, self._press)), # type: ignore[arg-type]
1693 )
1694 self._observers.append(
1695 self.AddObserver(
1696 'LeftButtonReleaseEvent', # type: ignore[arg-type]
1697 partial(try_callback, self._release),
1698 ),
1699 )
1700
1701 def _press(self, *_):
1702 # Figure out which renderer has the event and disable the
1703 # others
1704 self.OnLeftButtonDown()
1705 parent = self._parent()
1706 if len(parent._plotter.renderers) > 1: # type: ignore[union-attr]
1707 click_pos = parent.get_event_position() # type: ignore[union-attr]
1708 for renderer in parent._plotter.renderers: # type: ignore[union-attr]
1709 interact = renderer.IsInViewport(*click_pos)
1710 renderer.SetInteractive(interact)
1711
1712 def _release(self, *_):
1713 self.OnLeftButtonUp()
1714 parent = self._parent()
1715 if len(parent._plotter.renderers) > 1: # type: ignore[union-attr]
1716 for renderer in parent._plotter.renderers: # type: ignore[union-attr]
1717 renderer.SetInteractive(True)
1718
1719 def add_observer(self, event, callback):
1720 """Keep track of observers.
1721
1722 Parameters
1723 ----------
1724 event : str
1725 VTK event string
1726 callback : callable
1727 Function to call during callback
1728
1729 """
1730 self._observers.append(self.AddObserver(event, callback))
1731
1732 def remove_observers(self): # numpydoc ignore=SS06
1733 """Remove all observers added through
1734 :func:`~pyvista.plotting.render_window_interactor.InteractorStyleCaptureMixin.add_observer`.
1735 """ # noqa : D205
1736 for obs in self._observers:
1737 self.RemoveObserver(obs)
1738
1739
1740 # All interactor styles here inherit from `InteractorStyleCaptureMixin`, which
1741 # inherits from `DisableVtkSnakeCase`, so don't duplicate again.
1742 class InteractorStyleImage(InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleImage):
1743 """Image interactor style.
1744
1745 Wraps :vtk:`vtkInteractorStyleImage`.
1746
1747 See Also
1748 --------
1749 :meth:`pyvista.RenderWindowInteractor.enable_image_style`
1750
1751 """
1752
1753
1754 class InteractorStyleJoystickActor(
1755 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleJoystickActor
1756 ):
1757 """Joystick actor interactor style.
1758
1759 Wraps :vtk:`vtkInteractorStyleJoystickActor`.
1760
1761 See Also
1762 --------
1763 :meth:`pyvista.RenderWindowInteractor.enable_joystick_actor_style`
1764
1765 """
1766
1767
1768 class InteractorStyleJoystickCamera(
1769 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleJoystickCamera
1770 ):
1771 """Joystick camera interactor style.
1772
1773 Wraps :vtk:`vtkInteractorStyleJoystickCamera`.
1774
1775 See Also
1776 --------
1777 :meth:`pyvista.RenderWindowInteractor.enable_joystick_style`
1778
1779 """
1780
1781
1782 class InteractorStyleRubberBand2D(
1783 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleRubberBand2D
1784 ):
1785 """Rubber band 2D interactor style.
1786
1787 Wraps :vtk:`vtkInteractorStyleRubberBand2D`.
1788
1789 See Also
1790 --------
1791 :meth:`pyvista.RenderWindowInteractor.enable_rubber_band_2d_style`
1792
1793 """
1794
1795
1796 class InteractorStyleRubberBandPick(
1797 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleRubberBandPick
1798 ):
1799 """Rubber band pick interactor style.
1800
1801 Wraps :vtk:`vtkInteractorStyleRubberBandPick`.
1802
1803 See Also
1804 --------
1805 :meth:`pyvista.RenderWindowInteractor.enable_rubber_band_style`
1806
1807 """
1808
1809
1810 class InteractorStyleTrackballActor(
1811 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleTrackballActor
1812 ):
1813 """Trackball actor interactor style.
1814
1815 Wraps :vtk:`vtkInteractorStyleTrackballActor`.
1816
1817 See Also
1818 --------
1819 :meth:`pyvista.RenderWindowInteractor.enable_trackball_actor_style`
1820
1821 """
1822
1823
1824 class InteractorStyleTrackballCamera(
1825 InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleTrackballCamera
1826 ):
1827 """Trackball camera interactor style.
1828
1829 Wraps :vtk:`vtkInteractorStyleTrackballCamera`.
1830
1831 See Also
1832 --------
1833 :meth:`pyvista.RenderWindowInteractor.enable_trackball_style`
1834 :meth:`pyvista.RenderWindowInteractor.enable_custom_trackball_style`
1835 :meth:`pyvista.RenderWindowInteractor.enable_2d_style`
1836
1837 """
1838
1839
1840 class InteractorStyleTerrain(InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleTerrain):
1841 """Terrain interactor style.
1842
1843 Wraps :vtk:`vtkInteractorStyleTerrain`.
1844
1845 See Also
1846 --------
1847 :meth:`pyvista.RenderWindowInteractor.enable_terrain_style`
1848
1849 """
1850
1851
1852 class InteractorStyleZoom(InteractorStyleCaptureMixin, _vtk.vtkInteractorStyleRubberBandZoom):
1853 """Rubber band zoom interactor style.
1854
1855 Wraps :vtk:`vtkInteractorStyleRubberBandZoom`.
1856
1857 See Also
1858 --------
1859 :meth:`pyvista.RenderWindowInteractor.enable_zoom_style`
1860
1861 """