Clean up the parameters to TextEntry and populate the field

This commit is contained in:
Savanni D'Gerinel 2024-01-01 22:51:40 -05:00
parent a25b76d230
commit 2e3d5fc5a4
2 changed files with 44 additions and 19 deletions

View File

@ -248,9 +248,12 @@ impl Default for WeightViewPrivate {
.halign(gtk::Align::Start)
.can_focus(true)
.build();
let edit = TextEntry::<si::Kilogram<f64>>::new("weight", None, &|w: &str| {
w.parse::<f64>().map(|w| w * si::KG).map_err(|_| ParseError)
});
let edit = TextEntry::<si::Kilogram<f64>>::new(
"weight",
None,
|w: &si::Kilogram<f64>| w.to_string(),
|w: &str| w.parse::<f64>().map(|w| w * si::KG).map_err(|_| ParseError),
);
let current = view.clone();

View File

@ -23,43 +23,65 @@ pub struct ParseError;
pub struct TextEntry<T: Clone> {
value: Rc<RefCell<Option<T>>>,
widget: gtk::Entry,
renderer: Rc<Box<dyn Fn(&T) -> String>>,
validator: Rc<Box<dyn Fn(&str) -> Result<T, ParseError>>>,
}
impl<T: Clone> TextEntry<T> {
pub fn new(
placeholder: &str,
value: Option<T>,
validator: &'static dyn Fn(&str) -> Result<T, ParseError>,
) -> Self {
// I do not understand why the data should be 'static.
impl<T: Clone + 'static> TextEntry<T> {
pub fn new<R, V>(placeholder: &str, value: Option<T>, renderer: R, validator: V) -> Self
where
R: Fn(&T) -> String + 'static,
V: Fn(&str) -> Result<T, ParseError> + 'static,
{
let widget = gtk::Entry::builder().placeholder_text(placeholder).build();
match value {
Some(ref v) => widget.set_text(&renderer(&v)),
None => {}
}
let s = Self {
value: Rc::new(RefCell::new(value)),
widget,
renderer: Rc::new(Box::new(renderer)),
validator: Rc::new(Box::new(validator)),
};
s.widget.buffer().connect_text_notify({
let s = s.clone();
move |buffer| {
if buffer.text().is_empty() {
*s.value.borrow_mut() = None;
}
match validator(buffer.text().as_str()) {
Ok(v) => *s.value.borrow_mut() = Some(v),
// need to change the border to provide a visual indicator of an error
Err(_) => {}
}
}
move |buffer| s.handle_text_change(buffer)
});
s
}
fn handle_text_change(&self, buffer: &gtk::EntryBuffer) {
if buffer.text().is_empty() {
*self.value.borrow_mut() = None;
self.widget.remove_css_class("error");
return;
}
match (self.validator)(buffer.text().as_str()) {
Ok(v) => {
*self.value.borrow_mut() = Some(v);
self.widget.remove_css_class("error");
}
// need to change the border to provide a visual indicator of an error
Err(_) => {
self.widget.add_css_class("error");
}
}
}
pub fn value(&self) -> Option<T> {
self.value.borrow().clone()
}
pub fn set_value(&self, value: Option<T>) {
match value {
Some(ref v) => self.widget.set_text(&(self.renderer)(&v)),
None => {}
}
*self.value.borrow_mut() = value;
}