Debian Codegraph @

helix-term/src/ui/popup.rs

raw symbols SCIP
1 use crate::{
2 commands::Open,
3 compositor::{Callback, Component, Context, Event, EventResult},
4 ctrl, key,
5 };
6 use tui::{
7 buffer::Buffer as Surface,
8 widgets::{Block, Widget},
9 };
10
11 use helix_core::Position;
12 use helix_view::{
13 graphics::{Margin, Rect},
14 input::{MouseEvent, MouseEventKind},
15 Editor,
16 };
17
18 const MIN_HEIGHT: u16 = 6;
19 const MAX_HEIGHT: u16 = 26;
20 const MAX_WIDTH: u16 = 120;
21
22 struct RenderInfo {
23 area: Rect,
24 child_height: u16,
25 render_borders: bool,
26 is_menu: bool,
27 }
28
29 // TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return
30 // a width/height hint. maybe Popup(Box<Component>)
31
32 pub struct Popup<T: Component> {
33 contents: T,
34 position: Option<Position>,
35 area: Rect,
36 position_bias: Open,
37 scroll_half_pages: usize,
38 auto_close: bool,
39 ignore_escape_key: bool,
40 id: &'static str,
41 has_scrollbar: bool,
42 }
43
44 impl<T: Component> Popup<T> {
45 pub fn new(id: &'static str, contents: T) -> Self {
46 Self {
47 contents,
48 position: None,
49 position_bias: Open::Below,
50 area: Rect::new(0, 0, 0, 0),
51 scroll_half_pages: 0,
52 auto_close: false,
53 ignore_escape_key: false,
54 id,
55 has_scrollbar: true,
56 }
57 }
58
59 /// Set the anchor position next to which the popup should be drawn.
60 ///
61 /// Note that this is not the position of the top-left corner of the rendered popup itself,
62 /// but rather the screen-space position of the information to which the popup refers.
63 pub fn position(mut self, pos: Option<Position>) -> Self {
64 self.position = pos;
65 self
66 }
67
68 pub fn get_position(&self) -> Option<Position> {
69 self.position
70 }
71
72 /// Set the popup to prefer to render above or below the anchor position.
73 ///
74 /// This preference will be ignored if the viewport doesn't have enough space in the
75 /// chosen direction.
76 pub fn position_bias(mut self, bias: Open) -> Self {
77 self.position_bias = bias;
78 self
79 }
80
81 pub fn auto_close(mut self, auto_close: bool) -> Self {
82 self.auto_close = auto_close;
83 self
84 }
85
86 /// Ignores an escape keypress event, letting the outer layer
87 /// (usually the editor) handle it. This is useful for popups
88 /// in insert mode like completion and signature help where
89 /// the popup is closed on the mode change from insert to normal
90 /// which is done with the escape key. Otherwise the popup consumes
91 /// the escape key event and closes it, and an additional escape
92 /// would be required to exit insert mode.
93 pub fn ignore_escape_key(mut self, ignore: bool) -> Self {
94 self.ignore_escape_key = ignore;
95 self
96 }
97
98 pub fn scroll_half_page_down(&mut self) {
99 self.scroll_half_pages += 1;
100 }
101
102 pub fn scroll_half_page_up(&mut self) {
103 self.scroll_half_pages = self.scroll_half_pages.saturating_sub(1);
104 }
105
106 /// Toggles the Popup's scrollbar.
107 /// Consider disabling the scrollbar in case the child
108 /// already has its own.
109 pub fn with_scrollbar(mut self, enable_scrollbar: bool) -> Self {
110 self.has_scrollbar = enable_scrollbar;
111 self
112 }
113
114 pub fn contents(&self) -> &T {
115 &self.contents
116 }
117
118 pub fn contents_mut(&mut self) -> &mut T {
119 &mut self.contents
120 }
121
122 pub fn area(&mut self, viewport: Rect, editor: &Editor) -> Rect {
123 self.render_info(viewport, editor).area
124 }
125
126 fn render_info(&mut self, viewport: Rect, editor: &Editor) -> RenderInfo {
127 let mut position = editor.cursor().0.unwrap_or_default();
128 if let Some(old_position) = self
129 .position
130 .filter(|old_position| old_position.row == position.row)
131 {
132 position = old_position;
133 } else {
134 self.position = Some(position);
135 }
136
137 let is_menu = self
138 .contents
139 .type_name()
140 .starts_with("helix_term::ui::menu::Menu");
141
142 let mut render_borders = if is_menu {
143 editor.menu_border()
144 } else {
145 editor.popup_border()
146 };
147
148 // -- make sure frame doesn't stick out of bounds
149 let mut rel_x = position.col as u16;
150 let mut rel_y = position.row as u16;
151
152 // if there's a orientation preference, use that
153 // if we're on the top part of the screen, do below
154 // if we're on the bottom part, do above
155 let can_put_below = viewport.height > rel_y + MIN_HEIGHT;
156 let can_put_above = rel_y.checked_sub(MIN_HEIGHT).is_some();
157 let final_pos = match self.position_bias {
158 Open::Below => match can_put_below {
159 true => Open::Below,
160 false => Open::Above,
161 },
162 Open::Above => match can_put_above {
163 true => Open::Above,
164 false => Open::Below,
165 },
166 };
167
168 // compute maximum space available for child
169 let mut max_height = match final_pos {
170 Open::Above => rel_y,
171 Open::Below => viewport.height.saturating_sub(1 + rel_y),
172 };
173 max_height = max_height.min(MAX_HEIGHT);
174 let mut max_width = viewport.width.saturating_sub(2).min(MAX_WIDTH);
175 render_borders = render_borders && max_height > 3 && max_width > 3;
176 if render_borders {
177 max_width -= 2;
178 max_height -= 2;
179 }
180
181 // compute required child size and reclamp
182 let (mut width, child_height) = self
183 .contents
184 .required_size((max_width, max_height))
185 .expect("Component needs required_size implemented in order to be embedded in a popup");
186
187 width = width.min(MAX_WIDTH);
188 let height = if render_borders {
189 (child_height + 2).min(MAX_HEIGHT)
190 } else {
191 child_height.min(MAX_HEIGHT)
192 };
193 if render_borders {
194 width += 2;
195 }
196 if viewport.width <= rel_x + width + 2 {
197 rel_x = viewport.width.saturating_sub(width + 2);
198 width = viewport.width.saturating_sub(rel_x + 2)
199 }
200
201 let area = match final_pos {
202 Open::Above => {
203 rel_y = rel_y.saturating_sub(height);
204 Rect::new(rel_x, rel_y, width, position.row as u16 - rel_y)
205 }
206 Open::Below => {
207 rel_y += 1;
208 let y_max = viewport.bottom().min(height + rel_y);
209 Rect::new(rel_x, rel_y, width, y_max - rel_y)
210 }
211 };
212 RenderInfo {
213 area,
214 child_height,
215 render_borders,
216 is_menu,
217 }
218 }
219
220 fn handle_mouse_event(
221 &mut self,
222 &MouseEvent {
223 kind,
224 column: x,
225 row: y,
226 ..
227 }: &MouseEvent,
228 ) -> EventResult {
229 if self.auto_close && matches!(kind, MouseEventKind::Down(_)) {
230 let close_fn: Callback = Box::new(|compositor, _| {
231 // remove the layer
232 compositor.remove(self.id.as_ref());
233 });
234
235 return EventResult::Ignored(Some(close_fn));
236 }
237
238 let mouse_is_within_popup = x >= self.area.left()
239 && x < self.area.right()
240 && y >= self.area.top()
241 && y < self.area.bottom();
242
243 if !mouse_is_within_popup {
244 return EventResult::Ignored(None);
245 }
246
247 match kind {
248 MouseEventKind::ScrollDown if self.has_scrollbar => {
249 self.scroll_half_page_down();
250 EventResult::Consumed(None)
251 }
252 MouseEventKind::ScrollUp if self.has_scrollbar => {
253 self.scroll_half_page_up();
254 EventResult::Consumed(None)
255 }
256 _ => EventResult::Ignored(None),
257 }
258 }
259 }
260
261 impl<T: Component> Component for Popup<T> {
262 fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
263 let key = match event {
264 Event::Key(event) => *event,
265 Event::Mouse(event) => return self.handle_mouse_event(event),
266 Event::Resize(_, _) => {
267 // TODO: calculate inner area, call component's handle_event with that area
268 return EventResult::Ignored(None);
269 }
270 _ => return EventResult::Ignored(None),
271 };
272
273 if key!(Esc) == key && self.ignore_escape_key {
274 return EventResult::Ignored(None);
275 }
276
277 let close_fn: Callback = Box::new(|compositor, _| {
278 // remove the layer
279 compositor.remove(self.id.as_ref());
280 });
281
282 // Code completion handles arrows and page up/down itself,
283 // but code lens does not. First check whether content knows
284 // about the key event. When not, check the default keys.
285 match self.contents.handle_event(event, cx) {
286 EventResult::Ignored(fn_once) => {
287 match key {
288 // esc or ctrl-c aborts the completion and closes the menu
289 key!(Esc) | ctrl!('c') => {
290 let _ = self.contents.handle_event(event, cx);
291 EventResult::Consumed(Some(close_fn))
292 }
293 key!(PageDown) | ctrl!('d') => {
294 self.scroll_half_page_down();
295 EventResult::Consumed(None)
296 }
297 key!(PageUp) | ctrl!('u') => {
298 self.scroll_half_page_up();
299 EventResult::Consumed(None)
300 }
301 _ => {
302 // for some events, we want to process them but send ignore, specifically all input except
303 // tab/enter/ctrl-k or whatever will confirm the selection/ ctrl-n/ctrl-p for scroll.
304
305 if self.auto_close {
306 EventResult::Ignored(Some(close_fn))
307 } else {
308 EventResult::Ignored(fn_once)
309 }
310 }
311 }
312 }
313 ev => ev,
314 }
315 }
316
317 fn render(&mut self, viewport: Rect, surface: &mut Surface, cx: &mut Context) {
318 let RenderInfo {
319 area,
320 child_height,
321 render_borders,
322 is_menu,
323 } = self.render_info(viewport, cx.editor);
324 self.area = area;
325
326 // clear area
327 let background = if is_menu {
328 // TODO: consistently style menu
329 cx.editor
330 .theme
331 .try_get("ui.menu")
332 .unwrap_or_else(|| cx.editor.theme.get("ui.text"))
333 } else {
334 cx.editor.theme.get("ui.popup")
335 };
336 surface.clear_with(area, background);
337
338 let mut inner = area;
339 if render_borders {
340 inner = area.inner(Margin::all(1));
341 Widget::render(Block::bordered(), area, surface);
342 }
343 let border = usize::from(render_borders);
344
345 let max_offset = child_height.saturating_sub(inner.height) as usize;
346 let half_page_size = (inner.height / 2) as usize;
347 let scroll = max_offset.min(self.scroll_half_pages * half_page_size);
348 self.scroll_half_pages = scroll
349 .checked_div(half_page_size)
350 .unwrap_or(self.scroll_half_pages);
351 cx.scroll = Some(scroll);
352 self.contents.render(inner, surface, cx);
353
354 // render scrollbar if contents do not fit
355 if self.has_scrollbar {
356 let win_height = inner.height as usize;
357 let len = child_height as usize;
358 let fits = len <= win_height;
359 let scroll_style = cx.editor.theme.get("ui.menu.scroll");
360
361 if !fits {
362 let scroll_height = win_height.pow(2).div_ceil(len).min(win_height);
363 let scroll_line = (win_height - scroll_height) * scroll
364 / std::cmp::max(1, len.saturating_sub(win_height));
365
366 let mut cell;
367 for i in 0..win_height {
368 cell =
369 &mut surface[(inner.right() - 1 + border as u16, inner.top() + i as u16)];
370
371 let half_block = if render_borders { "▌" } else { "▐" };
372
373 if scroll_line <= i && i < scroll_line + scroll_height {
374 // Draw scroll thumb
375 cell.set_symbol(half_block);
376 cell.set_fg(scroll_style.fg.unwrap_or(helix_view::theme::Color::Reset));
377 } else if !render_borders {
378 // Draw scroll track
379 cell.set_symbol(half_block);
380 cell.set_fg(scroll_style.bg.unwrap_or(helix_view::theme::Color::Reset));
381 }
382 }
383 }
384 }
385 }
386
387 fn id(&self) -> Option<&'static str> {
388 Some(self.id)
389 }
390 }