Hotkeys & Clipboard¶
Nib provides global keyboard shortcuts (hotkeys) and clipboard access for integrating your menu bar app with system-wide workflows.
Global hotkeys¶
Register a global keyboard shortcut that works even when your app's popover is not visible:
import nib
def main(app: nib.App):
app.title = "Hotkey Demo"
app.icon = nib.SFSymbol("keyboard")
app.width = 300
app.height = 200
status = nib.Text("Press Cmd+Shift+N", font=nib.Font.HEADLINE)
def on_shortcut():
status.content = "Hotkey pressed!"
app.on_hotkey("cmd+shift+n", on_shortcut)
app.build(
nib.VStack(
controls=[status],
padding=24,
)
)
nib.run(main)
Modifier keys¶
Combine modifier keys with +:
| Modifier | Key name |
|---|---|
| Command | cmd |
| Shift | shift |
| Control | ctrl |
| Option/Alt | opt or alt |
Examples of valid shortcut strings:
app.on_hotkey("cmd+k", callback)
app.on_hotkey("cmd+shift+n", callback)
app.on_hotkey("ctrl+opt+p", callback)
app.on_hotkey("cmd+shift+ctrl+r", callback)
Note
Hotkey strings are case-insensitive and modifier order does not matter: "shift+cmd+N", "cmd+shift+n" and "command+shift+n" all register the same shortcut.
Accessibility access
Global hotkeys (pressed while another app is in front) need Accessibility access for the app under System Settings > Privacy & Security > Accessibility. Without it the runtime logs a warning, Python receives a hotkey:unavailable event, and shortcuts only work while the popover has focus.
Decorator syntax¶
Use the @app.hotkey() decorator as an alternative to app.on_hotkey():
@app.hotkey("cmd+shift+n")
def create_new():
print("Creating new item...")
@app.hotkey("cmd+k")
def toggle_search():
print("Toggle search...")
The decorator returns the original function, so you can still call it directly if needed.
Multiple hotkeys¶
Register as many hotkeys as you need:
app.on_hotkey("cmd+1", lambda: switch_tab(0))
app.on_hotkey("cmd+2", lambda: switch_tab(1))
app.on_hotkey("cmd+3", lambda: switch_tab(2))
app.on_hotkey("cmd+shift+c", copy_selection)
app.on_hotkey("cmd+shift+v", paste_special)
Clipboard¶
Writing to clipboard¶
Set the clipboard content directly with a string assignment:
app.clipboard = "Hello, World!"
Or use the method form:
app.set_clipboard("Hello, World!")
Both are equivalent. The content is sent to the system clipboard immediately.
Reading from clipboard¶
Clipboard reads are asynchronous because they require a round trip to the Swift runtime. Use get_clipboard() with a callback:
def on_clipboard(content: str):
print(f"Clipboard contains: {content}")
app.get_clipboard(on_clipboard)
The callback receives the current clipboard text as a string.
Related¶
- App for
on_hotkey,hotkey,clipboard,get_clipboard - Context Menu:
shortcut=on menu items - Drag and Drop:
on_drop