Clean up warnings and remove printlns

This commit is contained in:
Savanni D'Gerinel 2024-01-29 23:42:14 -05:00
parent 33c85ee7b3
commit e5e33f29f6
11 changed files with 57 additions and 161 deletions

View File

@ -110,7 +110,7 @@ where
.map_err(EmseriesReadError::JSONParseError)
.and_then(Record::try_from)
{
Ok(record) => records.insert(record.id.clone(), record.clone()),
Ok(record) => records.insert(record.id, record.clone()),
Err(EmseriesReadError::RecordDeleted(id)) => records.remove(&id),
Err(err) => return Err(err),
};
@ -126,7 +126,7 @@ where
pub fn put(&mut self, entry: T) -> Result<RecordId, EmseriesWriteError> {
let uuid = RecordId::default();
let record = Record {
id: uuid.clone(),
id: uuid,
data: entry,
};
self.update(record)?;
@ -136,7 +136,7 @@ where
/// Update an existing record. The [RecordId] of the record passed into this function must match
/// the [RecordId] of a record already in the database.
pub fn update(&mut self, record: Record<T>) -> Result<(), EmseriesWriteError> {
self.records.insert(record.id.clone(), record.clone());
self.records.insert(record.id, record.clone());
let write_res = match serde_json::to_string(&RecordOnDisk {
id: record.id,
data: Some(record.data),
@ -166,7 +166,7 @@ where
self.records.remove(uuid);
let rec: RecordOnDisk<T> = RecordOnDisk {
id: uuid.clone(),
id: *uuid,
data: None,
};
match serde_json::to_string(&rec) {

View File

@ -190,7 +190,7 @@ mod test {
impl Recordable for WeightRecord {
fn timestamp(&self) -> Timestamp {
Timestamp::Date(self.date.clone())
Timestamp::Date(self.date)
}
fn tags(&self) -> Vec<String> {

View File

@ -20,7 +20,7 @@ extern crate emseries;
#[cfg(test)]
mod test {
use chrono::{format::Fixed, prelude::*};
use chrono::{prelude::*};
use chrono_tz::Etc::UTC;
use dimensioned::si::{Kilogram, Meter, Second, M, S};
@ -42,7 +42,7 @@ mod test {
impl Recordable for BikeTrip {
fn timestamp(&self) -> Timestamp {
Timestamp::DateTime(self.datetime.clone())
Timestamp::DateTime(self.datetime)
}
fn tags(&self) -> Vec<String> {
Vec::new()
@ -99,7 +99,7 @@ mod test {
]
}
fn run_test<T>(test: T) -> ()
fn run_test<T>(test: T)
where
T: FnOnce(tempfile::TempPath),
{
@ -108,7 +108,7 @@ mod test {
test(tmp_path);
}
fn run<T>(test: T) -> ()
fn run<T>(test: T)
where
T: FnOnce(Series<BikeTrip>),
{
@ -280,8 +280,7 @@ mod test {
UTC.with_ymd_and_hms(2011, 11, 04, 0, 0, 0)
.unwrap()
.with_timezone(&FixedOffset::east_opt(0).unwrap()),
)
.into(),
),
true,
),
|l, r| l.timestamp().cmp(&r.timestamp()),

View File

@ -22,8 +22,7 @@ use crate::{
};
use adw::prelude::*;
use chrono::{Duration, Local};
use emseries::Record;
use ft_core::TraxRecord;
use gio::resources_lookup_data;
use gtk::STYLE_PROVIDER_PRIORITY_USER;
use std::{cell::RefCell, path::PathBuf, rc::Rc};
@ -100,10 +99,6 @@ impl AppWindow {
window.set_content(Some(&navigation));
window.present();
let gesture = gtk::GestureClick::new();
gesture.connect_released(|_, _, _, _| println!("detected gesture"));
layout.add_controller(gesture);
let s = Self {
app: ft_app,
layout,
@ -137,7 +132,7 @@ impl AppWindow {
fn show_historical_view(&self, start_date: chrono::NaiveDate, end_date: chrono::NaiveDate) {
let on_select_day = {
let s = self.clone();
move |date, records| {
move |date, _records| {
let s = s.clone();
glib::spawn_future_local(async move {
let view_model = DayDetailViewModel::new(date, s.app.clone()).await;
@ -172,7 +167,7 @@ impl AppWindow {
let end = Local::now().date_naive();
let start = end - Duration::days(7);
match s.app.records(start, end).await {
Ok(records) => s.show_historical_view(start, end),
Ok(_records) => s.show_historical_view(start, end),
Err(_) => s.show_welcome_view(),
}
}

View File

@ -97,13 +97,15 @@ 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);
self.append(&row);
let biking_summary = view_model.biking_summary();
time_distance_summary(biking_summary.0, biking_summary.1).map(|label| self.append(&label));
if let Some(label) = time_distance_summary(biking_summary.0, biking_summary.1) {
self.append(&label);
}
}
}
@ -259,10 +261,12 @@ impl DayEdit {
glib::spawn_future_local({
let s = self.clone();
async move {
let view_model = {
let view_model = s.imp().view_model.borrow();
let view_model = view_model
.as_ref()
.expect("DayEdit has not been initialized with the view model");
view_model
.clone()
.expect("DayEdit has not been initialized with the view model")
};
let _ = view_model.save().await;
(s.imp().on_finished.borrow())()
}
@ -270,7 +274,6 @@ impl DayEdit {
}
fn add_row(&self, workout: Record<TraxRecord>) {
println!("adding a row for {:?}", workout);
let workout_rows = self.imp().workout_rows.borrow();
let workout_id = workout.id;
@ -284,10 +287,7 @@ impl DayEdit {
| TraxRecord::Walk(ref w) => {
workout_rows.append(&TimeDistanceEdit::new(workout_type, w.clone(), {
let s = self.clone();
move |type_, data| {
println!("update workout callback on workout: {:?}", workout_id);
s.update_workout(workout_id, type_, data)
}
move |type_, data| s.update_workout(workout_id, type_, data)
}));
}
_ => {}
@ -295,7 +295,6 @@ impl DayEdit {
}
fn update_workout(&self, id: RecordId, type_: RecordType, data: ft_core::TimeDistance) {
println!("update workout");
let data = match type_ {
RecordType::BikeRide => TraxRecord::BikeRide(data),
RecordType::Row => TraxRecord::Row(data),
@ -317,7 +316,7 @@ fn control_buttons(s: &DayEdit, view_model: &DayDetailViewModel) -> ActionGroup
ActionGroup::builder()
.primary_action("Save", {
let s = s.clone();
let view_model = view_model.clone();
let _view_model = view_model.clone();
move || s.finish()
})
.secondary_action("Cancel", {

View File

@ -11,7 +11,8 @@ FitnessTrax is distributed in the hope that it will be useful, but WITHOUT ANY W
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License along with FitnessTrax. If not,
see <https://www.gnu.org/licenses/>.
*/
mod action_group;

View File

@ -19,7 +19,6 @@ use dimensioned::si;
use gtk::prelude::*;
use std::{cell::RefCell, rc::Rc};
pub type Renderer<T> = dyn Fn(&T) -> String;
pub type Parser<T> = dyn Fn(&str) -> Result<T, ParseError>;
pub type OnUpdate<T> = dyn Fn(Option<T>);
@ -27,7 +26,6 @@ pub type OnUpdate<T> = dyn Fn(Option<T>);
pub struct TextEntry<T: Clone + std::fmt::Debug> {
value: Rc<RefCell<Option<T>>>,
widget: gtk::Entry,
renderer: Rc<Renderer<T>>,
parser: Rc<Parser<T>>,
on_update: Rc<OnUpdate<T>>,
}
@ -64,7 +62,6 @@ 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),
};
@ -96,24 +93,6 @@ 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>()
}
@ -172,7 +151,7 @@ where
"0 minutes",
value,
|v| v.format(FormatOption::Abbreviated),
|s| Duration::parse(s),
Duration::parse,
on_update,
)
}

View File

@ -25,7 +25,7 @@ use dimensioned::si;
use ft_core::{RecordType, TimeDistance};
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, rc::Rc};
use std::cell::RefCell;
pub fn time_distance_summary(distance: Distance, duration: Duration) -> Option<gtk::Label> {
let text = match (*distance > si::M, *duration > si::S) {
@ -107,7 +107,7 @@ pub fn time_distance_detail(type_: ft_core::RecordType, record: ft_core::TimeDis
pub struct TimeDistanceEditPrivate {
type_: RefCell<RecordType>,
workout: RefCell<TimeDistance>,
on_update: Rc<RefCell<Box<dyn Fn(RecordType, TimeDistance)>>>,
on_update: RefCell<Box<dyn Fn(RecordType, TimeDistance)>>,
}
impl Default for TimeDistanceEditPrivate {
@ -115,7 +115,7 @@ impl Default for TimeDistanceEditPrivate {
Self {
type_: RefCell::new(RecordType::BikeRide),
workout: RefCell::new(TimeDistance::new(chrono::Utc::now().into())),
on_update: Rc::new(RefCell::new(Box::new(|_, _| {}))),
on_update: RefCell::new(Box::new(|_, _| {})),
}
}
}
@ -151,7 +151,6 @@ impl TimeDistanceEdit {
where
OnUpdate: Fn(ft_core::RecordType, ft_core::TimeDistance) + 'static,
{
println!("new TimeDistanceEdit");
let s = Self::default();
*s.imp().type_.borrow_mut() = type_;
@ -189,12 +188,11 @@ impl TimeDistanceEdit {
s
}
fn update_time(&self, time: Option<chrono::NaiveTime>) {
fn update_time(&self, _time: Option<chrono::NaiveTime>) {
unimplemented!()
}
fn update_distance(&self, distance: Option<si::Meter<f64>>) {
println!("update distance");
let mut workout = self.imp().workout.borrow_mut();
workout.distance = distance;
(self.imp().on_update.borrow())(self.imp().type_.borrow().clone(), workout.clone());

View File

@ -72,7 +72,6 @@ impl Distance {
pub fn parse(s: &str) -> Result<Distance, ParseError> {
let digits = take_digits(s.to_owned());
let value = digits.parse::<f64>().map_err(|_| ParseError)?;
println!("value: {}", value);
Ok(Distance {
value: value * 1000. * si::M,
})
@ -135,7 +134,7 @@ impl Duration {
fn hours_and_minutes(&self) -> (i64, i64) {
let minutes: i64 = (self.value.value_unsafe / 60.).round() as i64;
let hours: i64 = (minutes / 60) as i64;
let hours: i64 = minutes / 60;
let minutes = minutes - (hours * 60);
(hours, minutes)
}
@ -169,5 +168,7 @@ impl From<si::Second<f64>> for Duration {
}
fn take_digits(s: String) -> String {
s.chars().take_while(|t| t.is_digit(10)).collect::<String>()
s.chars()
.take_while(|t| t.is_ascii_digit())
.collect::<String>()
}

View File

@ -49,10 +49,10 @@ impl<T: Clone + emseries::Recordable> RecordState<T> {
fn data(&self) -> Option<&Record<T>> {
match self {
RecordState::Original(ref r) => Some(&r),
RecordState::New(ref r) => None,
RecordState::Updated(ref r) => Some(&r),
RecordState::Deleted(ref r) => Some(&r),
RecordState::Original(ref r) => Some(r),
RecordState::New(ref _r) => None,
RecordState::Updated(ref r) => Some(r),
RecordState::Deleted(ref r) => Some(r),
}
}
@ -192,29 +192,22 @@ impl DayDetailViewModel {
self.records
.write()
.unwrap()
.insert(new_record.id.clone(), RecordState::New(new_record.clone()));
println!(
"record added: {:?}",
self.records.read().unwrap().get(&new_record.id)
);
.insert(new_record.id, RecordState::New(new_record.clone()));
new_record
}
pub fn update_record(&self, update: Record<TraxRecord>) {
println!("updating a record: {:?}", update);
let mut records = self.records.write().unwrap();
records
.entry(update.id)
.and_modify(|mut record| record.set_value(update.data));
println!("record updated: {:?}", records.get(&update.id));
.and_modify(|record| record.set_value(update.data));
}
pub fn records(&self) -> Vec<Record<TraxRecord>> {
let read_lock = self.records.read().unwrap();
read_lock
.iter()
.map(|(_, record_state)| record_state.data())
.filter_map(|r| r)
.filter_map(|(_, record_state)| record_state.data())
.cloned()
.collect::<Vec<Record<TraxRecord>>>()
}
@ -270,7 +263,6 @@ impl DayDetailViewModel {
.collect::<Vec<RecordState<TraxRecord>>>();
for record in records {
println!("saving record: {:?}", record);
match record {
RecordState::New(Record { data, .. }) => {
let _ = s.app.put_record(data).await;
@ -289,7 +281,12 @@ impl DayDetailViewModel {
}
pub fn revert(&self) {
self.populate_records();
glib::spawn_future({
let s = self.clone();
async move {
s.populate_records().await;
}
});
}
async fn populate_records(&self) {
@ -303,7 +300,7 @@ impl DayDetailViewModel {
*self.weight.write().unwrap() = weight_records
.first()
.and_then(|r| match r.data {
TraxRecord::Weight(ref w) => Some((r.id.clone(), w.clone())),
TraxRecord::Weight(ref w) => Some((r.id, w.clone())),
_ => None,
})
.map(|(id, w)| RecordState::Original(Record { id, data: w }));
@ -311,14 +308,14 @@ impl DayDetailViewModel {
*self.steps.write().unwrap() = step_records
.first()
.and_then(|r| match r.data {
TraxRecord::Steps(ref w) => Some((r.id.clone(), w.clone())),
TraxRecord::Steps(ref w) => Some((r.id, w.clone())),
_ => None,
})
.map(|(id, w)| RecordState::Original(Record { id, data: w }));
*self.records.write().unwrap() = records
.into_iter()
.map(|r| (r.id.clone(), RecordState::Original(r)))
.map(|r| (r.id, RecordState::Original(r)))
.collect::<HashMap<RecordId, RecordState<TraxRecord>>>();
}
}

View File

@ -17,12 +17,12 @@ You should have received a copy of the GNU General Public License along with Fit
use crate::{
app::App, components::DaySummary, types::DayInterval, view_models::DayDetailViewModel,
};
use chrono::NaiveDate;
use emseries::Record;
use ft_core::TraxRecord;
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use std::{cell::RefCell, rc::Rc};
/// The historical view will show a window into the main database. It will show some version of
/// daily summaries, daily details, and will provide all functions the user may need for editing
@ -75,11 +75,7 @@ impl ObjectSubclass for HistoricalViewPrivate {
.expect("should be a DaySummary");
if let Some(app) = app.borrow().clone() {
let _ = glib::spawn_future_local(async move {
println!(
"setting up a DayDetailViewModel for {}",
date.date().format("%Y-%m-%d")
);
glib::spawn_future_local(async move {
let view_model = DayDetailViewModel::new(date.date(), app.clone()).await;
summary.set_data(view_model);
});
@ -111,7 +107,7 @@ impl HistoricalView {
*s.imp().app.borrow_mut() = Some(app);
let mut model = gio::ListStore::new::<Date>();
model.extend(interval.days().map(|d| Date::new(d)));
model.extend(interval.days().map(Date::new));
s.imp()
.list_view
.set_model(Some(&gtk::NoSelection::new(Some(model))));
@ -161,75 +157,6 @@ impl Date {
}
pub fn date(&self) -> chrono::NaiveDate {
self.imp().date.borrow().clone()
}
}
#[cfg(test)]
mod test {
use super::GroupedRecords;
use crate::types::DayInterval;
use chrono::{FixedOffset, NaiveDate, TimeZone};
use dimensioned::si::{KG, M, S};
use emseries::{Record, RecordId};
use ft_core::{Steps, TimeDistance, TraxRecord, Weight};
#[test]
fn groups_records() {
let records = vec![
Record {
id: RecordId::default(),
data: TraxRecord::Steps(Steps {
date: NaiveDate::from_ymd_opt(2023, 10, 13).unwrap(),
count: 1500,
}),
},
Record {
id: RecordId::default(),
data: TraxRecord::Weight(Weight {
date: NaiveDate::from_ymd_opt(2023, 10, 13).unwrap(),
weight: 85. * KG,
}),
},
Record {
id: RecordId::default(),
data: TraxRecord::Weight(Weight {
date: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
weight: 86. * KG,
}),
},
Record {
id: RecordId::default(),
data: TraxRecord::BikeRide(TimeDistance {
datetime: FixedOffset::west_opt(10 * 60 * 60)
.unwrap()
.with_ymd_and_hms(2019, 6, 15, 12, 0, 0)
.unwrap(),
distance: Some(1000. * M),
duration: Some(150. * S),
comments: Some("Test Comments".to_owned()),
}),
},
Record {
id: RecordId::default(),
data: TraxRecord::BikeRide(TimeDistance {
datetime: FixedOffset::west_opt(10 * 60 * 60)
.unwrap()
.with_ymd_and_hms(2019, 6, 15, 23, 0, 0)
.unwrap(),
distance: Some(1000. * M),
duration: Some(150. * S),
comments: Some("Test Comments".to_owned()),
}),
},
];
let groups = GroupedRecords::new(DayInterval {
start: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
end: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
})
.with_data(records)
.data;
assert_eq!(groups.len(), 3);
*self.imp().date.borrow()
}
}