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