on 2158366 help sign in
helix/helix-term/src/compositor.rs
252 lines 7.6 kB history raw
1// Each component declares it's own size constraints and gets fitted based on it's parent.
2// Q: how does this work with popups?
3// cursive does compositor.screen_mut().add_layer_at(pos::absolute(x, y), <component>)
4use helix_core::Position;
5use helix_view::graphics::{CursorKind, Rect};
7use crossterm::event::Event;
8use tui::buffer::Buffer as Surface;
10pub type Callback = Box<dyn FnOnce(&mut Compositor)>;
12// --> EventResult should have a callback that takes a context with methods like .popup(),
13// .prompt() etc. That way we can abstract it from the renderer.
14// Q: How does this interact with popups where we need to be able to specify the rendering of the
15// popup?
16// A: It could just take a textarea.
17//
18// If Compositor was specified in the callback that's then problematic because of
20// Cursive-inspired
21pub enum EventResult {
22 Ignored,
23 Consumed(Option<Callback>),
26use helix_view::Editor;
28use crate::job::Jobs;
30pub struct Context<'a> {
31 pub editor: &'a mut Editor,
32 pub scroll: Option<usize>,
33 pub jobs: &'a mut Jobs,
36pub trait Component: Any + AnyComponent {
37 /// Process input events, return true if handled.
38 fn handle_event(&mut self, _event: Event, _ctx: &mut Context) -> EventResult {
39 EventResult::Ignored
40 }
41 // , args: ()
43 /// Should redraw? Useful for saving redraw cycles if we know component didn't change.
44 fn should_update(&self) -> bool {
45 true
46 }
48 /// Render the component onto the provided surface.
49 fn render(&mut self, area: Rect, frame: &mut Surface, ctx: &mut Context);
51 /// Get cursor position and cursor kind.
52 fn cursor(&self, _area: Rect, _ctx: &Editor) -> (Option<Position>, CursorKind) {
53 (None, CursorKind::Hidden)
54 }
56 /// May be used by the parent component to compute the child area.
57 /// viewport is the maximum allowed area, and the child should stay within those bounds.
58 fn required_size(&mut self, _viewport: (u16, u16)) -> Option<(u16, u16)> {
59 // TODO: for scrolling, the scroll wrapper should place a size + offset on the Context
60 // that way render can use it
61 None
62 }
64 fn type_name(&self) -> &'static str {
65 std::any::type_name::<Self>()
66 }
69use anyhow::Error;
70use std::io::stdout;
71use tui::backend::{Backend, CrosstermBackend};
72type Terminal = tui::terminal::Terminal<CrosstermBackend<std::io::Stdout>>;
74pub struct Compositor {
75 layers: Vec<Box<dyn Component>>,
76 terminal: Terminal,
78 pub(crate) last_picker: Option<Box<dyn Component>>,
81impl Compositor {
82 pub fn new() -> Result<Self, Error> {
83 let backend = CrosstermBackend::new(stdout());
84 let terminal = Terminal::new(backend)?;
85 Ok(Self {
86 layers: Vec::new(),
87 terminal,
88 last_picker: None,
89 })
90 }
92 pub fn size(&self) -> Rect {
93 self.terminal.size().expect("couldn't get terminal size")
94 }
96 pub fn resize(&mut self, width: u16, height: u16) {
97 self.terminal
98 .resize(Rect::new(0, 0, width, height))
99 .expect("Unable to resize terminal")
100 }
102 pub fn save_cursor(&mut self) {
103 if self.terminal.cursor_kind() == CursorKind::Hidden {
104 self.terminal
105 .backend_mut()
106 .show_cursor(CursorKind::Block)
107 .ok();
108 }
109 }
111 pub fn load_cursor(&mut self) {
112 if self.terminal.cursor_kind() == CursorKind::Hidden {
113 self.terminal.backend_mut().hide_cursor().ok();
114 }
115 }
117 pub fn push(&mut self, mut layer: Box<dyn Component>) {
118 let size = self.size();
119 // trigger required_size on init
120 layer.required_size((size.width, size.height));
121 self.layers.push(layer);
122 }
124 pub fn pop(&mut self) -> Option<Box<dyn Component>> {
125 self.layers.pop()
126 }
128 pub fn handle_event(&mut self, event: Event, cx: &mut Context) -> bool {
129 // propagate events through the layers until we either find a layer that consumes it or we
130 // run out of layers (event bubbling)
131 for layer in self.layers.iter_mut().rev() {
132 match layer.handle_event(event, cx) {
133 EventResult::Consumed(Some(callback)) => {
134 callback(self);
135 return true;
136 }
137 EventResult::Consumed(None) => return true,
138 EventResult::Ignored => false,
139 };
140 }
141 false
142 }
144 pub fn render(&mut self, cx: &mut Context) {
145 self.terminal
146 .autoresize()
147 .expect("Unable to determine terminal size");
149 // TODO: need to recalculate view tree if necessary
151 let surface = self.terminal.current_buffer_mut();
153 let area = *surface.area();
155 for layer in &mut self.layers {
156 layer.render(area, surface, cx);
157 }
159 let (pos, kind) = self.cursor(area, cx.editor);
160 let pos = pos.map(|pos| (pos.col as u16, pos.row as u16));
162 self.terminal.draw(pos, kind).unwrap();
163 }
165 pub fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
166 for layer in self.layers.iter().rev() {
167 if let (Some(pos), kind) = layer.cursor(area, editor) {
168 return (Some(pos), kind);
169 }
170 }
171 (None, CursorKind::Hidden)
172 }
174 pub fn find(&mut self, type_name: &str) -> Option<&mut dyn Component> {
175 self.layers
176 .iter_mut()
177 .find(|component| component.type_name() == type_name)
178 .map(|component| component.as_mut())
179 }
182// View casting, taken straight from Cursive
184use std::any::Any;
186/// A view that can be downcasted to its concrete type.
187///
188/// This trait is automatically implemented for any `T: Component`.
189pub trait AnyComponent {
190 /// Downcast self to a `Any`.
191 fn as_any(&self) -> &dyn Any;
193 /// Downcast self to a mutable `Any`.
194 fn as_any_mut(&mut self) -> &mut dyn Any;
196 /// Returns a boxed any from a boxed self.
197 ///
198 /// Can be used before `Box::downcast()`.
199 ///
200 /// # Examples
201 ///
202 /// ```rust
203 /// use helix_term::{ui::Text, compositor::Component};
204 /// let boxed: Box<Component> = Box::new(Text::new("text".to_string()));
205 /// let text: Box<Text> = boxed.as_boxed_any().downcast().unwrap();
206 /// ```
207 fn as_boxed_any(self: Box<Self>) -> Box<dyn Any>;
210impl<T: Component> AnyComponent for T {
211 /// Downcast self to a `Any`.
212 fn as_any(&self) -> &dyn Any {
213 self
214 }
216 /// Downcast self to a mutable `Any`.
217 fn as_any_mut(&mut self) -> &mut dyn Any {
218 self
219 }
221 fn as_boxed_any(self: Box<Self>) -> Box<dyn Any> {
222 self
223 }
226impl dyn AnyComponent {
227 /// Attempts to downcast `self` to a concrete type.
228 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
229 self.as_any().downcast_ref()
230 }
232 /// Attempts to downcast `self` to a concrete type.
233 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
234 self.as_any_mut().downcast_mut()
235 }
237 /// Attempts to downcast `Box<Self>` to a concrete type.
238 pub fn downcast<T: Any>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
239 // Do the check here + unwrap, so the error
240 // value is `Self` and not `dyn Any`.
241 if self.as_any().is::<T>() {
242 Ok(self.as_boxed_any().downcast().unwrap())
243 } else {
244 Err(self)
245 }
246 }
248 /// Checks if this view is of type `T`.
249 pub fn is<T: Any>(&mut self) -> bool {
250 self.as_any().is::<T>()
251 }