use crate::minimal::Minimal;
use anyhow::Error;
use rat_salsa::event::RenderedEvent;
use rat_salsa::poll::{PollCrossterm, PollRendered, PollTasks, PollTimers};
use rat_salsa::timer::TimeOut;
use rat_salsa::{Control, RunConfig, SalsaAppContext, SalsaContext, run_tui};
use rat_theme4::create_salsa_theme;
use rat_theme4::theme::SalsaTheme;
use rat_widget::event::{ConsumedEvent, Dialog, HandleEvent, Regular, ct_event};
use rat_widget::focus::FocusBuilder;
use rat_widget::msgdialog::{MsgDialog, MsgDialogState};
use rat_widget::statusline::{StatusLine, StatusLineState};
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Layout, Rect};
use ratatui_core::widgets::StatefulWidget;
use ratatui_crossterm::crossterm::event::Event;
use std::fs;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
fn main() -> Result<(), Error> {
setup_logging()?;
let config = Config::default();
let theme = create_salsa_theme("Imperial Dark");
let mut global = Global::new(config, theme);
let mut state = Scenery::default();
run_tui(
init,
render,
event,
error,
&mut global,
&mut state,
RunConfig::inline(10, true)?
.poll(PollCrossterm)
.poll(PollTimers::default())
.poll(PollTasks::default())
.poll(PollRendered),
)?;
Ok(())
}
pub struct Global {
ctx: SalsaAppContext<AppEvent, Error>,
pub cfg: Config,
pub theme: SalsaTheme,
}
impl SalsaContext<AppEvent, Error> for Global {
fn set_salsa_ctx(&mut self, app_ctx: SalsaAppContext<AppEvent, Error>) {
self.ctx = app_ctx;
}
#[inline(always)]
fn salsa_ctx(&self) -> &SalsaAppContext<AppEvent, Error> {
&self.ctx
}
}
impl Global {
pub fn new(cfg: Config, theme: SalsaTheme) -> Self {
Self {
ctx: Default::default(),
cfg,
theme,
}
}
}
#[derive(Debug, Default)]
pub struct Config {}
#[derive(Debug)]
pub enum AppEvent {
Timer(TimeOut),
Event(Event),
Rendered,
Message(String),
Status(usize, String),
}
impl From<RenderedEvent> for AppEvent {
fn from(_: RenderedEvent) -> Self {
Self::Rendered
}
}
impl From<TimeOut> for AppEvent {
fn from(value: TimeOut) -> Self {
Self::Timer(value)
}
}
impl From<Event> for AppEvent {
fn from(value: Event) -> Self {
Self::Event(value)
}
}
#[derive(Debug, Default)]
pub struct Scenery {
pub minimal: Minimal,
pub status: StatusLineState,
pub error_dlg: MsgDialogState,
}
pub fn render(
area: Rect,
buf: &mut Buffer,
state: &mut Scenery,
ctx: &mut Global,
) -> Result<(), Error> {
let t0 = SystemTime::now();
minimal::render(area, buf, &mut state.minimal, ctx)?;
let layout = Layout::vertical([
Constraint::Length(1),
Constraint::Fill(1), ])
.split(area);
if state.error_dlg.active() {
MsgDialog::new().render(layout[1], buf, &mut state.error_dlg);
}
let el = t0.elapsed().unwrap_or(Duration::from_nanos(0));
state.status.status(1, format!("R {:.0?}", el).to_string());
let status_layout = Layout::horizontal([
Constraint::Fill(61), Constraint::Fill(39),
])
.split(layout[0]);
StatusLine::new()
.layout([
Constraint::Fill(1),
Constraint::Length(8),
Constraint::Length(8),
])
.render(status_layout[1], buf, &mut state.status);
Ok(())
}
pub fn init(state: &mut Scenery, ctx: &mut Global) -> Result<(), Error> {
ctx.set_focus(FocusBuilder::build_for(&state.minimal));
minimal::init(&mut state.minimal, ctx)?;
Ok(())
}
pub fn event(
event: &AppEvent,
state: &mut Scenery,
ctx: &mut Global,
) -> Result<Control<AppEvent>, Error> {
let t0 = SystemTime::now();
let mut r = match event {
AppEvent::Event(event) => {
let mut r = match &event {
ct_event!(resized) => Control::Changed,
ct_event!(key press CONTROL-'q') => Control::Quit,
_ => Control::Continue,
};
r = r.or_else(|| {
if state.error_dlg.active() {
state.error_dlg.handle(event, Dialog).into()
} else {
Control::Continue
}
});
let f = ctx.focus_mut().handle(event, Regular);
ctx.queue(f);
r
}
AppEvent::Rendered => {
ctx.set_focus(FocusBuilder::rebuild_for(&state.minimal, ctx.take_focus()));
Control::Continue
}
AppEvent::Message(s) => {
state.error_dlg.append(s.as_str());
Control::Changed
}
AppEvent::Status(n, s) => {
state.status.status(*n, s);
Control::Changed
}
_ => Control::Continue,
};
r = r.or_else_try(|| minimal::event(event, &mut state.minimal, ctx))?;
let el = t0.elapsed()?;
state.status.status(2, format!("E {:.0?}", el).to_string());
Ok(r)
}
pub fn error(
event: Error,
state: &mut Scenery,
_ctx: &mut Global,
) -> Result<Control<AppEvent>, Error> {
state.error_dlg.append(format!("{:?}", &*event).as_str());
Ok(Control::Changed)
}
pub mod minimal {
use crate::{AppEvent, Global};
use anyhow::Error;
use rat_salsa::{Control, SalsaContext};
use rat_theme4::StyleName;
use rat_theme4::WidgetStyle;
use rat_widget::event::{HandleEvent, MenuOutcome, Regular, try_flow};
use rat_widget::focus::impl_has_focus;
use rat_widget::menu::{MenuLine, MenuLineState};
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Layout, Rect};
use ratatui_core::style::Style;
use ratatui_core::text::{Line, Text};
use ratatui_core::widgets::{StatefulWidget, Widget};
#[derive(Debug, Default)]
pub struct Minimal {
pub menu: MenuLineState,
}
pub fn render(
area: Rect,
buf: &mut Buffer,
state: &mut Minimal,
ctx: &mut Global,
) -> Result<(), Error> {
let r = Layout::vertical([
Constraint::Length(1),
Constraint::Fill(1), ])
.split(area);
Text::from_iter([
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
Line::from("text text"),
])
.style(ctx.theme.style::<Style>(Style::CONTAINER_BASE))
.render(r[1], buf);
MenuLine::new()
.item_parsed("_First")
.item_parsed("_Second")
.item_parsed("_Third")
.item_parsed("_Quit")
.styles(ctx.theme.style(WidgetStyle::MENU))
.render(r[0], buf, &mut state.menu);
Ok(())
}
impl_has_focus!(menu for Minimal);
pub fn init(_state: &mut Minimal, ctx: &mut Global) -> Result<(), Error> {
ctx.focus().first();
Ok(())
}
#[allow(unused_variables)]
pub fn event(
event: &AppEvent,
state: &mut Minimal,
ctx: &mut Global,
) -> Result<Control<AppEvent>, Error> {
match event {
AppEvent::Event(event) => {
try_flow!(match state.menu.handle(event, Regular) {
MenuOutcome::Activated(3) => Control::Quit,
v => v.into(),
});
Ok(Control::Continue)
}
_ => Ok(Control::Continue),
}
}
}
fn setup_logging() -> Result<(), Error> {
let log_path = PathBuf::from(".");
let log_file = log_path.join("log.log");
_ = fs::remove_file(&log_file);
fern::Dispatch::new()
.format(|out, message, _record| {
out.finish(format_args!("{}", message)) })
.level(log::LevelFilter::Debug)
.chain(fern::log_file(&log_file)?)
.apply()?;
Ok(())
}