Compare commits

...

11 Commits

Author SHA1 Message Date
Savanni D'Gerinel b5dcee3737 Update the historical view when a change happens in the db 2023-12-28 22:47:47 -05:00
Savanni D'Gerinel 0c3ae062c8 Save real data to the database. Load data on app start. 2023-12-28 22:46:44 -05:00
Savanni D'Gerinel f422e233a1 Record data to the database
This isn't recording real data. It's basically discarding all
information from the weight edit field. But it is creating a record.
2023-12-28 22:43:56 -05:00
Savanni D'Gerinel 7a6e902fdd Create placeholders in the historical view for days that are unpopulated. 2023-12-28 22:36:44 -05:00
Savanni D'Gerinel 6d9e2ea382 Switch to the updated emseries record type 2023-12-28 22:36:40 -05:00
Savanni D'Gerinel 04a48574d3 Develop a pattern to detect clicking outside of a focused child
Be able to respond to blur events and potentially be able to record weight.
2023-12-28 22:34:09 -05:00
Savanni D'Gerinel e13e7cf4c3 Create a widget that can show the weight view and edit modes 2023-12-28 22:31:11 -05:00
Savanni D'Gerinel 383f809191 Open and style the day detail view and add it to the navigation stack 2023-12-28 22:31:07 -05:00
Savanni D'Gerinel d269924827 Refactorings and dead code removal 2023-12-28 22:20:30 -05:00
Savanni D'Gerinel 8049859816 Clean up showing the welcome and historical screens
Swapping is now done in dedicated functions instead of a big pattern
match.

After selecting a database, the app window will apply the configuration
by opening the database, saving the path to configuration, and switching
to the historical view.
2023-12-28 21:45:55 -05:00
Savanni D'Gerinel ac343a2af6 Switch from channel-based communication to async calls into the core 2023-12-28 19:09:12 -05:00
13 changed files with 760 additions and 269 deletions

View File

@ -178,7 +178,7 @@ impl fmt::Display for RecordId {
/// directly, as the database will create them.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Record<T: Clone + Recordable> {
pub(crate) id: RecordId,
pub id: RecordId,
pub data: T,
}

View File

@ -2,32 +2,38 @@
margin: 64px;
}
.welcome-title {
.welcome__title {
font-size: larger;
padding: 8px;
}
.welcome-content {
.welcome__content {
padding: 8px;
}
.welcome-footer {
.welcome__footer {
}
.dialog-row {
margin: 8px 0px 8px 0px;
.historical {
margin: 32px;
border-radius: 8px;
}
.day-summary {
padding: 8px;
}
.daysummary {
padding: 8px;
}
.daysummary-date {
.day-summary__date {
font-size: larger;
margin-bottom: 8px;
}
.daysummary-weight {
.day-summary__weight {
margin: 4px;
}
.weight-view {
padding: 8px;
margin: 8px;
}

View File

@ -14,80 +14,114 @@ 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/>.
*/
use emseries::Series;
use crate::types::DayInterval;
use chrono::NaiveDate;
use emseries::{time_range, Record, RecordId, Series, Timestamp};
use ft_core::TraxRecord;
use std::{
path::{Path, PathBuf},
path::PathBuf,
sync::{Arc, RwLock},
};
use tokio::runtime::Runtime;
/// Invocations are how parts of the application, primarily the UI, will send requests to the core.
#[derive(Debug)]
pub enum AppInvocation {
/// Tell the core to try to open a database.
OpenDatabase(PathBuf),
/// Request a set of records from the core.
// Note: this will require a time range, but doesn't yet.
RequestRecords,
}
/// Responses are messages that the core sends to the UI. Though they are called responses, the
/// could actually be pre-emptively sent, such as notifications. The UI will need to be able to
/// process those any time they arrive.
///
/// A typical use would be for the UI to send an [AppInvocation::RequestRecords] request and
/// receive [AppResponse::Records].
#[derive(Debug)]
pub enum AppResponse {
/// No database is available. The UI should typically display a placeholder, such as the
/// welcome view.
pub enum AppError {
NoDatabase,
/// The database is open and here is a set of records. Typically, the set of records will be
/// all of the records within a time frame, but this can actually be any set of records.
Records,
/// The database has been changed. This message is useful for telling the UI that a significant
/// change has happened. Further, the UI needs to save PathBuf to settings, because the
/// gio::Settings system can't be run in the fully async background.
DatabaseChanged(PathBuf),
FailedToOpenDatabase,
Unhandled,
}
/// The real, headless application. This is where all of the logic will reside.
#[derive(Clone)]
pub struct App {
runtime: Arc<Runtime>,
database: Arc<RwLock<Option<Series<TraxRecord>>>>,
}
impl App {
pub fn new(db_path: Option<PathBuf>) -> Self {
let database = db_path.map(|path| Series::open(path).unwrap());
let runtime = Arc::new(
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap(),
);
let s = Self {
runtime,
database: Arc::new(RwLock::new(database)),
};
s
}
pub async fn process_invocation(&self, invocation: AppInvocation) -> AppResponse {
match invocation {
AppInvocation::OpenDatabase(db_path) => {
self.open_db(&db_path);
AppResponse::DatabaseChanged(db_path)
}
AppInvocation::RequestRecords => {
if self.database.read().unwrap().is_none() {
AppResponse::NoDatabase
pub async fn records(
&self,
start: NaiveDate,
end: NaiveDate,
) -> Result<Vec<Record<TraxRecord>>, AppError> {
let db = self.database.clone();
self.runtime
.spawn_blocking(move || {
if let Some(ref db) = *db.read().unwrap() {
let records = db
.search(time_range(
Timestamp::Date(start),
true,
Timestamp::Date(end),
true,
))
.map(|record| record.clone())
.collect::<Vec<Record<TraxRecord>>>();
Ok(records)
} else {
AppResponse::Records
Err(AppError::NoDatabase)
}
}
}
})
.await
.unwrap()
}
fn open_db(&self, path: &Path) {
let db = Series::open(path).unwrap();
*self.database.write().unwrap() = Some(db);
pub async fn put_record(&self, record: TraxRecord) -> Result<RecordId, AppError> {
let db = self.database.clone();
self.runtime
.spawn_blocking(move || {
if let Some(ref mut db) = *db.write().unwrap() {
let id = db.put(record).unwrap();
Ok(id)
} else {
Err(AppError::NoDatabase)
}
})
.await
.unwrap()
.map_err(|_| AppError::Unhandled)
}
pub async fn update_record(&self, record: Record<TraxRecord>) -> Result<(), AppError> {
let db = self.database.clone();
self.runtime
.spawn_blocking(move || {
if let Some(ref mut db) = *db.write().unwrap() {
db.update(record).map_err(|_| AppError::Unhandled)
} else {
Err(AppError::NoDatabase)
}
})
.await
.unwrap()
.map_err(|_| AppError::Unhandled)
}
pub async fn open_db(&self, path: PathBuf) -> Result<(), AppError> {
let db_ref = self.database.clone();
self.runtime
.spawn_blocking(move || {
let db = Series::open(path).map_err(|_| AppError::FailedToOpenDatabase)?;
*db_ref.write().unwrap() = Some(db);
Ok(())
})
.await
.unwrap()
}
}

View File

@ -15,25 +15,23 @@ You should have received a copy of the GNU General Public License along with Fit
*/
use crate::{
app::{AppInvocation, AppResponse},
views::{HistoricalView, PlaceholderView, View, ViewName, WelcomeView},
app::App,
components::DayDetail,
views::{HistoricalView, PlaceholderView, View, WelcomeView},
};
use adw::prelude::*;
use async_channel::Sender;
use chrono::{NaiveDate, TimeZone};
use chrono_tz::America::Anchorage;
use dimensioned::si::{KG, M, S};
use ft_core::{Steps, TimeDistance, TraxRecord, Weight};
use chrono::{Duration, Local};
use emseries::Record;
use ft_core::TraxRecord;
use gio::resources_lookup_data;
use gtk::STYLE_PROVIDER_PRIORITY_USER;
use std::path::PathBuf;
use std::{cell::RefCell, rc::Rc};
use std::{cell::RefCell, path::PathBuf, rc::Rc};
/// The application window, or the main window, is the main user interface for the app. Almost
/// everything occurs here.
#[derive(Clone)]
pub struct AppWindow {
app_tx: Sender<AppInvocation>,
app: App,
layout: gtk::Box,
current_view: Rc<RefCell<View>>,
settings: gio::Settings,
@ -51,7 +49,7 @@ impl AppWindow {
app_id: &str,
resource_path: &str,
adw_app: &adw::Application,
app_tx: Sender<AppInvocation>,
ft_app: App,
) -> AppWindow {
let window = adw::ApplicationWindow::builder()
.application(adw_app)
@ -85,7 +83,6 @@ impl AppWindow {
let initial_view = View::Placeholder(PlaceholderView::new().upcast());
// layout.append(&header);
layout.append(&initial_view.widget());
let nav_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
@ -102,36 +99,71 @@ 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_tx,
app: ft_app,
layout,
current_view: Rc::new(RefCell::new(initial_view)),
settings: gio::Settings::new(app_id),
navigation,
};
s.load_records();
s
}
pub fn change_view(&self, view: ViewName) {
self.swap_main(self.construct_view(view));
fn show_welcome_view(&self) {
let view = View::Welcome(WelcomeView::new({
let s = self.clone();
move |path| s.on_apply_config(path)
}));
self.swap_main(view);
}
pub fn process_response(&self, response: AppResponse) {
match response {
AppResponse::DatabaseChanged(db_path) => {
self.settings
.set_string("series-path", db_path.to_str().unwrap())
.unwrap();
self.change_view(ViewName::Historical);
fn show_historical_view(&self, records: Vec<Record<TraxRecord>>) {
let view = View::Historical(HistoricalView::new(records, {
let s = self.clone();
Rc::new(move |date, records| {
let layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
layout.append(&adw::HeaderBar::new());
layout.append(&DayDetail::new(
date,
records,
{
let s = s.clone();
move |record| s.on_put_record(record)
},
{
let s = s.clone();
move |record| s.on_update_record(record)
},
));
let page = &adw::NavigationPage::builder()
.title(date.format("%Y-%m-%d").to_string())
.child(&layout)
.build();
s.navigation.push(page);
})
}));
self.swap_main(view);
}
fn load_records(&self) {
glib::spawn_future_local({
let s = self.clone();
async move {
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(records),
Err(_) => s.show_welcome_view(),
}
}
AppResponse::NoDatabase => {
self.change_view(ViewName::Welcome);
}
AppResponse::Records => {
self.change_view(ViewName::Historical);
}
}
});
}
// Switch views.
@ -146,20 +178,33 @@ impl AppWindow {
self.layout.append(&current_widget.widget());
}
fn construct_view(&self, view: ViewName) -> View {
match view {
ViewName::Welcome => View::Welcome(
WelcomeView::new({
let s = self.clone();
Box::new(move |path: PathBuf| {
s.app_tx
.send_blocking(AppInvocation::OpenDatabase(path))
.unwrap();
})
})
.upcast(),
),
ViewName::Historical => View::Historical(HistoricalView::new(vec![]).upcast()),
}
fn on_apply_config(&self, path: PathBuf) {
glib::spawn_future_local({
let s = self.clone();
async move {
if s.app.open_db(path.clone()).await.is_ok() {
let _ = s.settings.set("series-path", path.to_str().unwrap());
s.load_records();
}
}
});
}
fn on_put_record(&self, record: TraxRecord) {
glib::spawn_future_local({
let s = self.clone();
async move {
s.app.put_record(record).await;
}
});
}
fn on_update_record(&self, record: Record<TraxRecord>) {
glib::spawn_future_local({
let s = self.clone();
async move {
s.app.update_record(record).await;
}
});
}
}

View File

@ -16,12 +16,13 @@ You should have received a copy of the GNU General Public License along with Fit
// use chrono::NaiveDate;
// use ft_core::TraxRecord;
use ft_core::TraxRecord;
use dimensioned::si;
use emseries::Record;
use ft_core::{RecordType, TimeDistance, TraxRecord, Weight};
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::cell::RefCell;
use std::{cell::RefCell, rc::Rc};
#[derive(Default)]
pub struct DaySummaryPrivate {
date: gtk::Label,
weight: RefCell<Option<gtk::Label>>,
@ -35,7 +36,7 @@ impl ObjectSubclass for DaySummaryPrivate {
fn new() -> Self {
let date = gtk::Label::builder()
.css_classes(["daysummary-date"])
.css_classes(["day-summary__date"])
.halign(gtk::Align::Start)
.build();
Self {
@ -59,14 +60,14 @@ impl DaySummary {
pub fn new() -> Self {
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
s.set_css_classes(&["daysummary"]);
s.set_css_classes(&["day-summary"]);
s.append(&s.imp().date);
s
}
pub fn set_data(&self, date: chrono::NaiveDate, records: Vec<TraxRecord>) {
pub fn set_data(&self, date: chrono::NaiveDate, records: Vec<Record<TraxRecord>>) {
self.imp()
.date
.set_text(&date.format("%Y-%m-%d").to_string());
@ -75,16 +76,339 @@ impl DaySummary {
self.remove(weight_label);
}
if let Some(TraxRecord::Weight(weight_record)) =
records.iter().filter(|f| f.is_weight()).next()
if let Some(Record {
data: TraxRecord::Weight(weight_record),
..
}) = records.iter().filter(|f| f.data.is_weight()).next()
{
let label = gtk::Label::builder()
.halign(gtk::Align::Start)
.label(&format!("{}", weight_record.weight))
.css_classes(["daysummary-weight"])
.css_classes(["day-summary__weight"])
.build();
self.append(&label);
*self.imp().weight.borrow_mut() = Some(label);
}
/*
self.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label("15km of biking in 60 minutes")
.build(),
);
*/
}
}
pub struct DayDetailPrivate {
date: gtk::Label,
weight: RefCell<Option<gtk::Label>>,
}
#[glib::object_subclass]
impl ObjectSubclass for DayDetailPrivate {
const NAME: &'static str = "DayDetail";
type Type = DayDetail;
type ParentType = gtk::Box;
fn new() -> Self {
let date = gtk::Label::builder()
.css_classes(["daysummary-date"])
.halign(gtk::Align::Start)
.build();
Self {
date,
weight: RefCell::new(None),
}
}
}
impl ObjectImpl for DayDetailPrivate {}
impl WidgetImpl for DayDetailPrivate {}
impl BoxImpl for DayDetailPrivate {}
glib::wrapper! {
pub struct DayDetail(ObjectSubclass<DayDetailPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
}
impl DayDetail {
pub fn new<SaveRecordFn, UpdateRecordFn>(
date: chrono::NaiveDate,
records: Vec<Record<TraxRecord>>,
on_save_record: SaveRecordFn,
on_update_record: UpdateRecordFn,
) -> Self
where
SaveRecordFn: Fn(TraxRecord) + 'static,
UpdateRecordFn: Fn(Record<TraxRecord>) + 'static,
{
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
let click_controller = gtk::GestureClick::new();
click_controller.connect_released({
let s = s.clone();
move |_, _, _, _| {
println!("clicked outside of focusable entity");
if let Some(widget) = s.focus_child().and_downcast_ref::<WeightView>() {
println!("focused child is the weight view");
widget.blur();
}
}
});
s.add_controller(click_controller);
let weight_record = records.iter().find_map(|record| match record {
Record {
id,
data: TraxRecord::Weight(record),
} => Some((id.clone(), record.clone())),
_ => None,
});
let weight_view = match weight_record {
Some((id, data)) => WeightView::new(Some(data.clone()), move |weight| {
on_update_record(Record {
id: id.clone(),
data: TraxRecord::Weight(Weight { date, weight }),
})
}),
None => WeightView::new(None, move |weight| {
on_save_record(TraxRecord::Weight(Weight { date, weight }));
}),
};
s.append(&weight_view);
records.into_iter().for_each(|record| {
let record_view = match record {
Record {
data: TraxRecord::BikeRide(record),
..
} => Some(
TimeDistanceView::new(RecordType::BikeRide, record).upcast::<gtk::Widget>(),
),
Record {
data: TraxRecord::Row(record),
..
} => Some(TimeDistanceView::new(RecordType::Row, record).upcast::<gtk::Widget>()),
Record {
data: TraxRecord::Run(record),
..
} => Some(TimeDistanceView::new(RecordType::Row, record).upcast::<gtk::Widget>()),
Record {
data: TraxRecord::Swim(record),
..
} => Some(TimeDistanceView::new(RecordType::Row, record).upcast::<gtk::Widget>()),
Record {
data: TraxRecord::Walk(record),
..
} => Some(TimeDistanceView::new(RecordType::Row, record).upcast::<gtk::Widget>()),
_ => None,
};
if let Some(record_view) = record_view {
record_view.add_css_class("day-detail");
record_view.set_halign(gtk::Align::Start);
s.append(&record_view);
}
});
s
}
}
pub struct WeightViewPrivate {
record: RefCell<Option<Weight>>,
view: RefCell<gtk::Label>,
edit: RefCell<gtk::Entry>,
current: RefCell<gtk::Widget>,
on_edit_finished: RefCell<Box<dyn Fn(si::Kilogram<f64>)>>,
}
impl Default for WeightViewPrivate {
fn default() -> Self {
let view = gtk::Label::builder()
.css_classes(["card", "weight-view"])
.halign(gtk::Align::Start)
.can_focus(true)
.build();
let edit = gtk::Entry::builder().halign(gtk::Align::Start).build();
let current = view.clone();
Self {
record: RefCell::new(None),
view: RefCell::new(view),
edit: RefCell::new(edit),
current: RefCell::new(current.upcast()),
on_edit_finished: RefCell::new(Box::new(|_| {})),
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for WeightViewPrivate {
const NAME: &'static str = "WeightView";
type Type = WeightView;
type ParentType = gtk::Box;
}
impl ObjectImpl for WeightViewPrivate {}
impl WidgetImpl for WeightViewPrivate {}
impl BoxImpl for WeightViewPrivate {}
glib::wrapper! {
pub struct WeightView(ObjectSubclass<WeightViewPrivate>) @extends gtk::Box, gtk::Widget;
}
impl WeightView {
pub fn new<OnEditFinished>(weight: Option<Weight>, on_edit_finished: OnEditFinished) -> Self
where
OnEditFinished: Fn(si::Kilogram<f64>) + 'static,
{
let s: Self = Object::builder().build();
*s.imp().on_edit_finished.borrow_mut() = Box::new(on_edit_finished);
*s.imp().record.borrow_mut() = weight;
s.view();
let view_click_controller = gtk::GestureClick::new();
view_click_controller.connect_released({
let s = s.clone();
move |_, _, _, _| {
s.edit();
}
});
s.imp().view.borrow().add_controller(view_click_controller);
s
}
fn view(&self) {
let view = self.imp().view.borrow();
match *self.imp().record.borrow() {
Some(ref record) => {
view.remove_css_class("dim_label");
view.set_label(&format!("{:?}", record.weight));
}
None => {
view.add_css_class("dim_label");
view.set_label("No weight recorded");
}
}
self.swap(view.clone().upcast());
}
fn edit(&self) {
let edit = self.imp().edit.borrow();
match *self.imp().record.borrow() {
Some(ref record) => edit.buffer().set_text(&format!("{:?}", record.weight)),
None => edit.buffer().set_text(""),
}
self.swap(edit.clone().upcast());
edit.grab_focus();
}
fn swap(&self, new_view: gtk::Widget) {
let mut current = self.imp().current.borrow_mut();
self.remove(&*current);
self.append(&new_view);
*current = new_view;
}
fn blur(&self) {
let edit = self.imp().edit.borrow();
if *self.imp().current.borrow() == *edit {
let w = edit.buffer().text().parse::<f64>().unwrap();
self.imp().on_edit_finished.borrow()(w * si::KG);
self.view();
}
}
}
#[derive(Default)]
pub struct TimeDistanceViewPrivate {
record: RefCell<Option<TimeDistance>>,
}
#[glib::object_subclass]
impl ObjectSubclass for TimeDistanceViewPrivate {
const NAME: &'static str = "TimeDistanceView";
type Type = TimeDistanceView;
type ParentType = gtk::Box;
}
impl ObjectImpl for TimeDistanceViewPrivate {}
impl WidgetImpl for TimeDistanceViewPrivate {}
impl BoxImpl for TimeDistanceViewPrivate {}
glib::wrapper! {
pub struct TimeDistanceView(ObjectSubclass<TimeDistanceViewPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
}
impl TimeDistanceView {
pub fn new(type_: RecordType, record: TimeDistance) -> Self {
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
s.set_hexpand(true);
let first_row = gtk::Box::builder().homogeneous(true).build();
first_row.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label(&record.datetime.format("%H:%M").to_string())
.build(),
);
first_row.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label(format!("{:?}", type_))
.build(),
);
first_row.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label(
record
.distance
.map(|dist| format!("{}", dist))
.unwrap_or("".to_owned()),
)
.build(),
);
first_row.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label(
record
.duration
.map(|duration| format!("{}", duration))
.unwrap_or("".to_owned()),
)
.build(),
);
s.append(&first_row);
s.append(
&gtk::Label::builder()
.halign(gtk::Align::Start)
.label(
record
.comments
.map(|comments| format!("{}", comments))
.unwrap_or("".to_owned()),
)
.build(),
);
s
}
}

View File

@ -15,8 +15,8 @@ You should have received a copy of the GNU General Public License along with Fit
*/
mod day;
pub use day::{DayDetail, DaySummary};
pub use day::DaySummary;
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, path::PathBuf, rc::Rc};

View File

@ -17,11 +17,13 @@ You should have received a copy of the GNU General Public License along with Fit
mod app;
mod app_window;
mod components;
mod types;
mod views;
use adw::prelude::*;
use app_window::AppWindow;
use std::{env, path::PathBuf};
use types::DayInterval;
const APP_ID_DEV: &str = "com.luminescent-dreams.fitnesstrax.dev";
const APP_ID_PROD: &str = "com.luminescent-dreams.fitnesstrax";
@ -43,7 +45,7 @@ fn main() {
};
let settings = gio::Settings::new(app_id);
let app = app::App::new({
let ft_app = app::App::new({
let path = settings.string("series-path");
if path.is_empty() {
None
@ -57,54 +59,8 @@ fn main() {
.resource_base_path(RESOURCE_BASE_PATH)
.build();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
adw_app.connect_activate(move |adw_app| {
// These channels are used to send messages to the UI. Anything that needs to send a
// message to the UI will send it via `ui_tx`. We will have one single process that owns
// `ui_rx`. That process will read messages coming in and send them to [AppWindow] for proper
// processing.
//
// The core app will usually only send messages in response to a request, but this channel
// can also be used to tell the UI that something happened in the background, such as
// detecting a watch, detecting new tracks to import, and so forth.
let (ui_tx, ui_rx) = async_channel::unbounded::<app::AppResponse>();
// These channels are used for communicating with the app. Already I can see that a lot of
// different event handlers will need copies of app_tx in order to send requests into the
// UI.
let (app_tx, app_rx) = async_channel::unbounded::<app::AppInvocation>();
let window = AppWindow::new(app_id, RESOURCE_BASE_PATH, adw_app, app_tx.clone());
// Spawn a future where the UI will receive messages for the app window. Previously, this
// would have been done by creating a glib::MainContext::channel(), but that has been
// deprecated since gtk 4.10 in favor of using `async_channel`.
glib::spawn_future_local(async move {
// The app requests data to start with. This kicks everything off. The response from
// the app will cause the window to be updated shortly.
let _ = app_tx.send(app::AppInvocation::RequestRecords).await;
while let Ok(response) = ui_rx.recv().await {
window.process_response(response);
}
});
// The tokio runtime starts up here and will handle all of the asynchronous operations that
// the application needs to do. Messages arrive on `app_rx` and responses will be sent via
// `ui_tx`.
runtime.spawn({
let app = app.clone();
async move {
while let Ok(invocation) = app_rx.recv().await {
let response = app.process_invocation(invocation).await;
let _ = ui_tx.send(response).await;
}
}
});
AppWindow::new(app_id, RESOURCE_BASE_PATH, adw_app, ft_app.clone());
});
let args: Vec<String> = env::args().collect();

View File

@ -0,0 +1,47 @@
use chrono::{Duration, Local, NaiveDate};
// This interval doesn't feel right, either. The idea that I have a specific interval type for just
// NaiveDate is odd. This should be genericized, as should the iterator. Also, it shouldn't live
// here, but in utilities.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DayInterval {
pub start: NaiveDate,
pub end: NaiveDate,
}
impl Default for DayInterval {
fn default() -> Self {
Self {
start: (Local::now() - Duration::days(7)).date_naive(),
end: Local::now().date_naive(),
}
}
}
impl DayInterval {
pub fn days(&self) -> impl Iterator<Item = NaiveDate> {
DayIterator {
current: self.start.clone(),
end: self.end.clone(),
}
}
}
struct DayIterator {
current: NaiveDate,
end: NaiveDate,
}
impl Iterator for DayIterator {
type Item = NaiveDate;
fn next(&mut self) -> Option<Self::Item> {
if self.current <= self.end {
let val = self.current.clone();
self.current += Duration::days(1);
Some(val)
} else {
None
}
}
}

View File

@ -14,17 +14,21 @@ 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/>.
*/
use crate::components::DaySummary;
use emseries::{Recordable, Timestamp};
use crate::{components::DaySummary, types::DayInterval};
use chrono::{Duration, Local, NaiveDate};
use emseries::Record;
use ft_core::TraxRecord;
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, collections::HashMap};
use std::{cell::RefCell, collections::HashMap, 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
/// records.
pub struct HistoricalViewPrivate {}
pub struct HistoricalViewPrivate {
time_window: RefCell<DayInterval>,
list_view: gtk::ListView,
}
#[glib::object_subclass]
impl ObjectSubclass for HistoricalViewPrivate {
@ -33,28 +37,6 @@ impl ObjectSubclass for HistoricalViewPrivate {
type ParentType = gtk::Box;
fn new() -> Self {
Self {}
}
}
impl ObjectImpl for HistoricalViewPrivate {}
impl WidgetImpl for HistoricalViewPrivate {}
impl BoxImpl for HistoricalViewPrivate {}
glib::wrapper! {
pub struct HistoricalView(ObjectSubclass<HistoricalViewPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
}
impl HistoricalView {
pub fn new(records: Vec<TraxRecord>) -> Self {
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
let day_records: GroupedRecords = GroupedRecords::from(records);
let model = gio::ListStore::new::<DayRecords>();
model.extend_from_slice(&day_records.0);
let factory = gtk::SignalListItemFactory::new();
factory.connect_setup(move |_, list_item| {
list_item
@ -81,30 +63,79 @@ impl HistoricalView {
summary.set_data(records.date(), records.records());
});
let lst = gtk::ListView::builder()
.model(&gtk::NoSelection::new(Some(model)))
.factory(&factory)
.single_click_activate(true)
.build();
lst.connect_activate(|s, idx| {
// This gets triggered whenever the user clicks on an item on the list. What we
// actually want to do here is to open a modal dialog that shows all of the details of
// the day and which allows the user to edit items within that dialog.
let item = s.model().unwrap().item(idx).unwrap();
let records = item.downcast_ref::<DayRecords>().unwrap();
println!("list item activated: [{:?}] {:?}", idx, records.date());
Self {
time_window: RefCell::new(DayInterval::default()),
list_view: gtk::ListView::builder()
.factory(&factory)
.single_click_activate(true)
.build(),
}
}
}
impl ObjectImpl for HistoricalViewPrivate {}
impl WidgetImpl for HistoricalViewPrivate {}
impl BoxImpl for HistoricalViewPrivate {}
glib::wrapper! {
pub struct HistoricalView(ObjectSubclass<HistoricalViewPrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
}
impl HistoricalView {
pub fn new<SelectFn>(records: Vec<Record<TraxRecord>>, on_select_day: Rc<SelectFn>) -> Self
where
SelectFn: Fn(chrono::NaiveDate, Vec<Record<TraxRecord>>) + 'static,
{
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
s.set_css_classes(&["historical"]);
let grouped_records =
GroupedRecords::new((*s.imp().time_window.borrow()).clone()).with_data(records);
let mut model = gio::ListStore::new::<DayRecords>();
model.extend(grouped_records.items());
s.imp()
.list_view
.set_model(Some(&gtk::NoSelection::new(Some(model))));
s.imp().list_view.connect_activate({
let on_select_day = on_select_day.clone();
move |s, idx| {
// This gets triggered whenever the user clicks on an item on the list. What we
// actually want to do here is to open a modal dialog that shows all of the details of
// the day and which allows the user to edit items within that dialog.
let item = s.model().unwrap().item(idx).unwrap();
let records = item.downcast_ref::<DayRecords>().unwrap();
on_select_day(records.date(), records.records());
}
});
s.append(&lst);
s.append(&s.imp().list_view);
s
}
pub fn set_records(&self, records: Vec<Record<TraxRecord>>) {
println!("set_records: {:?}", records);
let grouped_records =
GroupedRecords::new((self.imp().time_window.borrow()).clone()).with_data(records);
let mut model = gio::ListStore::new::<DayRecords>();
model.extend(grouped_records.items());
self.imp()
.list_view
.set_model(Some(&gtk::NoSelection::new(Some(model))));
}
pub fn time_window(&self) -> DayInterval {
self.imp().time_window.borrow().clone()
}
}
#[derive(Default)]
pub struct DayRecordsPrivate {
date: RefCell<chrono::NaiveDate>,
records: RefCell<Vec<TraxRecord>>,
records: RefCell<Vec<Record<TraxRecord>>>,
}
#[glib::object_subclass]
@ -120,7 +151,7 @@ glib::wrapper! {
}
impl DayRecords {
pub fn new(date: chrono::NaiveDate, records: Vec<TraxRecord>) -> Self {
pub fn new(date: chrono::NaiveDate, records: Vec<Record<TraxRecord>>) -> Self {
let s: Self = Object::builder().build();
*s.imp().date.borrow_mut() = date;
@ -133,36 +164,53 @@ impl DayRecords {
self.imp().date.borrow().clone()
}
pub fn records(&self) -> Vec<TraxRecord> {
pub fn records(&self) -> Vec<Record<TraxRecord>> {
self.imp().records.borrow().clone()
}
pub fn add_record(&self, record: TraxRecord) {
pub fn add_record(&self, record: Record<TraxRecord>) {
self.imp().records.borrow_mut().push(record);
}
}
struct GroupedRecords(Vec<DayRecords>);
// This isn't feeling quite right. DayRecords is a glib object, but I'm not sure that I want to
// really be passing that around. It seems not generic enough. I feel like this whole grouped
// records thing can be made more generic.
struct GroupedRecords {
interval: DayInterval,
data: HashMap<NaiveDate, DayRecords>,
}
impl From<Vec<TraxRecord>> for GroupedRecords {
fn from(records: Vec<TraxRecord>) -> GroupedRecords {
GroupedRecords(
records
.into_iter()
.fold(HashMap::new(), |mut acc, rec| {
let date = match rec.timestamp() {
Timestamp::DateTime(dtz) => dtz.date_naive(),
Timestamp::Date(date) => date,
};
acc.entry(date)
.and_modify(|entry: &mut DayRecords| (*entry).add_record(rec.clone()))
.or_insert(DayRecords::new(date, vec![rec]));
acc
})
.values()
.cloned()
.collect::<Vec<DayRecords>>(),
)
impl GroupedRecords {
fn new(interval: DayInterval) -> Self {
let mut s = Self {
interval: interval.clone(),
data: HashMap::new(),
};
interval.days().for_each(|date| {
let _ = s.data.insert(date, DayRecords::new(date, vec![]));
});
s
}
fn with_data(mut self, records: Vec<Record<TraxRecord>>) -> Self {
records.into_iter().for_each(|record| {
self.data
.entry(record.date())
.and_modify(|entry: &mut DayRecords| (*entry).add_record(record.clone()))
.or_insert(DayRecords::new(record.date(), vec![record]));
});
self
}
fn items<'a>(&'a self) -> impl Iterator<Item = DayRecords> + 'a {
self.interval.days().map(|date| {
self.data
.get(&date)
.map(|rec| rec.clone())
.unwrap_or(DayRecords::new(date, vec![]))
})
}
}
@ -170,7 +218,6 @@ impl From<Vec<TraxRecord>> for GroupedRecords {
mod test {
use super::GroupedRecords;
use chrono::{FixedOffset, NaiveDate, TimeZone};
use chrono_tz::America::Anchorage;
use dimensioned::si::{KG, M, S};
use emseries::{Record, RecordId};
use ft_core::{Steps, TimeDistance, TraxRecord, Weight};
@ -178,36 +225,51 @@ mod test {
#[test]
fn groups_records() {
let records = vec![
TraxRecord::Steps(Steps {
date: NaiveDate::from_ymd_opt(2023, 10, 13).unwrap(),
count: 1500,
}),
TraxRecord::Weight(Weight {
date: NaiveDate::from_ymd_opt(2023, 10, 13).unwrap(),
weight: 85. * KG,
}),
TraxRecord::Weight(Weight {
date: NaiveDate::from_ymd_opt(2023, 10, 14).unwrap(),
weight: 86. * KG,
}),
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()),
}),
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()),
}),
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::from(records).0;

View File

@ -25,12 +25,6 @@ pub use placeholder_view::PlaceholderView;
mod welcome_view;
pub use welcome_view::WelcomeView;
#[derive(Clone, Debug, PartialEq)]
pub enum ViewName {
Welcome,
Historical,
}
pub enum View {
Placeholder(PlaceholderView),
Welcome(WelcomeView),

View File

@ -14,7 +14,7 @@ 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/>.
*/
use crate::components::FileChooserRow;
use crate::{app::App, components::FileChooserRow};
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::path::PathBuf;
@ -43,9 +43,9 @@ glib::wrapper! {
}
impl WelcomeView {
pub fn new<F>(on_save: Box<F>) -> Self
pub fn new<OnSave>(on_save: OnSave) -> Self
where
F: Fn(PathBuf) + 'static,
OnSave: Fn(PathBuf) + 'static,
{
let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical);
@ -55,11 +55,10 @@ impl WelcomeView {
// branch.
let title = gtk::Label::builder()
.label("Welcome to FitnessTrax")
.css_classes(["welcome-title"])
.css_classes(["welcome__title"])
.build();
let content = gtk::Box::builder()
.css_classes(["model-content"])
.orientation(gtk::Orientation::Vertical)
.vexpand(true)
.build();
@ -80,11 +79,11 @@ impl WelcomeView {
content.append(&gtk::Label::new(Some("Welcome to FitnessTrax. The application has not yet been configured, so I will walk you through that. Let's start out by selecting your database.")));
content.append(&db_row);
let on_save = on_save;
save_button.connect_clicked({
let db_row = db_row.clone();
move |_| {
if let Some(path) = db_row.path() {
on_save(path)
on_save(path);
}
}
});

View File

@ -1,3 +1,4 @@
mod legacy;
mod types;
pub use types::{Steps, TimeDistance, TraxRecord, Weight};
pub use types::{RecordType, Steps, TimeDistance, TraxRecord, Weight};

View File

@ -54,6 +54,17 @@ pub struct Weight {
pub weight: si::Kilogram<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum RecordType {
BikeRide,
Row,
Run,
Steps,
Swim,
Walk,
Weight,
}
/// The unified data structure for all records that are part of the app.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TraxRecord {
@ -67,6 +78,18 @@ pub enum TraxRecord {
}
impl TraxRecord {
pub fn workout_type(&self) -> RecordType {
match self {
TraxRecord::BikeRide(_) => RecordType::BikeRide,
TraxRecord::Row(_) => RecordType::Row,
TraxRecord::Run(_) => RecordType::Run,
TraxRecord::Steps(_) => RecordType::Steps,
TraxRecord::Swim(_) => RecordType::Swim,
TraxRecord::Walk(_) => RecordType::Walk,
TraxRecord::Weight(_) => RecordType::Weight,
}
}
pub fn is_weight(&self) -> bool {
match self {
TraxRecord::Weight(_) => true,