koekeishiya / skhd

Simple hotkey daemon for macOS
MIT License
6.05k stars 204 forks source link

Run commands on keyup #316

Closed AndreasNasman closed 9 months ago

AndreasNasman commented 9 months ago

Is it possible to run commands on keyup, i.e. when a key combination is released, instead of keydown?

For context, I have these skhd key bindings to run a desktop switcher script:

# skhdrc
# …
# Map for desktop (space) indexes to key codes:
# 1 => 18
# 2 => 19
# 3 => 20
# etc.
# https://superuser.com/a/368036
lalt - 1: switch-desktop 18
lalt - 2: switch-desktop 19
lalt - 3: switch-desktop 20
# …
# switch-desktop
#!/usr/bin/osascript

# https://stackoverflow.com/q/43444636
on run {desktopIndexAsKeyCode}
    tell application "System Events"
        key code desktopIndexAsKeyCode using control down
    end tell
end run

The problem I'm having is that I have to be super quick with the lalt - X key combinations, since switch-desktop triggers a ctrl - X command, often resulting in an unwanted ctrl + lalt - X command.

A workaround would be add a delay before the ctrl - X command

# switch-desktop
#!/usr/bin/osascript

# https://stackoverflow.com/q/43444636
on run {desktopIndexAsKeyCode}
    tell application "System Events"
+               delay 0.1
        key code desktopIndexAsKeyCode using control down
    end tell
end run

but a nicer solution would be to have lalt - X trigger on keyup instead, as I'm inconsistent with key presses from time to time like any human.

NB: I cannot use lalt - 1: yabai --message space --focus 1 etc. for I need to keep SIP enabled (work computer).

tjex commented 9 months ago

I've never heard of this being possible. skhd is only sending key presses. A key released event will require some background logic to keep a track of key press state.

could it potentially work to chuck a sleep 1 somewhere in a script, so that you give yourself more time to execute the subsequent command?

failing that, you could look at a program like keyboard maestro to handle the key release event (and then send an osascript / subsequent keypress).

AndreasNasman commented 9 months ago

Having used the switch-desktop keybinding for a while, I've noticed that this is a non-issue since my muscle memory has improved, and the script execution takes longer than me releasing the keys.