From 0046eba66dba0ad21a7186a42afd9617b5d3c34c Mon Sep 17 00:00:00 2001 From: Alexandre Bury Date: Sun, 22 Jul 2018 20:25:13 -0700 Subject: [PATCH] SelectVIew::selection now returns Option> --- examples/theme.rs | 4 ++-- src/views/select_view.rs | 21 ++++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/examples/theme.rs b/examples/theme.rs index c9cde61..9b72b82 100644 --- a/examples/theme.rs +++ b/examples/theme.rs @@ -1,7 +1,7 @@ extern crate cursive; use cursive::views::{Dialog, TextView}; -use cursive::{thene, Cursive}; +use cursive::{theme, Cursive}; fn main() { let mut siv = Cursive::default(); @@ -9,7 +9,7 @@ fn main() { siv.load_theme_file("assets/style.toml").unwrap(); // Or you can directly load it from a string for easy deployment. - siv.load_toml(include_str!("../assets/style.toml").unwrap()); + siv.load_toml(include_str!("../assets/style.toml")).unwrap(); siv.add_layer( Dialog::around(TextView::new( diff --git a/src/views/select_view.rs b/src/views/select_view.rs index a516ac9..d624fda 100644 --- a/src/views/select_view.rs +++ b/src/views/select_view.rs @@ -201,8 +201,13 @@ impl SelectView { /// Returns the value of the currently selected item. /// /// Panics if the list is empty. - pub fn selection(&self) -> Rc { - Rc::clone(&self.items[self.focus()].value) + pub fn selection(&self) -> Option> { + let focus = self.focus(); + if self.len() <= focus { + None + } else { + Some(Rc::clone(&self.items[focus].value)) + } } /// Removes all items from this view. @@ -414,9 +419,11 @@ impl SelectView { fn submit(&mut self) -> EventResult { let cb = self.on_submit.clone().unwrap(); - let v = self.selection(); // We return a Callback Rc<|s| cb(s, &*v)> - EventResult::Consumed(Some(Callback::from_fn(move |s| cb(s, &v)))) + EventResult::Consumed( + self.selection() + .map(|v| Callback::from_fn(move |s| cb(s, &v))), + ) } fn on_event_regular(&mut self, event: Event) -> EventResult { @@ -554,9 +561,9 @@ impl SelectView { /// Returns a callback from selection change. fn make_select_cb(&self) -> Option { - self.on_select.clone().map(|cb| { - let v = self.selection(); - Callback::from_fn(move |s| cb(s, &v)) + self.on_select.clone().and_then(|cb| { + self.selection() + .map(|v| Callback::from_fn(move |s| cb(s, &v))) }) }