Compare commits

..

No commits in common. "f2f1ae809b34c410cabb5c848c056ebcb4e3e945" and "de54ec676f9eea35d520cb82cd0ef5fafeb68ded" have entirely different histories.

24 changed files with 250 additions and 557 deletions

View File

@ -35,7 +35,7 @@ macro_rules! define_config {
$($name($struct)),+ $($name($struct)),+
} }
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug)]
pub struct Config { pub struct Config {
values: std::collections::HashMap<ConfigName, ConfigOption>, values: std::collections::HashMap<ConfigName, ConfigOption>,
} }

View File

@ -1,22 +1,5 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{ use crate::{
database::Database, database::Database,
library, settings,
types::{AppState, Config, ConfigOption, GameState, LibraryPath, Player, Rank}, types::{AppState, Config, ConfigOption, GameState, LibraryPath, Player, Rank},
}; };
use async_std::{ use async_std::{
@ -35,11 +18,8 @@ pub trait Observable<T> {
fn subscribe(&self) -> Receiver<T>; fn subscribe(&self) -> Receiver<T>;
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CoreRequest { pub enum CoreRequest {
Library(library::LibraryRequest),
Settings(settings::SettingsRequest),
/*
ChangeSetting(ChangeSettingRequest), ChangeSetting(ChangeSettingRequest),
CreateGame(CreateGameRequest), CreateGame(CreateGameRequest),
Home, Home,
@ -47,10 +27,8 @@ pub enum CoreRequest {
PlayingField, PlayingField,
PlayStone(PlayStoneRequest), PlayStone(PlayStoneRequest),
StartGame, StartGame,
*/
} }
/*
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChangeSettingRequest { pub enum ChangeSettingRequest {
LibraryPath(String), LibraryPath(String),
@ -87,25 +65,16 @@ impl From<HotseatPlayerRequest> for Player {
} }
} }
} }
*/
/*
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CoreResponse { pub enum CoreResponse {
Library(library::LibraryResponse), ConfigurationView(ConfigurationView),
Settings(settings::SettingsResponse), HomeView(HomeView),
} PlayingFieldView(PlayingFieldView),
UpdatedConfigurationView(ConfigurationView),
impl From<library::LibraryResponse> for CoreResponse {
fn from(r: library::LibraryResponse) -> Self {
Self::Library(r)
}
}
impl From<settings::SettingsResponse> for CoreResponse {
fn from(r: settings::SettingsResponse) -> Self {
Self::Settings(r)
}
} }
*/
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum CoreNotification { pub enum CoreNotification {
@ -123,19 +92,10 @@ pub struct Core {
impl Core { impl Core {
pub fn new(config: Config) -> Self { pub fn new(config: Config) -> Self {
println!("config: {:?}", config);
let library = if let Some(ref path) = config.get::<LibraryPath>() {
println!("loading initial library");
Some(Database::open_path(path.to_path_buf()).unwrap())
} else {
None
};
Self { Self {
config: Arc::new(RwLock::new(config)), config: Arc::new(RwLock::new(config)),
// state, // state,
library: Arc::new(RwLock::new(library)), library: Arc::new(RwLock::new(None)),
subscribers: Arc::new(RwLock::new(vec![])), subscribers: Arc::new(RwLock::new(vec![])),
} }
} }
@ -152,41 +112,17 @@ impl Core {
/// configuration is not a decision for the core library. /// configuration is not a decision for the core library.
pub async fn set_config(&self, config: Config) { pub async fn set_config(&self, config: Config) {
*self.config.write().unwrap() = config.clone(); *self.config.write().unwrap() = config.clone();
let subscribers = self.subscribers.read().unwrap().clone();
// let db = library::read_library(self.config.read().unwrap().get::<LibraryPath>()).await; for subscriber in subscribers {
let library_path = self.config.read().unwrap().get::<LibraryPath>(); let subscriber = subscriber.clone();
if let Some(ref path) = library_path { let _ = subscriber.send(CoreNotification::ConfigurationUpdated(config.clone())).await;
self.load_library(path);
} }
self.notify(CoreNotification::ConfigurationUpdated(config.clone()))
.await;
}
fn load_library(&self, path: &LibraryPath) {
let db = Database::open_path(path.to_path_buf()).unwrap();
*self.library.write().unwrap() = Some(db);
} }
pub fn library<'a>(&'a self) -> RwLockReadGuard<'_, Option<Database>> { pub fn library<'a>(&'a self) -> RwLockReadGuard<'_, Option<Database>> {
self.library.read().unwrap() self.library.read().unwrap()
} }
pub async fn dispatch(&self, request: CoreRequest) -> CoreResponse {
match request {
CoreRequest::Library(request) => library::handle(&self, request).await.into(),
CoreRequest::Settings(request) => settings::handle(&self, request).await.into(),
}
}
pub async fn notify(&self, notification: CoreNotification) {
let subscribers = self.subscribers.read().unwrap().clone();
for subscriber in subscribers {
let subscriber = subscriber.clone();
let _ = subscriber.send(notification.clone()).await;
}
}
/* /*
pub async fn dispatch(&self, request: CoreRequest) -> CoreResponse { pub async fn dispatch(&self, request: CoreRequest) -> CoreResponse {
match request { match request {

View File

@ -1,32 +1,13 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
extern crate config_derive; extern crate config_derive;
mod api; mod api;
pub use api::{Core, CoreNotification, CoreRequest, CoreResponse, Observable}; pub use api::{Core, CoreNotification, Observable};
mod board; mod board;
pub use board::*; pub use board::*;
mod database; mod database;
pub mod library;
mod types; mod types;
pub use types::{BoardError, Color, Config, ConfigOption, LibraryPath, Player, Rank, Size}; pub use types::{BoardError, Color, Config, ConfigOption, LibraryPath, Player, Rank, Size};
pub mod settings;

View File

@ -1,50 +0,0 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{Core, Config};
use serde::{Deserialize, Serialize};
use sgf::GameInfo;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LibraryRequest {
ListGames
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum LibraryResponse {
Games(Vec<GameInfo>)
}
async fn handle_list_games(model: &Core) -> LibraryResponse {
println!("handle_list_games");
let library = model.library();
println!("library: {:?}", *library);
match *library {
Some(ref library) => {
let info = library.all_games().map(|g| g.info.clone()).collect::<Vec<GameInfo>>();
LibraryResponse::Games(info)
}
None => LibraryResponse::Games(vec![]),
}
}
pub async fn handle(model: &Core, request: LibraryRequest) -> LibraryResponse {
match request {
LibraryRequest::ListGames => handle_list_games(model).await,
}
}

View File

@ -1,37 +0,0 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{types::LibraryPath, Core, Config};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SettingsRequest {
Get,
Set(Config),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SettingsResponse(pub Config);
pub async fn handle(model: &Core, request: SettingsRequest) -> SettingsResponse {
match request {
SettingsRequest::Get => SettingsResponse(model.get_config()),
SettingsRequest::Set(config) => {
model.set_config(config).await;
SettingsResponse(model.get_config())
}
}
}

View File

@ -1,4 +1,5 @@
use crate::{ use crate::{
api::PlayStoneRequest,
board::{Coordinate, Goban}, board::{Coordinate, Goban},
database::Database, database::Database,
}; };
@ -84,7 +85,6 @@ impl AppState {
} }
} }
/*
pub fn place_stone(&mut self, req: PlayStoneRequest) { pub fn place_stone(&mut self, req: PlayStoneRequest) {
if let Some(ref mut game) = self.game { if let Some(ref mut game) = self.game {
let _ = game.place_stone(Coordinate { let _ = game.place_stone(Coordinate {
@ -93,7 +93,6 @@ impl AppState {
}); });
} }
} }
*/
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]

View File

@ -14,19 +14,21 @@ General Public License for more details.
You should have received a copy of the GNU General Public License along with Kifu. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with Kifu. If not, see <https://www.gnu.org/licenses/>.
*/ */
use crate::CoreApi;
use adw::prelude::*; use adw::prelude::*;
use async_std::task::{block_on, spawn}; /*
use kifu_core::settings::SettingsResponse; use gio::resources_lookup_data;
use kifu_core::CoreResponse; use glib::IsA;
use kifu_core::{settings::SettingsRequest, Config, CoreRequest}; use gtk::STYLE_PROVIDER_PRIORITY_USER;
*/
use kifu_core::{Config, Core};
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use crate::views::{SettingsView, HomeView}; use crate::{view_models::HomeViewModel, view_models::SettingsViewModel};
#[derive(Clone)] #[derive(Clone)]
enum AppView { enum AppView {
Home, Settings(SettingsViewModel),
Home(HomeViewModel),
} }
// An application window should generally contain // An application window should generally contain
@ -50,15 +52,15 @@ pub struct AppWindow {
// Overlays are for transient content, such as about and settings, which can be accessed from // Overlays are for transient content, such as about and settings, which can be accessed from
// anywhere but shouldn't be part of the main application flow. // anywhere but shouldn't be part of the main application flow.
panel_overlay: gtk::Overlay, panel_overlay: gtk::Overlay,
core: CoreApi, core: Core,
// Not liking this, but I have to keep track of the settings view model separately from // Not liking this, but I have to keep track of the settings view model separately from
// anything else. I'll have to look into this later. // anything else. I'll have to look into this later.
settings_view_model: Arc<RwLock<Option<SettingsView>>>, settings_view_model: Arc<RwLock<Option<SettingsViewModel>>>,
} }
impl AppWindow { impl AppWindow {
pub fn new(app: &adw::Application, core: CoreApi) -> Self { pub fn new(app: &adw::Application, core: Core) -> Self {
let window = Self::setup_window(app); let window = Self::setup_window(app);
let header = Self::setup_header(); let header = Self::setup_header();
let panel_overlay = Self::setup_panel_overlay(); let panel_overlay = Self::setup_panel_overlay();
@ -85,56 +87,22 @@ impl AppWindow {
} }
pub fn open_settings(&self) { pub fn open_settings(&self) {
// This should return instantly and allow the UI to continue being functional. However, let view_model = SettingsViewModel::new(&self.window, self.core.clone(), {
// some tests indicate that this may not actually be working correctly, and that a
// long-running background thread may delay things.
glib::spawn_future_local({
let s = self.clone(); let s = self.clone();
async move {
if let CoreResponse::Settings(SettingsResponse(settings)) = s
.core
.dispatch(CoreRequest::Settings(SettingsRequest::Get))
.await
{
let view_model = SettingsView::new(
&s.window,
settings,
{
let s = s.clone();
move |config| {
glib::spawn_future_local({
let s = s.clone();
async move {
s.core
.dispatch(CoreRequest::Settings(SettingsRequest::Set(
config,
)))
.await
}
});
s.close_overlay();
}
},
{
let s = s.clone();
move || { move || {
s.close_overlay(); s.close_overlay();
} }
},
);
s.panel_overlay.add_overlay(&view_model);
*s.settings_view_model.write().unwrap() = Some(view_model);
}
}
}); });
self.panel_overlay.add_overlay(&view_model.widget);
*self.settings_view_model.write().unwrap() = Some(view_model);
} }
pub fn close_overlay(&self) { pub fn close_overlay(&self) {
let mut view = self.settings_view_model.write().unwrap(); let mut vm = self.settings_view_model.write().unwrap();
match *view { match *vm {
Some(ref mut settings) => { Some(ref mut view_model) => {
self.panel_overlay.remove_overlay(settings); self.panel_overlay.remove_overlay(&view_model.widget);
*view = None; *vm = None;
} }
None => {} None => {}
} }
@ -172,19 +140,31 @@ impl AppWindow {
gtk::Overlay::new() gtk::Overlay::new()
} }
fn setup_content(core: CoreApi) -> (adw::NavigationView, Vec<AppView>) { fn setup_content(core: Core) -> (adw::NavigationView, Vec<AppView>) {
let stack = adw::NavigationView::new(); let stack = adw::NavigationView::new();
let content = Vec::new(); let mut content = Vec::new();
let home = HomeView::new(core.clone()); let nothing_page = adw::StatusPage::builder().title("Nothing here").build();
let _ = stack.push( let _ = stack.push(
&adw::NavigationPage::builder() &adw::NavigationPage::builder()
.can_pop(false) .can_pop(false)
.title("Kifu") .title("Kifu")
.child(&home) .child(&nothing_page)
.build(), .build(),
); );
// content.push(AppView::Home(HomeViewModel::new(core))); content.push(AppView::Home(HomeViewModel::new(core.clone())));
/*
match *core.library() {
Some(_) => {
}
None => {
let settings_vm = SettingsViewModel::new(core.clone());
let _ = stack.push(&adw::NavigationPage::new(&settings_vm.widget, "Settings"));
content.push(AppView::Settings(settings_vm));
}
}
*/
(stack, content) (stack, content)
} }

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 Kifu. If not, see <https://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License along with Kifu. If not, see <https://www.gnu.org/licenses/>.
*/ */
pub mod components; pub mod ui;
mod app_window; mod app_window;
pub use app_window::AppWindow; pub use app_window::AppWindow;
@ -22,20 +22,31 @@ pub use app_window::AppWindow;
mod view_models; mod view_models;
mod views; mod views;
use async_std::task::{spawn, yield_now}; use async_std::task::yield_now;
use kifu_core::{Core, Observable, CoreRequest, CoreResponse}; use kifu_core::{Core, Observable};
use std::{rc::Rc, sync::Arc}; use std::{rc::Rc, sync::Arc};
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
#[derive(Clone)] #[derive(Clone)]
pub struct CoreApi { pub struct CoreApi {
pub rt: Arc<Runtime>,
pub core: Core, pub core: Core,
} }
impl CoreApi { impl CoreApi {
pub async fn dispatch(&self, request: CoreRequest) -> CoreResponse { /*
self.core.dispatch(request).await pub fn dispatch(&self, request: CoreRequest) {
/*
spawn({
/*
let gtk_tx = self.gtk_tx.clone();
let core = self.core.clone();
async move { gtk_tx.send(core.dispatch(request).await) }
*/
});
*/
} }
*/
} }
pub fn perftrace<F, A>(trace_name: &str, f: F) -> A pub fn perftrace<F, A>(trace_name: &str, f: F) -> A

View File

@ -90,8 +90,7 @@ fn setup_app_configuration_action(app: &adw::Application, app_window: AppWindow)
println!("setup_app_configuration_action"); println!("setup_app_configuration_action");
let action = ActionEntry::builder("show_settings") let action = ActionEntry::builder("show_settings")
.activate(move |_app: &adw::Application, _, _| { .activate(move |_app: &adw::Application, _, _| {
let app_window = app_window.clone(); app_window.open_settings();
app_window.open_settings()
}) })
.build(); .build();
app.add_action_entries([action]); app.add_action_entries([action]);
@ -110,7 +109,28 @@ fn main() {
let config = load_config(&app_id); let config = load_config(&app_id);
let core = Core::new(config.clone()); let runtime = Arc::new(
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap(),
);
/*
let config_path = std::env::var("CONFIG")
.map(std::path::PathBuf::from)
.or({
std::env::var("HOME").map(|base| {
let mut config_path = std::path::PathBuf::from(base);
config_path.push(".config");
config_path.push("kifu");
config_path
})
})
.expect("no config path could be found");
*/
let core = Core::new(config);
spawn({ spawn({
let notifier = core.subscribe(); let notifier = core.subscribe();
@ -118,22 +138,70 @@ fn main() {
handler(notifier, app_id) handler(notifier, app_id)
}); });
/*
let core_handle = runtime.spawn({
let core = core.clone();
async move {
core.run().await;
}
});
*/
let app = adw::Application::builder() let app = adw::Application::builder()
.application_id("com.luminescent-dreams.kifu-gtk") .application_id("com.luminescent-dreams.kifu-gtk")
.resource_base_path("/com/luminescent-dreams/kifu-gtk") .resource_base_path("/com/luminescent-dreams/kifu-gtk")
.build(); .build();
app.connect_activate({ app.connect_activate({
let runtime = runtime.clone();
move |app| { move |app| {
let core_api = CoreApi { core: core.clone() }; let mut app_window = AppWindow::new(app, core.clone());
let app_window = AppWindow::new(app, core_api);
match *core.library() {
Some(_) => {}
None => app_window.open_settings(),
}
setup_app_configuration_action(app, app_window.clone()); setup_app_configuration_action(app, app_window.clone());
/*
let api = CoreApi {
rt: runtime.clone(),
core: core.clone(),
};
*/
/*
let action_config = gio::SimpleAction::new("show-config", None);
action_config.connect_activate({
let api = api.clone();
move |_, _| {
api.dispatch(CoreRequest::OpenConfiguration);
}
});
app.add_action(&action_config);
*/
app_window.window.present(); app_window.window.present();
/*
gtk_rx.attach(None, {
let api = api.clone();
move |message| {
perftrace("handle_response", || {
handle_response(api.clone(), &app_window, message)
});
glib::ControlFlow::Continue
}
});
*/
// api.dispatch(CoreRequest::Home);
} }
}); });
println!("running the gtk loop"); println!("running the gtk loop");
app.run(); app.run();
/* let _ = runtime.block_on(core_handle); */
} }

View File

@ -1,13 +1,12 @@
use adw::{prelude::*, subclass::prelude::*}; use adw::{prelude::*, subclass::prelude::*};
use glib::Object; use glib::Object;
use gtk::glib; use gtk::glib;
// use kifu_core::ui::GamePreviewElement; use kifu_core::ui::GamePreviewElement;
use sgf::GameInfo;
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
#[derive(Default)] #[derive(Default)]
pub struct GameObjectPrivate { pub struct GameObjectPrivate {
game: Rc<RefCell<Option<GameInfo>>>, game: Rc<RefCell<Option<GamePreviewElement>>>,
} }
#[glib::object_subclass] #[glib::object_subclass]
@ -23,13 +22,13 @@ glib::wrapper! {
} }
impl GameObject { impl GameObject {
pub fn new(game: GameInfo) -> Self { pub fn new(game: GamePreviewElement) -> Self {
let s: Self = Object::builder().build(); let s: Self = Object::builder().build();
*s.imp().game.borrow_mut() = Some(game); *s.imp().game.borrow_mut() = Some(game);
s s
} }
pub fn game(&self) -> Option<GameInfo> { pub fn game(&self) -> Option<GamePreviewElement> {
self.imp().game.borrow().clone() self.imp().game.borrow().clone()
} }
} }
@ -78,14 +77,11 @@ impl Default for LibraryPrivate {
*/ */
let selection_model = gtk::NoSelection::new(Some(model.clone())); let selection_model = gtk::NoSelection::new(Some(model.clone()));
let list_view = gtk::ColumnView::builder() let list_view = gtk::ColumnView::builder().model(&selection_model).build();
.model(&selection_model)
.hexpand(true)
.build();
fn make_factory<F>(bind: F) -> gtk::SignalListItemFactory fn make_factory<F>(bind: F) -> gtk::SignalListItemFactory
where where
F: Fn(GameInfo) -> String + 'static, F: Fn(GamePreviewElement) -> String + 'static,
{ {
let factory = gtk::SignalListItemFactory::new(); let factory = gtk::SignalListItemFactory::new();
factory.connect_setup(|_, list_item| { factory.connect_setup(|_, list_item| {
@ -110,61 +106,25 @@ impl Default for LibraryPrivate {
factory factory
} }
list_view.append_column( list_view.append_column(&gtk::ColumnViewColumn::new(
&gtk::ColumnViewColumn::builder() Some("date"),
.title("date") Some(make_factory(|g| g.date)),
.factory(&make_factory(|g| { ));
g.date list_view.append_column(&gtk::ColumnViewColumn::new(
.iter() Some("title"),
.map(|date| { Some(make_factory(|g| g.name)),
format!("{}", date) ));
/* list_view.append_column(&gtk::ColumnViewColumn::new(
let l = locale!("en-US").into(); Some("black"),
let options = length::Bag::from_date_style(length::Date::Medium); Some(make_factory(|g| g.black_player)),
let date = Date::try_new_iso_date(date. ));
let dtfmt = list_view.append_column(&gtk::ColumnViewColumn::new(
DateFormatter::try_new_with_length(&l, options).unwrap(); Some("white"),
dtfmt.format(date).unwrap() Some(make_factory(|g| g.white_player)),
*/ ));
})
.collect::<Vec<String>>()
.join(", ")
}))
.expand(true)
.build(),
);
list_view.append_column(
&gtk::ColumnViewColumn::builder()
.title("game")
.factory(&make_factory(|g| {
g.game_name.unwrap_or("Unnamed".to_owned())
}))
.expand(true)
.build(),
);
list_view.append_column(
&gtk::ColumnViewColumn::builder()
.title("black")
.factory(&make_factory(|g| {
g.black_player.unwrap_or("Black".to_owned())
}))
.expand(true)
.build(),
);
list_view.append_column(
&gtk::ColumnViewColumn::builder()
.title("white")
.factory(&make_factory(|g| {
g.white_player.unwrap_or("White".to_owned())
}))
.expand(true)
.build(),
);
list_view.append_column(&gtk::ColumnViewColumn::new( list_view.append_column(&gtk::ColumnViewColumn::new(
Some("result"), Some("result"),
Some(make_factory(|g| { Some(make_factory(|g| g.result)),
g.result.map(|d| format!("{}", d)).unwrap_or("".to_owned())
})),
)); ));
Self { model, list_view } Self { model, list_view }
@ -196,7 +156,7 @@ impl Default for Library {
} }
impl Library { impl Library {
pub fn set_games(&self, games: Vec<GameInfo>) { pub fn set_games(&self, games: Vec<GamePreviewElement>) {
let games = games let games = games
.into_iter() .into_iter()
.map(GameObject::new) .map(GameObject::new)

View File

@ -7,8 +7,8 @@
// mod game_preview; // mod game_preview;
// pub use game_preview::GamePreview; // pub use game_preview::GamePreview;
mod library; // mod library;
pub use library::Library; // pub use library::Library;
// mod player_card; // mod player_card;
// pub use player_card::PlayerCard; // pub use player_card::PlayerCard;

View File

@ -16,22 +16,18 @@ You should have received a copy of the GNU General Public License along with Kif
use crate::LocalObserver; use crate::LocalObserver;
use kifu_core::{Core, CoreNotification}; use kifu_core::{Core, CoreNotification};
use crate::CoreApi;
use std::sync::Arc; use std::sync::Arc;
/// Home controls the view that the user sees when starting the application if there are no games in progress. It provides a window into the database, showing a list of recently recorded games. It also provides the UI for starting a new game. This will render an empty database view if the user hasn't configured a database yet. /// Home controls the view that the user sees when starting the application if there are no games in progress. It provides a window into the database, showing a list of recently recorded games. It also provides the UI for starting a new game. This will render an empty database view if the user hasn't configured a database yet.
#[derive(Clone)] #[derive(Clone)]
pub struct HomeViewModel { pub struct HomeViewModel {
/* core: Core,
core: CoreApi,
notification_observer: Arc<LocalObserver<CoreNotification>>, notification_observer: Arc<LocalObserver<CoreNotification>>,
widget: gtk::Box, widget: gtk::Box,
*/
} }
impl HomeViewModel { impl HomeViewModel {
pub fn new(core: CoreApi) -> Self { pub fn new(core: Core) -> Self {
/*
let notification_observer = LocalObserver::new(&core, |msg| { let notification_observer = LocalObserver::new(&core, |msg| {
println!("HomeViewModel handler called with message: {:?}", msg) println!("HomeViewModel handler called with message: {:?}", msg)
}); });
@ -41,8 +37,6 @@ impl HomeViewModel {
notification_observer: Arc::new(notification_observer), notification_observer: Arc::new(notification_observer),
widget: gtk::Box::new(gtk::Orientation::Horizontal, 0), widget: gtk::Box::new(gtk::Orientation::Horizontal, 0),
} }
*/
Self {}
} }
/// Create a new game with the given parameters. /// Create a new game with the given parameters.

View File

@ -28,3 +28,6 @@ pub use game_review_view_model::GameReviewViewModel;
mod home_view_model; mod home_view_model;
pub use home_view_model::HomeViewModel; pub use home_view_model::HomeViewModel;
mod settings_view_model;
pub use settings_view_model::SettingsViewModel;

View File

@ -0,0 +1,73 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{views, views::SettingsView, LocalObserver};
use async_std::task::spawn;
use gtk::prelude::*;
use kifu_core::{Config, Core, CoreNotification};
use std::{sync::Arc, rc::Rc};
/// SettingsViewModel
///
/// Listens for messages from the core, and serves as intermediary between the Settings UI and the
/// core. Because it needs to respond to events from the core, it owns the widget, which allows it
/// to tell the widget to update after certain events.
#[derive(Clone)]
pub struct SettingsViewModel {
core: Core,
// Technically, Settings doesn't care about any events from Core. We will keep this around for
// now as reference, until something which does care shows up.
notification_observer: Arc<LocalObserver<CoreNotification>>,
pub widget: views::SettingsView,
}
impl SettingsViewModel {
pub fn new(parent: &impl IsA<gtk::Window>, core: Core, on_close: impl Fn() + 'static) -> Self {
let on_close = Arc::new(on_close);
let notification_observer = LocalObserver::new(&core, |msg| {
println!("SettingsViewModel called with message: {:?}", msg)
});
let config = core.get_config();
let widget = SettingsView::new(
parent,
config,
{
let core = core.clone();
let on_close = on_close.clone();
move |new_config| {
spawn({
let core = core.clone();
on_close();
async move {
println!("running set_config in the background");
core.set_config(new_config).await;
}
});
}
},
move || on_close(),
);
Self {
core: core.clone(),
notification_observer: Arc::new(notification_observer),
widget,
}
}
}

View File

@ -1,208 +0,0 @@
/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
This file is part of Kifu.
Kifu is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Kifu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
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 Kifu. If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{components::Library, CoreApi};
use glib::Object;
use gtk::{glib, prelude::*, subclass::prelude::*};
use kifu_core::{
library::{LibraryRequest, LibraryResponse},
CoreRequest, CoreResponse,
};
use std::{cell::RefCell, rc::Rc};
/*
struct PlayerDataEntryPrivate {
name: gtk::Text,
rank: gtk::DropDown,
}
impl Default for PlayerDataEntryPrivate {
fn default() -> Self {
let rank = gtk::DropDown::builder().build();
Self {
name: gtk::Text::builder().build(),
rank,
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for PlayerDataEntryPrivate {
const NAME: &'static str = "PlayerDataEntry";
type Type = PlayerDataEntry;
type ParentType = gtk::Box;
}
impl ObjectImpl for PlayerDataEntryPrivate {}
impl WidgetImpl for PlayerDataEntryPrivate {}
impl BoxImpl for PlayerDataEntryPrivate {}
glib::wrapper! {
struct PlayerDataEntry(ObjectSubclass<PlayerDataEntryPrivate>) @extends gtk::Box, gtk::Widget;
}
impl PlayerDataEntry {
pub fn new(element: PlayerElement) -> PlayerDataEntry {
let s: Self = Object::builder().build();
let rank_model = gio::ListStore::new::<gtk::StringObject>();
s.imp().rank.set_model(Some(&rank_model));
match element {
PlayerElement::Hotseat(player) => {
if let Some(placeholder) = player.placeholder {
s.imp().name.set_placeholder_text(Some(&placeholder));
}
player.ranks.iter().for_each(|rank| rank_model.append(&gtk::StringObject::new(rank)));
}
// PlayerElement::Remote(_) => s.imp().placeholder.set_text("remote player"),
// PlayerElement::Bot(_) => s.imp().placeholder.set_text("bot player"),
}
s.append(&s.imp().name);
s.append(&s.imp().rank);
s
}
pub fn text(&self) -> String {
let name = self.imp().name.buffer().text().to_string();
if name.is_empty() {
self.imp()
.name
.placeholder_text()
.map(|s| s.to_string())
.unwrap_or("".to_owned())
} else {
name
}
}
pub fn rank(&self) -> Option<String> {
self.imp().rank.selected_item().and_then(|obj| {
let str_obj = obj.downcast::<gtk::StringObject>().ok()?;
Some(str_obj.string().clone().to_string())
})
}
}
*/
pub struct HomePrivate {
// black_player: Rc<RefCell<Option<PlayerDataEntry>>>,
// white_player: Rc<RefCell<Option<PlayerDataEntry>>>,
}
impl Default for HomePrivate {
fn default() -> Self {
Self {
// black_player: Rc::new(RefCell::new(None)),
// white_player: Rc::new(RefCell::new(None)),
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for HomePrivate {
const NAME: &'static str = "Home";
type Type = HomeView;
type ParentType = gtk::Box;
}
impl ObjectImpl for HomePrivate {}
impl WidgetImpl for HomePrivate {}
impl BoxImpl for HomePrivate {}
glib::wrapper! {
pub struct HomeView(ObjectSubclass<HomePrivate>) @extends gtk::Box, gtk::Widget, @implements gtk::Orientable;
}
impl HomeView {
pub fn new(api: CoreApi) -> Self {
let s: Self = Object::builder().build();
s.set_spacing(4);
s.set_homogeneous(false);
s.set_orientation(gtk::Orientation::Vertical);
/*
let players = gtk::Box::builder()
.spacing(4)
.orientation(gtk::Orientation::Horizontal)
.build();
s.append(&players);
let black_player = PlayerDataEntry::new(view.black_player);
players.append(&black_player);
*s.imp().black_player.borrow_mut() = Some(black_player.clone());
let white_player = PlayerDataEntry::new(view.white_player);
players.append(&white_player);
*s.imp().white_player.borrow_mut() = Some(white_player.clone());
let new_game_button = gtk::Button::builder()
.css_classes(vec!["suggested-action"])
.label(&view.start_game.label)
.build();
s.append(&new_game_button);
*/
let library = Library::default();
let library_view = gtk::ScrolledWindow::builder()
.hscrollbar_policy(gtk::PolicyType::Never)
.min_content_width(360)
.vexpand(true)
.hexpand(true)
.child(&library)
.build();
s.append(&library_view);
glib::spawn_future_local({
let library = library.clone();
let api = api.clone();
async move {
if let CoreResponse::Library(LibraryResponse::Games(games)) = api
.dispatch(CoreRequest::Library(LibraryRequest::ListGames))
.await
{
library.set_games(games);
}
}
});
/*
new_game_button.connect_clicked({
move |_| {
let black_player = black_player.clone();
let white_player = white_player.clone();
api.dispatch(CoreRequest::CreateGame(CreateGameRequest {
black_player: player_info(black_player.clone()),
white_player: player_info(white_player.clone()),
}));
}
});
*/
s
}
}
/*
fn player_info(player: PlayerDataEntry) -> PlayerInfoRequest {
PlayerInfoRequest::Hotseat(HotseatPlayerRequest {
name: player.text(),
rank: player.rank(),
})
}
*/

View File

@ -1,5 +1,2 @@
mod home;
pub use home::HomeView;
mod settings; mod settings;
pub use settings::SettingsView; pub use settings::SettingsView;

View File

@ -1,6 +1,4 @@
use crate::date::Date; use crate::date::Date;
use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error; use thiserror::Error;
@ -11,7 +9,7 @@ pub struct Game {
pub info: GameInfo, pub info: GameInfo,
} }
#[derive(Clone, Debug, Default, Serialize, Deserialize)] #[derive(Debug, Default)]
pub struct GameInfo { pub struct GameInfo {
pub black_player: Option<String>, pub black_player: Option<String>,
pub black_rank: Option<String>, pub black_rank: Option<String>,
@ -131,7 +129,7 @@ impl Color {
} }
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq)]
pub enum GameResult { pub enum GameResult {
Draw, Draw,
Black(Win), Black(Win),
@ -140,18 +138,6 @@ pub enum GameResult {
Unknown(String), Unknown(String),
} }
impl fmt::Display for GameResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GameResult::Draw => write!(f, "draw"),
GameResult::Black(_) => write!(f, "B"),
GameResult::White(_) => write!(f, "W"),
GameResult::Void => write!(f, "void"),
GameResult::Unknown(s) => write!(f, "{}", s),
}
}
}
impl TryFrom<&str> for GameResult { impl TryFrom<&str> for GameResult {
type Error = String; type Error = String;
fn try_from(s: &str) -> Result<GameResult, Self::Error> { fn try_from(s: &str) -> Result<GameResult, Self::Error> {
@ -179,7 +165,7 @@ impl TryFrom<&str> for GameResult {
} }
} }
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq)]
pub enum Win { pub enum Win {
Score(f32), Score(f32),
Resignation, Resignation,