-
Notifications
You must be signed in to change notification settings - Fork 9
/
xwrap.rs
205 lines (185 loc) · 6.51 KB
/
xwrap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use crate::config::Keybind;
use crate::errors::{self, Error, LeftError};
use crate::xkeysym_lookup;
use std::future::Future;
use std::os::raw::{c_int, c_ulong};
use std::pin::Pin;
use std::ptr;
use std::sync::Arc;
use tokio::sync::{oneshot, Notify};
use tokio::time::Duration;
use x11_dl::xlib;
pub struct XWrap {
pub xlib: xlib::Xlib,
pub display: *mut xlib::Display,
pub root: xlib::Window,
pub task_notify: Arc<Notify>,
_task_guard: oneshot::Receiver<()>,
}
impl Default for XWrap {
fn default() -> Self {
Self::new()
}
}
impl XWrap {
/// # Panics
///
/// Panics if unable to contact xorg.
#[must_use]
#[allow(clippy::items_after_statements)]
pub fn new() -> Self {
const SERVER: mio::Token = mio::Token(0);
let xlib = errors::exit_on_error!(xlib::Xlib::open());
let display = unsafe { (xlib.XOpenDisplay)(ptr::null()) };
assert!(!display.is_null(), "Null pointer in display");
let fd = unsafe { (xlib.XConnectionNumber)(display) };
let (guard, task_guard) = oneshot::channel();
let notify = Arc::new(Notify::new());
let task_notify = notify.clone();
let mut poll = errors::exit_on_error!(mio::Poll::new());
let mut events = mio::Events::with_capacity(1);
errors::exit_on_error!(poll.registry().register(
&mut mio::unix::SourceFd(&fd),
SERVER,
mio::Interest::READABLE,
));
let timeout = Duration::from_millis(100);
tokio::task::spawn_blocking(move || loop {
if guard.is_closed() {
return;
}
if let Err(err) = poll.poll(&mut events, Some(timeout)) {
tracing::warn!("Xlib socket poll failed with {:?}", err);
continue;
}
events
.iter()
.filter(|event| SERVER == event.token())
.for_each(|_| notify.notify_one());
});
let root = unsafe { (xlib.XDefaultRootWindow)(display) };
let xw = Self {
xlib,
display,
root,
task_notify,
_task_guard: task_guard,
};
// Setup cached keymap/modifier information, otherwise MappingNotify might never be called
// from:
// https://stackoverflow.com/questions/35569562/how-to-catch-keyboard-layout-change-event-and-get-current-new-keyboard-layout-on
xw.keysym_to_keycode(x11_dl::keysym::XK_F1);
// This is allowed for now as const extern fns
// are not yet stable (1.56.0, 16 Sept 2021)
// see issue #64926 <https://github.com/rust-lang/rust/issues/64926> for more information
// also this is the reason for #[allow(clippy::items_after_statements)] above
#[allow(clippy::missing_const_for_fn)]
extern "C" fn on_error_from_xlib(
_: *mut xlib::Display,
er: *mut xlib::XErrorEvent,
) -> c_int {
let err = unsafe { *er };
//ignore bad window errors
if err.error_code == xlib::BadWindow {
return 0;
}
1
}
unsafe {
(xw.xlib.XSetErrorHandler)(Some(on_error_from_xlib));
(xw.xlib.XSync)(xw.display, xlib::False);
};
xw
}
/// Shutdown connections to the xserver.
pub fn shutdown(&self) {
unsafe {
(self.xlib.XUngrabKey)(self.display, xlib::AnyKey, xlib::AnyModifier, self.root);
(self.xlib.XCloseDisplay)(self.display);
}
}
/// Grabs a list of keybindings.
pub fn grab_keys(&self, keybinds: &[Keybind]) {
// Cleanup key grabs.
unsafe {
(self.xlib.XUngrabKey)(self.display, xlib::AnyKey, xlib::AnyModifier, self.root);
}
// Grab all the key combos from the config file.
for kb in keybinds {
if let Some(keysym) = xkeysym_lookup::into_keysym(&kb.key) {
let modmask = xkeysym_lookup::into_modmask(&kb.modifier);
self.grab_key(self.root, keysym, modmask);
}
}
}
/// Grabs the keysym with the modifier for a window.
pub fn grab_key(&self, root: xlib::Window, keysym: u32, modifiers: u32) {
let code = unsafe { (self.xlib.XKeysymToKeycode)(self.display, c_ulong::from(keysym)) };
// Grab the keys with and without numlock (Mod2).
let mods: Vec<u32> = vec![
modifiers,
modifiers | xlib::Mod2Mask,
modifiers | xlib::LockMask,
];
for m in mods {
unsafe {
(self.xlib.XGrabKey)(
self.display,
i32::from(code),
m,
root,
1,
xlib::GrabModeAsync,
xlib::GrabModeAsync,
);
}
}
}
/// Updates the keyboard mapping.
/// # Errors
///
/// Will error if updating the keyboard failed.
pub fn refresh_keyboard(&self, evt: &mut xlib::XMappingEvent) -> Error {
let status = unsafe { (self.xlib.XRefreshKeyboardMapping)(evt) };
if status == 0 {
Err(LeftError::XFailedStatus)
} else {
Ok(())
}
}
/// Converts a keycode to a keysym.
#[must_use]
pub fn keycode_to_keysym(&self, keycode: u32) -> xkeysym_lookup::XKeysym {
// Not using XKeysymToKeycode because deprecated.
let sym = unsafe { (self.xlib.XkbKeycodeToKeysym)(self.display, keycode as u8, 0, 0) };
sym as u32
}
/// Converts a keysym to a keycode.
pub fn keysym_to_keycode(&self, keysym: xkeysym_lookup::XKeysym) -> u32 {
let code = unsafe { (self.xlib.XKeysymToKeycode)(self.display, keysym.into()) };
u32::from(code)
}
/// Returns the next `Xevent` of the xserver.
#[must_use]
pub fn get_next_event(&self) -> xlib::XEvent {
unsafe {
let mut event: xlib::XEvent = std::mem::zeroed();
(self.xlib.XNextEvent)(self.display, &mut event);
event
}
}
/// Returns how many events are waiting.
#[must_use]
pub fn queue_len(&self) -> i32 {
unsafe { (self.xlib.XPending)(self.display) }
}
pub fn flush(&self) {
unsafe { (self.xlib.XFlush)(self.display) };
}
pub fn wait_readable(&mut self) -> Pin<Box<dyn Future<Output = ()>>> {
let task_notify = self.task_notify.clone();
Box::pin(async move {
task_notify.notified().await;
})
}
}