Compare commits

...

2 Commits

Author SHA1 Message Date
Savanni D'Gerinel abac2d4df9 Add the on_update callback to TextEntry, and test the component 2024-01-30 09:44:17 -05:00
Savanni D'Gerinel 63107e72c0 Create a function which safely initializes GTK once
This is only available in test code, and it allows GUI component tests to run without having to worry about double-initializing GTK
2024-01-30 09:34:19 -05:00
6 changed files with 119 additions and 48 deletions

View File

@ -93,7 +93,7 @@ impl DaySummary {
.css_classes(["day-summary__weight"])
.build();
if let Some(s) = view_model.steps() {
label.set_label(&format!("{} steps", s.to_string()));
label.set_label(&format!("{} steps", s));
}
row.append(&label);
@ -285,8 +285,9 @@ impl DayEdit {
top_row.append(
&weight_editor(view_model.weight(), {
let view_model = view_model.clone();
move |w| {
view_model.set_weight(w);
move |w| match w {
Some(w) => view_model.set_weight(w),
None => eprintln!("have not implemented record delete"),
}
})
.widget(),
@ -295,7 +296,10 @@ impl DayEdit {
top_row.append(
&steps_editor(view_model.steps(), {
let view_model = view_model.clone();
move |s| view_model.set_steps(s)
move |s| match s {
Some(s) => view_model.set_steps(s),
None => eprintln!("have not implemented record delete"),
}
})
.widget(),
);

View File

@ -44,18 +44,13 @@ impl Steps {
pub fn steps_editor<OnUpdate>(value: Option<u32>, on_update: OnUpdate) -> TextEntry<u32>
where
OnUpdate: Fn(u32) + 'static,
OnUpdate: Fn(Option<u32>) + 'static,
{
TextEntry::new(
"0",
value,
|v| format!("{}", v),
move |v| match v.parse::<u32>() {
Ok(val) => {
on_update(val);
Ok(val)
}
Err(_) => Err(ParseError),
},
move |v| v.parse::<u32>().map_err(|_| ParseError),
on_update,
)
}

View File

@ -1,5 +1,5 @@
/*
Copyright 2023, Savanni D'Gerinel <savanni@luminescent-dreams.com>
Copyright 2023-2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of FitnessTrax.
@ -20,16 +20,16 @@ use std::{cell::RefCell, rc::Rc};
#[derive(Clone, Debug)]
pub struct ParseError;
type Renderer<T> = dyn Fn(&T) -> String;
type Parser<T> = dyn Fn(&str) -> Result<T, ParseError>;
type OnUpdate<T> = dyn Fn(Option<T>);
#[derive(Clone)]
pub struct TextEntry<T: Clone + std::fmt::Debug> {
value: Rc<RefCell<Option<T>>>,
widget: gtk::Entry,
#[allow(unused)]
renderer: Rc<Renderer<T>>,
parser: Rc<Parser<T>>,
on_update: Rc<OnUpdate<T>>,
}
impl<T: Clone + std::fmt::Debug> std::fmt::Debug for TextEntry<T> {
@ -44,10 +44,17 @@ impl<T: Clone + std::fmt::Debug> std::fmt::Debug for TextEntry<T> {
// I do not understand why the data should be 'static.
impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
pub fn new<R, V>(placeholder: &str, value: Option<T>, renderer: R, parser: V) -> Self
pub fn new<R, V, U>(
placeholder: &str,
value: Option<T>,
renderer: R,
parser: V,
on_update: U,
) -> Self
where
R: Fn(&T) -> String + 'static,
V: Fn(&str) -> Result<T, ParseError> + 'static,
U: Fn(Option<T>) + 'static,
{
let widget = gtk::Entry::builder().placeholder_text(placeholder).build();
if let Some(ref v) = value {
@ -57,8 +64,8 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
let s = Self {
value: Rc::new(RefCell::new(value)),
widget,
renderer: Rc::new(renderer),
parser: Rc::new(parser),
on_update: Rc::new(on_update),
};
s.widget.buffer().connect_text_notify({
@ -73,12 +80,14 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
if buffer.text().is_empty() {
*self.value.borrow_mut() = None;
self.widget.remove_css_class("error");
(self.on_update)(None);
return;
}
match (self.parser)(buffer.text().as_str()) {
Ok(v) => {
*self.value.borrow_mut() = Some(v);
*self.value.borrow_mut() = Some(v.clone());
self.widget.remove_css_class("error");
(self.on_update)(Some(v));
}
// need to change the border to provide a visual indicator of an error
Err(_) => {
@ -87,25 +96,84 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
}
}
#[allow(unused)]
pub fn value(&self) -> Option<T> {
let v = self.value.borrow().clone();
self.value.borrow().clone()
}
pub fn set_value(&self, value: Option<T>) {
if let Some(ref v) = value {
self.widget.set_text(&(self.renderer)(v))
}
*self.value.borrow_mut() = value;
}
#[allow(unused)]
pub fn grab_focus(&self) {
self.widget.grab_focus();
}
pub fn widget(&self) -> gtk::Widget {
self.widget.clone().upcast::<gtk::Widget>()
}
#[cfg(test)]
fn has_parse_error(&self) -> bool {
self.widget.has_css_class("error")
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::gtk_init::gtk_init;
fn setup_u32_entry() -> (Rc<RefCell<Option<u32>>>, TextEntry<u32>) {
let current_value = Rc::new(RefCell::new(None));
let entry = TextEntry::new(
"step count",
None,
|steps| format!("{}", steps),
|v| v.parse::<u32>().map_err(|_| ParseError),
{
let current_value = current_value.clone();
move |v| *current_value.borrow_mut() = v
},
);
(current_value, entry)
}
#[test]
fn it_responds_to_field_changes() {
gtk_init();
let (current_value, entry) = setup_u32_entry();
let buffer = entry.widget.buffer();
buffer.set_text("1");
assert_eq!(*current_value.borrow(), Some(1));
buffer.set_text("15");
assert_eq!(*current_value.borrow(), Some(15));
}
#[test]
fn it_preserves_last_value_in_parse_error() {
crate::gtk_init::gtk_init();
let (current_value, entry) = setup_u32_entry();
let buffer = entry.widget.buffer();
buffer.set_text("1");
assert_eq!(*current_value.borrow(), Some(1));
buffer.set_text("a5");
assert_eq!(*current_value.borrow(), Some(1));
assert!(entry.has_parse_error());
}
#[test]
fn it_update_on_empty_strings() {
gtk_init();
let (current_value, entry) = setup_u32_entry();
let buffer = entry.widget.buffer();
buffer.set_text("1");
assert_eq!(*current_value.borrow(), Some(1));
buffer.set_text("");
assert_eq!(*current_value.borrow(), None);
buffer.set_text("1");
assert_eq!(*current_value.borrow(), Some(1));
buffer.set_text("1a");
assert_eq!(*current_value.borrow(), Some(1));
assert!(entry.has_parse_error());
buffer.set_text("");
assert_eq!(*current_value.borrow(), None);
assert!(!entry.has_parse_error());
}
}

View File

@ -47,21 +47,13 @@ pub fn weight_editor<OnUpdate>(
on_update: OnUpdate,
) -> TextEntry<si::Kilogram<f64>>
where
OnUpdate: Fn(si::Kilogram<f64>) + 'static,
OnUpdate: Fn(Option<si::Kilogram<f64>>) + 'static,
{
TextEntry::new(
"0 kg",
weight,
|val: &si::Kilogram<f64>| val.to_string(),
move |v: &str| {
let new_weight = v.parse::<f64>().map(|w| w * si::KG).map_err(|_| ParseError);
match new_weight {
Ok(w) => {
on_update(w);
Ok(w)
}
Err(err) => Err(err),
}
},
move |v: &str| v.parse::<f64>().map(|w| w * si::KG).map_err(|_| ParseError),
on_update,
)
}

View File

@ -0,0 +1,10 @@
use std::sync::Once;
static INITIALIZED: Once = Once::new();
pub fn gtk_init() {
INITIALIZED.call_once(|| {
eprintln!("initializing GTK");
let _ = gtk::init();
});
}

View File

@ -17,6 +17,8 @@ You should have received a copy of the GNU General Public License along with Fit
mod app;
mod app_window;
mod components;
#[cfg(test)]
mod gtk_init;
mod types;
mod view_models;
mod views;