mod run;
mod sender;
mod session;
use crate::Model;
use crate::backend::Backend;
use crate::clock::{Clock, RealClock};
use crate::color::ColorProfile;
use crate::environ::Environment;
use crate::exec::{Event, Executor, Item};
use crate::msg::{Error, Msg};
use crate::renderer::Renderer;
use crate::style::{WidthMethod, set_width_method};
use run::{Frames, Loop, Settings};
pub use sender::Sender;
pub(crate) use session::Session;
use std::fmt;
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;
const DEFAULT_FPS: u32 = 60;
const MAX_FPS: u32 = 120;
pub struct Program<M: Model> {
model: M,
events: mpsc::Sender<Event<M::Msg>>,
inbox: Receiver<Event<M::Msg>>,
fps: u32,
environment: Option<Environment>,
profile: Option<ColorProfile>,
suspend_key: bool,
accessible: Option<bool>,
}
impl<M: Model> fmt::Debug for Program<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Program").finish_non_exhaustive()
}
}
#[derive(Debug)]
pub(crate) enum End {
Quit,
Interrupt,
Kill,
Panic(String),
}
impl End {
fn of<M>(item: Item<M>) -> Option<Self> {
match item {
Item::Quit => Some(Self::Quit),
Item::Interrupt => Some(Self::Interrupt),
Item::Kill => Some(Self::Kill),
Item::Panic(message) => Some(Self::Panic(message)),
_ => None,
}
}
}
impl<M: Model> Program<M> {
#[must_use]
pub fn new(model: M) -> Self {
let (events, inbox) = mpsc::channel();
Self {
model,
events,
inbox,
fps: DEFAULT_FPS,
environment: None,
profile: None,
suspend_key: true,
accessible: None,
}
}
#[must_use]
pub fn with_environment(mut self, environment: Environment) -> Self {
self.environment = Some(environment);
self
}
#[must_use]
pub const fn with_color_profile(mut self, profile: ColorProfile) -> Self {
self.profile = Some(profile);
self
}
#[must_use]
pub const fn with_suspend(mut self, on: bool) -> Self {
self.suspend_key = on;
self
}
#[must_use]
#[deprecated(since = "0.0.9", note = "use with_suspend(false)")]
pub const fn without_suspend(self) -> Self {
self.with_suspend(false)
}
#[must_use]
pub const fn with_accessible(mut self, on: bool) -> Self {
self.accessible = Some(on);
self
}
#[must_use]
pub fn with_fps(mut self, fps: u32) -> Self {
self.fps = fps.clamp(1, MAX_FPS);
self
}
#[must_use]
pub fn sender(&self) -> Sender<M::Msg> {
Sender(self.events.clone())
}
#[cfg(unix)]
pub fn run(self) -> Result<M, Error> {
self.run_with(crate::Terminal::new())
}
pub fn run_with(self, mut backend: impl Backend) -> Result<M, Error> {
backend.enter()?;
set_width_method(WidthMethod::WcWidth);
let result = match self.start(&mut backend, RealClock) {
Ok(mut session) => {
let end = session.run(&mut backend);
let (model, ended) = session.close(end, &mut backend);
ended.map(|()| model)
}
Err(err) => Err(err),
};
set_width_method(WidthMethod::WcWidth);
let left = backend.leave();
let model = result?;
left?;
Ok(model)
}
pub(crate) fn start<C: Clock>(
self,
backend: &mut impl Backend,
clock: C,
) -> Result<Session<M, C>, Error> {
let Self {
mut model,
events,
inbox,
fps,
environment,
profile,
suspend_key,
accessible,
} = self;
let keys = events.clone();
backend.start_input(Box::new(move |input| {
keys.send(Event::Input(input)).is_ok()
}));
let size = backend.size()?;
let environment = environment.unwrap_or_else(Environment::current);
let terminal = backend.is_terminal();
let accessible = accessible.unwrap_or_else(|| terminal && wants_accessible(&environment));
let settings = Settings {
interval: Duration::from_secs(1) / fps,
profile: profile.unwrap_or_else(|| detect(terminal, accessible, &environment)),
forced: profile.is_some() || accessible,
suspend_key,
terminal,
frames: if accessible {
Frames::Lines
} else {
Frames::Cells
},
};
let colors = settings.profile;
let mut state = Loop::new(Executor::new(events), Renderer::new(size), settings, clock);
state.query(backend, !accessible && should_query(&environment))?;
state.exec.push(Item::Msg(Msg::ColorProfile(colors)));
state.exec.push(Item::Msg(Msg::WindowSize(size)));
let now = state.now();
state.exec.run(model.init(), now);
Ok(Session::new(model, inbox, state))
}
}
fn detect(terminal: bool, accessible: bool, environment: &Environment) -> ColorProfile {
if accessible {
ColorProfile::NoTty
} else if terminal {
ColorProfile::detect(true, environment)
} else {
ColorProfile::TrueColor
}
}
fn wants_accessible(environment: &Environment) -> bool {
!environment.var("ACCESSIBLE").is_empty()
}
fn should_query(env: &Environment) -> bool {
let term = env.var("TERM");
let known = ["ghostty", "wezterm", "alacritty", "kitty", "rio"]
.iter()
.any(|t| term.contains(t));
let apple = env.var("TERM_PROGRAM").contains("Apple");
let ssh = env.get("SSH_TTY").is_some();
(!ssh && !apple) || env.get("WT_SESSION").is_some() || known
}
#[cfg(test)]
mod tests;