summaryrefslogtreecommitdiff
path: root/src/command.rs
blob: eaadf770d59aca1e7fb1296d637019214b2063b1 (plain)
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// See LICENSE file for copyright and license details.

//! Command execution module.
//!
use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::Result;
use std::ops::Deref;
use std::process::{Command,Child};
use std::ptr;

use libc::c_int;
use libc::pid_t;

use x11::xlib;
use x11::xlib::{XEvent, GrabModeAsync};

use dotwm::DotWM;
use dotwm::NetAtom;
use safe_x11::{grab_key,ungrab_key,grab_button,ungrab_button};

const WNOHANG: c_int = 0x00000001;

extern {
    /// wait for a child process to stop or terminate.
    pub fn waitpid(pid: pid_t, stat_loc: *mut c_int, options: c_int) -> pid_t;
}

/// Executes the given command.
pub fn exec_cmd<S: AsRef<OsStr>>(program: S, args: &[S]) -> Result<Child> {
    Command::new(program).args(args).spawn()
}

/// Collect all the zombies. There's no need to add another dependency for this
/// since it's trivial to implement.
///
/// See https://github.com/Kintaro/zombie for reference.
pub fn collect_zombies() {
    unsafe { 
        while waitpid(-1, ptr::null_mut(), WNOHANG) > 0 {}
    };
}

/// Defines a callback to call no certains events.
pub type ExecFn = fn(&mut DotWM, XEvent, &[String]) -> bool;

/// Map for keys => functions
pub type BindingHash = HashMap<(u32, u32), (ExecFn, Vec<String>)>;

/// Exec a binding function.
pub fn exec_func(wm: &mut DotWM, bindings: &mut BindingHash, key: u32, modifiers: u32, ev: xlib::XEvent) {
    if let Some(&(func, ref args)) = bindings.get(&(key, modifiers)) {
        let v = args.clone();
        func(wm, ev, &v);
    }
}

/// Exec a external function
pub fn exec(_: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    if let Some(program) = args.first() {
        let mut prog_args = vec![];
        for arg in args[1..].iter() {
            prog_args.push(arg);
        }
        exec_cmd(program, prog_args.deref()).unwrap();
    }
    true
}

/// Toggles the fullscreen of the current window
pub fn fullscreen(wm: &mut DotWM, _: xlib::XEvent, _: &[String]) -> bool {
    let wmstate = wm.netatoms[&NetAtom::NetWmState];
    let fs_atom = wm.netatoms[&NetAtom::NetFullscreen];

    if let Some(win) = wm.current_window_mut() {
        win.fullscreen(wmstate, fs_atom);
    };
    true
}

/// Move the window to a relative position
pub fn move_win(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    let x = args[0].parse::<i32>().unwrap();
    let y = args[1].parse::<i32>().unwrap();
    if let Some(ref win) = wm.current_window() {
        win.move_offset(x, y);
    };
    true
}

/// Move the window to an absolute position.
pub fn move_win_to(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    let x = args[0].parse::<i32>().unwrap();
    let y = args[1].parse::<i32>().unwrap();
    if let Some(ref win) = wm.current_window() {
        match win.move_to(x, y) {
            Ok(()) => true,
            Err(_) => {
                false
            }
        }
    } else {
        true
    }
}

pub fn move_win_sticky(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    if let Some(ref win) = wm.current_window() {
        let mut xgeometries = wm.x_geometries();
        let mut ygeometries = wm.y_geometries();

        match &*args[0] {
            "left" => {
                xgeometries.sort_by(|a,b| b.cmp(a));
                win.move_sticky_left(&xgeometries);
            },
            "right" => {
                xgeometries.sort_by(|a,b| a.cmp(b));
                win.move_sticky_right(&xgeometries);
            },
            "up" => {
                ygeometries.sort_by(|a,b| b.cmp(a));
                win.move_sticky_up(&ygeometries);
            },
            "down" => {
                ygeometries.sort_by(|a,b| a.cmp(b));
                win.move_sticky_down(&ygeometries);
            },
            _ => (),
        }
    }
    true
}

/// Drag the window. for now the dragging is relative to the center of the
/// window because win.cursor_coords is always `None`. Later we should
/// be able to `XGrabButton` on the child windows (not only on the root) and
/// set `win.cursor_coords` respectively.
pub fn move_win_drag(wm: &mut DotWM, e: xlib::XEvent, _: &[String]) -> bool {
    let ev = xlib::XMotionEvent::from(e);
    if let Some(ref win) = wm.current_window() {
        let attr = win.attributes();
        let (x0, y0) = win.cursor_coords.unwrap_or((attr.width/2, attr.height/2));
        // Move around the center of the cursor.
        let x = ev.x - x0;
        let y = ev.y - y0;
        win.move_to(x, y).is_ok()
    } else {
        println!("move_win_drag - nop");
        false
    }
}

/// Resize the window certain amount in x and y.
pub fn resize_win(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    let w = args[0].parse::<i32>().unwrap();
    let h = args[1].parse::<i32>().unwrap();

    if let Some(ref win) = wm.current_window() {
        win.resize(w, h);
    };

    true
}

/// Resizes the window sticking with other windows.
///
/// The movement of the `right` command is the same logic as the `down`, idem to the
/// movement between `left` and `up`
pub fn resize_win_sticky(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    if let Some(ref win) = wm.current_window() {
        let mut xgeometries = wm.x_geometries();
        let mut ygeometries = wm.y_geometries();

        match &*args[0] {
            "left" => {
                xgeometries.sort_by(|a,b| b.cmp(a));
                win.resize_sticky_left(&xgeometries);
            },
            "right" => {
                xgeometries.sort_by(|a,b| a.cmp(b));
                win.resize_sticky_right(&xgeometries);
            },
            "up" => {
                ygeometries.sort_by(|a,b| b.cmp(a));
                win.resize_sticky_up(&ygeometries);
            },
            "down" => {
                ygeometries.sort_by(|a,b| a.cmp(b));
                win.resize_sticky_down(&ygeometries);
            },
            _ => (),
        }
    }
    true
}

/// Close the current window
pub fn close_win(wm: &mut DotWM, _: xlib::XEvent, _: &[String]) -> bool {
    if let Some(ref win) = wm.current_window() {
        win.delete();
    };

    true
}

/// Focus the next window on the list
pub fn focus_next(wm: &mut DotWM, _: xlib::XEvent, _: &[String]) -> bool {
    wm.focus_next();
    true
}

/// Tells the window manager that is time to exit.
pub fn quit_dotwm(wm: &mut DotWM, _: xlib::XEvent, _: &[String]) -> bool {
    wm.finish = true;
    true
}

/// Add a binding to the WM.
///
/// # Example
///
/// ```
/// fn quit_dotwm(_: &mut DotWM, _: xlib::XEvent, _: &[String]) -> bool {
///     process::exit(0);
/// }
///
/// // ...
///
/// add_binding(keysym::XK_Return, xlib::Mod4Mask, exec,
///             &["xterm"]);
/// ```
pub fn add_binding(wm: &mut DotWM, bindings: &mut BindingHash,
               key: u32, modifiers: u32, func: ExecFn, args: &[&str]) {
        ungrab_key(wm.display, key, modifiers);
        grab_key(wm.display, key, modifiers, true, GrabModeAsync, GrabModeAsync);        
        let mut v = vec![];
        for arg in args {
            v.push(arg.to_string());
        }
        bindings.insert((key, modifiers), (func, v));
}

/// Add a button binding to the WM.
pub fn add_button_binding(wm: &mut DotWM, bindings: &mut BindingHash,
                          button: u32, modifiers: u32, func: ExecFn, args: &[&str]) {
    ungrab_button(wm.display, button, modifiers);
    grab_button(wm.display, button, modifiers, true,
                xlib::ButtonPressMask|xlib::ButtonReleaseMask|xlib::PointerMotionMask,
                GrabModeAsync, GrabModeAsync, 0, 0);
    let mut v = vec![];
    for arg in args {
        v.push(arg.to_string());
    }
    // for now we need the button1Mask here
    bindings.insert((button, modifiers | xlib::Button1Mask), (func, v));
}

/// Change the desktop, args parameter only have one usize on it that is the
/// index of the desktop (i.e.: 0 for the first, 1 for the second, etc).
pub fn change_desktop(wm: &mut DotWM, _: xlib::XEvent, args: &[String]) -> bool {
    let num = args[0].parse::<usize>().unwrap();
    wm.change_desktop(num);
    true
}