diff --git a/bin/commands/issue/list.rs b/bin/commands/issue/list.rs index e0ed3dd5..6961bb12 100644 --- a/bin/commands/issue/list.rs +++ b/bin/commands/issue/list.rs @@ -6,12 +6,12 @@ use std::str::FromStr; use anyhow::{bail, Result}; -use ratatui::Viewport; use termion::event::Key; use ratatui::layout::Constraint; use ratatui::style::Stylize; use ratatui::text::Text; +use ratatui::Viewport; use radicle::cob::thread::CommentId; use radicle::git::Oid; @@ -22,12 +22,13 @@ use radicle::Profile; use radicle_tui as tui; use tui::store; +use tui::task::EmptyProcessors; use tui::ui::rm::widget::container::{ Container, ContainerProps, Footer, FooterProps, Header, HeaderProps, SectionGroup, SectionGroupProps, SplitContainer, SplitContainerFocus, SplitContainerProps, }; -use tui::ui::rm::widget::input::{TextView, TextViewProps, TextViewState}; use tui::ui::rm::widget::list::{Tree, TreeProps}; +use tui::ui::rm::widget::text::{TextView, TextViewProps, TextViewState}; use tui::ui::rm::widget::window::{ Page, PageProps, Shortcuts, ShortcutsProps, Window, WindowProps, }; @@ -370,7 +371,14 @@ impl App { .into() }); - tui::rm(state, window, Viewport::Inline(20), channel).await + tui::rm( + state, + window, + Viewport::Inline(20), + channel, + EmptyProcessors::new(), + ) + .await } } diff --git a/bin/commands/issue/list/ui.rs b/bin/commands/issue/list/ui.rs index c26762a6..f79e4aeb 100644 --- a/bin/commands/issue/list/ui.rs +++ b/bin/commands/issue/list/ui.rs @@ -4,7 +4,7 @@ use std::vec; use radicle::issue::{self, CloseReason}; use ratatui::Frame; -use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::broadcast; use termion::event::Key; @@ -18,8 +18,8 @@ use tui::ui::rm::widget; use tui::ui::rm::widget::container::{ Container, ContainerProps, Footer, FooterProps, Header, HeaderProps, }; -use tui::ui::rm::widget::input::{TextField, TextFieldProps}; use tui::ui::rm::widget::list::{Table, TableProps}; +use tui::ui::rm::widget::text::{TextField, TextFieldProps}; use tui::ui::rm::widget::ViewProps; use tui::ui::rm::widget::{RenderProps, ToWidget, View}; use tui::ui::span; @@ -119,7 +119,7 @@ pub struct Browser { } impl Browser { - pub fn new(tx: UnboundedSender) -> Self { + pub fn new(tx: broadcast::Sender) -> Self { Self { issues: Container::default() .header(Header::default().to_widget(tx.clone()).on_update(|state| { diff --git a/bin/commands/patch/list.rs b/bin/commands/patch/list.rs index 23e6ef87..dd486487 100644 --- a/bin/commands/patch/list.rs +++ b/bin/commands/patch/list.rs @@ -7,31 +7,31 @@ use std::str::FromStr; use anyhow::Result; -use ratatui::Viewport; use termion::event::Key; -use radicle_tui as tui; - use ratatui::layout::Constraint; use ratatui::style::Stylize; use ratatui::text::Text; +use ratatui::Viewport; + +use radicle::patch::PatchId; +use radicle::storage::git::Repository; +use radicle::Profile; + +use radicle_tui as tui; use tui::store; +use tui::task::EmptyProcessors; use tui::ui::rm::widget::container::{Container, Footer, FooterProps, Header, HeaderProps}; -use tui::ui::rm::widget::input::{TextView, TextViewProps, TextViewState}; +use tui::ui::rm::widget::text::{TextView, TextViewProps, TextViewState}; use tui::ui::rm::widget::window::{ Page, PageProps, Shortcuts, ShortcutsProps, Window, WindowProps, }; use tui::ui::rm::widget::{ToWidget, Widget}; use tui::ui::Column; use tui::ui::{span, BufferedValue}; - use tui::{BoxedAny, Channel, Exit, PageStack}; -use radicle::patch::PatchId; -use radicle::storage::git::Repository; -use radicle::Profile; - use self::rmui::{Browser, BrowserProps}; use super::common::{Mode, PatchOperation}; @@ -65,7 +65,7 @@ impl App { let channel = Channel::default(); let state = imui::App::try_from(&self.context)?; - tui::im(state, viewport, channel).await + tui::im(state, viewport, channel, EmptyProcessors::new()).await } else { let channel = Channel::default(); let tx = channel.tx.clone(); @@ -81,7 +81,7 @@ impl App { .into() }); - tui::rm(state, window, viewport, channel).await + tui::rm(state, window, viewport, channel, EmptyProcessors::new()).await } } } diff --git a/bin/commands/patch/list/imui.rs b/bin/commands/patch/list/imui.rs index 3b1c6f5b..a1858349 100644 --- a/bin/commands/patch/list/imui.rs +++ b/bin/commands/patch/list/imui.rs @@ -20,7 +20,8 @@ use tui::{store, Exit}; use crate::cob::patch; use crate::tui_patch::common::{Mode, PatchOperation}; -use crate::ui::items::{Filter, PatchItem, PatchItemFilter}; +use crate::ui::items::filter::Filter; +use crate::ui::items::{PatchItem, PatchItemFilter}; use super::{Context, Selection}; diff --git a/bin/commands/patch/list/rmui.rs b/bin/commands/patch/list/rmui.rs index 3895306f..73425c96 100644 --- a/bin/commands/patch/list/rmui.rs +++ b/bin/commands/patch/list/rmui.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use std::vec; use ratatui::Frame; -use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::broadcast; use termion::event::Key; @@ -20,8 +20,8 @@ use tui::ui::rm::widget; use tui::ui::rm::widget::container::{ Container, ContainerProps, Footer, FooterProps, Header, HeaderProps, }; -use tui::ui::rm::widget::input::{TextField, TextFieldProps}; use tui::ui::rm::widget::list::{Table, TableProps}; +use tui::ui::rm::widget::text::{TextField, TextFieldProps}; use tui::ui::rm::widget::ViewProps; use tui::ui::rm::widget::{RenderProps, ToWidget, View}; use tui::ui::span; @@ -120,7 +120,7 @@ pub struct Browser { } impl Browser { - pub fn new(tx: UnboundedSender) -> Self { + pub fn new(tx: broadcast::Sender) -> Self { Self { patches: Container::default() .header(Header::default().to_widget(tx.clone()).on_update(|state| { diff --git a/bin/commands/patch/review.rs b/bin/commands/patch/review.rs index dd386356..7158e5f5 100644 --- a/bin/commands/patch/review.rs +++ b/bin/commands/patch/review.rs @@ -23,6 +23,7 @@ use radicle::Storage; use radicle_tui as tui; use tui::store; +use tui::task::EmptyProcessors; use tui::ui::im::widget::{PanesState, TableState, TextViewState, Window}; use tui::ui::im::{Borders, Context, Show, Ui}; use tui::ui::span; @@ -116,7 +117,7 @@ impl Tui { .unwrap_or(default); let app = App::new(self.storage, self.review, self.hunks, state, self.mode)?; - let response = tui::im(app, viewport, channel).await?; + let response = tui::im(app, viewport, channel, EmptyProcessors::new()).await?; if let Some(response) = response.as_ref() { store.write(&state::to_json(&response.state)?)?; @@ -236,7 +237,7 @@ impl AppState { } } -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct App<'a> { /// All hunks. hunks: Arc>>>, diff --git a/bin/ui/rm.rs b/bin/ui/rm.rs index d5b8ded4..c8964cc4 100644 --- a/bin/ui/rm.rs +++ b/bin/ui/rm.rs @@ -17,7 +17,7 @@ use tui::ui::{layout, span, BufferedValue}; use super::format; use super::items::IssueItem; -use crate::ui::items::Filter; +use crate::ui::items::filter::Filter; /// A `BrowserState` represents the internal state of a browser widget. /// A browser widget would consist of 2 child widgets: a list of items and a diff --git a/examples/basic_rmui.rs b/examples/basic_rmui.rs index 63838c49..afcb1aac 100644 --- a/examples/basic_rmui.rs +++ b/examples/basic_rmui.rs @@ -1,15 +1,16 @@ use anyhow::Result; -use ratatui::Viewport; use termion::event::Key; use ratatui::layout::Constraint; +use ratatui::Viewport; use radicle_tui as tui; use tui::store; +use tui::task::EmptyProcessors; use tui::ui::rm::widget::container::{Container, Header, HeaderProps}; -use tui::ui::rm::widget::input::{TextView, TextViewProps, TextViewState}; +use tui::ui::rm::widget::text::{TextView, TextViewProps, TextViewState}; use tui::ui::rm::widget::window::{Page, Shortcuts, ShortcutsProps, Window, WindowProps}; use tui::ui::rm::widget::ToWidget; use tui::ui::Column; @@ -17,11 +18,11 @@ use tui::{BoxedAny, Channel, Exit}; const CONTENT: &str = r#" Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor -incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud -exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure +incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud +exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. -Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt +Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "#; @@ -108,7 +109,14 @@ pub async fn main() -> Result<()> { }) .on_update(|_| WindowProps::default().current_page(0).to_boxed_any().into()); - tui::rm(app, window, Viewport::default(), channel).await?; + tui::rm( + app, + window, + Viewport::default(), + channel, + EmptyProcessors::new(), + ) + .await?; Ok(()) } diff --git a/examples/hello.rs b/examples/hello.rs index b291c284..1f62acc1 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -8,6 +8,7 @@ use ratatui::{Frame, Viewport}; use radicle_tui as tui; use tui::store; +use tui::task::EmptyProcessors; use tui::ui::im::widget::Window; use tui::ui::im::Show; use tui::ui::im::{Borders, Context}; @@ -73,7 +74,13 @@ pub async fn main() -> Result<()> { alien: ALIEN.to_string(), }; - tui::im(app, Viewport::default(), Channel::default()).await?; + tui::im( + app, + Viewport::default(), + Channel::default(), + EmptyProcessors::new(), + ) + .await?; Ok(()) } diff --git a/examples/hello_rrmui.rs b/examples/hello_rrmui.rs index 5de49408..687c39c5 100644 --- a/examples/hello_rrmui.rs +++ b/examples/hello_rrmui.rs @@ -9,22 +9,23 @@ use ratatui::text::Text; use radicle_tui as tui; use tui::store; -use tui::ui::rm::widget::input::{TextArea, TextAreaProps}; +use tui::task::EmptyProcessors; +use tui::ui::rm::widget::text::{TextArea, TextAreaProps}; use tui::ui::rm::widget::ToWidget; use tui::{BoxedAny, Channel, Exit}; const ALIEN: &str = r#" - /// /// ,---------------------------------. + /// /// ,---------------------------------. /// /// | Hey there, press (q) to quit... | - // // '---------------------------------' - //,,,///,,,// .. - /////////////////// . - //////@@@@@//////@@@@@/// - //////@@###//////@@###/// + // // '---------------------------------' + //,,,///,,,// .. + /////////////////// . + //////@@@@@//////@@@@@/// + //////@@###//////@@###/// ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, - ,,, /// /// ,,, - ,,, /// /// ,,, - /// /// + ,,, /// /// ,,, + ,,, /// /// ,,, + /// /// ///// ///// "#; @@ -70,7 +71,14 @@ pub async fn main() -> Result<()> { .into() }); - tui::rm(app, scene, Viewport::default(), channel).await?; + tui::rm( + app, + scene, + Viewport::default(), + channel, + EmptyProcessors::new(), + ) + .await?; Ok(()) } diff --git a/examples/selection.rs b/examples/selection.rs index bb9d9a0e..348cb7e1 100644 --- a/examples/selection.rs +++ b/examples/selection.rs @@ -12,6 +12,7 @@ use ratatui::{Frame, Viewport}; use radicle_tui as tui; +use tui::task::EmptyProcessors; use tui::ui::im::widget::Window; use tui::ui::im::{Borders, Context}; use tui::ui::{Column, ToRow}; @@ -144,7 +145,14 @@ pub async fn main() -> Result<()> { selector: TableState::new(Some(0)), }; - if let Some(exit) = tui::im(app, Viewport::Inline(12), Channel::default()).await? { + if let Some(exit) = tui::im( + app, + Viewport::Inline(12), + Channel::default(), + EmptyProcessors::new(), + ) + .await? + { println!("{exit}"); } else { anyhow::bail!("No selection"); diff --git a/src/lib.rs b/src/lib.rs index 21b8d0da..9c954863 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,19 +7,25 @@ pub mod ui; use std::any::Any; use std::fmt::Debug; -use ratatui::Viewport; -use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +use anyhow::Result; + +#[cfg(unix)] +use tokio::signal::unix::signal; + +use tokio::sync::broadcast; +use tokio::sync::mpsc::unbounded_channel; use serde::ser::{Serialize, SerializeStruct, Serializer}; -use anyhow::Result; +use ratatui::Viewport; use store::Update; -use task::Interrupted; use ui::im; use ui::im::Show; use ui::rm; +use crate::task::Process; + /// An optional return value. #[derive(Clone, Debug)] pub struct Exit { @@ -76,6 +82,14 @@ where } } +/// Implementors of `Share` can be used inside the multi-threaded +/// application environment. +pub trait Share: Clone + Debug + Send + Sync + 'static {} + +/// Blanket implementation for all types that implement the required +/// traits. +impl Share for T {} + /// Provide implementations for conversions to and from `Box`. pub trait BoxedAny { fn from_boxed_any(any: Box) -> Option @@ -136,41 +150,75 @@ impl PageStack { } } -/// A multi-producer, single-consumer message channel. +/// A multi-producer, multi-consumer message channel. pub struct Channel { - pub tx: UnboundedSender, - pub rx: UnboundedReceiver, + pub tx: broadcast::Sender, + pub rx: broadcast::Receiver, } -impl Default for Channel { +impl Default for Channel { fn default() -> Self { - let (tx, rx) = mpsc::unbounded_channel(); - Self { tx: tx.clone(), rx } + let (tx, rx) = broadcast::channel(1000); + Self { tx, rx } } } /// Initialize a `Store` with the `State` given and a `Frontend` with the `Widget` given, -/// and run their main loops concurrently. Connect them to the `Channel` and also to +/// and run their main loops in parallel. Connect them to the `Channel` and also to /// an interrupt broadcast channel also initialized in this function. -pub async fn rm( +/// Additionally, a list of processors can be passed. Processors will also receive all +/// applications messages and can emit new ones. They will be executed by an internal worker. +pub async fn rm( state: S, root: rm::widget::Widget, viewport: Viewport, channel: Channel, -) -> Result> + processors: Vec, +) -> Result> where - S: Update + Clone + Debug + Send + Sync + 'static, - M: Debug + Send + Sync + 'static, - P: Clone + Debug + Send + Sync + 'static, + S: Update + Share, + T: Process + Share, + M: Share, + R: Share, { - let (terminator, mut interrupt_rx) = task::create_termination(); + let (terminator, mut interrupt_rx) = create_termination(); + let (state_tx, state_rx) = unbounded_channel(); + let (work_tx, work_rx) = unbounded_channel(); - let (store, state_rx) = store::Store::::new(); + let store = store::Store::::new(state_tx.clone()); + let worker = task::Worker::::new(work_tx.clone()); let frontend = rm::Frontend::default(); - tokio::try_join!( - store.run(state, terminator, channel.rx, interrupt_rx.resubscribe()), - frontend.run(root, state_rx, interrupt_rx.resubscribe(), viewport), + let worker_interrupt_rx = interrupt_rx.resubscribe(); + let store_interrupt_rx = interrupt_rx.resubscribe(); + let frontend_interrupt_rx = interrupt_rx.resubscribe(); + + let worker_message_rx = channel.rx.resubscribe(); + let store_message_rx = channel.rx.resubscribe(); + + // TODO(erikli): Handle errors properly + let _ = tokio::try_join!( + tokio::spawn(async move { + worker + .run(processors, worker_message_rx, worker_interrupt_rx) + .await + }), + tokio::spawn(async move { + store + .run( + state, + terminator, + store_message_rx, + work_rx, + store_interrupt_rx, + ) + .await + }), + tokio::spawn(async move { + frontend + .run(root, state_rx, frontend_interrupt_rx, viewport) + .await + }), )?; if let Ok(reason) = interrupt_rx.recv().await { @@ -186,21 +234,42 @@ where /// Initialize a `Store` with the `State` given and a `Frontend` with the `App` given, /// and run their main loops concurrently. Connect them to the `Channel` and also to /// an interrupt broadcast channel also initialized in this function. -pub async fn im(state: S, viewport: Viewport, channel: Channel) -> Result> +/// Additionally, a list of processors can be passed. Processors will also receive all +/// applications messages and can emit new ones. They will be executed by an internal worker. +pub async fn im( + state: S, + viewport: Viewport, + channel: Channel, + processors: Vec, +) -> Result> where - S: Update + Show + Clone + Send + Sync + 'static, - M: Clone + Debug + Send + Sync + 'static, - P: Clone + Debug + Send + Sync + 'static, + S: Update + Show + Share, + T: Process + Share, + M: Share, + R: Share, { - let (terminator, mut interrupt_rx) = task::create_termination(); + let (terminator, mut interrupt_rx) = create_termination(); + let (state_tx, state_rx) = unbounded_channel(); + let (work_tx, work_rx) = unbounded_channel(); - let state_tx = channel.tx.clone(); - let (store, state_rx) = store::Store::::new(); + let store = store::Store::::new(state_tx.clone()); + let worker = task::Worker::::new(work_tx.clone()); let frontend = im::Frontend::default(); tokio::try_join!( - store.run(state, terminator, channel.rx, interrupt_rx.resubscribe()), - frontend.run(state_tx, state_rx, interrupt_rx.resubscribe(), viewport), + worker.run( + processors, + channel.rx.resubscribe(), + interrupt_rx.resubscribe() + ), + store.run( + state, + terminator, + channel.rx.resubscribe(), + work_rx, + interrupt_rx.resubscribe() + ), + frontend.run(channel.tx, state_rx, interrupt_rx.resubscribe(), viewport), )?; if let Ok(reason) = interrupt_rx.recv().await { @@ -212,3 +281,70 @@ where anyhow::bail!("exited because of an unexpected error"); } } + +/// An `Interrupt` message that is produced by either an OS signal (e.g. kill) +/// or the user by requesting the application to close. +#[derive(Debug, Clone)] +pub enum Interrupted

+where + P: Clone + Send + Sync + Debug, +{ + OsSignal, + User { payload: Option

}, +} + +/// The `Terminator` wraps a broadcast channel and can send an interrupt messages. +#[derive(Debug, Clone)] +pub struct Terminator

+where + P: Clone + Send + Sync + Debug, +{ + interrupt_tx: broadcast::Sender>, +} + +impl

Terminator

+where + P: Clone + Send + Sync + Debug + 'static, +{ + /// Create a `Terminator` that stores the sending end of a broadcast channel. + pub fn new(interrupt_tx: broadcast::Sender>) -> Self { + Self { interrupt_tx } + } + + /// Send interrupt message to the broadcast channel. + pub fn terminate(&mut self, interrupted: Interrupted

) -> anyhow::Result<()> { + self.interrupt_tx.send(interrupted)?; + + Ok(()) + } +} + +/// Receive `SIGINT` and call terminator which sends the interrupt message to its broadcast channel. +#[cfg(unix)] +async fn terminate_by_unix_signal

(mut terminator: Terminator

) +where + P: Clone + Send + Sync + Debug + 'static, +{ + let mut interrupt_signal = signal(tokio::signal::unix::SignalKind::interrupt()) + .expect("failed to create interrupt signal stream"); + + interrupt_signal.recv().await; + + terminator + .terminate(Interrupted::OsSignal) + .expect("failed to send interrupt signal"); +} + +/// Create a broadcast channel and spawn a task for retrieving the applications' kill signal. +pub fn create_termination

() -> (Terminator

, broadcast::Receiver>) +where + P: Clone + Send + Sync + Debug + 'static, +{ + let (tx, rx) = broadcast::channel(1); + let terminator = Terminator::new(tx); + + #[cfg(unix)] + tokio::spawn(terminate_by_unix_signal(terminator.clone())); + + (terminator, rx) +} diff --git a/src/store.rs b/src/store.rs index 9f4bb9b8..a32257ac 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,13 +1,12 @@ -use std::fmt::Debug; use std::marker::PhantomData; use std::time::Duration; -use tokio::sync::broadcast; -use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +use tokio::sync::{ + broadcast, + mpsc::{UnboundedReceiver, UnboundedSender}, +}; -use crate::Exit; - -use super::task::{Interrupted, Terminator}; +use super::{Exit, Interrupted, Share, Terminator}; const STORE_TICK_RATE: Duration = Duration::from_millis(1000); @@ -26,37 +25,32 @@ pub trait Update { /// The `Store` updates the applications' state concurrently. It handles /// messages coming from the frontend and updates the state accordingly. -pub struct Store +pub struct Store where - S: Update + Clone + Send + Sync, - P: Clone + Debug + Send + Sync, + S: Update + Share, { state_tx: UnboundedSender, - _phantom: PhantomData<(M, P)>, + _phantom: PhantomData<(M, R)>, } -impl Store +impl Store where - S: Update + Clone + Send + Sync, - P: Clone + Debug + Send + Sync, + S: Update + Share, + R: Share, { - pub fn new() -> (Self, UnboundedReceiver) { - let (state_tx, state_rx) = mpsc::unbounded_channel::(); - - ( - Store { - state_tx, - _phantom: PhantomData, - }, - state_rx, - ) + pub fn new(tx: UnboundedSender) -> Self { + Self { + state_tx: tx, + _phantom: PhantomData, + } } } -impl Store +impl Store where - S: Update + Clone + Send + Sync + 'static, - P: Clone + Debug + Send + Sync + 'static, + S: Update + Share, + M: Share, + R: Share, { /// By calling `main_loop`, the store will wait for new messages coming /// from the frontend and update the applications' state accordingly. It will @@ -65,10 +59,11 @@ where pub async fn run( self, mut state: S, - mut terminator: Terminator

, - mut message_rx: UnboundedReceiver, - mut interrupt_rx: broadcast::Receiver>, - ) -> anyhow::Result> { + mut terminator: Terminator, + mut message_rx: broadcast::Receiver, + mut work_rx: UnboundedReceiver, + mut interrupt_rx: broadcast::Receiver>, + ) -> anyhow::Result> { // Send the initial state once self.state_tx.send(state.clone())?; @@ -78,13 +73,18 @@ where tokio::select! { // Handle the messages coming from the frontend // and process them to do async operations - Some(message) = message_rx.recv() => { + Ok(message) = message_rx.recv() => { if let Some(exit) = state.update(message) { let interrupted = Interrupted::User { payload: exit.value }; let _ = terminator.terminate(interrupted.clone()); break interrupted; } + self.state_tx.send(state.clone())?; + }, + Some(message) = work_rx.recv() => { + state.update(message); + self.state_tx.send(state.clone())?; }, // Tick to terminate the select every N milliseconds _ = ticker.tick() => { @@ -95,8 +95,6 @@ where break interrupted; } } - - self.state_tx.send(state.clone())?; }; Ok(result) diff --git a/src/task.rs b/src/task.rs index 4bd9087f..c9a9b924 100644 --- a/src/task.rs +++ b/src/task.rs @@ -1,72 +1,79 @@ -use std::fmt::Debug; +use std::marker::PhantomData; +use std::{fmt::Debug, future::Future}; -#[cfg(unix)] -use tokio::signal::unix::signal; -use tokio::sync::broadcast; +use tokio::sync::{broadcast, mpsc::UnboundedSender}; -/// An `Interrupt` message that is produced by either an OS signal (e.g. kill) -/// or the user by requesting the application to close. -#[derive(Debug, Clone)] -pub enum Interrupted

-where - P: Clone + Send + Sync + Debug, -{ - OsSignal, - User { payload: Option

}, +use super::{Interrupted, Share}; + +pub type EmptyProcessors = Vec; + +/// A task that can be run. +pub trait Task: Debug + Send + Sync + 'static { + type Return; + + fn run(&self) -> anyhow::Result>; } -/// The `Terminator` wraps a broadcast channel and can send an interrupt messages. -#[derive(Debug, Clone)] -pub struct Terminator

-where - P: Clone + Send + Sync + Debug, -{ - interrupt_tx: broadcast::Sender>, +/// A processor that can be added to the application environment. +/// Processors will receive application messages and can produce new ones. +pub trait Process { + fn process(&mut self, _message: M) -> impl Future>> + Send; } -impl

Terminator

-where - P: Clone + Send + Sync + Debug + 'static, -{ - /// Create a `Terminator` that stores the sending end of a broadcast channel. - pub fn new(interrupt_tx: broadcast::Sender>) -> Self { - Self { interrupt_tx } - } +/// An empty processor that does nothing. +#[derive(Debug, Clone)] +pub struct EmptyProcessor; - /// Send interrupt message to the broadcast channel. - pub fn terminate(&mut self, interrupted: Interrupted

) -> anyhow::Result<()> { - self.interrupt_tx.send(interrupted)?; - - Ok(()) +impl Process for EmptyProcessor { + async fn process(&mut self, _message: M) -> anyhow::Result> { + Ok(vec![]) } } -/// Receive `SIGINT` and call terminator which sends the interrupt message to its broadcast channel. -#[cfg(unix)] -async fn terminate_by_unix_signal

(mut terminator: Terminator

) -where - P: Clone + Send + Sync + Debug + 'static, -{ - let mut interrupt_signal = signal(tokio::signal::unix::SignalKind::interrupt()) - .expect("failed to create interrupt signal stream"); - - interrupt_signal.recv().await; - - terminator - .terminate(Interrupted::OsSignal) - .expect("failed to send interrupt signal"); +/// A worker that is spawned by the application. Invokes +/// all processors and sends received application messages. +pub struct Worker { + work_tx: UnboundedSender, + _phantom: PhantomData<(P, M, R)>, } -/// Create a broadcast channel and spawn a task for retrieving the applications' kill signal. -pub fn create_termination

() -> (Terminator

, broadcast::Receiver>) +impl Worker where - P: Clone + Send + Sync + Debug + 'static, + P: Process + Share, + M: Share, + R: Share, { - let (tx, rx) = broadcast::channel(1); - let terminator = Terminator::new(tx); + pub fn new(tx: UnboundedSender) -> Self { + Self { + work_tx: tx, + _phantom: PhantomData, + } + } - #[cfg(unix)] - tokio::spawn(terminate_by_unix_signal(terminator.clone())); + pub async fn run( + &self, + processors: Vec

, + mut message_rx: broadcast::Receiver, + mut interrupt_rx: broadcast::Receiver>, + ) -> anyhow::Result> { + let result = loop { + tokio::select! { + Ok(message) = message_rx.recv() => { + for mut p in processors.clone() { + for m in p.process(message.clone()).await? { + if let Err(err) = self.work_tx.send(m) { + log::error!(target: "worker", "Unable to send message: {err}") + } + } + } + }, + // Catch and handle interrupt signal to gracefully shutdown + Ok(interrupted) = interrupt_rx.recv() => { + break interrupted; + } + } + }; - (terminator, rx) + Ok(result) + } } diff --git a/src/ui/im.rs b/src/ui/im.rs index 92486b2e..a9818bed 100644 --- a/src/ui/im.rs +++ b/src/ui/im.rs @@ -10,7 +10,7 @@ use anyhow::Result; use ratatui::style::Stylize; use ratatui::text::{Span, Text}; use tokio::sync::broadcast; -use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; +use tokio::sync::mpsc::UnboundedReceiver; use termion::event::Key; @@ -19,11 +19,11 @@ use ratatui::{Frame, Viewport}; use crate::event::Event; use crate::store::Update; -use crate::task::Interrupted; use crate::terminal; use crate::terminal::Terminal; use crate::ui::theme::Theme; use crate::ui::{Column, ToRow}; +use crate::Interrupted; use crate::ui::im::widget::{HeaderedTable, Widget}; @@ -42,17 +42,17 @@ pub trait Show { pub struct Frontend {} impl Frontend { - pub async fn run( + pub async fn run( self, - state_tx: UnboundedSender, + message_tx: broadcast::Sender, mut state_rx: UnboundedReceiver, - mut interrupt_rx: broadcast::Receiver>, + mut interrupt_rx: broadcast::Receiver>, viewport: Viewport, - ) -> anyhow::Result> + ) -> anyhow::Result> where - S: Update + Show, + S: Update + Show, M: Clone, - P: Clone + Send + Sync + Debug, + R: Clone + Send + Sync + Debug, { let mut ticker = tokio::time::interval(RENDERING_TICK_RATE); @@ -60,9 +60,9 @@ impl Frontend { let mut events_rx = terminal::events(); let mut state = state_rx.recv().await.unwrap(); - let mut ctx = Context::default().with_sender(state_tx); + let mut ctx = Context::default().with_sender(message_tx); - let result: anyhow::Result> = loop { + let result: anyhow::Result> = loop { tokio::select! { // Tick to terminate the select every N milliseconds _ = ticker.tick() => (), @@ -131,7 +131,7 @@ pub struct Context { /// Current frame of the application. pub(crate) frame_size: Rect, /// The message sender used by the `Ui` to send application messages. - pub(crate) sender: Option>, + pub(crate) sender: Option>, } impl Default for Context { @@ -162,7 +162,7 @@ impl Context { self } - pub fn with_sender(mut self, sender: UnboundedSender) -> Self { + pub fn with_sender(mut self, sender: broadcast::Sender) -> Self { self.sender = Some(sender); self } diff --git a/src/ui/rm.rs b/src/ui/rm.rs index 481ff6b9..32ee789e 100644 --- a/src/ui/rm.rs +++ b/src/ui/rm.rs @@ -9,11 +9,11 @@ use tokio::sync::mpsc::UnboundedReceiver; use crate::event::Event; use crate::store::Update; -use crate::task::Interrupted; use crate::terminal; use crate::terminal::Terminal; use crate::ui::rm::widget::RenderProps; use crate::ui::rm::widget::Widget; +use crate::Interrupted; const RENDERING_TICK_RATE: Duration = Duration::from_millis(250); @@ -60,6 +60,7 @@ impl Frontend { let mut root = { let state = state_rx.recv().await.unwrap(); + root.init(); root.update(&state); root }; diff --git a/src/ui/rm/widget.rs b/src/ui/rm/widget.rs index b8833ed5..b9251006 100644 --- a/src/ui/rm/widget.rs +++ b/src/ui/rm/widget.rs @@ -1,13 +1,13 @@ pub mod container; -pub mod input; pub mod list; +pub mod text; pub mod utils; pub mod window; use std::any::Any; use std::rc::Rc; -use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::broadcast; use termion::event::Key; @@ -15,13 +15,14 @@ use ratatui::prelude::*; use self::{ container::SectionGroupState, - input::{TextAreaState, TextViewState}, + text::{TextAreaState, TextViewState}, }; pub type BoxedView = Box>; pub type UpdateCallback = fn(&S) -> ViewProps; pub type EventCallback = fn(Key, Option<&ViewState>, Option<&ViewProps>) -> Option; pub type RenderCallback = fn(Option<&ViewProps>, &RenderProps) -> Option; +pub type InitCallback = fn() -> Option; /// `ViewProps` are properties of a `View`. They define a `View`s data, configuration etc. /// Since the framework itself does not know the concrete type of `View`, it also does not @@ -254,14 +255,17 @@ pub trait View { pub struct Widget { view: BoxedView, props: Option, - sender: UnboundedSender, + sender: broadcast::Sender, + on_init: Option>, on_update: Option>, on_event: Option>, on_render: Option>, } +unsafe impl Send for Widget {} + impl Widget { - pub fn new(view: V, sender: UnboundedSender) -> Self + pub fn new(view: V, sender: broadcast::Sender) -> Self where Self: Sized, V: View + 'static, @@ -270,6 +274,7 @@ impl Widget { view: Box::new(view), props: None, sender: sender.clone(), + on_init: None, on_update: None, on_event: None, on_render: None, @@ -297,6 +302,13 @@ impl Widget { } } + /// Initializes the widget + pub fn init(&mut self) { + if let Some(on_init) = self.on_init { + (on_init)().and_then(|message| self.sender.send(message).ok()); + } + } + /// Applications are usually defined by app-specific widgets that do know /// the type of `state`. These can use widgets from the library that do not know the /// type of `state`. @@ -321,11 +333,11 @@ impl Widget { } /// Sets the optional custom event handler. - pub fn on_event(mut self, callback: EventCallback) -> Self + pub fn on_init(mut self, callback: InitCallback) -> Self where Self: Sized, { - self.on_event = Some(callback); + self.on_init = Some(callback); self } @@ -338,6 +350,15 @@ impl Widget { self } + /// Sets the optional custom event handler. + pub fn on_event(mut self, callback: EventCallback) -> Self + where + Self: Sized, + { + self.on_event = Some(callback); + self + } + /// Sets the optional update handler. pub fn on_render(mut self, callback: RenderCallback) -> Self where @@ -351,7 +372,7 @@ impl Widget { /// A `View` needs to be wrapped into a `Widget` in order to be used with the framework. /// `ToWidget` provides a blanket implementation for all `View`s. pub trait ToWidget { - fn to_widget(self, tx: UnboundedSender) -> Widget + fn to_widget(self, tx: broadcast::Sender) -> Widget where Self: Sized + 'static; } @@ -362,7 +383,7 @@ where S: 'static, M: 'static, { - fn to_widget(self, tx: UnboundedSender) -> Widget + fn to_widget(self, tx: broadcast::Sender) -> Widget where Self: Sized + 'static, { diff --git a/src/ui/rm/widget/input.rs b/src/ui/rm/widget/text.rs similarity index 95% rename from src/ui/rm/widget/input.rs rename to src/ui/rm/widget/text.rs index 0b5188aa..d84042bc 100644 --- a/src/ui/rm/widget/input.rs +++ b/src/ui/rm/widget/text.rs @@ -8,10 +8,67 @@ use ratatui::text::{Line, Span, Text}; use ratatui::widgets::Paragraph; use ratatui::Frame; -use crate::ui::theme::Theme; +use crate::ui::theme::{self, Theme}; use super::{utils, RenderProps, View, ViewProps, ViewState}; +#[derive(Clone, Debug)] +pub struct LabelProps { + pub text: String, + pub style: Style, +} + +impl LabelProps { + pub fn text(mut self, text: &str) -> Self { + self.text = text.to_string(); + self + } + + pub fn style(mut self, style: Style) -> Self { + self.style = style; + self + } +} + +impl Default for LabelProps { + fn default() -> Self { + Self { + text: "".to_string(), + style: theme::style::reset(), + } + } +} + +pub struct Label { + /// Phantom + phantom: PhantomData<(S, M)>, +} + +impl Default for Label { + fn default() -> Self { + Self { + phantom: PhantomData, + } + } +} + +impl View for Label { + type Message = M; + type State = S; + + fn render(&mut self, props: Option<&ViewProps>, render: RenderProps, frame: &mut Frame) { + let default = LabelProps::default(); + let props = props + .and_then(|props| props.inner_ref::()) + .unwrap_or(&default); + + frame.render_widget( + Paragraph::new(props.text.clone()).style(props.style), + render.area, + ); + } +} + #[derive(Clone)] pub struct TextFieldProps { /// The label of this input field.