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
16// A: It could just take a textarea.
18// If Compositor was specified in the callback that's then problematic because of
23 Consumed(Option<Callback>),
26use helix_view::Editor;
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 {
43 /// Should redraw? Useful for saving redraw cycles if we know component didn't change.
44 fn should_update(&self) -> bool {
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)
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
64 fn type_name(&self) -> &'static str {
65 std::any::type_name::<Self>()
71use tui::backend::{Backend, CrosstermBackend};
72type Terminal = tui::terminal::Terminal<CrosstermBackend<std::io::Stdout>>;
74pub struct Compositor {
75 layers: Vec<Box<dyn Component>>,
78 pub(crate) last_picker: Option<Box<dyn Component>>,
82 pub fn new() -> Result<Self, Error> {
83 let backend = CrosstermBackend::new(stdout());
84 let terminal = Terminal::new(backend)?;
92 pub fn size(&self) -> Rect {
93 self.terminal.size().expect("couldn't get terminal size")
96 pub fn resize(&mut self, width: u16, height: u16) {
98 .resize(Rect::new(0, 0, width, height))
99 .expect("Unable to resize terminal")
102 pub fn save_cursor(&mut self) {
103 if self.terminal.cursor_kind() == CursorKind::Hidden {
106 .show_cursor(CursorKind::Block)
111 pub fn load_cursor(&mut self) {
112 if self.terminal.cursor_kind() == CursorKind::Hidden {
113 self.terminal.backend_mut().hide_cursor().ok();
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);
124 pub fn pop(&mut self) -> Option<Box<dyn Component>> {
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)) => {
137 EventResult::Consumed(None) => return true,
138 EventResult::Ignored => false,
144 pub fn render(&mut self, cx: &mut Context) {
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);
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();
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);
171 (None, CursorKind::Hidden)
174 pub fn find(&mut self, type_name: &str) -> Option<&mut dyn Component> {
177 .find(|component| component.type_name() == type_name)
178 .map(|component| component.as_mut())
182// View casting, taken straight from Cursive
186/// A view that can be downcasted to its concrete type.
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.
198 /// Can be used before `Box::downcast()`.
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();
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 {
216 /// Downcast self to a mutable `Any`.
217 fn as_any_mut(&mut self) -> &mut dyn Any {
221 fn as_boxed_any(self: Box<Self>) -> Box<dyn Any> {
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()
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()
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())
248 /// Checks if this view is of type `T`.
249 pub fn is<T: Any>(&mut self) -> bool {
250 self.as_any().is::<T>()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list