Skip to main content

iced_code_editor/canvas_editor/render/
view.rs

1//! Iced UI view and rendering logic.
2
3use iced::Size;
4use iced::advanced::input_method;
5use iced::widget::canvas::Canvas;
6use iced::widget::{
7    Column, Row, Scrollable, Space, container, scrollable, text,
8};
9use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
10use iced_aw::ContextMenu;
11
12use super::wrapping::{self, WrappingCalculator};
13use crate::canvas_editor::features::context_menu;
14use crate::canvas_editor::features::goto_line::dialog as goto_line_dialog;
15use crate::canvas_editor::features::search::dialog as search_dialog;
16use crate::canvas_editor::input::ime_requester::ImeRequester;
17use crate::canvas_editor::{CodeEditor, GUTTER_WIDTH, Message};
18use std::rc::Rc;
19
20/// Builds the transparent-container scrollable style shared by the canvas
21/// editor's vertical and horizontal scrollbars.
22fn canvas_scrollbar_style(
23    scrollbar_bg: Color,
24    scroller_color: Color,
25) -> scrollable::Style {
26    scrollable::Style {
27        container: container::Style {
28            background: Some(Background::Color(Color::TRANSPARENT)),
29            ..container::Style::default()
30        },
31        vertical_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
32        horizontal_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
33        gap: None,
34        auto_scroll: scrollable::AutoScroll {
35            background: Color::TRANSPARENT.into(),
36            border: Border::default(),
37            shadow: Shadow::default(),
38            icon: Color::TRANSPARENT,
39        },
40    }
41}
42
43impl CodeEditor {
44    /// Calculates visual lines and canvas height for the editor.
45    ///
46    /// Returns a tuple of (visual_lines, canvas_height) where:
47    /// - visual_lines: The visual line mapping with wrapping applied
48    /// - canvas_height: The total height needed for the canvas
49    fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
50        // Reuse memoized visual lines so view layout (canvas height + IME cursor rect)
51        // does not trigger repeated wrapping computation.
52        let visual_lines = self.visual_lines_cached(self.viewport_width);
53        let total_visual_lines = visual_lines.len();
54        let content_height = total_visual_lines as f32 * self.line_height;
55
56        // Use max of content height and viewport height to ensure the canvas
57        // always covers the visible area (prevents visual artifacts when
58        // content is shorter than viewport after reset/file change)
59        let canvas_height = content_height.max(self.viewport_height);
60
61        (visual_lines, canvas_height)
62    }
63
64    /// Creates the scrollable style function with custom colors.
65    ///
66    /// Returns a style function that configures the scrollbar appearance.
67    fn create_scrollable_style(
68        &self,
69    ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
70        let scrollbar_bg = self.style.scrollbar_background;
71        let scroller_color = self.style.scroller_color;
72
73        move |_theme, _status| {
74            canvas_scrollbar_style(scrollbar_bg, scroller_color)
75        }
76    }
77
78    /// Creates the canvas widget wrapped in a scrollable container.
79    ///
80    /// # Arguments
81    ///
82    /// * `canvas_height` - The total height of the canvas
83    ///
84    /// # Returns
85    ///
86    /// A configured scrollable widget containing the canvas
87    fn create_canvas_with_scrollable(
88        &self,
89        canvas_height: f32,
90    ) -> Scrollable<'_, Message> {
91        let canvas = Canvas::new(self)
92            .width(Length::Fill)
93            .height(Length::Fixed(canvas_height));
94
95        Scrollable::new(canvas)
96            .id(self.scrollable_id.clone())
97            .width(Length::Fill)
98            .height(Length::Fill)
99            .on_scroll(Message::Scrolled)
100            .style(self.create_scrollable_style())
101    }
102
103    /// Creates the horizontal scrollbar element when wrap is disabled and content overflows.
104    ///
105    /// # Arguments
106    ///
107    /// * `max_content_width` - The total pixel width of the widest line
108    ///
109    /// # Returns
110    ///
111    /// `Some(element)` if a horizontal scrollbar is needed, `None` otherwise
112    fn create_horizontal_scrollbar(
113        &self,
114        max_content_width: f32,
115    ) -> Option<Element<'_, Message>> {
116        if self.wrap_enabled || max_content_width <= self.viewport_width {
117            return None;
118        }
119
120        let scrollbar_bg = self.style.scrollbar_background;
121        let scroller_color = self.style.scroller_color;
122
123        let h_scrollable = Scrollable::new(
124            Space::new().width(Length::Fixed(max_content_width)).height(0.0),
125        )
126        .id(self.horizontal_scrollable_id.clone())
127        .width(Length::Fill)
128        .height(Length::Fixed(12.0))
129        .direction(scrollable::Direction::Horizontal(
130            scrollable::Scrollbar::new(),
131        ))
132        .on_scroll(Message::HorizontalScrolled)
133        .style(move |_theme, _status| {
134            canvas_scrollbar_style(scrollbar_bg, scroller_color)
135        });
136
137        Some(h_scrollable.into())
138    }
139
140    /// Creates the gutter background container if line numbers are enabled.
141    ///
142    /// # Returns
143    ///
144    /// Some(container) if line numbers are enabled, None otherwise
145    fn create_gutter_container(
146        &self,
147    ) -> Option<container::Container<'_, Message>> {
148        if self.line_numbers_enabled {
149            let gutter_background = self.style.gutter_background;
150            Some(
151                container(
152                    Space::new().width(Length::Fill).height(Length::Fill),
153                )
154                .width(Length::Fixed(GUTTER_WIDTH))
155                .height(Length::Fill)
156                .style(move |_| container::Style {
157                    background: Some(Background::Color(gutter_background)),
158                    ..container::Style::default()
159                }),
160            )
161        } else {
162            None
163        }
164    }
165
166    /// Creates the code area background container.
167    ///
168    /// # Returns
169    ///
170    /// The code background container widget
171    fn create_code_background_container(
172        &self,
173    ) -> container::Container<'_, Message> {
174        let background_color = self.style.background;
175        container(Space::new().width(Length::Fill).height(Length::Fill))
176            .width(Length::Fill)
177            .height(Length::Fill)
178            .style(move |_| container::Style {
179                background: Some(Background::Color(background_color)),
180                ..container::Style::default()
181            })
182    }
183
184    /// Creates the fixed Vim status and command line shown below the editor.
185    fn create_vim_status_bar(&self) -> Element<'_, Message> {
186        let (left_text, right_text) = self.vim_state.status_line_text();
187        let background = self.style.gutter_background;
188        let text_color = self.style.text_color;
189
190        container(
191            Row::new()
192                .push(
193                    text(left_text).size(self.font_size).style(move |_| {
194                        text::Style { color: Some(text_color) }
195                    }),
196                )
197                .push(Space::new().width(Length::Fill))
198                .push(
199                    text(right_text).size(self.font_size).style(move |_| {
200                        text::Style { color: Some(text_color) }
201                    }),
202                ),
203        )
204        .padding([2, 8])
205        .width(Length::Fill)
206        .height(Length::Fixed(self.line_height.max(20.0)))
207        .style(move |_| container::Style {
208            background: Some(Background::Color(background)),
209            ..container::Style::default()
210        })
211        .into()
212    }
213
214    /// Creates the background layer combining gutter and code backgrounds.
215    ///
216    /// # Returns
217    ///
218    /// A row containing the background elements
219    fn create_background_layer(&self) -> Row<'_, Message> {
220        let gutter_container = self.create_gutter_container();
221        let code_background_container = self.create_code_background_container();
222
223        if let Some(gutter) = gutter_container {
224            Row::new().push(gutter).push(code_background_container)
225        } else {
226            Row::new().push(code_background_container)
227        }
228    }
229
230    /// Calculates the IME cursor rectangle for the current cursor position.
231    ///
232    /// # Arguments
233    ///
234    /// * `visual_lines` - The visual line mapping
235    ///
236    /// # Returns
237    ///
238    /// A rectangle representing the cursor position for IME
239    fn calculate_ime_cursor_rect(
240        &self,
241        visual_lines: &[wrapping::VisualLine],
242    ) -> Rectangle {
243        let ime_enabled = self.is_focused() && self.has_canvas_focus;
244
245        if !ime_enabled {
246            return Rectangle::new(
247                iced::Point::new(0.0, 0.0),
248                Size::new(0.0, 0.0),
249            );
250        }
251
252        if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
253            visual_lines,
254            self.cursors.primary_position().0,
255            self.cursors.primary_position().1,
256        ) {
257            let vl = &visual_lines[cursor_visual];
258            let line_content = self.buffer.line(vl.logical_line);
259            let prefix_len =
260                self.cursors.primary_position().1.saturating_sub(vl.start_col);
261            let prefix_text: String = line_content
262                .chars()
263                .skip(vl.start_col)
264                .take(prefix_len)
265                .collect();
266            let cursor_x = self.gutter_width()
267                + 5.0
268                + crate::canvas_editor::measure_text_width(
269                    &prefix_text,
270                    self.full_char_width,
271                    self.char_width,
272                )
273                - self.horizontal_scroll_offset;
274
275            // Calculate visual Y position relative to the viewport
276            // We subtract viewport_scroll because the content is scrolled up/down
277            // but the cursor position sent to IME must be relative to the visible area
278            let cursor_y = (cursor_visual as f32 * self.line_height)
279                - self.viewport_scroll;
280
281            Rectangle::new(
282                iced::Point::new(cursor_x, cursor_y + 2.0),
283                Size::new(2.0, self.line_height - 4.0),
284            )
285        } else {
286            Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
287        }
288    }
289
290    /// Creates the IME (Input Method Editor) layer widget.
291    ///
292    /// # Arguments
293    ///
294    /// * `cursor_rect` - The rectangle representing the cursor position
295    ///
296    /// # Returns
297    ///
298    /// An element containing the IME requester widget
299    fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
300        let ime_enabled = self.is_focused() && self.has_canvas_focus;
301
302        let preedit =
303            self.ime_preedit.as_ref().map(|p| input_method::Preedit {
304                content: p.content.clone(),
305                selection: p.selection.clone(),
306                text_size: None,
307            });
308
309        let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, preedit);
310        iced::Element::new(ime_layer)
311    }
312
313    /// Creates the view element with scrollable wrapper.
314    ///
315    /// The backgrounds (editor and gutter) are handled by container styles
316    /// to ensure proper clipping when the pane is resized.
317    pub fn view(&self) -> Element<'_, Message> {
318        // Calculate canvas height and visual lines
319        let (visual_lines, canvas_height) = self.calculate_canvas_height();
320
321        // Create scrollable containing the canvas
322        let scrollable = self.create_canvas_with_scrollable(canvas_height);
323
324        // Create background layer with gutter and code backgrounds
325        let background_row = self.create_background_layer();
326
327        // Build editor stack: backgrounds + scrollable
328        let mut editor_stack =
329            iced::widget::Stack::new().push(background_row).push(scrollable);
330
331        // Add IME layer for input method support.
332        // The IME requester needs the cursor rect in viewport coordinates, which
333        // depends on the current logical↔visual mapping.
334        let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
335        let ime_layer = self.create_ime_layer(cursor_rect);
336        editor_stack = editor_stack.push(ime_layer);
337
338        // Add search dialog overlay if open
339        if self.search_state.is_open {
340            let search_dialog =
341                search_dialog::view(&self.search_state, &self.translations);
342
343            // Position the dialog in top-right corner with 20px margin
344            let positioned_dialog = container(
345                Row::new()
346                    .push(Space::new().width(Length::Fill))
347                    .push(search_dialog),
348            )
349            .padding(20)
350            .width(Length::Fill)
351            .height(Length::Shrink);
352
353            editor_stack = editor_stack.push(positioned_dialog);
354        }
355
356        // Add the compact go-to-line dialog in the top center.
357        if self.goto_line_state.is_open {
358            let goto_line_dialog = goto_line_dialog::view(
359                &self.goto_line_state,
360                self.buffer.line_count(),
361            );
362            let positioned_dialog = container(
363                Row::new()
364                    .push(Space::new().width(Length::Fill))
365                    .push(goto_line_dialog)
366                    .push(Space::new().width(Length::Fill)),
367            )
368            .padding(20)
369            .width(Length::Fill)
370            .height(Length::Shrink);
371
372            editor_stack = editor_stack.push(positioned_dialog);
373        }
374
375        // Wrap the editor stack in a container with clip
376        let editor_container = container(editor_stack)
377            .width(Length::Fill)
378            .height(Length::Fill)
379            .clip(true);
380
381        // The context menu owns its transient open/close state and positions
382        // itself at the right-click location. The canvas still receives the
383        // right-click event so it can preserve or reposition the selection.
384        let can_undo = self.history.can_undo();
385        let can_redo = self.history.can_redo();
386        let has_selection =
387            self.cursors.iter().any(|cursor| cursor.has_selection());
388        let has_content =
389            self.buffer.line_count() > 1 || self.buffer.line_len(0) > 0;
390        let custom_context_menu_entries =
391            self.custom_context_menu_entries().to_vec();
392        let default_context_menu_enabled = self.default_context_menu_enabled();
393        let reveal_in_file_manager_enabled =
394            self.reveal_in_file_manager_enabled();
395        let translations = self.translations;
396        let editor_container = ContextMenu::new(editor_container, move || {
397            context_menu::view(
398                &custom_context_menu_entries,
399                default_context_menu_enabled,
400                context_menu::MenuState {
401                    can_undo,
402                    can_redo,
403                    has_selection,
404                    has_content,
405                    reveal_in_file_manager_enabled,
406                },
407                translations,
408            )
409        });
410
411        // When wrap is disabled, add a horizontal scrollbar below the editor.
412        let editor_body: Element<'_, Message> = if self.wrap_enabled {
413            editor_container.into()
414        } else {
415            // Measuring the widest line scans the entire buffer. It is only
416            // needed for the horizontal scrollbar, so never do that work while
417            // wrapping is enabled (the default), especially after every edit in
418            // a large file.
419            let max_content_width = self.max_content_width();
420            if let Some(h_scrollbar) =
421                self.create_horizontal_scrollbar(max_content_width)
422            {
423                Column::new().push(editor_container).push(h_scrollbar).into()
424            } else {
425                editor_container.into()
426            }
427        };
428
429        if self.vim_enabled {
430            Column::new()
431                .push(editor_body)
432                .push(self.create_vim_status_bar())
433                .width(Length::Fill)
434                .height(Length::Fill)
435                .into()
436        } else {
437            editor_body
438        }
439    }
440}
441
442/// Builds a plain-color scrollable rail: a solid background track with a
443/// solid-color scroller, square corners of `radius`, and no border.
444///
445/// Shared by the canvas editor's own scrollbars ([`view`]) and the LSP
446/// overlay panels ([`lsp::process::overlay`]), which derive their colors from
447/// a theme palette instead of plain [`Color`]s.
448///
449/// # Examples
450///
451/// ```ignore
452/// let rail = scrollable_rail(Color::BLACK, Color::WHITE, 4.0);
453/// ```
454pub(crate) fn scrollable_rail(
455    background: Color,
456    scroller: Color,
457    radius: f32,
458) -> iced::widget::scrollable::Rail {
459    iced::widget::scrollable::Rail {
460        background: Some(background.into()),
461        border: iced::Border {
462            radius: radius.into(),
463            width: 0.0,
464            color: Color::TRANSPARENT,
465        },
466        scroller: iced::widget::scrollable::Scroller {
467            background: scroller.into(),
468            border: iced::Border {
469                radius: radius.into(),
470                width: 0.0,
471                color: Color::TRANSPARENT,
472            },
473        },
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn test_scrollable_rail_sets_background_scroller_and_radius() {
483        let bg = Color::from_rgb(0.1, 0.2, 0.3);
484        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
485        let rail = scrollable_rail(bg, scroller, 4.0);
486
487        assert_eq!(rail.background, Some(iced::Background::Color(bg)));
488        assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
489        assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
490        assert!(rail.border.width.abs() < f32::EPSILON);
491        assert_eq!(
492            rail.scroller.border.radius,
493            iced::border::Radius::from(4.0)
494        );
495    }
496
497    #[test]
498    fn test_canvas_scrollbar_style_uses_transparent_container() {
499        let bg = Color::from_rgb(0.1, 0.2, 0.3);
500        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
501        let style = canvas_scrollbar_style(bg, scroller);
502
503        assert_eq!(
504            style.container.background,
505            Some(Background::Color(Color::TRANSPARENT))
506        );
507        let expected_rail = scrollable_rail(bg, scroller, 4.0);
508        assert_eq!(style.vertical_rail.background, expected_rail.background);
509        assert_eq!(style.horizontal_rail.background, expected_rail.background);
510    }
511}