diff --git a/cursive-core/src/cursive.rs b/cursive-core/src/cursive.rs index 406ecbc..752881f 100644 --- a/cursive-core/src/cursive.rs +++ b/cursive-core/src/cursive.rs @@ -511,6 +511,15 @@ impl Cursive { self.call_on(&view::Selector::Name(name), callback) } + /// Call the given closure on all views with the given name and the correct type. + pub fn call_on_all_named(&mut self, name: &str, callback: F) + where + V: View, + F: FnMut(&mut V), + { + self.root.call_on_all(&view::Selector::Name(name), callback); + } + /// Same as [`call_on_name`](Cursive::call_on_name). #[deprecated(note = "`call_on_id` is being renamed to `call_on_name`")] pub fn call_on_id(&mut self, id: &str, callback: F) -> Option diff --git a/cursive-core/src/view/finder.rs b/cursive-core/src/view/finder.rs index dd5833c..c8ea038 100644 --- a/cursive-core/src/view/finder.rs +++ b/cursive-core/src/view/finder.rs @@ -20,7 +20,25 @@ pub trait Finder { ) -> Option where V: View, - F: FnOnce(&mut V) -> R; + F: FnOnce(&mut V) -> R, + { + let mut callback = Some(callback); + let mut result = None; + self.call_on_all(sel, |v: &mut V| { + if let Some(callback) = callback.take() { + result = Some(callback(v)); + } + }); + result + } + + /// Runs a callback on all views identified by `sel`. + /// + /// Useful if you have multiple views of the same type with the same name. + fn call_on_all(&mut self, sel: &Selector<'_>, callback: F) + where + V: View, + F: FnMut(&mut V); /// Convenient method to use `call_on` with a `view::Selector::Name`. fn call_on_name(&mut self, name: &str, callback: F) -> Option @@ -60,36 +78,18 @@ pub trait Finder { } impl Finder for T { - fn call_on( - &mut self, - sel: &Selector<'_>, - callback: F, - ) -> Option + fn call_on_all(&mut self, sel: &Selector<'_>, mut callback: F) where V: View, - F: FnOnce(&mut V) -> R, + F: FnMut(&mut V), { - let mut result = None; - { - let result_ref = &mut result; - - let mut callback = Some(callback); - let mut callback = |v: &mut dyn View| { - if let Some(callback) = callback.take() { - if v.is::() { - *result_ref = - v.downcast_mut::().map(|v| callback(v)); - } else if v.is::>() { - // Special case - *result_ref = v - .downcast_mut::>() - .and_then(|v| v.with_view_mut(callback)); - } - } - }; - self.call_on_any(sel, &mut callback); - } - result + self.call_on_any(sel, &mut |v: &mut dyn View| { + if let Some(v) = v.downcast_mut::() { + callback(v); + } else if let Some(v) = v.downcast_mut::>() { + v.with_view_mut(&mut callback); + } + }); } }