From 9d445643883985e2d65c3d503bab0d88cf102d97 Mon Sep 17 00:00:00 2001 From: Philipp Schlegel Date: Sun, 12 May 2024 16:46:39 +0100 Subject: [PATCH] add an `bind_key` method --- docs/controls.md | 8 ++++++++ octarine/viewer.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/docs/controls.md b/docs/controls.md index 2883711..63d5fe8 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -73,6 +73,14 @@ While the viewer or widget is active you can use a set of hotkeys to control the | `f` | Show/hide frames per second | | `c` | Show/hide control panel (requires PySide6) | +You can bind custom keys using the [`octarine.Viewer.bind_key`][]`()` method: + +```python +>>> v = oc.Viewer() +>>> # Bind `x` key to clearing the viewer +>>> v.bind_key(key="x", func=v.clear) +``` + ## GUI Controls ### Shell/IPython diff --git a/octarine/viewer.py b/octarine/viewer.py index 80c5ee1..f39993c 100644 --- a/octarine/viewer.py +++ b/octarine/viewer.py @@ -1224,3 +1224,40 @@ def set_view(self, view): ) else: raise TypeError(f"Unable to set view from {type(view)}") + + def bind_key(self, key, func, modifiers=None): + """Bind a function to a key press. + + Note that any existing keybindings for `key` + `modifiers` will be + silently overwritten. + + Parameters + ---------- + key : str + Key to bind to. Can be any key on the keyboard. + func : callable + Function to call when key is pressed. + modifiers : str | list thereof, optional + Modifier(s) to use with the key. Can be "Shift", "Control", + "Alt" or "Meta". + + """ + if not callable(func): + raise TypeError("`func` needs to be callable") + + if not isinstance(key, str): + raise TypeError(f"Expected `key` to be a string, got {type(key)}") + + if modifiers is None: + self._key_events[key] = func + else: + # We need to make `modifiers` is hashable + if isinstance(key, str): + key = (key,) + elif isinstance(key, (set, list)): + key = tuple(key) + + if not isinstance(modifiers, tuple): + raise TypeError(f"Unexpected datatype for `modifiers`: {type(modifiers)}") + + self._key_events[(key, modifiers)] = func \ No newline at end of file