Compare commits
8 Commits
f2f1ae809b
...
49571b0f82
Author | SHA1 | Date |
---|---|---|
Savanni D'Gerinel | 49571b0f82 | |
Savanni D'Gerinel | 89a289a1ae | |
Savanni D'Gerinel | fe082773e3 | |
Savanni D'Gerinel | db9efbaedd | |
Savanni D'Gerinel | 1d959117aa | |
Savanni D'Gerinel | a5990a2a30 | |
Savanni D'Gerinel | bd6d5b62e3 | |
Savanni D'Gerinel | 82c1765513 |
|
@ -3687,6 +3687,7 @@ dependencies = [
|
|||
"serde 1.0.193",
|
||||
"thiserror",
|
||||
"typeshare",
|
||||
"uuid 0.8.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
@ -35,7 +35,7 @@ macro_rules! define_config {
|
|||
$($name($struct)),+
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Config {
|
||||
values: std::collections::HashMap<ConfigName, ConfigOption>,
|
||||
}
|
||||
|
|
|
@ -1,5 +1,22 @@
|
|||
/*
|
||||
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::{
|
||||
database::Database,
|
||||
library, settings,
|
||||
types::{AppState, Config, ConfigOption, GameState, LibraryPath, Player, Rank},
|
||||
};
|
||||
use async_std::{
|
||||
|
@ -18,8 +35,11 @@ pub trait Observable<T> {
|
|||
fn subscribe(&self) -> Receiver<T>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum CoreRequest {
|
||||
Library(library::LibraryRequest),
|
||||
Settings(settings::SettingsRequest),
|
||||
/*
|
||||
ChangeSetting(ChangeSettingRequest),
|
||||
CreateGame(CreateGameRequest),
|
||||
Home,
|
||||
|
@ -27,8 +47,10 @@ pub enum CoreRequest {
|
|||
PlayingField,
|
||||
PlayStone(PlayStoneRequest),
|
||||
StartGame,
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ChangeSettingRequest {
|
||||
LibraryPath(String),
|
||||
|
@ -65,16 +87,25 @@ impl From<HotseatPlayerRequest> for Player {
|
|||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum CoreResponse {
|
||||
ConfigurationView(ConfigurationView),
|
||||
HomeView(HomeView),
|
||||
PlayingFieldView(PlayingFieldView),
|
||||
UpdatedConfigurationView(ConfigurationView),
|
||||
Library(library::LibraryResponse),
|
||||
Settings(settings::SettingsResponse),
|
||||
}
|
||||
|
||||
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)]
|
||||
pub enum CoreNotification {
|
||||
|
@ -92,10 +123,18 @@ pub struct Core {
|
|||
|
||||
impl Core {
|
||||
pub fn new(config: Config) -> Self {
|
||||
println!("config: {:?}", config);
|
||||
|
||||
let library = if let Some(ref path) = config.get::<LibraryPath>() {
|
||||
Some(Database::open_path(path.to_path_buf()).unwrap())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Self {
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
// state,
|
||||
library: Arc::new(RwLock::new(None)),
|
||||
library: Arc::new(RwLock::new(library)),
|
||||
subscribers: Arc::new(RwLock::new(vec![])),
|
||||
}
|
||||
}
|
||||
|
@ -112,17 +151,41 @@ impl Core {
|
|||
/// configuration is not a decision for the core library.
|
||||
pub async fn set_config(&self, config: Config) {
|
||||
*self.config.write().unwrap() = config.clone();
|
||||
let subscribers = self.subscribers.read().unwrap().clone();
|
||||
for subscriber in subscribers {
|
||||
let subscriber = subscriber.clone();
|
||||
let _ = subscriber.send(CoreNotification::ConfigurationUpdated(config.clone())).await;
|
||||
|
||||
// let db = library::read_library(self.config.read().unwrap().get::<LibraryPath>()).await;
|
||||
let library_path = self.config.read().unwrap().get::<LibraryPath>();
|
||||
if let Some(ref path) = library_path {
|
||||
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>> {
|
||||
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 {
|
||||
match request {
|
||||
|
|
|
@ -43,10 +43,12 @@ impl Database {
|
|||
match parse_sgf(&buffer) {
|
||||
Ok(sgfs) => {
|
||||
for sgf in sgfs {
|
||||
games.push(sgf);
|
||||
if let Ok(sgf) = sgf {
|
||||
games.push(sgf);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => println!("Error parsing {:?}: {:?}", entry.path(), err),
|
||||
Err(err) => println!("Error parsing {:?}", entry.path()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,13 +1,32 @@
|
|||
/*
|
||||
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;
|
||||
|
||||
mod api;
|
||||
pub use api::{Core, CoreNotification, Observable};
|
||||
pub use api::{Core, CoreNotification, CoreRequest, CoreResponse, Observable};
|
||||
|
||||
mod board;
|
||||
pub use board::*;
|
||||
|
||||
mod database;
|
||||
|
||||
pub mod library;
|
||||
|
||||
mod types;
|
||||
pub use types::{BoardError, Color, Config, ConfigOption, LibraryPath, Player, Rank, Size};
|
||||
|
||||
pub mod settings;
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
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::Game;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum LibraryRequest {
|
||||
ListGames
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum LibraryResponse {
|
||||
Games(Vec<Game>)
|
||||
}
|
||||
|
||||
async fn handle_list_games(model: &Core) -> LibraryResponse {
|
||||
let library = model.library();
|
||||
match *library {
|
||||
Some(ref library) => {
|
||||
let info = library.all_games().map(|g| g.clone()).collect::<Vec<Game>>();
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
/*
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,5 +1,4 @@
|
|||
use crate::{
|
||||
api::PlayStoneRequest,
|
||||
board::{Coordinate, Goban},
|
||||
database::Database,
|
||||
};
|
||||
|
@ -85,6 +84,7 @@ impl AppState {
|
|||
}
|
||||
}
|
||||
|
||||
/*
|
||||
pub fn place_stone(&mut self, req: PlayStoneRequest) {
|
||||
if let Some(ref mut game) = self.game {
|
||||
let _ = game.place_stone(Coordinate {
|
||||
|
@ -93,6 +93,7 @@ impl AppState {
|
|||
});
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
|
@ -14,21 +14,19 @@ 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::CoreApi;
|
||||
use adw::prelude::*;
|
||||
/*
|
||||
use gio::resources_lookup_data;
|
||||
use glib::IsA;
|
||||
use gtk::STYLE_PROVIDER_PRIORITY_USER;
|
||||
*/
|
||||
use kifu_core::{Config, Core};
|
||||
use async_std::task::{block_on, spawn};
|
||||
use kifu_core::settings::SettingsResponse;
|
||||
use kifu_core::CoreResponse;
|
||||
use kifu_core::{settings::SettingsRequest, Config, CoreRequest};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crate::{view_models::HomeViewModel, view_models::SettingsViewModel};
|
||||
use crate::views::{SettingsView, HomeView};
|
||||
|
||||
#[derive(Clone)]
|
||||
enum AppView {
|
||||
Settings(SettingsViewModel),
|
||||
Home(HomeViewModel),
|
||||
Home,
|
||||
}
|
||||
|
||||
// An application window should generally contain
|
||||
|
@ -52,15 +50,15 @@ pub struct AppWindow {
|
|||
// 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.
|
||||
panel_overlay: gtk::Overlay,
|
||||
core: Core,
|
||||
core: CoreApi,
|
||||
|
||||
// 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.
|
||||
settings_view_model: Arc<RwLock<Option<SettingsViewModel>>>,
|
||||
settings_view_model: Arc<RwLock<Option<SettingsView>>>,
|
||||
}
|
||||
|
||||
impl AppWindow {
|
||||
pub fn new(app: &adw::Application, core: Core) -> Self {
|
||||
pub fn new(app: &adw::Application, core: CoreApi) -> Self {
|
||||
let window = Self::setup_window(app);
|
||||
let header = Self::setup_header();
|
||||
let panel_overlay = Self::setup_panel_overlay();
|
||||
|
@ -87,22 +85,56 @@ impl AppWindow {
|
|||
}
|
||||
|
||||
pub fn open_settings(&self) {
|
||||
let view_model = SettingsViewModel::new(&self.window, self.core.clone(), {
|
||||
// This should return instantly and allow the UI to continue being functional. However,
|
||||
// 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();
|
||||
move || {
|
||||
s.close_overlay();
|
||||
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 || {
|
||||
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) {
|
||||
let mut vm = self.settings_view_model.write().unwrap();
|
||||
match *vm {
|
||||
Some(ref mut view_model) => {
|
||||
self.panel_overlay.remove_overlay(&view_model.widget);
|
||||
*vm = None;
|
||||
let mut view = self.settings_view_model.write().unwrap();
|
||||
match *view {
|
||||
Some(ref mut settings) => {
|
||||
self.panel_overlay.remove_overlay(settings);
|
||||
*view = None;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
@ -140,31 +172,19 @@ impl AppWindow {
|
|||
gtk::Overlay::new()
|
||||
}
|
||||
|
||||
fn setup_content(core: Core) -> (adw::NavigationView, Vec<AppView>) {
|
||||
fn setup_content(core: CoreApi) -> (adw::NavigationView, Vec<AppView>) {
|
||||
let stack = adw::NavigationView::new();
|
||||
let mut content = Vec::new();
|
||||
let content = Vec::new();
|
||||
|
||||
let nothing_page = adw::StatusPage::builder().title("Nothing here").build();
|
||||
let home = HomeView::new(core.clone());
|
||||
let _ = stack.push(
|
||||
&adw::NavigationPage::builder()
|
||||
.can_pop(false)
|
||||
.title("Kifu")
|
||||
.child(¬hing_page)
|
||||
.child(&home)
|
||||
.build(),
|
||||
);
|
||||
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));
|
||||
}
|
||||
}
|
||||
*/
|
||||
// content.push(AppView::Home(HomeViewModel::new(core)));
|
||||
|
||||
(stack, content)
|
||||
}
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
use adw::{prelude::*, subclass::prelude::*};
|
||||
use glib::Object;
|
||||
use gtk::glib;
|
||||
use kifu_core::ui::GamePreviewElement;
|
||||
// use kifu_core::ui::GamePreviewElement;
|
||||
use sgf::Game;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct GameObjectPrivate {
|
||||
game: Rc<RefCell<Option<GamePreviewElement>>>,
|
||||
game: Rc<RefCell<Option<Game>>>,
|
||||
}
|
||||
|
||||
#[glib::object_subclass]
|
||||
|
@ -22,13 +23,13 @@ glib::wrapper! {
|
|||
}
|
||||
|
||||
impl GameObject {
|
||||
pub fn new(game: GamePreviewElement) -> Self {
|
||||
pub fn new(game: Game) -> Self {
|
||||
let s: Self = Object::builder().build();
|
||||
*s.imp().game.borrow_mut() = Some(game);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn game(&self) -> Option<GamePreviewElement> {
|
||||
pub fn game(&self) -> Option<Game> {
|
||||
self.imp().game.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
@ -77,11 +78,14 @@ impl Default for LibraryPrivate {
|
|||
*/
|
||||
|
||||
let selection_model = gtk::NoSelection::new(Some(model.clone()));
|
||||
let list_view = gtk::ColumnView::builder().model(&selection_model).build();
|
||||
let list_view = gtk::ColumnView::builder()
|
||||
.model(&selection_model)
|
||||
.hexpand(true)
|
||||
.build();
|
||||
|
||||
fn make_factory<F>(bind: F) -> gtk::SignalListItemFactory
|
||||
where
|
||||
F: Fn(GamePreviewElement) -> String + 'static,
|
||||
F: Fn(Game) -> String + 'static,
|
||||
{
|
||||
let factory = gtk::SignalListItemFactory::new();
|
||||
factory.connect_setup(|_, list_item| {
|
||||
|
@ -106,25 +110,61 @@ impl Default for LibraryPrivate {
|
|||
factory
|
||||
}
|
||||
|
||||
list_view.append_column(>k::ColumnViewColumn::new(
|
||||
Some("date"),
|
||||
Some(make_factory(|g| g.date)),
|
||||
));
|
||||
list_view.append_column(>k::ColumnViewColumn::new(
|
||||
Some("title"),
|
||||
Some(make_factory(|g| g.name)),
|
||||
));
|
||||
list_view.append_column(>k::ColumnViewColumn::new(
|
||||
Some("black"),
|
||||
Some(make_factory(|g| g.black_player)),
|
||||
));
|
||||
list_view.append_column(>k::ColumnViewColumn::new(
|
||||
Some("white"),
|
||||
Some(make_factory(|g| g.white_player)),
|
||||
));
|
||||
list_view.append_column(
|
||||
>k::ColumnViewColumn::builder()
|
||||
.title("date")
|
||||
.factory(&make_factory(|g| {
|
||||
g.dates
|
||||
.iter()
|
||||
.map(|date| {
|
||||
format!("{}", date)
|
||||
/*
|
||||
let l = locale!("en-US").into();
|
||||
let options = length::Bag::from_date_style(length::Date::Medium);
|
||||
let date = Date::try_new_iso_date(date.
|
||||
let dtfmt =
|
||||
DateFormatter::try_new_with_length(&l, options).unwrap();
|
||||
dtfmt.format(date).unwrap()
|
||||
*/
|
||||
})
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ")
|
||||
}))
|
||||
.expand(true)
|
||||
.build(),
|
||||
);
|
||||
list_view.append_column(
|
||||
>k::ColumnViewColumn::builder()
|
||||
.title("game")
|
||||
.factory(&make_factory(|g| {
|
||||
g.game_name.unwrap_or("Unnamed".to_owned())
|
||||
}))
|
||||
.expand(true)
|
||||
.build(),
|
||||
);
|
||||
list_view.append_column(
|
||||
>k::ColumnViewColumn::builder()
|
||||
.title("black")
|
||||
.factory(&make_factory(|g| {
|
||||
g.black_player.name.unwrap_or("Black".to_owned())
|
||||
}))
|
||||
.expand(true)
|
||||
.build(),
|
||||
);
|
||||
list_view.append_column(
|
||||
>k::ColumnViewColumn::builder()
|
||||
.title("white")
|
||||
.factory(&make_factory(|g| {
|
||||
g.white_player.name.unwrap_or("White".to_owned())
|
||||
}))
|
||||
.expand(true)
|
||||
.build(),
|
||||
);
|
||||
list_view.append_column(>k::ColumnViewColumn::new(
|
||||
Some("result"),
|
||||
Some(make_factory(|g| g.result)),
|
||||
Some(make_factory(|g| {
|
||||
g.result.map(|d| format!("{}", d)).unwrap_or("".to_owned())
|
||||
})),
|
||||
));
|
||||
|
||||
Self { model, list_view }
|
||||
|
@ -156,7 +196,7 @@ impl Default for Library {
|
|||
}
|
||||
|
||||
impl Library {
|
||||
pub fn set_games(&self, games: Vec<GamePreviewElement>) {
|
||||
pub fn set_games(&self, games: Vec<Game>) {
|
||||
let games = games
|
||||
.into_iter()
|
||||
.map(GameObject::new)
|
|
@ -7,8 +7,8 @@
|
|||
// mod game_preview;
|
||||
// pub use game_preview::GamePreview;
|
||||
|
||||
// mod library;
|
||||
// pub use library::Library;
|
||||
mod library;
|
||||
pub use library::Library;
|
||||
|
||||
// mod player_card;
|
||||
// pub use player_card::PlayerCard;
|
|
@ -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/>.
|
||||
*/
|
||||
|
||||
pub mod ui;
|
||||
pub mod components;
|
||||
|
||||
mod app_window;
|
||||
pub use app_window::AppWindow;
|
||||
|
@ -22,31 +22,20 @@ pub use app_window::AppWindow;
|
|||
mod view_models;
|
||||
mod views;
|
||||
|
||||
use async_std::task::yield_now;
|
||||
use kifu_core::{Core, Observable};
|
||||
use async_std::task::{spawn, yield_now};
|
||||
use kifu_core::{Core, Observable, CoreRequest, CoreResponse};
|
||||
use std::{rc::Rc, sync::Arc};
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CoreApi {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub core: Core,
|
||||
}
|
||||
|
||||
impl CoreApi {
|
||||
/*
|
||||
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 async fn dispatch(&self, request: CoreRequest) -> CoreResponse {
|
||||
self.core.dispatch(request).await
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
pub fn perftrace<F, A>(trace_name: &str, f: F) -> A
|
||||
|
|
|
@ -90,7 +90,8 @@ fn setup_app_configuration_action(app: &adw::Application, app_window: AppWindow)
|
|||
println!("setup_app_configuration_action");
|
||||
let action = ActionEntry::builder("show_settings")
|
||||
.activate(move |_app: &adw::Application, _, _| {
|
||||
app_window.open_settings();
|
||||
let app_window = app_window.clone();
|
||||
app_window.open_settings()
|
||||
})
|
||||
.build();
|
||||
app.add_action_entries([action]);
|
||||
|
@ -109,28 +110,7 @@ fn main() {
|
|||
|
||||
let config = load_config(&app_id);
|
||||
|
||||
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);
|
||||
let core = Core::new(config.clone());
|
||||
|
||||
spawn({
|
||||
let notifier = core.subscribe();
|
||||
|
@ -138,70 +118,22 @@ fn main() {
|
|||
handler(notifier, app_id)
|
||||
});
|
||||
|
||||
/*
|
||||
let core_handle = runtime.spawn({
|
||||
let core = core.clone();
|
||||
async move {
|
||||
core.run().await;
|
||||
}
|
||||
});
|
||||
*/
|
||||
|
||||
let app = adw::Application::builder()
|
||||
.application_id("com.luminescent-dreams.kifu-gtk")
|
||||
.resource_base_path("/com/luminescent-dreams/kifu-gtk")
|
||||
.build();
|
||||
|
||||
app.connect_activate({
|
||||
let runtime = runtime.clone();
|
||||
move |app| {
|
||||
let mut app_window = AppWindow::new(app, core.clone());
|
||||
|
||||
match *core.library() {
|
||||
Some(_) => {}
|
||||
None => app_window.open_settings(),
|
||||
}
|
||||
let core_api = CoreApi { core: core.clone() };
|
||||
let app_window = AppWindow::new(app, core_api);
|
||||
|
||||
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();
|
||||
|
||||
/*
|
||||
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");
|
||||
app.run();
|
||||
|
||||
/* let _ = runtime.block_on(core_handle); */
|
||||
}
|
||||
|
|
|
@ -16,18 +16,22 @@ You should have received a copy of the GNU General Public License along with Kif
|
|||
|
||||
use crate::LocalObserver;
|
||||
use kifu_core::{Core, CoreNotification};
|
||||
use crate::CoreApi;
|
||||
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.
|
||||
#[derive(Clone)]
|
||||
pub struct HomeViewModel {
|
||||
core: Core,
|
||||
/*
|
||||
core: CoreApi,
|
||||
notification_observer: Arc<LocalObserver<CoreNotification>>,
|
||||
widget: gtk::Box,
|
||||
*/
|
||||
}
|
||||
|
||||
impl HomeViewModel {
|
||||
pub fn new(core: Core) -> Self {
|
||||
pub fn new(core: CoreApi) -> Self {
|
||||
/*
|
||||
let notification_observer = LocalObserver::new(&core, |msg| {
|
||||
println!("HomeViewModel handler called with message: {:?}", msg)
|
||||
});
|
||||
|
@ -37,6 +41,8 @@ impl HomeViewModel {
|
|||
notification_observer: Arc::new(notification_observer),
|
||||
widget: gtk::Box::new(gtk::Orientation::Horizontal, 0),
|
||||
}
|
||||
*/
|
||||
Self {}
|
||||
}
|
||||
|
||||
/// Create a new game with the given parameters.
|
||||
|
|
|
@ -28,6 +28,3 @@ pub use game_review_view_model::GameReviewViewModel;
|
|||
|
||||
mod home_view_model;
|
||||
pub use home_view_model::HomeViewModel;
|
||||
|
||||
mod settings_view_model;
|
||||
pub use settings_view_model::SettingsViewModel;
|
||||
|
|
|
@ -1,73 +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::{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,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,208 @@
|
|||
/*
|
||||
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(>k::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(),
|
||||
})
|
||||
}
|
||||
*/
|
|
@ -1,2 +1,5 @@
|
|||
mod home;
|
||||
pub use home::HomeView;
|
||||
|
||||
mod settings;
|
||||
pub use settings::SettingsView;
|
||||
|
|
|
@ -11,6 +11,7 @@ nom = { version = "7" }
|
|||
serde = { version = "1", features = [ "derive" ] }
|
||||
thiserror = { version = "1"}
|
||||
typeshare = { version = "1" }
|
||||
uuid = { version = "0.8", features = ["v4", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cool_asserts = { version = "2" }
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
use sgf::parse_sgf_file;
|
||||
use std::path::PathBuf;
|
||||
use std::env;
|
||||
|
||||
fn main() {
|
||||
let mut args = env::args();
|
||||
|
||||
let _ = args.next();
|
||||
let file = PathBuf::from(args.next().unwrap());
|
||||
|
||||
println!("{:?}", file);
|
||||
|
||||
let games = parse_sgf_file(&file).unwrap();
|
||||
for sgf in games {
|
||||
if let Ok(sgf) = sgf {
|
||||
println!("{:?}", sgf.white_player);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,820 @@
|
|||
use crate::{
|
||||
parser::{self, Annotation, Evaluation, Move, SetupInstr, Size, UnknownProperty},
|
||||
Color, Date, GameResult, GameType,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::HashSet, time::Duration};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameError {
|
||||
InvalidGame,
|
||||
RequiredPropertiesMissing,
|
||||
InvalidGameNode(GameNodeError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum MoveNodeError {
|
||||
IncompatibleProperty(parser::Property),
|
||||
ConflictingProperty,
|
||||
NotAMoveNode,
|
||||
ChildError(Box<GameNodeError>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SetupNodeError {
|
||||
IncompatibleProperty(parser::Property),
|
||||
ConflictingProperty,
|
||||
ConflictingPosition,
|
||||
NotASetupNode,
|
||||
ChildError(Box<GameNodeError>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameNodeError {
|
||||
UnsupportedGameNode(MoveNodeError, SetupNodeError),
|
||||
ConflictingProperty,
|
||||
ConflictingPosition,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
|
||||
pub struct Player {
|
||||
pub name: Option<String>,
|
||||
pub rank: Option<String>,
|
||||
pub team: Option<String>,
|
||||
}
|
||||
|
||||
/// This represents the more semantic version of the game parser. Where the `parser` crate pulls
|
||||
/// out a raw set of nodes, this structure is guaranteed to be a well-formed game. Getting to this
|
||||
/// level, the interpreter will reject any games that have setup properties and move properties
|
||||
/// mixed in a single node. If there are other semantic problems, the interpreter will reject
|
||||
/// those, as well. Where the function of the parser is to understand and correct fundamental
|
||||
/// syntax issues, the result of the Game is to have a fully-understood game. However, this doesn't
|
||||
/// (yet?) go quite to the level of apply the game type (i.e., this is Go, Chess, Yinsh, or
|
||||
/// whatever).
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Game {
|
||||
pub game_type: GameType,
|
||||
|
||||
// TODO: board size is not necessary in all games. Hive has no defined board size.
|
||||
pub board_size: Size,
|
||||
pub black_player: Player,
|
||||
pub white_player: Player,
|
||||
|
||||
pub app: Option<String>,
|
||||
pub annotator: Option<String>,
|
||||
pub copyright: Option<String>,
|
||||
pub dates: Vec<Date>,
|
||||
pub event: Option<String>,
|
||||
pub game_name: Option<String>,
|
||||
pub extra_info: Option<String>,
|
||||
pub opening_info: Option<String>,
|
||||
pub location: Option<String>,
|
||||
pub result: Option<GameResult>,
|
||||
pub round: Option<String>,
|
||||
pub rules: Option<String>,
|
||||
pub source: Option<String>,
|
||||
pub time_limit: Option<Duration>,
|
||||
pub overtime: Option<String>,
|
||||
pub transcriber: Option<String>,
|
||||
|
||||
pub children: Vec<GameNode>,
|
||||
}
|
||||
|
||||
impl Game {
|
||||
pub fn new(
|
||||
game_type: GameType,
|
||||
board_size: Size,
|
||||
black_player: Player,
|
||||
white_player: Player,
|
||||
) -> Self {
|
||||
Self {
|
||||
game_type,
|
||||
board_size,
|
||||
black_player,
|
||||
white_player,
|
||||
|
||||
app: None,
|
||||
annotator: None,
|
||||
copyright: None,
|
||||
dates: vec![],
|
||||
event: None,
|
||||
game_name: None,
|
||||
extra_info: None,
|
||||
opening_info: None,
|
||||
location: None,
|
||||
result: None,
|
||||
round: None,
|
||||
rules: None,
|
||||
source: None,
|
||||
time_limit: None,
|
||||
overtime: None,
|
||||
transcriber: None,
|
||||
|
||||
children: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for Game {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode {
|
||||
self.children.push(node);
|
||||
self.children.last_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Tree> for Game {
|
||||
type Error = GameError;
|
||||
|
||||
fn try_from(tree: &parser::Tree) -> Result<Self, Self::Error> {
|
||||
let mut ty = None;
|
||||
let mut size = None;
|
||||
let mut black_player = Player {
|
||||
name: None,
|
||||
rank: None,
|
||||
team: None,
|
||||
};
|
||||
let mut white_player = Player {
|
||||
name: None,
|
||||
rank: None,
|
||||
team: None,
|
||||
};
|
||||
|
||||
for prop in tree.root.properties.iter() {
|
||||
match prop {
|
||||
parser::Property::GameType(ty_) => ty = Some(ty_.clone()),
|
||||
parser::Property::BoardSize(size_) => size = Some(size_.clone()),
|
||||
parser::Property::BlackPlayer(name) => {
|
||||
black_player.name = Some(name.clone());
|
||||
}
|
||||
parser::Property::WhitePlayer(name) => {
|
||||
white_player.name = Some(name.clone());
|
||||
}
|
||||
parser::Property::BlackRank(rank) => {
|
||||
black_player.rank = Some(rank.clone());
|
||||
}
|
||||
parser::Property::WhiteRank(rank) => {
|
||||
white_player.rank = Some(rank.clone());
|
||||
}
|
||||
parser::Property::BlackTeam(team) => {
|
||||
black_player.team = Some(team.clone());
|
||||
}
|
||||
parser::Property::WhiteTeam(team) => {
|
||||
white_player.team = Some(team.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let mut s = match (ty, size) {
|
||||
(Some(ty), Some(size)) => Ok(Self::new(ty, size, black_player, white_player)),
|
||||
_ => Err(Self::Error::RequiredPropertiesMissing),
|
||||
}?;
|
||||
|
||||
for prop in tree.root.properties.iter() {
|
||||
match prop {
|
||||
parser::Property::GameType(_)
|
||||
| parser::Property::BoardSize(_)
|
||||
| parser::Property::BlackPlayer(_)
|
||||
| parser::Property::WhitePlayer(_)
|
||||
| parser::Property::BlackRank(_)
|
||||
| parser::Property::WhiteRank(_)
|
||||
| parser::Property::BlackTeam(_)
|
||||
| parser::Property::WhiteTeam(_) => {}
|
||||
parser::Property::Application(v) => s.app = Some(v.clone()),
|
||||
parser::Property::Annotator(v) => s.annotator = Some(v.clone()),
|
||||
parser::Property::Copyright(v) => s.copyright = Some(v.clone()),
|
||||
parser::Property::EventDates(v) => s.dates = v.clone(),
|
||||
parser::Property::EventName(v) => s.event = Some(v.clone()),
|
||||
parser::Property::GameName(v) => s.game_name = Some(v.clone()),
|
||||
parser::Property::ExtraGameInformation(v) => s.extra_info = Some(v.clone()),
|
||||
parser::Property::GameOpening(v) => s.opening_info = Some(v.clone()),
|
||||
parser::Property::GameLocation(v) => s.location = Some(v.clone()),
|
||||
parser::Property::Result(v) => s.result = Some(v.clone()),
|
||||
parser::Property::Round(v) => s.round = Some(v.clone()),
|
||||
parser::Property::Ruleset(v) => s.rules = Some(v.clone()),
|
||||
parser::Property::Source(v) => s.source = Some(v.clone()),
|
||||
parser::Property::TimeLimit(v) => s.time_limit = Some(v.clone()),
|
||||
parser::Property::Overtime(v) => s.overtime = Some(v.clone()),
|
||||
// parser::Property::Data(v) => s.transcriber = Some(v.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
s.children = tree
|
||||
.root
|
||||
.next
|
||||
.iter()
|
||||
.map(|node| GameNode::try_from(node))
|
||||
.collect::<Result<Vec<GameNode>, GameNodeError>>()
|
||||
.map_err(GameError::InvalidGameNode)?;
|
||||
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum GameNode {
|
||||
MoveNode(MoveNode),
|
||||
SetupNode(SetupNode),
|
||||
}
|
||||
|
||||
pub trait Node {
|
||||
/// Provide a pre-order traversal of all of the nodes in the game tree.
|
||||
fn nodes<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children()
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let mut children = node.nodes();
|
||||
let mut v = vec![*node];
|
||||
v.append(&mut children);
|
||||
v
|
||||
})
|
||||
.flatten()
|
||||
.collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode>;
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode;
|
||||
}
|
||||
|
||||
impl GameNode {
|
||||
pub fn id(&self) -> Uuid {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.id,
|
||||
GameNode::SetupNode(node) => node.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for GameNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.children(),
|
||||
GameNode::SetupNode(node) => node.children(),
|
||||
}
|
||||
}
|
||||
|
||||
fn nodes<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.nodes(),
|
||||
GameNode::SetupNode(node) => node.nodes(),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, new_node: GameNode) -> &'a mut GameNode {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.add_child(new_node),
|
||||
GameNode::SetupNode(node) => node.add_child(new_node),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for GameNode {
|
||||
type Error = GameNodeError;
|
||||
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
// I originally wrote this recursively. However, on an ordinary game of a couple hundred
|
||||
// moves, that meant that I was recursing 500 functions, and that exceeded the stack limit.
|
||||
// So, instead, I need to unroll everything to non-recursive form.
|
||||
//
|
||||
// So, I can treat each branch of the tree as a single line. Iterate over that line. I can
|
||||
// only use the MoveNode::try_from and SetupNode::try_from if those functions don't
|
||||
// recurse. Instead, I'm going to process just that node, then return to here and process
|
||||
// the children.
|
||||
let move_node = MoveNode::try_from(n);
|
||||
let setup_node = SetupNode::try_from(n);
|
||||
|
||||
// I'm much too tired when writing this. I'm still recursing, but I did cut the number of
|
||||
// recursions in half. This helps, but it still doesn't guarantee that I'm going to be able
|
||||
// to parse all possible games. So, still, treat each branch of the game as a single line.
|
||||
// Iterate over that line, don't recurse. Create bookmarks at each branch point, and then
|
||||
// come back to each one.
|
||||
let children = n
|
||||
.next
|
||||
.iter()
|
||||
.map(|n| GameNode::try_from(n))
|
||||
.collect::<Result<Vec<Self>, Self::Error>>()?;
|
||||
|
||||
let node = match (move_node, setup_node) {
|
||||
(Ok(mut node), _) => {
|
||||
node.children = children;
|
||||
Ok(Self::MoveNode(node))
|
||||
}
|
||||
(Err(_), Ok(mut node)) => {
|
||||
node.children = children;
|
||||
Ok(Self::SetupNode(node))
|
||||
}
|
||||
(Err(move_err), Err(setup_err)) => {
|
||||
Err(Self::Error::UnsupportedGameNode(move_err, setup_err))
|
||||
}
|
||||
}?;
|
||||
|
||||
Ok(node)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub struct MoveNode {
|
||||
id: Uuid,
|
||||
color: Color,
|
||||
mv: Move,
|
||||
children: Vec<GameNode>,
|
||||
|
||||
time_left: Option<Duration>,
|
||||
moves_left: Option<usize>,
|
||||
name: Option<String>,
|
||||
evaluation: Option<Evaluation>,
|
||||
value: Option<f64>,
|
||||
comments: Option<String>,
|
||||
annotation: Option<Annotation>,
|
||||
unknown_props: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl MoveNode {
|
||||
pub fn new(color: Color, mv: Move) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4(),
|
||||
color,
|
||||
mv,
|
||||
children: Vec::new(),
|
||||
|
||||
time_left: None,
|
||||
moves_left: None,
|
||||
name: None,
|
||||
evaluation: None,
|
||||
value: None,
|
||||
comments: None,
|
||||
annotation: None,
|
||||
unknown_props: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for MoveNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode {
|
||||
self.children.push(node);
|
||||
self.children.last_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for MoveNode {
|
||||
type Error = MoveNodeError;
|
||||
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
let s = match n.mv() {
|
||||
Some((color, mv)) => {
|
||||
let mut s = Self::new(color, mv);
|
||||
|
||||
for prop in n.properties.iter() {
|
||||
match prop {
|
||||
parser::Property::Move((color, mv)) => {
|
||||
if s.color != *color || s.mv != *mv {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
}
|
||||
parser::Property::TimeLeft((color, duration)) => {
|
||||
if s.color != *color {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
if s.time_left.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.time_left = Some(duration.clone());
|
||||
}
|
||||
parser::Property::Comment(cmt) => {
|
||||
if s.comments.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.comments = Some(cmt.clone());
|
||||
}
|
||||
parser::Property::Evaluation(evaluation) => {
|
||||
if s.evaluation.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.evaluation = Some(*evaluation)
|
||||
}
|
||||
parser::Property::Annotation(annotation) => {
|
||||
if s.annotation.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.annotation = Some(*annotation)
|
||||
}
|
||||
parser::Property::Territory(..) => {
|
||||
eprintln!("not processing territory property");
|
||||
}
|
||||
parser::Property::Unknown(UnknownProperty { ident, value }) => {
|
||||
s.unknown_props.push((ident.clone(), value.clone()));
|
||||
}
|
||||
_ => return Err(Self::Error::IncompatibleProperty(prop.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(s)
|
||||
}
|
||||
None => Err(Self::Error::NotAMoveNode),
|
||||
}?;
|
||||
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub struct SetupNode {
|
||||
id: Uuid,
|
||||
|
||||
positions: Vec<parser::SetupInstr>,
|
||||
children: Vec<GameNode>,
|
||||
}
|
||||
|
||||
impl SetupNode {
|
||||
pub fn new(positions: Vec<parser::SetupInstr>) -> Result<Self, SetupNodeError> {
|
||||
let mut board = HashSet::new();
|
||||
for position in positions.iter() {
|
||||
let point = match position {
|
||||
SetupInstr::Piece((_, point)) => point,
|
||||
SetupInstr::Clear(point) => point,
|
||||
};
|
||||
if board.contains(point) {
|
||||
return Err(SetupNodeError::ConflictingPosition);
|
||||
}
|
||||
board.insert(point);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
id: Uuid::new_v4(),
|
||||
positions,
|
||||
children: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for SetupNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn add_child<'a>(&'a mut self, _node: GameNode) -> &'a mut GameNode {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for SetupNode {
|
||||
type Error = SetupNodeError;
|
||||
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
match n.setup() {
|
||||
Some(elements) => Self::new(elements),
|
||||
None => Err(Self::Error::NotASetupNode),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn path_to_node<'a>(node: &'a GameNode, id: Uuid) -> Vec<&'a GameNode> {
|
||||
if node.id() == id {
|
||||
return vec![node];
|
||||
}
|
||||
|
||||
for child in node.children() {
|
||||
let mut path = path_to_node(child, id);
|
||||
if path.len() > 1 {
|
||||
path.push(child);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
#[test]
|
||||
fn it_can_create_an_empty_game_tree() {
|
||||
let tree = Game::new(
|
||||
GameType::Go,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19,
|
||||
},
|
||||
Player::default(),
|
||||
Player::default(),
|
||||
);
|
||||
assert_eq!(tree.nodes().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_add_moves_to_a_game() {
|
||||
let mut game = Game::new(
|
||||
GameType::Go,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19,
|
||||
},
|
||||
Player::default(),
|
||||
Player::default(),
|
||||
);
|
||||
|
||||
let first_move = MoveNode::new(Color::Black, Move::Move("dd".to_owned()));
|
||||
let first_ = game.add_child(GameNode::MoveNode(first_move.clone()));
|
||||
let second_move = MoveNode::new(Color::White, Move::Move("qq".to_owned()));
|
||||
first_.add_child(GameNode::MoveNode(second_move.clone()));
|
||||
|
||||
let nodes = game.nodes();
|
||||
assert_eq!(nodes.len(), 2);
|
||||
assert_eq!(nodes[0].id(), first_move.id);
|
||||
assert_eq!(nodes[1].id(), second_move.id);
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_can_set_up_a_game() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_can_load_tree_from_sgf() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn game_node_can_parse_sgf_move_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::Comment("Comments in the game".to_owned()),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(GameNode::try_from(&n), Ok(GameNode::MoveNode(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod root_node_tests {
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_rejects_move_properties() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_rejects_setup_properties() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_can_parse_a_root_sgf() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod move_node_tests {
|
||||
use crate::parser::PositionList;
|
||||
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_an_sgf_move_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::Comment("Comments in the game".to_owned()),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(MoveNode::try_from(&n), Ok(node) => {
|
||||
assert_eq!(node.color, Color::White);
|
||||
assert_eq!(node.mv, Move::Move("dp".to_owned()));
|
||||
assert_eq!(node.children, vec![]);
|
||||
assert_eq!(node.time_left, Some(Duration::from_secs(176)));
|
||||
assert_eq!(node.comments, Some("Comments in the game".to_owned()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_rejects_an_sgf_setup_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::SetupBlackStones(PositionList(vec![
|
||||
"dd".to_owned(),
|
||||
"de".to_owned(),
|
||||
])),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(
|
||||
MoveNode::try_from(&n),
|
||||
Err(MoveNodeError::IncompatibleProperty(_))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod setup_node_tests {
|
||||
use crate::parser::SetupInstr;
|
||||
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn it_can_parse_an_sgf_setup_node() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_rejects_conflicting_placement_properties() {
|
||||
assert_matches!(
|
||||
SetupNode::new(vec![
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
]),
|
||||
Err(SetupNodeError::ConflictingPosition)
|
||||
);
|
||||
assert_matches!(
|
||||
SetupNode::new(vec![
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
SetupInstr::Piece((Color::Black, "ee".to_owned())),
|
||||
SetupInstr::Piece((Color::White, "ee".to_owned())),
|
||||
]),
|
||||
Err(SetupNodeError::ConflictingPosition)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod path_test {
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn returns_empty_list_if_no_game_nodes() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn returns_empty_list_if_node_not_found() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn path_excludes_root_node() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod file_test {
|
||||
use super::*;
|
||||
use crate::Win;
|
||||
use cool_asserts::assert_matches;
|
||||
use parser::parse_collection;
|
||||
use std::{fs::File, io::Read};
|
||||
|
||||
fn with_text(text: &str, f: impl FnOnce(Vec<Game>)) {
|
||||
let (_, games) = parse_collection::<nom::error::VerboseError<&str>>(text).unwrap();
|
||||
let games = games
|
||||
.into_iter()
|
||||
.map(|game| Game::try_from(&game).expect("game to parse"))
|
||||
.collect::<Vec<Game>>();
|
||||
f(games);
|
||||
}
|
||||
|
||||
fn with_file(path: &std::path::Path, f: impl FnOnce(Vec<Game>)) {
|
||||
let mut file = File::open(path).unwrap();
|
||||
let mut text = String::new();
|
||||
let _ = file.read_to_string(&mut text);
|
||||
with_text(&text, f);
|
||||
}
|
||||
|
||||
/// This test checks against an ordinary game from SGF. It is unannotated and should contain
|
||||
/// only move nodes with no setup nodes. The original source is from a game I played on KGS.
|
||||
#[test]
|
||||
fn it_can_load_an_ordinary_unannotated_game() {
|
||||
with_file(
|
||||
std::path::Path::new("test_data/2020 USGO DDK, Round 1.sgf"),
|
||||
|games| {
|
||||
assert_eq!(games.len(), 1);
|
||||
let game = &games[0];
|
||||
|
||||
assert_eq!(game.game_type, GameType::Go);
|
||||
assert_eq!(
|
||||
game.board_size,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
game.black_player,
|
||||
Player {
|
||||
name: Some("savanni".to_owned()),
|
||||
rank: Some("23k".to_owned()),
|
||||
team: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
game.white_player,
|
||||
Player {
|
||||
name: Some("Geckoz".to_owned()),
|
||||
rank: None,
|
||||
team: None
|
||||
}
|
||||
);
|
||||
assert_eq!(game.app, Some("CGoban:3".to_owned()));
|
||||
|
||||
assert_eq!(game.annotator, None);
|
||||
assert_eq!(game.copyright, None);
|
||||
assert_eq!(
|
||||
game.dates,
|
||||
vec![Date::Date(
|
||||
chrono::NaiveDate::from_ymd_opt(2020, 8, 5).unwrap()
|
||||
)]
|
||||
);
|
||||
assert_eq!(game.event, None);
|
||||
assert_eq!(game.game_name, None);
|
||||
assert_eq!(game.extra_info, None);
|
||||
assert_eq!(game.opening_info, None);
|
||||
assert_eq!(
|
||||
game.location,
|
||||
Some("The KGS Go Server at http://www.gokgs.com/".to_owned())
|
||||
);
|
||||
assert_eq!(game.result, Some(GameResult::White(Win::Score(17.5))));
|
||||
assert_eq!(game.round, None);
|
||||
assert_eq!(game.rules, Some("AGA".to_owned()));
|
||||
assert_eq!(game.source, None);
|
||||
assert_eq!(game.time_limit, Some(Duration::from_secs(1800)));
|
||||
assert_eq!(game.overtime, Some("5x30 byo-yomi".to_owned()));
|
||||
assert_eq!(game.transcriber, None);
|
||||
|
||||
/*
|
||||
Property {
|
||||
ident: "KM".to_owned(),
|
||||
values: vec!["7.50".to_owned()],
|
||||
},
|
||||
];
|
||||
|
||||
for i in 0..16 {
|
||||
assert_eq!(node.properties[i], expected_properties[i]);
|
||||
}
|
||||
*/
|
||||
|
||||
let children = game.children();
|
||||
let node = children.first().unwrap();
|
||||
assert_matches!(node, GameNode::MoveNode(node) => {
|
||||
assert_eq!(node.color, Color::Black);
|
||||
assert_eq!(node.mv, Move::Move("pp".to_owned()));
|
||||
assert_eq!(node.time_left, Some(Duration::from_secs(1795)));
|
||||
assert_eq!(node.comments, Some("Geckoz [?]: Good game\nsavanni [23k?]: There we go! This UI is... tough.\nsavanni [23k?]: Have fun! Talk to you at the end.\nGeckoz [?]: Yeah, OGS is much better; I'm a UX professional\n".to_owned())
|
||||
)});
|
||||
|
||||
let children = node.children();
|
||||
let node = children.first().unwrap();
|
||||
assert_matches!(node, GameNode::MoveNode(node) => {
|
||||
assert_eq!(node.color, Color::White);
|
||||
assert_eq!(node.mv, Move::Move("dp".to_owned()));
|
||||
assert_eq!(node.time_left, Some(Duration::from_secs(1765)));
|
||||
assert_eq!(node.comments, None);
|
||||
});
|
||||
/*
|
||||
let node = node.next().unwrap();
|
||||
let expected_properties = vec![
|
||||
Property {
|
||||
ident: "W".to_owned(),
|
||||
values: vec!["dp".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "WL".to_owned(),
|
||||
values: vec!["1765.099".to_owned()],
|
||||
},
|
||||
];
|
||||
for i in 0..2 {
|
||||
assert_eq!(node.properties[i], expected_properties[i]);
|
||||
}
|
||||
*/
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,12 +1,13 @@
|
|||
mod date;
|
||||
pub use date::Date;
|
||||
|
||||
mod game;
|
||||
mod parser;
|
||||
pub use parser::parse_collection;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
mod types;
|
||||
|
||||
use std::{fs::File, io::Read};
|
||||
pub use date::Date;
|
||||
pub use game::Game;
|
||||
pub use parser::parse_collection;
|
||||
use thiserror::Error;
|
||||
pub use types::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -57,6 +58,41 @@ impl From<nom::error::Error<&str>> for ParseError {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn parse_sgf(_input: &str) -> Result<Vec<Game>, Error> {
|
||||
Ok(vec![Game::default()])
|
||||
pub fn parse_sgf(input: &str) -> Result<Vec<Result<Game, game::GameError>>, Error> {
|
||||
let (_, games) = parse_collection::<nom::error::VerboseError<&str>>(&input)?;
|
||||
let games = games.into_iter()
|
||||
.map(|game| Game::try_from(&game))
|
||||
.collect::<Vec<Result<Game, game::GameError>>>();
|
||||
|
||||
Ok(games)
|
||||
}
|
||||
|
||||
pub fn parse_sgf_file(path: &std::path::Path) -> Result<Vec<Result<Game, game::GameError>>, Error> {
|
||||
let mut file = File::open(path).unwrap();
|
||||
let mut text = String::new();
|
||||
let _ = file.read_to_string(&mut text);
|
||||
|
||||
parse_sgf(&text)
|
||||
}
|
||||
|
||||
/*
|
||||
pub fn parse_sgf(_input: &str) -> Result<Vec<Game>, Error> {
|
||||
Ok(vec![Game::new(
|
||||
GameType::Go,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19,
|
||||
},
|
||||
Player {
|
||||
name: None,
|
||||
rank: None,
|
||||
team: None,
|
||||
},
|
||||
Player {
|
||||
name: None,
|
||||
rank: None,
|
||||
team: None,
|
||||
},
|
||||
)])
|
||||
}
|
||||
*/
|
||||
|
|
|
@ -9,6 +9,7 @@ use nom::{
|
|||
multi::{many0, many1, separated_list1},
|
||||
IResult, Parser,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{num::ParseIntError, time::Duration};
|
||||
|
||||
impl From<ParseSizeError> for Error {
|
||||
|
@ -29,7 +30,7 @@ impl From<ParseIntError> for ParseSizeError {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Annotation {
|
||||
BadMove,
|
||||
DoubtfulMove,
|
||||
|
@ -37,7 +38,7 @@ pub enum Annotation {
|
|||
Tesuji,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Evaluation {
|
||||
Even,
|
||||
GoodForBlack,
|
||||
|
@ -147,7 +148,7 @@ impl ToString for GameType {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Size {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
|
@ -200,7 +201,7 @@ pub struct Node {
|
|||
pub next: Vec<Node>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum SetupInstr {
|
||||
Piece((Color, String)),
|
||||
Clear(String),
|
||||
|
@ -288,7 +289,7 @@ impl ToString for Node {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Move {
|
||||
Move(String),
|
||||
Pass,
|
||||
|
|
|
@ -1,26 +1,9 @@
|
|||
use crate::date::Date;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// This is a placeholder structure. It is not meant to represent a game, only to provide a mock
|
||||
/// interface for code already written that expects a Game data type to exist.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Game {
|
||||
pub info: GameInfo,
|
||||
}
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct GameInfo {
|
||||
pub black_player: Option<String>,
|
||||
pub black_rank: Option<String>,
|
||||
pub white_player: Option<String>,
|
||||
pub white_rank: Option<String>,
|
||||
pub result: Option<GameResult>,
|
||||
pub game_name: Option<String>,
|
||||
pub date: Vec<Date>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum GameType {
|
||||
Go,
|
||||
Othello,
|
||||
|
@ -113,7 +96,7 @@ impl From<nom::error::Error<&str>> for ParseError {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Color {
|
||||
Black,
|
||||
White,
|
||||
|
@ -129,7 +112,7 @@ impl Color {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub enum GameResult {
|
||||
Draw,
|
||||
Black(Win),
|
||||
|
@ -138,6 +121,18 @@ pub enum GameResult {
|
|||
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 {
|
||||
type Error = String;
|
||||
fn try_from(s: &str) -> Result<GameResult, Self::Error> {
|
||||
|
@ -165,7 +160,7 @@ impl TryFrom<&str> for GameResult {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Win {
|
||||
Score(f32),
|
||||
Resignation,
|
||||
|
|
Loading…
Reference in New Issue