diff --git a/examples/widgets2.rs b/examples/widgets2.rs new file mode 100644 index 000000000..169428c78 --- /dev/null +++ b/examples/widgets2.rs @@ -0,0 +1,118 @@ +//! This example shows how to make a basic widget that accumulates +//! text input and renders it to the screen +extern crate failure; +extern crate termwiz; + +use failure::Error; +use termwiz::caps::Capabilities; +use termwiz::cell::AttributeChange; +use termwiz::color::{AnsiColor, ColorAttribute, RgbColor}; +use termwiz::input::*; +use termwiz::surface::Change; +use termwiz::terminal::buffered::BufferedTerminal; +use termwiz::terminal::Blocking; +use termwiz::terminal::{new_terminal, Terminal}; +use termwiz::widgets::*; + +#[derive(Default)] +struct MainScreen {} + +impl Widget2 for MainScreen { + type State = String; + type Event = (); + + fn init_state(&self) -> String { + String::new() + } + + fn update_state(&self, args: &mut WidgetUpdate) { + let mut text = args.state_mut(); + for event in args.events() { + match event { + WidgetEvent::Input(InputEvent::Key(KeyEvent { + key: KeyCode::Char(c), + .. + })) => text.push(c), + WidgetEvent::Input(InputEvent::Key(KeyEvent { + key: KeyCode::Enter, + .. + })) => { + text.push_str("\r\n"); + } + WidgetEvent::Input(InputEvent::Paste(s)) => { + text.push_str(&s); + } + _ => {} + } + } + + let mut surface = args.surface_mut(); + + surface.add_change(Change::ClearScreen( + ColorAttribute::TrueColorWithPaletteFallback( + RgbColor::new(0x31, 0x1B, 0x92), + AnsiColor::Black.into(), + ), + )); + surface.add_change(Change::Attribute(AttributeChange::Foreground( + ColorAttribute::TrueColorWithPaletteFallback( + RgbColor::new(0xB3, 0x88, 0xFF), + AnsiColor::Purple.into(), + ), + ))); + let dims = surface.dimensions(); + surface.add_change(format!("🤷 surface size is {:?}\r\n", dims)); + surface.add_change(text.clone()); + + *args.cursor_mut() = CursorShapeAndPosition { + coords: surface.cursor_position().into(), + shape: termwiz::surface::CursorShape::SteadyBar, + ..Default::default() + }; + } +} + +fn main() -> Result<(), Error> { + let caps = Capabilities::new_from_env()?; + + let mut buf = BufferedTerminal::new(new_terminal(caps)?)?; + buf.terminal().set_raw_mode()?; + + let mut ui = Ui::new(); + + let main_id = WidgetIdNr::new(); + ui.set_focus(main_id); + + loop { + { + MainScreen {}.build_ui_root(main_id, &mut ui); + } + ui.render_to_screen(&mut buf)?; + buf.flush()?; + + match buf.terminal().poll_input(Blocking::Wait) { + Ok(Some(InputEvent::Resized { rows, cols })) => { + buf.add_change(Change::ClearScreen(Default::default())); + buf.resize(cols, rows); + } + Ok(Some(input)) => match input { + InputEvent::Key(KeyEvent { + key: KeyCode::Escape, + .. + }) => { + break; + } + input @ _ => { + ui.queue_event(WidgetEvent::Input(input)); + } + }, + Ok(None) => {} + Err(e) => { + print!("{:?}\r\n", e); + break; + } + } + } + + Ok(()) +} diff --git a/src/widgets/mod.rs b/src/widgets/mod.rs index 46a62cd80..213d7b413 100644 --- a/src/widgets/mod.rs +++ b/src/widgets/mod.rs @@ -1,9 +1,13 @@ use color::ColorAttribute; use failure::Error; use input::InputEvent; +use std::any::Any; use std::cell::{Ref, RefCell, RefMut}; +use std::collections::{HashMap, VecDeque}; use std::fmt::{Debug, Error as FmtError, Formatter}; use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; use std::rc::{Rc, Weak}; use surface::{Change, CursorShape, Position, SequenceNo, Surface}; @@ -30,6 +34,136 @@ pub struct CursorShapeAndPosition { pub color: ColorAttribute, } +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Rect { + pub x: usize, + pub y: usize, + pub width: usize, + pub height: usize, +} + +pub struct WidgetUpdate<'a, T: Widget2> { + pub id: WidgetIdNr, + pub parent_id: Option, + pub rect: Rect, + cursor: &'a RefCell, + surface: &'a RefCell, + state: &'a RefCell>, + ui: &'a mut Ui, + _phantom: PhantomData, +} + +pub struct StateRef<'a, T: 'a> { + cell: Ref<'a, Box>, + _phantom: PhantomData, +} + +impl<'a, T: 'static> Deref for StateRef<'a, T> { + type Target = T; + fn deref(&self) -> &T { + self.cell.downcast_ref().unwrap() + } +} + +pub struct StateRefMut<'a, T: 'a> { + cell: RefMut<'a, Box>, + _phantom: PhantomData, +} + +impl<'a, T: 'static> Deref for StateRefMut<'a, T> { + type Target = T; + fn deref(&self) -> &T { + self.cell.downcast_ref().unwrap() + } +} + +impl<'a, T: 'static> DerefMut for StateRefMut<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.cell.downcast_mut().unwrap() + } +} + +impl<'a, T: Widget2> WidgetUpdate<'a, T> { + pub fn state(&'a self) -> StateRef<'a, T::State> { + StateRef { + cell: self.state.borrow(), + _phantom: PhantomData, + } + } + + pub fn surface(&self) -> Ref { + self.surface.borrow() + } + + pub fn state_mut(&self) -> StateRefMut<'a, T::State> { + StateRefMut { + cell: self.state.borrow_mut(), + _phantom: PhantomData, + } + } + + pub fn surface_mut(&self) -> RefMut { + self.surface.borrow_mut() + } + + pub fn cursor_mut(&self) -> RefMut { + self.cursor.borrow_mut() + } + + pub fn events(&'a self) -> impl Iterator + 'a { + self.ui.input_queue.iter().filter_map(move |evt| { + match evt { + WidgetEvent::FocusLost | WidgetEvent::FocusGained => None, + WidgetEvent::Input(InputEvent::Resized { .. }) => None, + WidgetEvent::Input(InputEvent::Mouse(m)) => { + let mut m = m.clone(); + // TODO: screen to client coords + Some(WidgetEvent::Input(InputEvent::Mouse(m))) + } + WidgetEvent::Input(InputEvent::Paste(s)) => match self.ui.focused { + Some(id) if id == self.id => { + Some(WidgetEvent::Input(InputEvent::Paste(s.clone()))) + } + _ => None, + }, + WidgetEvent::Input(InputEvent::Key(key)) => match self.ui.focused { + Some(id) if id == self.id => { + let key = key.clone(); + Some(WidgetEvent::Input(InputEvent::Key(key))) + } + _ => None, + }, + } + }) + } +} + +pub trait Widget2: Sized { + type State: Any + Send; + type Event; + + /// Called by the Ui the first time that a give WidgetIdNr is used. + /// The widget shall return its initial state value. + fn init_state(&self) -> Self::State; + + /// Called by the Ui on each update cycle. + /// The widget should process state updates and draw itself to + /// the surface embedded in `args`. + fn update_state(&self, args: &mut WidgetUpdate) -> Self::Event; + + fn get_size_constraints(&self, _state: &Self::State) -> layout::Constraints { + Default::default() + } + + fn build_ui_root(self, id: WidgetIdNr, ui: &mut Ui) -> Self::Event { + ui.add_or_update_widget(id, None, self) + } + + fn build_ui_child(self, id: WidgetIdNr, args: &mut WidgetUpdate) -> Self::Event { + args.ui.add_or_update_widget(id, args.parent_id, self) + } +} + pub trait WidgetImpl { /// Called once by the widget manager to inform the widget /// of its identifier @@ -67,6 +201,12 @@ impl ParentRelativeCoords { } } +impl From<(usize, usize)> for ParentRelativeCoords { + fn from(coords: (usize, usize)) -> ParentRelativeCoords { + ParentRelativeCoords::new(coords.0, coords.1) + } +} + /// Relative to the top left of the screen #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScreenRelativeCoords { @@ -87,6 +227,207 @@ impl ScreenRelativeCoords { } } +static WIDGET_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::ATOMIC_USIZE_INIT; + +#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct WidgetIdNr(usize); + +impl WidgetIdNr { + pub fn new() -> Self { + WidgetIdNr(WIDGET_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)) + } +} + +pub struct WidgetState { + surface: RefCell, + coordinates: ParentRelativeCoords, + cursor: RefCell, + constraints: RefCell, + children: Vec, + parent: Option, + state: RefCell>, +} + +pub struct Ui { + state: HashMap, + focused: Option, + root: Option, + input_queue: VecDeque, +} + +impl Ui { + pub fn new() -> Self { + Self { + state: HashMap::new(), + focused: None, + root: None, + input_queue: VecDeque::new(), + } + } + + fn add_or_update_widget( + &mut self, + id: WidgetIdNr, + parent: Option, + w: W, + ) -> W::Event { + let widget_state = self.state.remove(&id).unwrap_or_else(|| WidgetState { + surface: RefCell::new(Surface::new(80, 24)), + coordinates: ParentRelativeCoords::new(0, 0), + children: Vec::new(), + parent: parent, + state: RefCell::new(Box::new(w.init_state())), + cursor: RefCell::new(Default::default()), + constraints: RefCell::new(Default::default()), + }); + + // Dealing with re-parenting is a PITA, so we just panic for now + assert_eq!(parent, widget_state.parent); + + // Ensure that the parent links to this child + match widget_state.parent { + Some(parent_id) => match self.state.get_mut(&parent_id) { + Some(parent) => { + if !parent.children.contains(&id) { + parent.children.push(id); + } + } + None => panic!("missing parent!"), + }, + None => { + // It has no parent, therefore it is the root + self.root = Some(id); + } + } + + *widget_state.constraints.borrow_mut() = + w.get_size_constraints(widget_state.state.borrow().downcast_ref().unwrap()); + + // TODO: incrementally update the layout solver + + let coords = widget_state.coordinates; + let dims = widget_state.surface.borrow().dimensions(); + + let event = { + let mut args = WidgetUpdate { + id, + parent_id: None, + rect: Rect { + x: coords.x, + y: coords.y, + width: dims.0, + height: dims.1, + }, + surface: &widget_state.surface, + state: &widget_state.state, + cursor: &widget_state.cursor, + ui: self, + _phantom: PhantomData, + }; + w.update_state(&mut args) + }; + + self.state.insert(id, widget_state); + + event + } + + pub fn queue_event(&mut self, event: WidgetEvent) { + self.input_queue.push_back(event); + } + + pub fn set_focus(&mut self, id: WidgetIdNr) { + self.focused = Some(id); + } + + fn render_recursive( + &mut self, + id: WidgetIdNr, + screen: &mut Surface, + abs_coords: &ScreenRelativeCoords, + ) -> Result<(), Error> { + let (child_ids, abs_coords) = match self.state.get_mut(&id) { + Some(widget_state) => { + let abs_coords = ScreenRelativeCoords::new( + widget_state.coordinates.x + abs_coords.x, + widget_state.coordinates.y + abs_coords.y, + ); + screen.draw_from_screen( + &widget_state.surface.borrow_mut(), + abs_coords.x, + abs_coords.y, + ); + widget_state + .surface + .borrow_mut() + .flush_changes_older_than(SequenceNo::max_value()); + + (widget_state.children.clone(), abs_coords) + } + None => bail!("missing state for widget {:?}", id), + }; + + for child in child_ids { + self.render_recursive(child, screen, &abs_coords)?; + } + + Ok(()) + } + + pub fn render_to_screen(&mut self, screen: &mut Surface) -> Result<(), Error> { + let root_id = self.root.unwrap(); + self.render_recursive(root_id, screen, &ScreenRelativeCoords::new(0, 0))?; + self.input_queue.clear(); + + match self.focused { + Some(id) => match self.state.get(&id) { + Some(widget_state) => { + let cursor = widget_state.cursor.borrow(); + let coords = self.to_screen_coords(id, &cursor.coords); + + screen.add_changes(vec![ + Change::CursorShape(cursor.shape), + Change::CursorColor(cursor.color), + Change::CursorPosition { + x: Position::Absolute(coords.x), + y: Position::Absolute(coords.y), + }, + ]); + } + _ => {} + }, + _ => {} + } + + Ok(()) + } + + pub fn to_screen_coords( + &self, + widget: WidgetIdNr, + coords: &ParentRelativeCoords, + ) -> ScreenRelativeCoords { + let mut x = coords.x; + let mut y = coords.y; + let mut widget = widget; + loop { + let parent = match self.state.get(&widget) { + Some(widget_state) => { + x += widget_state.coordinates.x; + y += widget_state.coordinates.y; + match widget_state.parent { + Some(parent) => parent, + None => break, + } + } + None => break, + }; + widget = parent; + } + ScreenRelativeCoords { x, y } + } +} + pub struct Widget { id: WidgetId, inner: Box,