obv-mikhail / InputBot

Rust library for creating global hotkeys, and simulating inputs
MIT License
421 stars 74 forks source link

Static state is required? #95

Open NWoodsman opened 10 months ago

NWoodsman commented 10 months ago

This might be better suited as a discussion thread on a social media platform but I wanted to ask the users of this project.

Since the callbacks are static implemented, the only way to maintain some kind of state is... how? Should I keep some state in an unsafe struct? I think this probably has wider implications for the hooks being called from different threads, so maybe not a good idea... any thoughts?

Basically I want to implement a hotkey system by holding space bar. I will only send a space key press on the key-up so that it will get sent during normal typing, but if space is held down, a timeout will trigger after _ milliseconds (the average time it takes during normal typing for the spacebar to raise) and enter hotkey mode until space is released.

Therefore in pseudo-speak I need an enum "hotkey layer enabled" or "disabled" with a state struct stored in a global variable (current thinking) but looking for ideas to avoid that.

masonk commented 10 months ago

"callbacks are static implemented" is a phrase I don't understand, but anyway: when you register a handler for device input, those handlers are going to get called whenever the OS decides to call them, and the Rust compiler cannot prove anything about them. The library correctly has strict type bounds on those handlers.

If you need to maintain state between different such handlers, you need to set up your own synchronization. My own app which uses InputBot is full of Arc<Mutex<>> because of this. If a bunch of your handlers need to do something different if spacekey has been held down for a while, they probably all need to hold an Arc<Mutex<bool>> or Arc<RwLock<bool>>. (Or you can wrap bool into a HotkeyState enum or something).