molehole/src/app.rs

83 lines
2.5 KiB
Rust
Raw Normal View History

2024-03-06 06:11:00 +00:00
use crossterm::event::Event;
2024-03-06 04:34:55 +00:00
use eyre::Result;
use ratatui::prelude::*;
use std::time::Duration;
2024-03-06 06:11:00 +00:00
use crate::app_event::AppEvent;
use crate::component::Component;
use crate::components;
2024-03-06 04:34:55 +00:00
use crate::tui;
pub struct App {
2024-03-06 06:11:00 +00:00
pub tui: tui::Tui,
2024-03-06 04:34:55 +00:00
pub tick_rate: Duration,
2024-03-06 06:11:00 +00:00
pub components: Vec<Box<dyn Component>>,
2024-03-06 04:34:55 +00:00
}
impl App {
2024-03-06 06:11:00 +00:00
pub fn new(tick_rate: Duration) -> Result<Self> {
let tui = tui::init()?;
let hello_world = components::hello_world::HelloWorld::default();
let hello_world1 = components::hello_world::HelloWorld::default();
let hello_world2 = components::hello_world::HelloWorld::default();
let hello_world3 = components::hello_world::HelloWorld::default();
2024-03-06 04:34:55 +00:00
Ok(Self {
2024-03-06 06:11:00 +00:00
tui,
2024-03-06 04:34:55 +00:00
tick_rate,
2024-03-06 06:11:00 +00:00
components: vec![
Box::new(hello_world),
Box::new(hello_world1),
Box::new(hello_world2),
Box::new(hello_world3),
],
2024-03-06 04:34:55 +00:00
})
}
pub fn run(&mut self) -> Result<()> {
2024-03-06 06:11:00 +00:00
loop {
let event: Option<AppEvent> = match tui::get_event(self.tick_rate)?
{
Some(event) => match event {
Event::Key(key) => Some(AppEvent::Key(key)),
Event::Mouse(mouse) => Some(AppEvent::Mouse(mouse)),
Event::FocusGained => todo!(),
Event::FocusLost => todo!(),
Event::Paste(_) => todo!(),
Event::Resize(_, _) => todo!(),
},
None => None,
};
if event.is_some() {
for component in self.components.iter_mut() {
let _ = component.handle_event(event.expect(""))?;
}
}
self.tui.draw(|frame| {
let layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
])
.split(frame.size());
for (i, component) in self.components.iter_mut().enumerate() {
let _ = component.render(frame, layout[i]);
}
})?;
}
2024-03-06 04:34:55 +00:00
}
pub fn quit(&mut self) -> Result<()> {
tui::restore()?;
Ok(())
}
}