Skip to content

Commit

Permalink
add an bind_key method
Browse files Browse the repository at this point in the history
  • Loading branch information
schlegelp committed May 12, 2024
1 parent d3272f9 commit 9d44564
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/controls.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions octarine/viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 9d44564

Please sign in to comment.