日本語

Global shortcuts

Os::shortcut registers a key the application hears while another application has focus, such as push-to-talk.

Registering a shortcut

impl Shortcut {
    pub const fn new(modifiers: Modifiers, key: Key) -> Self;
}

impl Os {
    pub async fn shortcut(&self, shortcut: Shortcut) -> Result<Presses, Error>;
}

impl Presses {
    pub async fn next(&mut self) -> Option<Press>;
}

A page's own shortcuts work only while its window has focus. Os::shortcut registers a Shortcut with the system for the rest of the run, so the application hears it while another application has focus, as push-to-talk does. The key is a Key and the modifiers are Modifiers joined with and, so a shortcut is never a string. Shortcut::new in a const fails to compile without a modifier unless the key is a function key, since the application would take that key from every other application. Modifiers::PRIMARY is Command on macOS and Control elsewhere.

Each call returns its own Presses, and next waits for the next Press::Pressed or Press::Released, so a key held down can be told from one tapped:

use hypersig_desktop::{Key, Modifiers, Os, Press, Shortcut};
use tokio::sync::watch;

/// Command+Shift+Space on macOS, and Control+Shift+Space elsewhere.
const TALK: Shortcut = Shortcut::new(Modifiers::PRIMARY.and(Modifiers::SHIFT), Key::Space);

/// Keeps `held` true while the person holds the push-to-talk key.
async fn push_to_talk(os: &Os, held: watch::Sender<bool>) -> Result<(), hypersig_desktop::Error> {
    let mut presses = os.shortcut(TALK).await?;
    tokio::spawn(async move {
        while let Some(press) = presses.next().await {
            held.send_replace(press == Press::Pressed);
        }
    });
    Ok(())
}

It fails with ErrorKind::Shortcut when the system does not register the shortcut, as when another application holds it. A shortcut asked for again is not registered twice. In a test, FakeOs::has_shortcut tells whether the handlers registered a shortcut, and FakeOs::press_shortcut presses or releases it. examples/meter shows "Talking" while its key is held.

On each system

  • On macOS, a press and a release of examples/meter's key sent from System Events reached the page.
  • On Linux, the shortcut is grabbed from the X server, and CI presses examples/meter's key there with xdotool. A Wayland session delivers it only while an X11 window has focus, and none at all without Xwayland, where Os::shortcut still returns Ok.
  • On Windows, the shortcut is registered with RegisterHotKey, and no run has pressed it yet.