monorepo/kifu/gtk/src/ui/game_database.rs

97 lines
2.8 KiB
Rust
Raw Normal View History

2023-08-20 00:46:43 +00:00
use glib::{Object, Properties};
use gtk::{glib, prelude::*, subclass::prelude::*};
use std::{cell::RefCell, rc::Rc};
#[derive(Default)]
pub struct IntegerObjectPrivate {
number: Rc<RefCell<i32>>,
}
#[glib::object_subclass]
impl ObjectSubclass for IntegerObjectPrivate {
const NAME: &'static str = "IntegerObject";
type Type = IntegerObject;
}
impl ObjectImpl for IntegerObjectPrivate {}
glib::wrapper! {
pub struct IntegerObject(ObjectSubclass<IntegerObjectPrivate>);
}
impl IntegerObject {
pub fn new(number: i32) -> Self {
let s: Self = Object::builder().build();
*s.imp().number.borrow_mut() = number;
s
}
pub fn number(&self) -> i32 {
self.imp().number.borrow().clone()
}
}
pub struct GameDatabasePrivate {
list_view: gtk::ListView,
}
impl Default for GameDatabasePrivate {
fn default() -> Self {
let vector: Vec<IntegerObject> = (0..=500).map(IntegerObject::new).collect();
let model = gio::ListStore::new(glib::types::Type::OBJECT);
model.extend_from_slice(&vector);
let factory = gtk::SignalListItemFactory::new();
factory.connect_setup(move |_, list_item| {
let label = gtk::Label::new(None);
list_item
.downcast_ref::<gtk::ListItem>()
.expect("Needs to be a ListItem")
.set_child(Some(&label));
});
factory.connect_bind(move |_, list_item| {
let integer_object = list_item
.downcast_ref::<gtk::ListItem>()
.expect("Needs to be ListItem")
.item()
.and_downcast::<IntegerObject>()
.expect("The item has to be an IntegerObject.");
let label = list_item
.downcast_ref::<gtk::ListItem>()
.expect("Needs to be ListItem")
.child()
.and_downcast::<gtk::Label>()
.expect("The child has to be an Label.");
label.set_label(&integer_object.number().to_string());
});
let selection_model = gtk::SingleSelection::new(Some(model));
let list_view = gtk::ListView::new(Some(selection_model), Some(factory));
Self { list_view }
}
}
#[glib::object_subclass]
impl ObjectSubclass for GameDatabasePrivate {
const NAME: &'static str = "GameDatabase";
type Type = GameDatabase;
type ParentType = gtk::Box;
}
impl ObjectImpl for GameDatabasePrivate {}
impl WidgetImpl for GameDatabasePrivate {}
impl BoxImpl for GameDatabasePrivate {}
glib::wrapper! {
pub struct GameDatabase(ObjectSubclass<GameDatabasePrivate>) @extends gtk::Widget, gtk::Box;
}
impl GameDatabase {
pub fn new() -> Self {
let s: Self = Object::builder().build();
s.append(&s.imp().list_view);
s
}
}