Compare commits

..

8 Commits

Author SHA1 Message Date
Savanni D'Gerinel f8f39fc542 Update the historical view when a change happens in the db 2023-12-28 14:34:32 -05:00
Savanni D'Gerinel ff77c4cedd Save real data to the database. Load data on app start. 2023-12-28 14:07:09 -05:00
Savanni D'Gerinel 487071a89b 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 14:07:09 -05:00
Savanni D'Gerinel b4b831f641 Create placeholders in the historical view for days that are unpopulated. 2023-12-28 14:07:09 -05:00
Savanni D'Gerinel 00994d51c0 Switch to the updated emseries record type 2023-12-28 14:07:03 -05:00
Savanni D'Gerinel 819078c15b 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 14:06:55 -05:00
Savanni D'Gerinel 8f75568bf6 Create a widget that can show the weight view and edit modes 2023-12-28 14:06:55 -05:00
Savanni D'Gerinel 721ba09bb9 Open and style the day detail view and add it to the navigation stack 2023-12-28 14:06:34 -05:00
5 changed files with 242 additions and 165 deletions

View File

@ -15,113 +15,118 @@ You should have received a copy of the GNU General Public License along with Fit
*/ */
use crate::types::DayInterval; use crate::types::DayInterval;
use chrono::NaiveDate;
use emseries::{time_range, Record, RecordId, Series, Timestamp}; use emseries::{time_range, Record, RecordId, Series, Timestamp};
use ft_core::TraxRecord; use ft_core::TraxRecord;
use std::{ use std::{
path::PathBuf, path::{Path, PathBuf},
sync::{Arc, RwLock}, sync::{Arc, RwLock},
}; };
use tokio::runtime::Runtime;
pub enum AppError { /// 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(DayInterval),
UpdateRecord(Record<TraxRecord>),
PutRecord(TraxRecord),
DeleteRecord(RecordId),
}
/// 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.
NoDatabase, NoDatabase,
FailedToOpenDatabase,
Unhandled, /// 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(Vec<Record<TraxRecord>>),
/// 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),
RecordSaved(RecordId),
} }
/// The real, headless application. This is where all of the logic will reside. /// The real, headless application. This is where all of the logic will reside.
#[derive(Clone)] #[derive(Clone)]
pub struct App { pub struct App {
runtime: Arc<Runtime>,
database: Arc<RwLock<Option<Series<TraxRecord>>>>, database: Arc<RwLock<Option<Series<TraxRecord>>>>,
} }
impl App { impl App {
pub fn new(db_path: Option<PathBuf>) -> Self { pub fn new(db_path: Option<PathBuf>) -> Self {
let database = db_path.map(|path| Series::open(path).unwrap()); 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 { let s = Self {
runtime,
database: Arc::new(RwLock::new(database)), database: Arc::new(RwLock::new(database)),
}; };
s s
} }
pub async fn records( pub async fn process_invocation(&self, invocation: AppInvocation) -> AppResponse {
&self, match invocation {
start: NaiveDate, AppInvocation::OpenDatabase(db_path) => {
end: NaiveDate, self.open_db(&db_path);
) -> Result<Vec<Record<TraxRecord>>, AppError> { AppResponse::DatabaseChanged(db_path)
let db = self.database.clone(); }
self.runtime AppInvocation::RequestRecords(interval) => match &*self.database.read().unwrap() {
.spawn_blocking(move || { Some(database) => {
if let Some(ref db) = *db.read().unwrap() { let records = database
let records = db
.search(time_range( .search(time_range(
Timestamp::Date(start), Timestamp::Date(interval.start),
true, true,
Timestamp::Date(end), Timestamp::Date(interval.end),
true, true,
)) ))
.map(|record| record.clone()) .map(|record| record.clone())
.collect::<Vec<Record<TraxRecord>>>(); .collect::<Vec<Record<TraxRecord>>>();
Ok(records) AppResponse::Records(records)
} else { }
Err(AppError::NoDatabase) None => AppResponse::NoDatabase,
},
AppInvocation::UpdateRecord(record) => match *self.database.write().unwrap() {
Some(ref mut database) => {
let id = record.id.clone();
database.update(record).unwrap();
AppResponse::RecordSaved(id)
}
None => AppResponse::NoDatabase,
},
AppInvocation::PutRecord(record) => match *self.database.write().unwrap() {
Some(ref mut database) => {
let id = database.put(record).unwrap();
AppResponse::RecordSaved(id)
}
None => AppResponse::NoDatabase,
},
AppInvocation::DeleteRecord(record_id) => match *self.database.write().unwrap() {
Some(ref mut database) => {
database.delete(&record_id).unwrap();
AppResponse::Records(vec![])
}
None => AppResponse::NoDatabase,
},
} }
})
.await
.unwrap()
} }
pub async fn put_record(&self, record: TraxRecord) -> Result<RecordId, AppError> { fn open_db(&self, path: &Path) {
let db = self.database.clone(); let db = Series::open(path).unwrap();
self.runtime *self.database.write().unwrap() = Some(db);
.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,23 +15,26 @@ You should have received a copy of the GNU General Public License along with Fit
*/ */
use crate::{ use crate::{
app::App, app::{AppInvocation, AppResponse},
components::DayDetail, components::DayDetail,
views::{HistoricalView, PlaceholderView, View, WelcomeView}, views::{HistoricalView, PlaceholderView, View, ViewName, WelcomeView},
}; };
use adw::prelude::*; use adw::prelude::*;
use chrono::{Duration, Local}; use async_channel::Sender;
use emseries::Record; use chrono::{FixedOffset, NaiveDate, TimeZone};
use ft_core::TraxRecord; use dimensioned::si::{KG, M, S};
use emseries::{Record, RecordId};
use ft_core::{Steps, TimeDistance, TraxRecord, Weight};
use gio::resources_lookup_data; use gio::resources_lookup_data;
use gtk::STYLE_PROVIDER_PRIORITY_USER; use gtk::STYLE_PROVIDER_PRIORITY_USER;
use std::{cell::RefCell, path::PathBuf, rc::Rc}; use std::path::PathBuf;
use std::{cell::RefCell, rc::Rc};
/// The application window, or the main window, is the main user interface for the app. Almost /// The application window, or the main window, is the main user interface for the app. Almost
/// everything occurs here. /// everything occurs here.
#[derive(Clone)] #[derive(Clone)]
pub struct AppWindow { pub struct AppWindow {
app: App, app_tx: Sender<AppInvocation>,
layout: gtk::Box, layout: gtk::Box,
current_view: Rc<RefCell<View>>, current_view: Rc<RefCell<View>>,
settings: gio::Settings, settings: gio::Settings,
@ -49,7 +52,7 @@ impl AppWindow {
app_id: &str, app_id: &str,
resource_path: &str, resource_path: &str,
adw_app: &adw::Application, adw_app: &adw::Application,
ft_app: App, app_tx: Sender<AppInvocation>,
) -> AppWindow { ) -> AppWindow {
let window = adw::ApplicationWindow::builder() let window = adw::ApplicationWindow::builder()
.application(adw_app) .application(adw_app)
@ -104,66 +107,60 @@ impl AppWindow {
layout.add_controller(gesture); layout.add_controller(gesture);
let s = Self { let s = Self {
app: ft_app, app_tx,
layout, layout,
current_view: Rc::new(RefCell::new(initial_view)), current_view: Rc::new(RefCell::new(initial_view)),
settings: gio::Settings::new(app_id), settings: gio::Settings::new(app_id),
navigation, navigation,
}; };
s.load_records();
s s
} }
fn show_welcome_view(&self) { pub fn change_view(&self, view: ViewName) {
let view = View::Welcome(WelcomeView::new({ self.swap_main(self.construct_view(view));
let s = self.clone();
move |path| s.on_apply_config(path)
}));
self.swap_main(view);
} }
fn show_historical_view(&self, records: Vec<Record<TraxRecord>>) { pub fn process_response(&self, response: AppResponse) {
let view = View::Historical(HistoricalView::new(records, { println!("processing response: {:?}", response);
let s = self.clone(); match response {
Rc::new(move |date, records| { AppResponse::DatabaseChanged(db_path) => {
let layout = gtk::Box::new(gtk::Orientation::Vertical, 0); self.settings
layout.append(&adw::HeaderBar::new()); .set_string("series-path", db_path.to_str().unwrap())
layout.append(&DayDetail::new( .unwrap();
date, self.change_view(ViewName::Historical(vec![]));
records, }
{ AppResponse::NoDatabase => {
let s = s.clone(); self.change_view(ViewName::Welcome);
move |record| s.on_put_record(record) }
AppResponse::RecordSaved(_) => match *self.current_view.borrow_mut() {
View::Historical(ref view) => {
let _ = self
.app_tx
.send_blocking(AppInvocation::RequestRecords(view.time_window()));
}
_ => {}
}, },
{ AppResponse::Records(records) => {
let s = s.clone(); let mut current = self.current_view.borrow_mut();
move |record| s.on_update_record(record) if let View::Historical(ref view) = *current {
}, view.set_records(records);
)); } else {
let page = &adw::NavigationPage::builder() self.layout.remove(&current.widget());
.title(date.format("%Y-%m-%d").to_string()) *current = self.construct_view(ViewName::Historical(records));
.child(&layout) self.layout.append(&current.widget());
.build();
s.navigation.push(page);
})
}));
self.swap_main(view);
} }
/*
fn load_records(&self) { match self.current_view.borrow_mut() {
glib::spawn_future_local({ View::Historical(ref view) => view.set_records(records),
let s = self.clone(); mut current => {
async move { self.layout.remove(&current.widget());
let end = Local::now().date_naive(); *current = self.construct_view(ViewName::Historical(records));
let start = end - Duration::days(7); self.layout.append(&current.widget());
match s.app.records(start, end).await { }
Ok(records) => s.show_historical_view(records), */
Err(_) => s.show_welcome_view(),
} }
} }
});
} }
// Switch views. // Switch views.
@ -178,33 +175,51 @@ impl AppWindow {
self.layout.append(&current_widget.widget()); self.layout.append(&current_widget.widget());
} }
fn on_apply_config(&self, path: PathBuf) { fn construct_view(&self, view: ViewName) -> View {
glib::spawn_future_local({ match view {
ViewName::Welcome => View::Welcome(
WelcomeView::new({
let s = self.clone(); let s = self.clone();
async move { Box::new(move |path: PathBuf| {
if s.app.open_db(path.clone()).await.is_ok() { s.app_tx
let _ = s.settings.set("series-path", path.to_str().unwrap()); .send_blocking(AppInvocation::OpenDatabase(path))
s.load_records(); .unwrap();
} })
} })
}); .upcast(),
} ),
ViewName::Historical(records) => View::Historical(
fn on_put_record(&self, record: TraxRecord) { HistoricalView::new(records, {
glib::spawn_future_local({
let s = self.clone(); let s = self.clone();
async move { Rc::new(move |date: chrono::NaiveDate, records| {
s.app.put_record(record).await; let layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
layout.append(&adw::HeaderBar::new());
layout.append(&DayDetail::new(
date,
records,
{
let app_tx = s.app_tx.clone();
move |record| {
let _ = app_tx.send_blocking(AppInvocation::PutRecord(record));
} }
}); },
{
let app_tx = s.app_tx.clone();
move |record| {
let _ =
app_tx.send_blocking(AppInvocation::UpdateRecord(record));
} }
},
fn on_update_record(&self, record: Record<TraxRecord>) { ));
glib::spawn_future_local({ let page = &adw::NavigationPage::builder()
let s = self.clone(); .title(date.format("%Y-%m-%d").to_string())
async move { .child(&layout)
s.app.update_record(record).await; .build();
s.navigation.push(page);
})
})
.upcast(),
),
} }
});
} }
} }

View File

@ -45,7 +45,7 @@ fn main() {
}; };
let settings = gio::Settings::new(app_id); let settings = gio::Settings::new(app_id);
let ft_app = app::App::new({ let app = app::App::new({
let path = settings.string("series-path"); let path = settings.string("series-path");
if path.is_empty() { if path.is_empty() {
None None
@ -59,8 +59,56 @@ fn main() {
.resource_base_path(RESOURCE_BASE_PATH) .resource_base_path(RESOURCE_BASE_PATH)
.build(); .build();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
adw_app.connect_activate(move |adw_app| { adw_app.connect_activate(move |adw_app| {
AppWindow::new(app_id, RESOURCE_BASE_PATH, adw_app, ft_app.clone()); // 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(DayInterval::default()))
.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;
}
}
});
}); });
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();

View File

@ -25,6 +25,15 @@ pub use placeholder_view::PlaceholderView;
mod welcome_view; mod welcome_view;
pub use welcome_view::WelcomeView; pub use welcome_view::WelcomeView;
use emseries::Record;
use ft_core::TraxRecord;
#[derive(Clone, Debug, PartialEq)]
pub enum ViewName {
Welcome,
Historical(Vec<Record<TraxRecord>>),
}
pub enum View { pub enum View {
Placeholder(PlaceholderView), Placeholder(PlaceholderView),
Welcome(WelcomeView), 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/>. 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::{app::App, components::FileChooserRow}; use crate::components::FileChooserRow;
use glib::Object; use glib::Object;
use gtk::{prelude::*, subclass::prelude::*}; use gtk::{prelude::*, subclass::prelude::*};
use std::path::PathBuf; use std::path::PathBuf;
@ -43,9 +43,9 @@ glib::wrapper! {
} }
impl WelcomeView { impl WelcomeView {
pub fn new<OnSave>(on_save: OnSave) -> Self pub fn new<F>(on_save: Box<F>) -> Self
where where
OnSave: Fn(PathBuf) + 'static, F: Fn(PathBuf) + 'static,
{ {
let s: Self = Object::builder().build(); let s: Self = Object::builder().build();
s.set_orientation(gtk::Orientation::Vertical); s.set_orientation(gtk::Orientation::Vertical);
@ -79,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(&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); content.append(&db_row);
let on_save = on_save;
save_button.connect_clicked({ save_button.connect_clicked({
let db_row = db_row.clone();
move |_| { move |_| {
if let Some(path) = db_row.path() { if let Some(path) = db_row.path() {
on_save(path); on_save(path)
} }
} }
}); });