Remove channel-based communications #135
|
@ -14,80 +14,113 @@ 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 emseries::Series;
|
use chrono::NaiveDate;
|
||||||
|
use emseries::{time_range, Record, RecordId, Series, Timestamp};
|
||||||
use ft_core::TraxRecord;
|
use ft_core::TraxRecord;
|
||||||
use std::{
|
use std::{
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::{Arc, RwLock},
|
sync::{Arc, RwLock},
|
||||||
};
|
};
|
||||||
|
use tokio::runtime::Runtime;
|
||||||
|
|
||||||
/// Invocations are how parts of the application, primarily the UI, will send requests to the core.
|
pub enum AppError {
|
||||||
#[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.
|
|
||||||
NoDatabase,
|
NoDatabase,
|
||||||
|
FailedToOpenDatabase,
|
||||||
/// The database is open and here is a set of records. Typically, the set of records will be
|
Unhandled,
|
||||||
/// 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),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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 process_invocation(&self, invocation: AppInvocation) -> AppResponse {
|
pub async fn records(
|
||||||
match invocation {
|
&self,
|
||||||
AppInvocation::OpenDatabase(db_path) => {
|
start: NaiveDate,
|
||||||
self.open_db(&db_path);
|
end: NaiveDate,
|
||||||
AppResponse::DatabaseChanged(db_path)
|
) -> Result<Vec<Record<TraxRecord>>, AppError> {
|
||||||
}
|
let db = self.database.clone();
|
||||||
AppInvocation::RequestRecords => {
|
self.runtime
|
||||||
if self.database.read().unwrap().is_none() {
|
.spawn_blocking(move || {
|
||||||
AppResponse::NoDatabase
|
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 {
|
} else {
|
||||||
AppResponse::Records
|
Err(AppError::NoDatabase)
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_db(&self, path: &Path) {
|
pub async fn put_record(&self, record: TraxRecord) -> Result<RecordId, AppError> {
|
||||||
let db = Series::open(path).unwrap();
|
let db = self.database.clone();
|
||||||
*self.database.write().unwrap() = Some(db);
|
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 save_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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,25 +15,20 @@ You should have received a copy of the GNU General Public License along with Fit
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
app::{AppInvocation, AppResponse},
|
app::App,
|
||||||
views::{HistoricalView, PlaceholderView, View, ViewName, WelcomeView},
|
views::{HistoricalView, PlaceholderView, View, ViewName, WelcomeView},
|
||||||
};
|
};
|
||||||
use adw::prelude::*;
|
use adw::prelude::*;
|
||||||
use async_channel::Sender;
|
use chrono::{Duration, Local};
|
||||||
use chrono::{NaiveDate, TimeZone};
|
|
||||||
use chrono_tz::America::Anchorage;
|
|
||||||
use dimensioned::si::{KG, M, S};
|
|
||||||
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::path::PathBuf;
|
|
||||||
use std::{cell::RefCell, rc::Rc};
|
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_tx: Sender<AppInvocation>,
|
app: App,
|
||||||
layout: gtk::Box,
|
layout: gtk::Box,
|
||||||
current_view: Rc<RefCell<View>>,
|
current_view: Rc<RefCell<View>>,
|
||||||
settings: gio::Settings,
|
settings: gio::Settings,
|
||||||
|
@ -51,7 +46,7 @@ impl AppWindow {
|
||||||
app_id: &str,
|
app_id: &str,
|
||||||
resource_path: &str,
|
resource_path: &str,
|
||||||
adw_app: &adw::Application,
|
adw_app: &adw::Application,
|
||||||
app_tx: Sender<AppInvocation>,
|
ft_app: App,
|
||||||
) -> AppWindow {
|
) -> AppWindow {
|
||||||
let window = adw::ApplicationWindow::builder()
|
let window = adw::ApplicationWindow::builder()
|
||||||
.application(adw_app)
|
.application(adw_app)
|
||||||
|
@ -103,13 +98,25 @@ impl AppWindow {
|
||||||
window.present();
|
window.present();
|
||||||
|
|
||||||
let s = Self {
|
let s = Self {
|
||||||
app_tx,
|
app: ft_app,
|
||||||
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,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
glib::spawn_future_local({
|
||||||
|
let s = s.clone();
|
||||||
|
async move {
|
||||||
|
let end = Local::now().date_naive();
|
||||||
|
let start = end - Duration::days(7);
|
||||||
|
match s.app.records(start, end).await {
|
||||||
|
Ok(_) => s.change_view(ViewName::Historical),
|
||||||
|
Err(_) => s.change_view(ViewName::Welcome),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
s
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -117,23 +124,6 @@ impl AppWindow {
|
||||||
self.swap_main(self.construct_view(view));
|
self.swap_main(self.construct_view(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);
|
|
||||||
}
|
|
||||||
AppResponse::NoDatabase => {
|
|
||||||
self.change_view(ViewName::Welcome);
|
|
||||||
}
|
|
||||||
AppResponse::Records => {
|
|
||||||
self.change_view(ViewName::Historical);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Switch views.
|
// Switch views.
|
||||||
//
|
//
|
||||||
// This function only replaces the old view with the one which matches the current view state.
|
// This function only replaces the old view with the one which matches the current view state.
|
||||||
|
@ -149,13 +139,9 @@ impl AppWindow {
|
||||||
fn construct_view(&self, view: ViewName) -> View {
|
fn construct_view(&self, view: ViewName) -> View {
|
||||||
match view {
|
match view {
|
||||||
ViewName::Welcome => View::Welcome(
|
ViewName::Welcome => View::Welcome(
|
||||||
WelcomeView::new({
|
WelcomeView::new(self.app.clone(), {
|
||||||
let s = self.clone();
|
let s = self.clone();
|
||||||
Box::new(move |path: PathBuf| {
|
move || s.change_view(ViewName::Historical)
|
||||||
s.app_tx
|
|
||||||
.send_blocking(AppInvocation::OpenDatabase(path))
|
|
||||||
.unwrap();
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
.upcast(),
|
.upcast(),
|
||||||
),
|
),
|
||||||
|
|
|
@ -43,7 +43,7 @@ fn main() {
|
||||||
};
|
};
|
||||||
|
|
||||||
let settings = gio::Settings::new(app_id);
|
let settings = gio::Settings::new(app_id);
|
||||||
let app = app::App::new({
|
let ft_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
|
||||||
|
@ -63,23 +63,9 @@ fn main() {
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
adw_app.connect_activate(move |adw_app| {
|
adw_app.connect_activate(move |adw_app| {
|
||||||
// These channels are used to send messages to the UI. Anything that needs to send a
|
AppWindow::new(app_id, RESOURCE_BASE_PATH, adw_app, ft_app.clone());
|
||||||
// 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
|
// 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
|
// 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`.
|
// deprecated since gtk 4.10 in favor of using `async_channel`.
|
||||||
|
@ -105,6 +91,7 @@ fn main() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
*/
|
||||||
});
|
});
|
||||||
|
|
||||||
let args: Vec<String> = env::args().collect();
|
let args: Vec<String> = env::args().collect();
|
||||||
|
|
|
@ -14,10 +14,10 @@ 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::components::FileChooserRow;
|
use crate::{app::App, components::FileChooserRow};
|
||||||
use glib::Object;
|
use glib::Object;
|
||||||
use gtk::{prelude::*, subclass::prelude::*};
|
use gtk::{prelude::*, subclass::prelude::*};
|
||||||
use std::path::PathBuf;
|
use std::rc::Rc;
|
||||||
|
|
||||||
/// This is the view to show if the application has not yet been configured. It will walk the user
|
/// This is the view to show if the application has not yet been configured. It will walk the user
|
||||||
/// through the most critical setup steps so that we can move on to the other views in the app.
|
/// through the most critical setup steps so that we can move on to the other views in the app.
|
||||||
|
@ -43,9 +43,9 @@ glib::wrapper! {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WelcomeView {
|
impl WelcomeView {
|
||||||
pub fn new<F>(on_save: Box<F>) -> Self
|
pub fn new<OnSave>(app: App, on_save: OnSave) -> Self
|
||||||
where
|
where
|
||||||
F: Fn(PathBuf) + 'static,
|
OnSave: Fn() + '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);
|
||||||
|
@ -80,14 +80,25 @@ impl WelcomeView {
|
||||||
content.append(>k::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(>k::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 on_save = Rc::new(on_save);
|
||||||
|
let app = app.clone();
|
||||||
|
let db_row = db_row.clone();
|
||||||
move |_| {
|
move |_| {
|
||||||
|
println!("save button clicked. Do something");
|
||||||
|
let app = app.clone();
|
||||||
|
let db_row = db_row.clone();
|
||||||
|
let on_save = on_save.clone();
|
||||||
|
glib::spawn_future_local(async move {
|
||||||
|
println!("{:?}", db_row.path());
|
||||||
if let Some(path) = db_row.path() {
|
if let Some(path) = db_row.path() {
|
||||||
on_save(path)
|
if app.open_db(path).await.is_ok() {
|
||||||
|
on_save();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
s.append(&title);
|
s.append(&title);
|
||||||
s.append(&content);
|
s.append(&content);
|
||||||
|
|
Loading…
Reference in New Issue