Debian Codegraph @

helix-term/src/compositor.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Each component declares its own size constraints and gets fitted based on its parent.
2 // Q: how does this work with popups?
3 // cursive does compositor.screen_mut().add_layer_at(pos::absolute(x, y), <component>)
4 use helix_core::Position;
5 use helix_view::graphics::{CursorKind, Rect};
6
7 use tui::buffer::Buffer as Surface;
8
9 pub type Callback = Box<dyn FnOnce(&mut Compositor, &mut Context)>;
10 pub type SyncCallback = Box<dyn FnOnce(&mut Compositor, &mut Context) + Sync>;
11
12 // Cursive-inspired
13 pub enum EventResult {
14 Ignored(Option<Callback>),
15 Consumed(Option<Callback>),
16 }
17
18 use crate::job::Jobs;
19 use crate::ui::picker;
20 use helix_view::Editor;
21
22 pub use helix_view::input::Event;
23
24 pub struct Context<'a> {
25 pub editor: &'a mut Editor,
26 pub scroll: Option<usize>,
27 pub jobs: &'a mut Jobs,
28 }
29
30 impl Context<'_> {
31 /// Waits on all pending jobs, and then tries to flush all pending write
32 /// operations for all documents.
33 pub fn block_try_flush_writes(&mut self) -> anyhow::Result<()> {
34 tokio::task::block_in_place(|| helix_lsp::block_on(self.jobs.finish(self.editor, None)))?;
35 tokio::task::block_in_place(|| helix_lsp::block_on(self.editor.flush_writes()))?;
36 Ok(())
37 }
38 }
39
40 pub trait Component: Any + AnyComponent {
41 /// Process input events, return true if handled.
42 fn handle_event(&mut self, _event: &Event, _ctx: &mut Context) -> EventResult {
43 EventResult::Ignored(None)
44 }
45 // , args: ()
46
47 /// Should redraw? Useful for saving redraw cycles if we know component didn't change.
48 fn should_update(&self) -> bool {
49 true
50 }
51
52 /// Render the component onto the provided surface.
53 fn render(&mut self, area: Rect, frame: &mut Surface, ctx: &mut Context);
54
55 /// Get cursor position and cursor kind.
56 fn cursor(&self, _area: Rect, _ctx: &Editor) -> (Option<Position>, CursorKind) {
57 (None, CursorKind::Hidden)
58 }
59
60 /// May be used by the parent component to compute the child area.
61 /// viewport is the maximum allowed area, and the child should stay within those bounds.
62 ///
63 /// The returned size might be larger than the viewport if the child is too big to fit.
64 /// In this case the parent can use the values to calculate scroll.
65 fn required_size(&mut self, _viewport: (u16, u16)) -> Option<(u16, u16)> {
66 None
67 }
68
69 fn type_name(&self) -> &'static str {
70 std::any::type_name::<Self>()
71 }
72
73 fn id(&self) -> Option<&'static str> {
74 None
75 }
76 }
77
78 pub struct Compositor {
79 layers: Vec<Box<dyn Component>>,
80 area: Rect,
81
82 pub(crate) last_picker: Option<Box<dyn Component>>,
83 pub(crate) full_redraw: bool,
84 }
85
86 impl Compositor {
87 pub fn new(area: Rect) -> Self {
88 Self {
89 layers: Vec::new(),
90 area,
91 last_picker: None,
92 full_redraw: false,
93 }
94 }
95
96 pub fn size(&self) -> Rect {
97 self.area
98 }
99
100 pub fn resize(&mut self, area: Rect) {
101 self.area = area;
102 }
103
104 /// Add a layer to be rendered in front of all existing layers.
105 pub fn push(&mut self, mut layer: Box<dyn Component>) {
106 // immediately clear last_picker field to avoid excessive memory
107 // consumption for picker with many items
108 if layer.id() == Some(picker::ID) {
109 self.last_picker = None;
110 }
111 let size = self.size();
112 // trigger required_size on init
113 layer.required_size((size.width, size.height));
114 self.layers.push(layer);
115 }
116
117 /// Replace a component that has the given `id` with the new layer and if
118 /// no component is found, push the layer normally.
119 pub fn replace_or_push<T: Component>(&mut self, id: &'static str, layer: T) {
120 if let Some(component) = self.find_id(id) {
121 *component = layer;
122 } else {
123 self.push(Box::new(layer))
124 }
125 }
126
127 pub fn pop(&mut self) -> Option<Box<dyn Component>> {
128 self.layers.pop()
129 }
130
131 pub fn remove(&mut self, id: &'static str) -> Option<Box<dyn Component>> {
132 let idx = self
133 .layers
134 .iter()
135 .position(|layer| layer.id() == Some(id))?;
136 Some(self.layers.remove(idx))
137 }
138
139 pub fn remove_type<T: 'static>(&mut self) {
140 let type_name = std::any::type_name::<T>();
141 self.layers
142 .retain(|component| component.type_name() != type_name);
143 }
144 pub fn handle_event(&mut self, event: &Event, cx: &mut Context) -> bool {
145 // If it is a key event, a macro is being recorded, and a macro isn't being replayed,
146 // push the key event to the recording.
147 if let (Event::Key(key), Some((_, keys))) = (event, &mut cx.editor.macro_recording) {
148 if cx.editor.macro_replaying.is_empty() {
149 keys.push(*key);
150 }
151 }
152
153 let mut callbacks = Vec::new();
154 let mut consumed = false;
155
156 // propagate events through the layers until we either find a layer that consumes it or we
157 // run out of layers (event bubbling), starting at the front layer and then moving to the
158 // background.
159 for layer in self.layers.iter_mut().rev() {
160 match layer.handle_event(event, cx) {
161 EventResult::Consumed(Some(callback)) => {
162 callbacks.push(callback);
163 consumed = true;
164 break;
165 }
166 EventResult::Consumed(None) => {
167 consumed = true;
168 break;
169 }
170 EventResult::Ignored(Some(callback)) => {
171 callbacks.push(callback);
172 }
173 EventResult::Ignored(None) => {}
174 };
175 }
176
177 for callback in callbacks {
178 callback(self, cx)
179 }
180
181 consumed
182 }
183
184 pub fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
185 for layer in &mut self.layers {
186 layer.render(area, surface, cx);
187 }
188 }
189
190 pub fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
191 for layer in self.layers.iter().rev() {
192 if let (Some(pos), kind) = layer.cursor(area, editor) {
193 return (Some(pos), kind);
194 }
195 }
196 (None, CursorKind::Hidden)
197 }
198
199 pub fn has_component(&self, type_name: &str) -> bool {
200 self.layers
201 .iter()
202 .any(|component| component.type_name() == type_name)
203 }
204
205 pub fn find<T: 'static>(&mut self) -> Option<&mut T> {
206 let type_name = std::any::type_name::<T>();
207 self.layers
208 .iter_mut()
209 .find(|component| component.type_name() == type_name)
210 .and_then(|component| component.as_any_mut().downcast_mut())
211 }
212
213 pub fn find_id<T: 'static>(&mut self, id: &'static str) -> Option<&mut T> {
214 self.layers
215 .iter_mut()
216 .find(|component| component.id() == Some(id))
217 .and_then(|component| component.as_any_mut().downcast_mut())
218 }
219
220 pub fn need_full_redraw(&mut self) {
221 self.full_redraw = true;
222 }
223
224 pub fn layer_count(&self) -> usize {
225 self.layers.len()
226 }
227 }
228
229 // View casting, taken straight from Cursive
230
231 use std::any::Any;
232
233 /// A view that can be downcasted to its concrete type.
234 ///
235 /// This trait is automatically implemented for any `T: Component`.
236 pub trait AnyComponent {
237 /// Downcast self to a `Any`.
238 fn as_any(&self) -> &dyn Any;
239
240 /// Downcast self to a mutable `Any`.
241 fn as_any_mut(&mut self) -> &mut dyn Any;
242
243 /// Returns a boxed any from a boxed self.
244 ///
245 /// Can be used before `Box::downcast()`.
246 ///
247 /// # Examples
248 ///
•249 /// ```rust,no_run
250 /// use helix_term::{ui::Text, compositor::Component};
251 /// let boxed: Box<dyn Component> = Box::new(Text::new("text".to_string()));
252 /// let text: Box<Text> = boxed.as_boxed_any().downcast().unwrap();
253 /// ```
254 fn as_boxed_any(self: Box<Self>) -> Box<dyn Any>;
255 }
256
257 impl<T: Component> AnyComponent for T {
258 /// Downcast self to a `Any`.
259 fn as_any(&self) -> &dyn Any {
260 self
261 }
262
263 /// Downcast self to a mutable `Any`.
264 fn as_any_mut(&mut self) -> &mut dyn Any {
265 self
266 }
267
268 fn as_boxed_any(self: Box<Self>) -> Box<dyn Any> {
269 self
270 }
271 }
272
273 impl dyn AnyComponent {
274 /// Attempts to downcast `self` to a concrete type.
275 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
276 self.as_any().downcast_ref()
277 }
278
279 /// Attempts to downcast `self` to a concrete type.
280 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
281 self.as_any_mut().downcast_mut()
282 }
283
284 /// Attempts to downcast `Box<Self>` to a concrete type.
285 pub fn downcast<T: Any>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
286 // Do the check here + unwrap, so the error
287 // value is `Self` and not `dyn Any`.
288 if self.as_any().is::<T>() {
289 Ok(self.as_boxed_any().downcast().unwrap())
290 } else {
291 Err(self)
292 }
293 }
294
295 /// Checks if this view is of type `T`.
296 pub fn is<T: Any>(&mut self) -> bool {
297 self.as_any().is::<T>()
298 }
299 }