petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! The handle other threads send a program messages with.

use crate::exec::Event;
use std::fmt;
use std::sync::mpsc;

/// Sends messages to a program from other threads: Bubble Tea's
/// `Program.Send`, `Quit` and `Kill`. Sending to a program that has
/// stopped does nothing; [`Sender::send`] says so by returning `false`.
pub struct Sender<M>(pub(super) mpsc::Sender<Event<M>>);

impl<M> Clone for Sender<M> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<M> fmt::Debug for Sender<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Sender(..)")
    }
}

impl<M> Sender<M> {
    /// Delivers `msg` to the model as [`Msg::App`](crate::Msg::App). `true` when the
    /// message was queued: the program is running, or has not started
    /// yet and sees it once it does. `false` when the program has
    /// stopped, and the message is dropped; a thread feeding the program
    /// can stop on it. Bubble Tea's `Program.Send` blocks instead until
    /// the program reads the message, and returns nothing.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use std::time::Duration;
    ///
    /// struct Echo;
    ///
    /// impl tea::Model for Echo {
    ///     type Msg = ();
    ///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
    ///         match msg {
    ///             tea::Msg::App(()) => tea::quit(),
    ///             _ => tea::Cmd::none(),
    ///         }
    ///     }
    ///     fn view(&self) -> tea::View {
    ///         "echo".into()
    ///     }
    /// }
    ///
    /// let program = tea::Program::new(Echo);
    /// let sender = program.sender();
    /// let terminal = tea::testing::TestTerminal::new(10, 1);
    /// let mut test = tea::testing::TestProgram::with_terminal(program, terminal);
    /// assert!(sender.send(()), "queued for the running program");
    /// assert!(test.wait_finished(Duration::from_secs(1)));
    /// assert!(!sender.send(()), "the program has stopped");
    /// ```
    pub fn send(&self, msg: M) -> bool {
        self.0.send(Event::Send(msg)).is_ok()
    }

    /// Stops the program as [`quit`](crate::quit) does.
    pub fn quit(&self) {
        let _ = self.0.send(Event::Quit);
    }

    /// Stops the program at once, without a final frame;
    /// [`Program::run`](crate::Program::run) returns [`Error::Killed`](crate::Error::Killed).
    pub fn kill(&self) {
        let _ = self.0.send(Event::Kill);
    }
}