Implement hotkey support and improve error handling

Fixes #5
This commit is contained in:
Julian Ospald 2017-07-14 00:27:46 +02:00
parent b7beebc20f
commit ee847ff896
No known key found for this signature in database
GPG Key ID: 511B62C09D50CD28
21 changed files with 1536 additions and 56 deletions

View File

@ -36,6 +36,13 @@ which = "*"
xdg = "*" xdg = "*"
libnotify = { git = "https://github.com/hasufell/rust-libnotify.git", branch = "git-deps", optional = true } libnotify = { git = "https://github.com/hasufell/rust-libnotify.git", branch = "git-deps", optional = true }
png = "^0.9.0" png = "^0.9.0"
lazy_static = "^0.2.8"
w_result = "^0.1.2"
[dependencies.x11]
version = "^2.14.0"
features = ["xlib", "xtst"]
[dependencies.gtk] [dependencies.gtk]
git = "https://github.com/gtk-rs/gtk.git" git = "https://github.com/gtk-rs/gtk.git"

View File

@ -51,6 +51,6 @@ Pretty much the same. Differences are:
TODO TODO
---- ----
- [ ] [hotkey support](https://github.com/hasufell/pnmixer-rust/issues/5) - [x] [hotkey support](https://github.com/hasufell/pnmixer-rust/issues/5)
- [ ] [translation](https://github.com/hasufell/pnmixer-rust/issues/4) - [ ] [translation](https://github.com/hasufell/pnmixer-rust/issues/4)
- [X] [documentation](https://github.com/hasufell/pnmixer-rust/issues/3) - [X] [documentation](https://github.com/hasufell/pnmixer-rust/issues/3)

188
data/ui/hotkey-dialog.glade Normal file
View File

@ -0,0 +1,188 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
<requires lib="gtk+" version="3.12"/>
<object class="GtkDialog" id="hotkey_dialog">
<property name="width_request">300</property>
<property name="height_request">200</property>
<property name="can_focus">False</property>
<property name="border_width">5</property>
<property name="title">Set xxx HotKey</property>
<property name="modal">True</property>
<property name="destroy_with_parent">True</property>
<property name="icon_name">input-keyboard</property>
<property name="type_hint">dialog</property>
<child internal-child="vbox">
<object class="GtkBox" id="dialog-vbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="spacing">2</property>
<child internal-child="action_area">
<object class="GtkButtonBox" id="dialog-action_area1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="layout_style">end</property>
<child>
<object class="GtkButton" id="button1">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<child>
<object class="GtkBox" id="box4">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">center</property>
<child>
<object class="GtkImage" id="image4">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="icon_name">gtk-cancel</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_start">5</property>
<property name="label" translatable="yes">Cancel</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="pack_type">end</property>
<property name="position">3</property>
</packing>
</child>
<child>
<object class="GtkBox" id="hbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImage" id="image1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_start">10</property>
<property name="margin_end">10</property>
<property name="pixel_size">57</property>
<property name="icon_name">input-keyboard</property>
<property name="icon_size">3</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkBox" id="vbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Defining HotKey</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="hotkey_reset_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(press &lt;Ctrl&gt;C to reset)</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkHSeparator" id="hseparator1">
<property name="visible">True</property>
<property name="can_focus">False</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="instruction_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label">Press new HotKey for xxx</property>
<property name="use_markup">True</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="key_pressed_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">4</property>
</packing>
</child>
</object>
</child>
<action-widgets>
<action-widget response="0">button1</action-widget>
</action-widgets>
</object>
</interface>

View File

@ -926,10 +926,229 @@
</packing> </packing>
</child> </child>
<child> <child>
<placeholder/> <object class="GtkBox" id="hotkeys_vbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">start</property>
<property name="margin_start">5</property>
<property name="margin_end">5</property>
<property name="margin_top">5</property>
<property name="margin_bottom">5</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkFrame" id="frame8">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<object class="GtkBox" id="vbox6">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_start">12</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkCheckButton" id="hotkeys_enable_check">
<property name="label" translatable="yes">Enable HotKeys</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="halign">start</property>
<property name="draw_indicator">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="padding">5</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid" id="hotkeys_grid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="row_spacing">12</property>
<property name="column_spacing">12</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkLabel" id="label20">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">start</property>
<property name="label" translatable="yes">Command</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label7">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">start</property>
<property name="label" translatable="yes">Mute/Unmute:</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label8">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">start</property>
<property name="label" translatable="yes">Volume Up:</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">2</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label18">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">start</property>
<property name="label" translatable="yes">Volume Down:</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">3</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label21">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">HotKey</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkEventBox" id="hotkeys_mute_eventbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="hotkeys_mute_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(None)</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkEventBox" id="hotkeys_up_eventbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="hotkeys_up_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(None)</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">2</property>
</packing>
</child>
<child>
<object class="GtkEventBox" id="hotkeys_down_eventbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="hotkeys_down_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">(None)</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">3</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label19">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Double-click a HotKey to assign a new HotKey</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">4</property>
<property name="width">2</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
<child type="label">
<object class="GtkLabel" id="label24">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_bottom">5</property>
<property name="label" translatable="yes">&lt;b&gt;HotKey Settings&lt;/b&gt;</property>
<property name="use_markup">True</property>
</object>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="padding">5</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="position">3</property>
</packing>
</child> </child>
<child type="tab"> <child type="tab">
<placeholder/> <object class="GtkLabel" id="hotkeys_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">HotKeys</property>
</object>
<packing>
<property name="position">3</property>
<property name="tab_fill">False</property>
</packing>
</child> </child>
</object> </object>
<packing> <packing>

View File

@ -316,7 +316,6 @@ extern "C" fn watch_cb(chan: *mut glib_sys::GIOChannel,
error!("GIO error has occurred"); error!("GIO error has occurred");
cb(AlsaEvent::AlsaCardError); cb(AlsaEvent::AlsaCardError);
} }
_ => warn!("Unknown status from g_io_channel_read_chars()"),
} }
return true as glib_sys::gboolean; return true as glib_sys::gboolean;
} }

View File

@ -4,8 +4,10 @@
use audio::{Audio, AudioUser}; use audio::{Audio, AudioUser};
use errors::*; use errors::*;
use gtk; use gtk;
use hotkeys::Hotkeys;
use prefs::*; use prefs::*;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc;
use support_audio::*; use support_audio::*;
use ui_entry::Gui; use ui_entry::Gui;
@ -21,12 +23,15 @@ pub struct AppS {
/// Mostly static GUI state. /// Mostly static GUI state.
pub gui: Gui, pub gui: Gui,
/// Audio state. /// Audio state.
pub audio: Audio, pub audio: Rc<Audio>,
/// Preferences state. /// Preferences state.
pub prefs: RefCell<Prefs>, pub prefs: RefCell<Prefs>,
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
/// Notification state. /// Notification state. In case of initialization failure, this
pub notif: Notif, /// is set to `None`.
pub notif: Option<Notif>,
/// Hotkey state.
pub hotkeys: RefCell<Box<Hotkeys>>, // Gets an Rc to Audio.
} }
@ -39,9 +44,8 @@ impl AppS {
let builder_popup_menu = let builder_popup_menu =
gtk::Builder::new_from_string(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), gtk::Builder::new_from_string(include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/data/ui/popup-menu.glade"))); "/data/ui/popup-menu.glade")));
let prefs = RefCell::new(Prefs::new().unwrap()); let prefs = RefCell::new(unwrap_error!(Prefs::new(), None));
let gui =
Gui::new(builder_popup_window, builder_popup_menu, &prefs.borrow());
let card_name = prefs.borrow() let card_name = prefs.borrow()
.device_prefs .device_prefs
@ -53,15 +57,26 @@ impl AppS {
.clone(); .clone();
// TODO: better error handling // TODO: better error handling
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
let notif = Notif::new(&prefs.borrow()).unwrap(); let notif = result_warn!(Notif::new(&prefs.borrow()), None).ok();
let audio = Rc::new(unwrap_error!(Audio::new(Some(card_name),
Some(chan_name)),
None));
let hotkeys = unwrap_error!(wresult_warn!(Hotkeys::new(&prefs.borrow(),
audio.clone()), None),
None);
let gui =
Gui::new(builder_popup_window, builder_popup_menu, &prefs.borrow());
return AppS { return AppS {
_cant_construct: (), _cant_construct: (),
gui, gui,
audio: Audio::new(Some(card_name), Some(chan_name)).unwrap(), audio: audio,
prefs, prefs,
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
notif, notif,
hotkeys: RefCell::new(hotkeys),
}; };
} }
@ -84,15 +99,16 @@ impl AppS {
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
/// Update the notification state. /// Update the notification state.
pub fn update_notify(&self) -> Result<()> { pub fn update_notify(&self) {
return self.notif.reload(&self.prefs.borrow()); match self.notif {
Some(ref n) => n.reload(&self.prefs.borrow()),
None => warn!("Notification system not unitialized, skipping update"),
}
} }
#[cfg(not(feature = "notify"))] #[cfg(not(feature = "notify"))]
/// Update the notification state. /// Update the notification state.
pub fn update_notify(&self) -> Result<()> { pub fn update_notify(&self) {}
return Ok(());
}
/// Update the audio state. /// Update the audio state.
pub fn update_audio(&self, user: AudioUser) -> Result<()> { pub fn update_audio(&self, user: AudioUser) -> Result<()> {
@ -104,4 +120,10 @@ impl AppS {
let prefs = self.prefs.borrow_mut(); let prefs = self.prefs.borrow_mut();
return prefs.store_config(); return prefs.store_config();
} }
/// Update hotkey state.
pub fn update_hotkeys(&self) -> Result<()> {
let prefs = self.prefs.borrow();
return self.hotkeys.borrow_mut().reload(&prefs);
}
} }

View File

@ -1,4 +1,5 @@
#![allow(missing_docs)] // enums #![allow(missing_docs)] // enums
#![allow(illegal_floating_point_literal_pattern)]
//! High-level audio subsystem. //! High-level audio subsystem.
//! //!
@ -443,6 +444,5 @@ fn on_alsa_event(last_action_timestamp: &mut i64,
self::AudioSignal::ValuesChanged, self::AudioSignal::ValuesChanged,
self::AudioUser::Unknown); self::AudioUser::Unknown);
} }
e => warn!("Unhandled alsa event: {:?}", e),
} }
} }

View File

@ -6,17 +6,12 @@ extern crate pnmixerlib;
use pnmixerlib::*; use pnmixerlib::*;
use app_state::*; use app_state::*;
#[cfg(feature = "notify")]
use libnotify::*;
use std::rc::Rc; use std::rc::Rc;
fn main() { fn main() {
gtk::init().unwrap(); gtk::init().unwrap();
// TODO: error handling
#[cfg(feature = "notify")]
init("PNMixer-rs").unwrap();
flexi_logger::LogOptions::new() flexi_logger::LogOptions::new()
.log_to_file(false) .log_to_file(false)
// ... your configuration options go here ... // ... your configuration options go here ...
@ -29,6 +24,5 @@ fn main() {
gtk::main(); gtk::main();
#[cfg(feature = "notify")] // TODO: clean deallocation?
uninit();
} }

View File

@ -15,6 +15,13 @@ error_chain! {
Toml(toml::de::Error); Toml(toml::de::Error);
Png(png::DecodingError); Png(png::DecodingError);
} }
errors {
GtkResponseCancel(t: String) {
description("User hit cancel")
display("User hit cancel: {}", t)
}
}
} }
@ -107,3 +114,121 @@ macro_rules! try_e {
}, },
}) })
} }
#[macro_export]
/// Unwraps a `Result<T, E>` by yielding a value of the samet ype
/// for either case.
macro_rules! unwrap_any {
($expr:expr, $fmt_ok:expr, $fmt_err:expr) => (match $expr {
::std::result::Result::Ok(val) => $fmt_ok,
::std::result::Result::Err(err) => $fmt_err,
})
}
#[macro_export]
/// Warns on err and yields `()` without returning the function.
macro_rules! just_warn {
($expr:expr) => (match $expr {
::std::result::Result::Ok(_) => (),
::std::result::Result::Err(err) => {
warn!("{:?}", err);
()
},
});
}
#[macro_export]
/// Present a gtk error dialog with given message.
/// Provides only a close button.
macro_rules! error_dialog {
($msg:expr, $parent:expr) => {
{
use gtk::DialogExt;
use gtk::WidgetExt;
use gtk::WindowExt;
let parent: Option<&gtk::Window> = $parent;
let dialog = gtk::MessageDialog::new(parent,
gtk::DIALOG_DESTROY_WITH_PARENT,
gtk::MessageType::Error,
gtk::ButtonsType::Close,
$msg);
dialog.set_title("PNMixer-rs Error");
dialog.run();
dialog.destroy();
}
};
}
#[macro_export]
/// Present a gtk error dialog with the error from the `Result` type,
/// if any.
/// Provides only a close button.
macro_rules! result_warn {
($expr:expr, $parent:expr) => (match $expr {
::std::result::Result::Ok(v) => Ok(v),
::std::result::Result::Err(err) => {
use std::error::Error;
let warn_string = format!("{}\n\nCause: {}", err.description(),
err.cause().map(|e| e.description()).unwrap_or(""));
warn!("{}", warn_string);
error_dialog!(warn_string.as_str(), $parent);
Err(err)
},
});
}
#[macro_export]
/// Convert `WResult` to `Result`. All warnings are printed via the `log`
/// crate and are shown via Gtk dialogs.
macro_rules! wresult_warn {
($expr:expr, $parent:expr) => (match $expr {
::w_result::WResult::WOk(t, ws) => {
use std::error::Error;
for w in ws {
let warn_string = format!("{}\n\nCause: {}", w.description(),
w.cause().map(|e| e.description()).unwrap_or(""));
warn!("{}", warn_string);
error_dialog!(warn_string.as_str(), $parent);
}
Ok(t)
},
::w_result::WResult::WErr(err) => Err(err),
});
}
#[macro_export]
/// If there is an error in the expression, push it to
/// the given mutable warning vector.
macro_rules! push_warning {
($expr:expr, $vec:ident) => (match $expr {
Err(e) => $vec.push(e),
_ => ()
});
}
#[macro_export]
/// If there is a value in the Result type, unwrap it, otherwise error-log
/// the error, show it via gtk dialog and exit the whole program.
macro_rules! unwrap_error {
($expr:expr, $parent:expr) => (match $expr {
::std::result::Result::Ok(v) => v,
::std::result::Result::Err(err) => {
use std::error::Error;
let err_string = format!("{}\n\nCause: {}", err.description(),
err.cause().map(|e| e.description()).unwrap_or(""));
error!("{}", err_string);
error_dialog!(err_string.as_str(), $parent);
::std::process::exit(1);
},
});
}

77
src/gdk_x11.rs Normal file
View File

@ -0,0 +1,77 @@
//! Glue code between gdk and x11, allowing some `gdk_x11_*` functions.
//!
//! This is not a complete binding, but just provides what we need in a
//! reasonable way.
use gdk;
use gdk_sys::GdkDisplay;
use glib::translate::*;
use x11::xlib::{Display, Window};
// https://developer.gnome.org/gdk3/stable/gdk3-X-Window-System-Interaction.html
mod ffi {
use gdk_sys::{GdkDisplay, GdkWindow};
use x11::xlib::{Display, Window};
extern "C" {
pub fn gdk_x11_get_default_xdisplay() -> *mut Display;
pub fn gdk_x11_get_default_root_xwindow() -> Window;
pub fn gdk_x11_window_foreign_new_for_display(display: *mut GdkDisplay,
window: Window) -> * mut GdkWindow;
}
}
/// Gets the default GTK+ display.
///
/// # Returns
///
/// the Xlib Display* for the display specified in the `--display`
/// command line option or the `DISPLAY` environment variable.
pub fn gdk_x11_get_default_xdisplay() -> *mut Display {
unsafe {
return ffi::gdk_x11_get_default_xdisplay();
}
}
/// Gets the root window of the default screen (see `gdk_x11_get_default_screen()`).
///
/// # Returns
///
/// an Xlib Window.
pub fn gdk_x11_get_default_root_xwindow() -> Window {
unsafe {
return ffi::gdk_x11_get_default_root_xwindow();
}
}
/// Wraps a native window in a GdkWindow. The function will try to look up the
/// window using `gdk_x11_window_lookup_for_display()` first. If it does not find
/// it there, it will create a new window.
///
/// This may fail if the window has been destroyed. If the window was already
/// known to GDK, a new reference to the existing GdkWindow is returned.
/// ## `display`
/// the GdkDisplay where the window handle comes from.
/// ## ` window`
/// an Xlib Window
///
/// # Returns
///
/// a GdkWindow wrapper for the native window, or `None` if the window has been
/// destroyed. The wrapper will be newly created, if one doesnt exist already.
pub fn gdk_x11_window_foreign_new_for_display(gdk_display: &mut gdk::Display,
xwindow: Window)
-> Option<gdk::Window> {
unsafe {
let display: *mut GdkDisplay =
mut_override(gdk_display.to_glib_none().0);
return from_glib_full(
ffi::gdk_x11_window_foreign_new_for_display(display, xwindow));
}
}

181
src/hotkey.rs Normal file
View File

@ -0,0 +1,181 @@
//! The hotkey subsystem.
//!
//! This file defines what's a hotkey and deals with the low-level XKBlib and
//! Gtk/Gdk.
use errors::*;
use gdk;
use gdk_sys;
use gdk_x11::*;
use gtk;
use x11;
use libc::c_int;
use libc::c_uint;
/// `xmodmap -pm`
/// List of key modifiers which will be ignored whenever
/// we check whether the defined hotkeys have been pressed.
lazy_static! {
static ref KEY_MASKS: Vec<c_uint> = vec![
gdk_sys::GdkModifierType::empty().bits(), // No Modkey
gdk_sys::GDK_MOD2_MASK.bits(), // Numlock
gdk_sys::GDK_LOCK_MASK.bits(), // Capslock
gdk_sys::GDK_MOD2_MASK.bits() | gdk_sys::GDK_LOCK_MASK.bits(),
];
}
#[derive(Debug)]
/// A hotkey, described by the underlying gdk/X11 representation.
pub struct Hotkey {
/// The hardware keycode.
pub code: gdk::key,
/// The modifier keys and mouse button that have been pressed
/// in addition to the main key (e.g. Numlock/Capslock).
/// This is the raw bit representation and can be converted to
/// `gtk::ModifierType` via `self.mods()`.
pub mod_bits: u32, // Makes serialize/deserialize easier
/// X key symbol.
pub sym: u64,
/// Gtk Accelerator string.
pub gtk_accel: String,
}
impl Hotkey {
/// Creates a new hotkey and grabs it.
pub fn new(code: gdk::key, mods: gdk::ModifierType) -> Result<Hotkey> {
let display = gdk_x11_get_default_xdisplay();
let mod_bits = mods.bits();
let sym =
unsafe { x11::xlib::XkbKeycodeToKeysym(display, code as u8, 0, 0) };
let gtk_accel = gtk::accelerator_name(sym as u32, mods)
.ok_or("Could net get accelerator name")?;
let hotkey = Hotkey {
code,
mod_bits,
sym,
gtk_accel,
};
hotkey.grab()?;
return Ok(hotkey);
}
/// Creates a new hotkey from an accelerator string and grabs it.
pub fn new_from_accel(accel: &str) -> Result<Hotkey> {
let (code, mods) = hotkey_accel_to_code(accel);
return Hotkey::new(code, mods);
}
/// Grab a key manually. Should be paired with a ungrab() call.
pub fn grab(&self) -> Result<()> {
let display = gdk_x11_get_default_xdisplay();
/* Init error handling */
let old_hdlr = unsafe {
GRAB_ERROR = 0;
x11::xlib::XSetErrorHandler(Some(grab_error_handler))
};
/* Grab the key */
for key in KEY_MASKS.iter() {
unsafe {
x11::xlib::XGrabKey(display,
self.code,
self.mod_bits | key,
gdk_x11_get_default_root_xwindow(),
1,
x11::xlib::GrabModeAsync,
x11::xlib::GrabModeAsync);
}
}
/* Synchronize X */
unsafe {
x11::xlib::XFlush(display);
x11::xlib::XSync(display, false as c_int);
}
/* Restore error handler */
unsafe {
x11::xlib::XSetErrorHandler(old_hdlr);
}
/* Check for error */
unsafe {
ensure!(GRAB_ERROR == 0, "Error grabbing");
}
return Ok(());
}
/// Ungrab a key manually. Should be paired with a grab() call.
pub fn ungrab(&self) {
let display = gdk_x11_get_default_xdisplay();
for key in KEY_MASKS.iter() {
unsafe {
x11::xlib::XUngrabKey(display,
self.code,
self.mod_bits | key,
gdk_x11_get_default_root_xwindow());
}
}
}
/// Checks if the keycode we got (minus modifiers like
/// numlock/capslock) matches the hotkey.
/// Thus numlock + o will match o.
pub fn matches(&self, code: gdk::key, mods: gdk::ModifierType) -> bool {
if code != self.code {
return false;
}
for key in KEY_MASKS.iter() {
if (self.mod_bits | key) == mods.bits() {
return true;
}
}
return false;
}
}
impl Drop for Hotkey {
fn drop(&mut self) {
debug!("Ungrabbing hotkey");
self.ungrab();
}
}
/// Translate a Gtk Accelerator string to a key code and mods.
pub fn hotkey_accel_to_code(accel: &str) -> (gdk::key, gdk::ModifierType) {
let display = gdk_x11_get_default_xdisplay();
let (sym, mods) = gtk::accelerator_parse(accel);
unsafe {
if sym != 0 {
return (x11::xlib::XKeysymToKeycode(display, sym as u64) as i32,
mods);
} else {
return (-1, mods);
}
}
}
static mut GRAB_ERROR: u8 = 0;
extern "C" fn grab_error_handler(_: *mut x11::xlib::Display,
_: *mut x11::xlib::XErrorEvent)
-> c_int {
warn!("Error while grabbing hotkey");
unsafe {
GRAB_ERROR = 1;
}
return 0;
}

292
src/hotkeys.rs Normal file
View File

@ -0,0 +1,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;
}

View File

@ -59,11 +59,16 @@ pub extern crate gtk;
extern crate gtk_sys; extern crate gtk_sys;
extern crate libc; extern crate libc;
extern crate png; extern crate png;
extern crate w_result;
extern crate which; extern crate which;
extern crate x11;
extern crate xdg; extern crate xdg;
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
extern crate libnotify; pub extern crate libnotify;
#[macro_use]
extern crate lazy_static;
#[macro_use] #[macro_use]
mod errors; mod errors;
@ -74,6 +79,9 @@ mod glade_helpers;
mod alsa_card; mod alsa_card;
pub mod app_state; pub mod app_state;
mod audio; mod audio;
mod gdk_x11;
mod hotkey;
mod hotkeys;
mod prefs; mod prefs;
mod support_alsa; mod support_alsa;
mod support_audio; mod support_audio;
@ -81,6 +89,7 @@ mod support_cmd;
#[macro_use] #[macro_use]
mod support_ui; mod support_ui;
pub mod ui_entry; pub mod ui_entry;
mod ui_hotkey_dialog;
mod ui_popup_menu; mod ui_popup_menu;
mod ui_popup_window; mod ui_popup_window;
mod ui_prefs_dialog; mod ui_prefs_dialog;
@ -88,3 +97,6 @@ mod ui_tray_icon;
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
mod notif; mod notif;
// TODO: run_error_dialog an more occasions

View File

@ -21,7 +21,7 @@ pub struct Notif {
enabled: Cell<bool>, enabled: Cell<bool>,
from_popup: Cell<bool>, from_popup: Cell<bool>,
from_tray: Cell<bool>, from_tray: Cell<bool>,
// TODO: from hotkey from_hotkeys: Cell<bool>,
from_external: Cell<bool>, from_external: Cell<bool>,
volume_notif: libnotify::Notification, volume_notif: libnotify::Notification,
@ -30,30 +30,36 @@ pub struct Notif {
impl Notif { impl Notif {
/// Create a new notification instance from the current preferences. /// Create a new notification instance from the current preferences.
/// This should only be done once at startup. This also initializes
/// the libnotify system.
pub fn new(prefs: &Prefs) -> Result<Self> { pub fn new(prefs: &Prefs) -> Result<Self> {
libnotify::init("PNMixer-rs")?;
let notif = Notif { let notif = Notif {
enabled: Cell::new(false), enabled: Cell::new(false),
from_popup: Cell::new(false), from_popup: Cell::new(false),
from_tray: Cell::new(false), from_tray: Cell::new(false),
from_hotkeys: Cell::new(false),
from_external: Cell::new(false), from_external: Cell::new(false),
volume_notif: libnotify::Notification::new("", None, None), volume_notif: libnotify::Notification::new("", None, None),
text_notif: libnotify::Notification::new("", None, None), text_notif: libnotify::Notification::new("", None, None),
}; };
notif.reload(prefs)?; notif.reload(prefs);
return Ok(notif); return Ok(notif);
} }
/// Reload the notification instance from the current /// Reload the notification instance from the current
/// preferences. /// preferences.
pub fn reload(&self, prefs: &Prefs) -> Result<()> { pub fn reload(&self, prefs: &Prefs) {
let timeout = prefs.notify_prefs.notifcation_timeout; let timeout = prefs.notify_prefs.notifcation_timeout;
self.enabled.set(prefs.notify_prefs.enable_notifications); self.enabled.set(prefs.notify_prefs.enable_notifications);
self.from_popup.set(prefs.notify_prefs.notify_popup); self.from_popup.set(prefs.notify_prefs.notify_popup);
self.from_tray.set(prefs.notify_prefs.notify_mouse_scroll); self.from_tray.set(prefs.notify_prefs.notify_mouse_scroll);
self.from_hotkeys.set(prefs.notify_prefs.notify_hotkeys);
self.from_external.set(prefs.notify_prefs.notify_external); self.from_external.set(prefs.notify_prefs.notify_external);
self.volume_notif.set_timeout(timeout as i32); self.volume_notif.set_timeout(timeout as i32);
@ -64,8 +70,6 @@ impl Notif {
self.text_notif.set_timeout(timeout as i32); self.text_notif.set_timeout(timeout as i32);
self.text_notif.set_hint("x-canonical-private-synchronous", self.text_notif.set_hint("x-canonical-private-synchronous",
Some("".to_variant())); Some("".to_variant()));
return Ok(());
} }
/// Shows a volume notification, e.g. for volume or mute state change. /// Shows a volume notification, e.g. for volume or mute state change.
@ -120,38 +124,46 @@ impl Notif {
} }
} }
impl Drop for Notif {
fn drop(&mut self) {
libnotify::uninit();
}
}
/// Initialize the notification subsystem. /// Initialize the notification subsystem.
pub fn init_notify(appstate: Rc<AppS>) { pub fn init_notify(appstate: Rc<AppS>) {
debug!("Blah");
{ {
/* connect handler */ /* connect handler */
let apps = appstate.clone(); let apps = appstate.clone();
appstate.audio.connect_handler(Box::new(move |s, u| { appstate.audio.connect_handler(Box::new(move |s, u| {
let notif = &apps.notif; let notif = &apps.notif;
if !notif.enabled.get() { if notif.is_none() || !notif.as_ref().unwrap().enabled.get() {
return; return;
} }
let notif = notif.as_ref().unwrap();
match (s, match (s,
u, u,
(notif.from_popup.get(), (notif.from_popup.get(),
notif.from_tray.get(), notif.from_tray.get(),
notif.from_external.get())) { notif.from_external.get(),
notif.from_hotkeys.get())) {
(AudioSignal::NoCard, _, _) => try_w!(notif.show_text_notif("No sound card", "No playable soundcard found")), (AudioSignal::NoCard, _, _) => try_w!(notif.show_text_notif("No sound card", "No playable soundcard found")),
(AudioSignal::CardDisconnected, _, _) => try_w!(notif.show_text_notif("Soundcard disconnected", "Soundcard has been disconnected, reloading sound system...")), (AudioSignal::CardDisconnected, _, _) => try_w!(notif.show_text_notif("Soundcard disconnected", "Soundcard has been disconnected, reloading sound system...")),
(AudioSignal::CardError, _, _) => (), (AudioSignal::CardError, _, _) => (),
(AudioSignal::ValuesChanged, (AudioSignal::ValuesChanged,
AudioUser::TrayIcon, AudioUser::TrayIcon,
(_, true, _)) => try_w!(notif.show_volume_notif(&apps.audio)), (_, true, _, _)) => try_w!(notif.show_volume_notif(&apps.audio)),
(AudioSignal::ValuesChanged, (AudioSignal::ValuesChanged,
AudioUser::Popup, AudioUser::Popup,
(true, _, _)) => try_w!(notif.show_volume_notif(&apps.audio)), (true, _, _, _)) => try_w!(notif.show_volume_notif(&apps.audio)),
(AudioSignal::ValuesChanged, (AudioSignal::ValuesChanged,
AudioUser::Unknown, AudioUser::Unknown,
(_, _, true)) => try_w!(notif.show_volume_notif(&apps.audio)), (_, _, true, _)) => try_w!(notif.show_volume_notif(&apps.audio)),
(AudioSignal::ValuesChanged,
// TODO hotkeys AudioUser::Hotkeys,
(_, _, _, true)) => try_w!(notif.show_volume_notif(&apps.audio)),
_ => (), _ => (),
} }
})); }));

View File

@ -165,8 +165,8 @@ pub struct NotifyPrefs {
pub notifcation_timeout: i64, pub notifcation_timeout: i64,
pub notify_mouse_scroll: bool, pub notify_mouse_scroll: bool,
pub notify_popup: bool, pub notify_popup: bool,
pub notify_external: bool, pub notify_external: bool,
// TODO: notify_hotkeys? pub notify_hotkeys: bool,
} }
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
@ -178,11 +178,23 @@ impl Default for NotifyPrefs {
notify_mouse_scroll: true, notify_mouse_scroll: true,
notify_popup: true, notify_popup: true,
notify_external: true, notify_external: true,
notify_hotkeys: true,
}; };
} }
} }
#[derive(Deserialize, Debug, Serialize, Default)]
/// Hotkey preferences.
/// The `String`s represent gtk accelerator strings.
pub struct HotkeyPrefs {
pub enable_hotkeys: bool,
pub mute_unmute_key: Option<String>,
pub vol_up_key: Option<String>,
pub vol_down_key: Option<String>,
}
#[derive(Deserialize, Debug, Serialize, Default)] #[derive(Deserialize, Debug, Serialize, Default)]
#[serde(default)] #[serde(default)]
/// Main preferences struct, holding all sub-preferences. /// Main preferences struct, holding all sub-preferences.
@ -191,8 +203,8 @@ pub struct Prefs {
pub view_prefs: ViewPrefs, pub view_prefs: ViewPrefs,
pub behavior_prefs: BehaviorPrefs, pub behavior_prefs: BehaviorPrefs,
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
pub notify_prefs: NotifyPrefs, pub notify_prefs: NotifyPrefs,
// TODO: HotKeys? pub hotkey_prefs: HotkeyPrefs,
} }
impl Prefs { impl Prefs {
@ -223,6 +235,7 @@ impl Prefs {
} }
// TODO: unused
/// Reload the current preferences from the config file. /// Reload the current preferences from the config file.
pub fn reload_config(&mut self) -> Result<()> { pub fn reload_config(&mut self) -> Result<()> {
debug!("Reloading config..."); debug!("Reloading config...");
@ -241,8 +254,10 @@ impl Prefs {
debug!("Storing config in {:?}", config_path); debug!("Storing config in {:?}", config_path);
let mut f = File::create(config_path)?; let mut f = File::create(config_path)
f.write_all(self.to_str().as_bytes())?; .chain_err(|| "Could not open/create config file for writing")?;
f.write_all(self.to_str().as_bytes())
.chain_err(|| "Could not write to config file")?;
return Ok(()); return Ok(());
} }

View File

@ -1,5 +1,6 @@
//! Helper functions for invoking system commands. //! Helper functions for invoking system commands.
use errors::*; use errors::*;
use glib; use glib;
use prefs::Prefs; use prefs::Prefs;

134
src/ui_hotkey_dialog.rs Normal file
View File

@ -0,0 +1,134 @@
//! The ui hotkey preferences dialog.
//!
//! Usually run from the preferences window.
use errors::*;
use gdk::DeviceExt;
use gdk;
use gdk_sys;
use glib::translate::*;
use gtk::prelude::*;
use gtk;
use gtk_sys;
use libc::c_uint;
use std;
/// Hotkey dialog struct holding the relevant gtk widgets.
pub struct HotkeyDialog {
hotkey_dialog: gtk::Dialog,
// instruction_label: gtk::Label, // not needed
key_pressed_label: gtk::Label,
}
impl HotkeyDialog {
/// Creates a new hotkey dialog.
pub fn new<P>(parent: &P, hotkey: String) -> HotkeyDialog
where P: IsA<gtk::Window>
{
let builder =
gtk::Builder::new_from_string(include_str!(concat!(env!("CARGO_MANIFEST_DIR"),
"/data/ui/hotkey-dialog.glade")));
let hotkey_dialog: gtk::Dialog = builder.get_object("hotkey_dialog")
.unwrap();
let instruction_label: gtk::Label = builder.get_object("instruction_label")
.unwrap();
let key_pressed_label: gtk::Label = builder.get_object("key_pressed_label")
.unwrap();
hotkey_dialog.set_title(format!("Set {} HotKey", hotkey).as_str());
instruction_label.set_markup(format!("Press new HotKey for <b>{}</b>",
hotkey)
.as_str());
hotkey_dialog.set_transient_for(parent);
{
let key_pressed_label = key_pressed_label.clone();
hotkey_dialog.connect_key_press_event(move |_, e| {
let mut state = e.get_state();
unsafe {
let mut keyval: c_uint = 0;
let mut consumed: gdk_sys::GdkModifierType =
gdk_sys::GdkModifierType::empty();
gdk_sys::gdk_keymap_translate_keyboard_state(
gdk_sys::gdk_keymap_get_default(),
e.get_hardware_keycode() as u32,
state.to_glib(),
e.get_group() as i32,
&mut keyval as *mut c_uint,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut consumed as *mut gdk_sys::GdkModifierType);
let consumed: gdk::ModifierType = from_glib(!consumed);
state = state & consumed;
state = state & gtk::accelerator_get_default_mod_mask();
let key_text = gtk::accelerator_name(keyval, state);
key_pressed_label.set_text(key_text
.unwrap_or(String::from("(None)"))
.as_str());
};
return Inhibit(false);
});
}
hotkey_dialog.connect_key_release_event(move |w, _| {
w.response(gtk_sys::GtkResponseType::Ok as i32);
return Inhibit(false);
});
return HotkeyDialog {
hotkey_dialog,
key_pressed_label,
};
}
/// Runs the hotkey dialog and returns a String representing the hotkey
/// that has been pressed.
pub fn run(&self) -> Result<String> {
self.hotkey_dialog.show_now();
let device = gtk::get_current_event_device()
.ok_or("Could not get current device")?;
let window = self.hotkey_dialog
.get_window()
.ok_or("Could not get window")?;
let m_grab_status =
device.grab(&window,
gdk::GrabOwnership::Application,
true,
gdk::KEY_PRESS_MASK,
None,
gdk_sys::GDK_CURRENT_TIME as u32);
if m_grab_status != gdk::GrabStatus::Success {
bail!("Could not grab the keyboard");
}
let resp = self.hotkey_dialog.run();
device.ungrab(gdk_sys::GDK_CURRENT_TIME as u32);
if resp != gtk::ResponseType::Ok.into() {
bail!(ErrorKind::GtkResponseCancel(String::from("not assigning hotkey")));
}
return Ok(self.key_pressed_label
.get_text()
.ok_or("Could not get text")?);
}
}
impl Drop for HotkeyDialog {
fn drop(&mut self) {
self.hotkey_dialog.destroy();
}
}

View File

@ -74,7 +74,8 @@ pub fn init_popup_menu(appstate: Rc<AppS>) {
let apps = appstate.clone(); let apps = appstate.clone();
let mixer_item = &appstate.gui.popup_menu.mixer_item; let mixer_item = &appstate.gui.popup_menu.mixer_item;
mixer_item.connect_activate(move |_| { mixer_item.connect_activate(move |_| {
try_w!(execute_vol_control_command(&apps.prefs.borrow())); let _ = result_warn!(execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window));
}); });
} }

View File

@ -205,7 +205,8 @@ pub fn init_popup_window(appstate: Rc<AppS>) {
.popup_window .popup_window
.popup_window .popup_window
.hide(); .hide();
try_w!(execute_vol_control_command(&apps.prefs.borrow())); let _ = result_warn!(execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window));
}); });
} }
} }

View File

@ -4,13 +4,17 @@
use app_state::*; use app_state::*;
use audio::{AudioUser, AudioSignal}; use audio::{AudioUser, AudioSignal};
use errors::*;
use gdk; use gdk;
use gtk::ResponseType; use gtk::ResponseType;
use gtk::prelude::*; use gtk::prelude::*;
use gtk; use gtk;
use prefs::*; use prefs::*;
use std::ascii::AsciiExt;
use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use support_audio::*; use support_audio::*;
use ui_hotkey_dialog::HotkeyDialog;
@ -51,6 +55,21 @@ pub struct PrefsDialog {
noti_popup_check: gtk::CheckButton, noti_popup_check: gtk::CheckButton,
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
noti_ext_check: gtk::CheckButton, noti_ext_check: gtk::CheckButton,
#[cfg(feature = "notify")]
noti_hotkey_check: gtk::CheckButton,
/* HotkeyPrefs */
hotkeys_enable_check: gtk::CheckButton,
hotkeys_mute_label: gtk::Label,
hotkeys_up_label: gtk::Label,
hotkeys_down_label: gtk::Label,
/* Hotkey stuff (not prefs) */
hotkeys_mute_eventbox: gtk::EventBox,
hotkeys_up_eventbox: gtk::EventBox,
hotkeys_down_eventbox: gtk::EventBox,
hotkey_dialog: RefCell<Option<HotkeyDialog>>,
} }
impl PrefsDialog { impl PrefsDialog {
@ -99,6 +118,26 @@ impl PrefsDialog {
noti_popup_check: builder.get_object("noti_popup_check").unwrap(), noti_popup_check: builder.get_object("noti_popup_check").unwrap(),
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
noti_ext_check: builder.get_object("noti_ext_check").unwrap(), noti_ext_check: builder.get_object("noti_ext_check").unwrap(),
#[cfg(feature = "notify")]
noti_hotkey_check: builder.get_object("noti_hotkey_check").unwrap(),
/* HotkeyPrefs */
hotkeys_enable_check: builder.get_object("hotkeys_enable_check")
.unwrap(),
hotkeys_mute_label: builder.get_object("hotkeys_mute_label")
.unwrap(),
hotkeys_up_label: builder.get_object("hotkeys_up_label").unwrap(),
hotkeys_down_label: builder.get_object("hotkeys_down_label")
.unwrap(),
/* Hotkey stuff (not prefs) */
hotkeys_mute_eventbox: builder.get_object("hotkeys_mute_eventbox")
.unwrap(),
hotkeys_up_eventbox: builder.get_object("hotkeys_up_eventbox")
.unwrap(),
hotkeys_down_eventbox: builder.get_object("hotkeys_down_eventbox")
.unwrap(),
hotkey_dialog: RefCell::new(None),
}; };
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
@ -173,7 +212,27 @@ impl PrefsDialog {
.set_active(prefs.notify_prefs.notify_mouse_scroll); .set_active(prefs.notify_prefs.notify_mouse_scroll);
self.noti_popup_check.set_active(prefs.notify_prefs.notify_popup); self.noti_popup_check.set_active(prefs.notify_prefs.notify_popup);
self.noti_ext_check.set_active(prefs.notify_prefs.notify_external); self.noti_ext_check.set_active(prefs.notify_prefs.notify_external);
self.noti_hotkey_check
.set_active(prefs.notify_prefs.notify_hotkeys);
} }
/* hotkey prefs */
self.hotkeys_enable_check.set_active(prefs.hotkey_prefs.enable_hotkeys);
self.hotkeys_mute_label.set_text(prefs.hotkey_prefs
.mute_unmute_key
.clone()
.unwrap_or(String::from("(None)"))
.as_str());
self.hotkeys_up_label.set_text(prefs.hotkey_prefs
.vol_up_key
.clone()
.unwrap_or(String::from("(None)"))
.as_str());
self.hotkeys_down_label.set_text(prefs.hotkey_prefs
.vol_down_key
.clone()
.unwrap_or(String::from("(None)"))
.as_str());
} }
@ -236,6 +295,28 @@ impl PrefsDialog {
notify_mouse_scroll: self.noti_mouse_check.get_active(), notify_mouse_scroll: self.noti_mouse_check.get_active(),
notify_popup: self.noti_popup_check.get_active(), notify_popup: self.noti_popup_check.get_active(),
notify_external: self.noti_ext_check.get_active(), notify_external: self.noti_ext_check.get_active(),
notify_hotkeys: self.noti_hotkey_check.get_active(),
};
let hotkey_prefs = HotkeyPrefs {
enable_hotkeys: self.hotkeys_enable_check.get_active(),
mute_unmute_key:
self.hotkeys_mute_label.get_text().and_then(|s| if s ==
"(None)" {
None
} else {
Some(s)
}),
vol_up_key:
self.hotkeys_up_label.get_text().and_then(|s| if s ==
"(None)" {
None
} else {
Some(s)
}),
vol_down_key: self.hotkeys_down_label.get_text().and_then(|s| {
if s == "(None)" { None } else { Some(s) }
}),
}; };
return Prefs { return Prefs {
@ -244,6 +325,7 @@ impl PrefsDialog {
behavior_prefs, behavior_prefs,
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
notify_prefs, notify_prefs,
hotkey_prefs,
}; };
} }
@ -355,16 +437,51 @@ fn init_prefs_dialog(appstate: &Rc<AppS>) {
if response_id == ResponseType::Ok.into() || if response_id == ResponseType::Ok.into() ||
response_id == ResponseType::Apply.into() { response_id == ResponseType::Apply.into() {
// TODO: update hotkeys
try_w!(apps.update_notify());
try_w!(apps.update_tray_icon());
try_w!(apps.update_popup_window()); try_w!(apps.update_popup_window());
try_w!(apps.update_tray_icon());
let _ = result_warn!(apps.update_hotkeys(),
Some(&apps.gui.popup_menu.menu_window));
apps.update_notify();
try_w!(apps.update_audio(AudioUser::PrefsWindow)); try_w!(apps.update_audio(AudioUser::PrefsWindow));
try_w!(apps.update_config()); let _ = result_warn!(apps.update_config(),
Some(&apps.gui.popup_menu.menu_window));
} }
}); });
} }
/* prefs_dialog.hotkeys_mute_eventbox */
{
let apps = appstate.clone();
let m_pd = appstate.gui.prefs_dialog.borrow();
let pd = m_pd.as_ref().unwrap();
pd.hotkeys_mute_eventbox.connect_button_press_event(move |w, e| {
return Inhibit(on_hotkey_event_box_button_press_event(&apps, &w, e));
});
}
/* prefs_dialog.hotkeys_up_eventbox */
{
let apps = appstate.clone();
let m_pd = appstate.gui.prefs_dialog.borrow();
let pd = m_pd.as_ref().unwrap();
pd.hotkeys_up_eventbox.connect_button_press_event(move |w, e| {
return Inhibit(on_hotkey_event_box_button_press_event(&apps, &w, e));
});
}
/* prefs_dialog.hotkeys_down_eventbox */
{
let apps = appstate.clone();
let m_pd = appstate.gui.prefs_dialog.borrow();
let pd = m_pd.as_ref().unwrap();
pd.hotkeys_down_eventbox.connect_button_press_event(move |w, e| {
return Inhibit(on_hotkey_event_box_button_press_event(&apps, &w, e));
});
}
} }
@ -424,3 +541,82 @@ fn fill_chan_combo(appstate: &AppS, cardname: Option<String>) {
chan_combo.set_active(c_index); chan_combo.set_active(c_index);
} }
fn on_hotkey_event_box_button_press_event(appstate: &AppS,
widget: &gtk::EventBox,
event: &gdk::EventButton)
-> bool {
let borrow = appstate.gui.prefs_dialog.borrow();
let prefs_dialog = &borrow.as_ref().unwrap();
/* we want a left-click */
if event.get_button() != 1 {
return false;
}
/* we want it to be double-click */
if event.get_event_type() != gdk::EventType::DoubleButtonPress {
return false;
}
let (hotkey_label, hotkey) = {
if *widget == prefs_dialog.hotkeys_mute_eventbox {
(prefs_dialog.hotkeys_mute_label.clone(),
String::from("Mute/Unmute"))
} else if *widget == prefs_dialog.hotkeys_up_eventbox {
(prefs_dialog.hotkeys_up_label.clone(), String::from("Volume Up"))
} else if *widget == prefs_dialog.hotkeys_down_eventbox {
(prefs_dialog.hotkeys_down_label.clone(),
String::from("Volume Down"))
} else {
warn!("Unknown hotkey eventbox");
return false;
}
};
/* Ensure there's no dialog already running */
if prefs_dialog.hotkey_dialog.borrow().is_some() {
return false;
}
/* Unbind hotkeys */
appstate.hotkeys.borrow().unbind();
/* Run the hotkey dialog */
let hotkey_dialog = &prefs_dialog.hotkey_dialog;
*hotkey_dialog.borrow_mut() =
Some(HotkeyDialog::new(&prefs_dialog.prefs_dialog, hotkey));
let key_pressed = hotkey_dialog.borrow()
.as_ref()
.unwrap()
.run();
*hotkey_dialog.borrow_mut() = None;
/* Bind hotkeys */
appstate.hotkeys.borrow().bind();
/* Check the response */
match key_pressed {
Ok(k) => {
println!("k: {}", k);
if k.eq_ignore_ascii_case("<Primary>c") {
hotkey_label.set_text("(None)");
} else {
hotkey_label.set_text(k.as_str());
}
}
Err(Error(ErrorKind::GtkResponseCancel(msg), _)) => {
info!("{}", ErrorKind::GtkResponseCancel(msg));
return false;
}
Err(e) => {
// Could not grab hotkey, most likely
error_dialog!(e.description(),
Some(&appstate.gui.popup_menu.menu_window));
warn!("{}", e);
return false;
}
}
return false;
}

View File

@ -42,7 +42,8 @@ pub struct TrayIcon {
impl TrayIcon { impl TrayIcon {
/// Constructor. `audio_pix` is initialized as empty GdkPixbuf, to save /// Constructor. `audio_pix` is initialized as empty GdkPixbuf, to save
/// one iteration of png decoding (`update_all()` is triggered immediately /// one iteration of png decoding (`update_all()` is triggered immediately
/// on startup through `tray_icon.connect_size_changed`. /// on startup through `tray_icon.connect_size_changed` usually,
/// otherwise we have to trigger it manually).
pub fn new(prefs: &Prefs) -> Result<TrayIcon> { pub fn new(prefs: &Prefs) -> Result<TrayIcon> {
let draw_vol_meter = prefs.view_prefs.draw_vol_meter; let draw_vol_meter = prefs.view_prefs.draw_vol_meter;
@ -534,12 +535,15 @@ fn on_tray_button_release_event(appstate: &Rc<AppS>,
// TODO // TODO
&MiddleClickAction::ShowPreferences => show_prefs_dialog(&appstate), &MiddleClickAction::ShowPreferences => show_prefs_dialog(&appstate),
&MiddleClickAction::VolumeControl => { &MiddleClickAction::VolumeControl => {
try_wr!(execute_vol_control_command(&appstate.prefs.borrow()), let _ = result_warn!(execute_vol_control_command(&appstate.prefs.borrow()),
false); Some(&appstate.gui.popup_menu.menu_window));
} }
&MiddleClickAction::CustomCommand => { &MiddleClickAction::CustomCommand => {
match custom_command { match custom_command {
&Some(ref cmd) => try_wr!(execute_command(cmd.as_str()), false), &Some(ref cmd) => {
let _ = result_warn!(execute_command(cmd.as_str()),
Some(&appstate.gui.popup_menu.menu_window));
}
&None => warn!("No custom command found"), &None => warn!("No custom command found"),
} }
} }