summaryrefslogtreecommitdiff
path: root/src/dotwm.rs
blob: 77f09b3ac47d69214bcc7bb508ff2275d61a251d (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
use x11::xlib;
use x11::xlib::{
    Display,
    XErrorEvent,
    XEvent,

    GrabModeAsync,
};

use safe_x11::{
    open_display,
    close_display,
    grab_key,
};

use safe_x11::window::XWindow;

use std::ptr;
use std::process::exit;
use std::mem::uninitialized;
use std::collections::HashMap;
use libc::c_int;

#[allow(unused_variables)]
unsafe extern "C" fn error_handler(d: *mut Display, evptr: *mut XErrorEvent) -> c_int {
    println!("ERRORR");
    let ev = ptr::read(evptr);
    if ev.error_code == xlib::BadAccess {
        println!("Another widnow manager is running :C");
        exit(1);
    }

    0
}

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

pub struct DotWM {
    pub display: *mut Display,
    // Map with the keys as (key, mod)
    bindings: HashMap<(u32, u32), (ExecFn, Vec<String>)>,
    cw_idx: usize,
    pub window_list: Vec<XWindow>,
}

/// DotWM state.
impl DotWM {
    /// Create a state of the Dot Window Manager
    pub fn new() -> DotWM {
        let d = open_display("").unwrap();
        unsafe { xlib::XSetErrorHandler(Some(error_handler)) };
        // Some testings.
        unsafe {
            let root = xlib::XDefaultRootWindow(d);
            let mut attrs: xlib::XSetWindowAttributes = uninitialized();
            attrs.event_mask = xlib::SubstructureNotifyMask;
            xlib::XChangeWindowAttributes(d, root, xlib::CWEventMask, &mut attrs);
        }

        DotWM {
            display: d,
            bindings: HashMap::new(),
            cw_idx: 0,
            window_list: vec![],
        }
    }
    
    /// Add a binding to the WM.
    ///
    /// # Example
    ///
    /// ```
    /// fn exec(_: &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
    /// }
    ///
    /// // ...
    ///
    /// dotwm.add_binding(keysym::XK_Return, xlib::Mod4Mask, exec,
    ///                   &["xterm"]);
    /// ```
    pub fn add_binding(&mut self, key: u32, modifiers: u32, func: ExecFn, args: &[&str]) {
        grab_key(self.display, key, modifiers, true, GrabModeAsync, GrabModeAsync);        
        let mut v = vec![];
        for arg in args {
            v.push(arg.to_string());
        }
        self.bindings.insert((key, modifiers), (func, v));
    }

    pub fn exec_func(&mut self, key: u32, modifiers: u32, ev: xlib::XEvent) {
        if let Some(&(func, ref args)) = self.bindings.get(&(key, modifiers)) {
            let v = args.clone();
            func(&self, ev, &v);
        }
    }

    pub fn add_window(&mut self, w: xlib::Window) {
        self.unfocus_current_window();
        if let Some(w) = XWindow::new(self.display, w) {
            w.select_input(xlib::EnterWindowMask);
            self.window_list.push(w);
            // Last windows get focus.
            self.cw_idx = self.window_list.len() - 1;
            self.focus_current_window();
        }
    }

    pub fn current_window(&self) -> Option<&XWindow> {
        println!("trying to get {} from list of len {}", self.cw_idx, self.window_list.len());
        if self.cw_idx < self.window_list.len() {
            self.window_list.get(self.cw_idx)
        } else {
            None
        }
    }

    pub fn remove_window(&mut self, w: xlib::Window) {
        let pos = self.window_list.iter().position(|xw| xw.inner == w);
        println!("Removing widnow {}: pos: {:?}", w, pos);
        
        match pos {
            Some(idx) => { 
                let new_idx = if idx == 0 { usize::max_value() } else { idx - 1 };
                self.window_list.remove(idx);
                self.cw_idx = new_idx;
                self.focus_current_window();
            },
            None => (),
        }
    }

    pub fn change_focus_of(&mut self, idx: usize) {
        let w = &self.window_list[idx];
        self.unfocus_current_window();
        self.cw_idx = idx;
        w.set_border_width(1);
        w.set_border_color("red");
        w.raise();
    }

    pub fn find_window(&self, w: xlib::Window) -> Option<usize> {
        self.window_list.iter().position(|xw| xw.inner == w)
    }


    fn focus_current_window(&self) {
        if let Some(win) = self.current_window() {
            win.set_border_width(1);
            win.set_border_color("red");
        }
    }

    fn unfocus_current_window(&self) {
        if let Some(win) = self.current_window() {
            win.set_border_width(1);
            win.set_border_color("black");
        }
    }
}

impl Drop for DotWM {
    fn drop(&mut self) {
        println!("Closing display");
        close_display(self.display);
    }
}