Made it possible to add menu items using builder

This commit is contained in:
Daniel Collin 2016-05-08 09:28:43 +02:00
parent 25ed203497
commit 835837286f
3 changed files with 57 additions and 11 deletions

View file

@ -90,9 +90,11 @@ fn main() {
let mut menu = Menu::new("TestMenu").unwrap(); let mut menu = Menu::new("TestMenu").unwrap();
menu.add_item(&MenuItem::new("Item 1", 1).shortcut(Key::S, 0)); menu.add_menu_item(&MenuItem::new("Item 1", 1).shortcut(Key::S, 0));
menu.add_item(&MenuItem::new("Item 2", 2)); menu.add_menu_item(&MenuItem::new("Item 2", 2));
menu.add_item(&MenuItem::new("Item 3", 3)); menu.add_menu_item(&MenuItem::new("Item 3", 3));
menu.add_item("Some item", 2).shortcut(Key::Y, 0).build();
let _ = window.add_menu(&menu); let _ = window.add_menu(&menu);

View file

@ -530,8 +530,18 @@ impl Menu {
} }
#[inline] #[inline]
pub fn add_item(&mut self, item: &MenuItem) -> MenuItemHandle { pub fn add_menu_item(&mut self, item: &MenuItem) -> MenuItemHandle {
self.0.add_item(item) self.0.add_menu_item(item)
}
#[inline]
pub fn add_item(&mut self, name: &str, id: usize) -> MenuItem {
MenuItem {
id: id,
label: name.to_owned(),
menu: Some(self),
..MenuItem::default()
}
} }
#[inline] #[inline]
@ -540,22 +550,47 @@ impl Menu {
} }
} }
pub struct MenuItem { pub struct MenuItem<'a> {
pub id: usize, pub id: usize,
pub label: String, pub label: String,
pub enabled: bool, pub enabled: bool,
pub key: Key, pub key: Key,
pub modifier: u32, pub modifier: u32,
pub menu: Option<&'a mut Menu>,
} }
impl MenuItem { impl<'a> Default for MenuItem<'a> {
fn default() -> Self {
MenuItem {
id: MENU_ID_SEPARATOR,
label: "".to_owned(),
enabled: true,
key: Key::Unknown,
modifier: 0,
menu: None,
}
}
}
impl<'a> Clone for MenuItem<'a> {
fn clone(&self) -> Self {
MenuItem {
id: self.id,
label: self.label.clone(),
enabled: self.enabled,
key: self.key,
modifier: self.modifier,
menu: None,
}
}
}
impl<'a> MenuItem<'a> {
pub fn new(name: &str, id: usize) -> MenuItem { pub fn new(name: &str, id: usize) -> MenuItem {
MenuItem { MenuItem {
id: id, id: id,
label: name.to_owned(), label: name.to_owned(),
enabled: true, ..MenuItem::default()
key: Key::Unknown,
modifier: 0,
} }
} }
#[inline] #[inline]
@ -580,6 +615,15 @@ impl MenuItem {
.. self .. self
} }
} }
#[inline]
pub fn build(&mut self) -> MenuItemHandle {
let t = self.clone();
if let Some(ref mut menu) = self.menu {
menu.0.add_menu_item(&t)
} else {
MenuItemHandle(0)
}
}
} }
// Impl for WindowOptions // Impl for WindowOptions

View file

@ -616,7 +616,7 @@ impl Menu {
} }
} }
pub fn add_item(&mut self, item: &MenuItem) -> MenuItemHandle { pub fn add_menu_item(&mut self, item: &MenuItem) -> MenuItemHandle {
unsafe { unsafe {
let item_name = CString::new(item.label.as_str()).unwrap(); let item_name = CString::new(item.label.as_str()).unwrap();
let conv_key = Self::map_key_to_menu_key(item.key); let conv_key = Self::map_key_to_menu_key(item.key);