Skip to content

Commit

Permalink
livesplit-hotkey: Add new_consuming on macOS
Browse files Browse the repository at this point in the history
  • Loading branch information
tmandry committed Jan 14, 2024
1 parent dd0a229 commit b68db6e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions crates/livesplit-hotkey/src/macos/cg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ bitflags::bitflags! {
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
pub fn CGEventGetFlags(event: EventRef) -> EventFlags;
pub fn CGEventSetType(event: EventRef, event_type: EventType);

pub fn CGEventTapCreate(
tap: EventTapLocation,
Expand Down
21 changes: 18 additions & 3 deletions crates/livesplit-hotkey/src/macos/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use self::{
CFRunLoopGetCurrent, CFRunLoopRemoveSource, CFRunLoopRun,
},
cg::{
CGEventGetFlags, CGEventTapCreate, EventField, EventFlags, EventMask, EventRef,
EventTapLocation, EventTapOptions, EventTapPlacement, EventTapProxy, EventType,
CGEventGetFlags, CGEventSetType, CGEventTapCreate, EventField, EventFlags, EventMask,
EventRef, EventTapLocation, EventTapOptions, EventTapPlacement, EventTapProxy, EventType,
},
};
use crate::{Hotkey, KeyCode, Modifiers};
Expand Down Expand Up @@ -108,6 +108,16 @@ impl Drop for Hook {
impl Hook {
/// Creates a new hook.
pub fn new() -> Result<Self> {
Self::new_inner(false)
}

/// Creates a new hook that consumes its registered hotkeys, meaning they
/// are not pass on to other apps.
pub fn new_consuming() -> Result<Self> {
Self::new_inner(true)
}

fn new_inner(is_consuming: bool) -> Result<Self> {
let state = Arc::new(State {
hotkeys: Mutex::new(HashMap::new()),
});
Expand All @@ -131,7 +141,11 @@ impl Hook {
let port = CGEventTapCreate(
EventTapLocation::SESSION,
EventTapPlacement::HEAD_INSERT_EVENT_TAP,
EventTapOptions::DEFAULT_TAP,
if is_consuming {
EventTapOptions::DEFAULT_TAP
} else {
EventTapOptions::LISTEN_ONLY
},
EventMask::KEY_DOWN,
Some(callback),
state_ptr as *mut c_void,
Expand Down Expand Up @@ -488,6 +502,7 @@ unsafe extern "C" fn callback(
.get_mut(&key_code.with_modifiers(modifiers))
{
callback();
CGEventSetType(event, EventType::NULL);
}

event
Expand Down

0 comments on commit b68db6e

Please sign in to comment.