/* Copyright 2024, Savanni D'Gerinel 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 . */ use async_std::{channel::Receiver, task::yield_now}; use kifu_core::{Color, Core, CoreNotification, Goban, Observable, Player}; use std::{cell::RefCell, rc::Rc, time::Duration}; pub struct GameState { goban: Goban, white_clock: Duration, black_clock: Duration, white_score: f32, black_score: f32, current: Color, } struct GameViewModelPrivate { white: Player, /* Maybe this should be PlayerState, instead, combining the player info, current clock, and current captures. */ black: Player, state: GameState, } /// The Game View Model manages the current state of the game. It shows the two player cards, the board, the current capture count, the current player, and it maintains the UI for the clock (bearing in mind that the real clock is managed in the core). This view model should only be created once the details of the game, whether a game in progress or a new game (this view model won't know the difference) is known. pub struct GameViewModel { core: Core, notification_handler: glib::JoinHandle<()>, widget: gtk::Box, data: Rc>, } impl GameViewModelPrivate { fn handle(&mut self, message: CoreNotification) {} } impl GameViewModel { pub fn new(white: Player, black: Player, game: GameState, core: Core) -> Self { let data = Rc::new(RefCell::new(GameViewModelPrivate { white, black, state: game, })); let notification_handler = { let notifications = core.subscribe(); let data: Rc> = data.clone(); glib::spawn_future_local(Self::listen(notifications, data)) }; Self { core, notification_handler, widget: gtk::Box::new(gtk::Orientation::Horizontal, 0), data, } } async fn listen( notifications: Receiver, data: Rc>, ) { loop { match notifications.recv().await { Ok(msg) => data.borrow_mut().handle(msg), Err(err) => { unimplemented!("Should display an error message in the UI: {}", err) } } yield_now().await; } } } impl Drop for GameViewModel { fn drop(&mut self) { self.notification_handler.abort(); } }