use super::End;
use super::run::Loop;
use crate::Model;
use crate::backend::Backend;
use crate::clock::Clock;
use crate::exec::Event;
use crate::msg::Error;
use std::sync::mpsc::Receiver;
use std::time::Instant;
pub(crate) struct Session<M: Model, C> {
model: M,
inbox: Receiver<Event<M::Msg>>,
state: Loop<M::Msg, C>,
}
impl<M: Model, C: Clock> Session<M, C> {
pub(super) const fn new(
model: M,
inbox: Receiver<Event<M::Msg>>,
state: Loop<M::Msg, C>,
) -> Self {
Self {
model,
inbox,
state,
}
}
pub(crate) fn run(&mut self, backend: &mut impl Backend) -> Result<End, Error> {
self.state.run(&mut self.model, &self.inbox, backend)
}
pub(crate) fn step(&mut self, backend: &mut impl Backend) -> Result<Option<End>, Error> {
self.state.step(&mut self.model, &self.inbox, backend)
}
pub(crate) fn wake(&mut self) -> bool {
self.state.wait(&self.inbox);
self.state.exec.has_ready()
}
pub(crate) fn next_wake(&self) -> Option<Instant> {
self.state.next_wake()
}
pub(crate) const fn model(&self) -> &M {
&self.model
}
pub(crate) fn close(
mut self,
end: Result<End, Error>,
backend: &mut impl Backend,
) -> (M, Result<(), Error>) {
let cleared = self.state.modes.clear(backend);
let ended = end.and_then(|end| match end {
End::Quit => Ok(()),
End::Interrupt => Err(Error::Interrupted),
End::Kill => Err(Error::Killed),
End::Panic(message) => Err(Error::Panic(message)),
});
(self.model, ended.and(cleared.map_err(Error::from)))
}
}