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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! The hotkeys subsystem.
//!
//! This handles the PNMixer-rs specific hotkeys as a whole,
//! including communication with Xlib and intercepting key presses
//! before they can be interpreted by Gtk/Gdk.


use audio::{Audio, AudioUser};
use errors::*;
use errors;
use gdk;
use gdk_sys;
use gdk_x11;
use glib::translate::*;
use glib_sys;
use hotkey::*;
use prefs::*;
use std::mem;
use std::rc::Rc;
use w_result::*;
use x11;



/// The possible Hotkeys for manipulating the volume.
pub struct Hotkeys {
    enabled: bool,
    mute_key: Option<Hotkey>,
    up_key: Option<Hotkey>,
    down_key: Option<Hotkey>,

    // need this to access audio in 'key_filter'
    audio: Rc<Audio>,
    auto_unmute: bool,
}

impl Hotkeys {
    /// Creates the hotkeys subsystem and binds the hotkeys.
    pub fn new(prefs: &Prefs,
               audio: Rc<Audio>)
               -> WResult<Box<Hotkeys>, errors::Error, errors::Error> {
        debug!("Creating hotkeys control");
        let mut hotkeys =
            Box::new(Hotkeys {
                         enabled: false,
                         mute_key: None,
                         up_key: None,
                         down_key: None,
                         audio: audio,
                         auto_unmute: prefs.behavior_prefs.unmute_on_vol_change,
                     });
        let mut warn = vec![];
        push_warning!(hotkeys.reload(prefs), warn);

        /* bind hotkeys */
        let data_ptr =
            unsafe {
                mem::transmute::<&Hotkeys,
                                 glib_sys::gpointer>(hotkeys.as_ref())
            };
        hotkeys_add_filter(Some(key_filter), data_ptr);
        return WOk(hotkeys, warn);
    }

    /// Reload the Hotkeys from the preferences.
    /// If hotkeys are disabled, just sets all members to `None`.
    /// This has to be called each time the preferences are modified.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, otherwise `Err(str)` if some of the hotkeys
    /// could not be grabbed, where `str` is a String that can be
    /// presented via e.g. `run_error_dialog()`.
    pub fn reload(&mut self, prefs: &Prefs) -> Result<()> {
        self.enabled = prefs.hotkey_prefs.enable_hotkeys;
        self.mute_key = None;
        self.up_key = None;
        self.down_key = None;

        /* Return if hotkeys are disabled */
        if self.enabled == false {
            return Ok(());
        }

        let hotkey_prefs = &prefs.hotkey_prefs;
        let new_hotkey = |keyname: &Option<String>| -> (Option<Hotkey>, bool) {
            match keyname {
                &Some(ref k) => {
                    let hotkey = Hotkey::new_from_accel(k.as_str());
                    if hotkey.as_ref().is_err() {
                        (None, true)
                    } else {
                        (Some(hotkey.unwrap()), false)
                    }
                }
                &None => (None, false), // no actual error, just no key
            }
        };

        /* Setup mute hotkey */
        let (m_unmute_key, mute_err) =
            new_hotkey(&hotkey_prefs.mute_unmute_key);
        if m_unmute_key.is_some() {
            self.mute_key = Some(m_unmute_key.unwrap());
        }

        /* Setup volume uphotkey */
        let (m_up_key, up_err) = new_hotkey(&hotkey_prefs.vol_up_key);
        if m_up_key.is_some() {
            self.up_key = Some(m_up_key.unwrap());
        }

        /* Setup volume down hotkey */
        let (m_down_key, down_err) = new_hotkey(&hotkey_prefs.vol_down_key);
        if m_down_key.is_some() {
            self.down_key = Some(m_down_key.unwrap());
        }

        if mute_err || up_err || down_err {
            bail!("Could not grab the following hotkeys:\n{}{}{}",
                  if mute_err { "(Mute/Unmute)\n" } else { "" },
                  if up_err { "(Volume Up)\n" } else { "" },
                  if down_err { "(Volume Down)\n" } else { "" },
                  );
        }

        return Ok(());
    }

    /// Bind hotkeys manually. Should be paired with an `unbind()` call.
    pub fn bind(&self) {
        debug!("Bind hotkeys");
        if self.mute_key.is_some() {
            if self.mute_key
                   .as_ref()
                   .unwrap()
                   .grab()
                   .is_err() {
                warn!("Could not grab mute key");
            };
        }
        if self.up_key.is_some() {
            if self.up_key
                   .as_ref()
                   .unwrap()
                   .grab()
                   .is_err() {
                warn!("Could not grab volume up key");
            };
        }
        if self.down_key.is_some() {
            if self.down_key
                   .as_ref()
                   .unwrap()
                   .grab()
                   .is_err() {
                warn!("Could not grab volume down key");
            };
        }

        let data_ptr =
            unsafe { mem::transmute::<&Hotkeys, glib_sys::gpointer>(self) };
        hotkeys_add_filter(Some(key_filter), data_ptr);
    }

    /// Unbind hotkeys manually. Should be paired with a `bind()` call.
    pub fn unbind(&self) {
        debug!("Unbind hotkeys");
        if self.mute_key.is_some() {
            self.mute_key
                .as_ref()
                .unwrap()
                .ungrab();
        }
        if self.up_key.is_some() {
            self.up_key
                .as_ref()
                .unwrap()
                .ungrab();
        }
        if self.down_key.is_some() {
            self.down_key
                .as_ref()
                .unwrap()
                .ungrab();
        }

        let data_ptr =
            unsafe { mem::transmute::<&Hotkeys, glib_sys::gpointer>(self) };
        hotkeys_remove_filter(Some(key_filter), data_ptr);
    }
}

impl Drop for Hotkeys {
    fn drop(&mut self) {
        debug!("Freeing hotkeys");
        self.mute_key = None;
        self.up_key = None;
        self.down_key = None;

        let data_ptr =
            unsafe { mem::transmute::<&mut Hotkeys, glib_sys::gpointer>(self) };

        hotkeys_remove_filter(Some(key_filter), data_ptr)
    }
}


/// Attaches the `key_filter()` function as a filter
/// to the root window, so it will intercept window events.
fn hotkeys_add_filter(function: gdk_sys::GdkFilterFunc,
                      data: glib_sys::gpointer) {
    // TODO: all the unwrapping :/
    let window = gdk_x11::gdk_x11_window_foreign_new_for_display(
        &mut gdk::Display::get_default().unwrap(),
        gdk_x11::gdk_x11_get_default_root_xwindow()
        ).unwrap();

    unsafe {
        gdk_sys::gdk_window_add_filter(window.to_glib_none().0, function, data);
    }
}


/// Removes the previously attached `key_filter()` function from
/// the root window.
fn hotkeys_remove_filter(function: gdk_sys::GdkFilterFunc,
                         data: glib_sys::gpointer) {
    // TODO: all the unwrapping :/
    let window = gdk_x11::gdk_x11_window_foreign_new_for_display(
        &mut gdk::Display::get_default().unwrap(),
        gdk_x11::gdk_x11_get_default_root_xwindow()
        ).unwrap();

    unsafe {
        gdk_sys::gdk_window_remove_filter(window.to_glib_none().0,
                                          function,
                                          data);
    }

}


/// This function is called before Gtk/Gdk can respond
/// to any(!) window event and handles pressed hotkeys.
extern "C" fn key_filter(gdk_xevent: *mut gdk_sys::GdkXEvent,
                         _: *mut gdk_sys::GdkEvent,
                         data: glib_sys::gpointer)
                         -> gdk_sys::GdkFilterReturn {
    let xevent = gdk_xevent as *mut x11::xlib::XKeyEvent;

    let hotkeys: &Hotkeys =
        unsafe { mem::transmute::<glib_sys::gpointer, &Hotkeys>(data) };
    let mute_key = &hotkeys.mute_key;
    let up_key = &hotkeys.up_key;
    let down_key = &hotkeys.down_key;
    let audio = &hotkeys.audio;

    let xevent_type = unsafe { (*xevent).type_ };
    if xevent_type == x11::xlib::KeyPress {
        return gdk_sys::GdkFilterReturn::Continue;
    }

    let xevent_key = unsafe { (*xevent).keycode };
    let xevent_state = unsafe { (*xevent).state };


    if mute_key.as_ref().is_some() &&
       mute_key.as_ref()
           .unwrap()
           .matches(xevent_key as i32,
                    gdk::ModifierType::from_bits(xevent_state).unwrap()) {
        just_warn!(audio.toggle_mute(AudioUser::Hotkeys));
    } else if up_key.as_ref().is_some() &&
              up_key.as_ref()
                  .unwrap()
                  .matches(xevent_key as i32,
                           gdk::ModifierType::from_bits(xevent_state)
                               .unwrap()) {
        just_warn!(audio.increase_vol(AudioUser::Hotkeys, hotkeys.auto_unmute));

    } else if down_key.as_ref().is_some() &&
              down_key.as_ref()
                  .unwrap()
                  .matches(xevent_key as i32,
                           gdk::ModifierType::from_bits(xevent_state)
                               .unwrap()) {
        just_warn!(audio.decrease_vol(AudioUser::Hotkeys, hotkeys.auto_unmute));
    }

    return gdk_sys::GdkFilterReturn::Continue;
}