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    ///
318    /// Call this from the host application's `view`, mapping the editor's
319    /// [`Message`] into the host's own message type.
320    ///
321    /// # Returns
322    ///
323    /// An `Element` rendering the editor, its gutter, and any open overlay
324    ///
325    /// # Example
326    ///
327    /// ```
328    /// use iced::Element;
329    /// use iced_code_editor::{CodeEditor, Message};
330    ///
331    /// /// The host application's own message type.
332    /// #[derive(Debug, Clone)]
333    /// enum AppMessage {
334    ///     Editor(Message),
335    /// }
336    ///
337    /// fn view(editor: &CodeEditor) -> Element<'_, AppMessage> {
338    ///     editor.view().map(AppMessage::Editor)
339    /// }
340    /// ```
341    pub fn view(&self) -> Element<'_, Message> {
342        // Calculate canvas height and visual lines
343        let (visual_lines, canvas_height) = self.calculate_canvas_height();
344
345        // Create scrollable containing the canvas
346        let scrollable = self.create_canvas_with_scrollable(canvas_height);
347
348        // Create background layer with gutter and code backgrounds
349        let background_row = self.create_background_layer();
350
351        // Build editor stack: backgrounds + scrollable
352        let mut editor_stack =
353            iced::widget::Stack::new().push(background_row).push(scrollable);
354
355        // Add IME layer for input method support.
356        // The IME requester needs the cursor rect in viewport coordinates, which
357        // depends on the current logical↔visual mapping.
358        let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
359        let ime_layer = self.create_ime_layer(cursor_rect);
360        editor_stack = editor_stack.push(ime_layer);
361
362        // Add search dialog overlay if open
363        if self.search_state.is_open {
364            let search_dialog =
365                search_dialog::view(&self.search_state, &self.translations);
366
367            // Position the dialog in top-right corner with 20px margin
368            let positioned_dialog = container(
369                Row::new()
370                    .push(Space::new().width(Length::Fill))
371                    .push(search_dialog),
372            )
373            .padding(20)
374            .width(Length::Fill)
375            .height(Length::Shrink);
376
377            editor_stack = editor_stack.push(positioned_dialog);
378        }
379
380        // Add the compact go-to-line dialog in the top center.
381        if self.goto_line_state.is_open {
382            let goto_line_dialog = goto_line_dialog::view(
383                &self.goto_line_state,
384                self.buffer.line_count(),
385            );
386            let positioned_dialog = container(
387                Row::new()
388                    .push(Space::new().width(Length::Fill))
389                    .push(goto_line_dialog)
390                    .push(Space::new().width(Length::Fill)),
391            )
392            .padding(20)
393            .width(Length::Fill)
394            .height(Length::Shrink);
395
396            editor_stack = editor_stack.push(positioned_dialog);
397        }
398
399        // Wrap the editor stack in a container with clip
400        let editor_container = container(editor_stack)
401            .width(Length::Fill)
402            .height(Length::Fill)
403            .clip(true);
404
405        // The context menu owns its transient open/close state and positions
406        // itself at the right-click location. The canvas still receives the
407        // right-click event so it can preserve or reposition the selection.
408        let can_undo = self.history.can_undo();
409        let can_redo = self.history.can_redo();
410        let has_selection =
411            self.cursors.iter().any(|cursor| cursor.has_selection());
412        let has_content =
413            self.buffer.line_count() > 1 || self.buffer.line_len(0) > 0;
414        let custom_context_menu_entries =
415            self.custom_context_menu_entries().to_vec();
416        let default_context_menu_enabled = self.default_context_menu_enabled();
417        let reveal_in_file_manager_enabled =
418            self.reveal_in_file_manager_enabled();
419        let translations = self.translations;
420        let editor_container = ContextMenu::new(editor_container, move || {
421            context_menu::view(
422                &custom_context_menu_entries,
423                default_context_menu_enabled,
424                context_menu::MenuState {
425                    can_undo,
426                    can_redo,
427                    has_selection,
428                    has_content,
429                    reveal_in_file_manager_enabled,
430                },
431                translations,
432            )
433        });
434
435        // When wrap is disabled, add a horizontal scrollbar below the editor.
436        let editor_body: Element<'_, Message> = if self.wrap_enabled {
437            editor_container.into()
438        } else {
439            // Measuring the widest line scans the entire buffer. It is only
440            // needed for the horizontal scrollbar, so never do that work while
441            // wrapping is enabled (the default), especially after every edit in
442            // a large file.
443            let max_content_width = self.max_content_width();
444            if let Some(h_scrollbar) =
445                self.create_horizontal_scrollbar(max_content_width)
446            {
447                Column::new().push(editor_container).push(h_scrollbar).into()
448            } else {
449                editor_container.into()
450            }
451        };
452
453        if self.vim_enabled {
454            Column::new()
455                .push(editor_body)
456                .push(self.create_vim_status_bar())
457                .width(Length::Fill)
458                .height(Length::Fill)
459                .into()
460        } else {
461            editor_body
462        }
463    }
464}
465
466/// Builds a plain-color scrollable rail: a solid background track with a
467/// solid-color scroller, square corners of `radius`, and no border.
468///
469/// Shared by the canvas editor's own scrollbars ([`view`]) and the LSP
470/// overlay panels ([`lsp::process::overlay`]), which derive their colors from
471/// a theme palette instead of plain [`Color`]s.
472///
473/// # Examples
474///
475/// ```text
476/// let rail = scrollable_rail(Color::BLACK, Color::WHITE, 4.0);
477/// ```
478pub(crate) fn scrollable_rail(
479    background: Color,
480    scroller: Color,
481    radius: f32,
482) -> iced::widget::scrollable::Rail {
483    iced::widget::scrollable::Rail {
484        background: Some(background.into()),
485        border: iced::Border {
486            radius: radius.into(),
487            width: 0.0,
488            color: Color::TRANSPARENT,
489        },
490        scroller: iced::widget::scrollable::Scroller {
491            background: scroller.into(),
492            border: iced::Border {
493                radius: radius.into(),
494                width: 0.0,
495                color: Color::TRANSPARENT,
496            },
497        },
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn test_scrollable_rail_sets_background_scroller_and_radius() {
507        let bg = Color::from_rgb(0.1, 0.2, 0.3);
508        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
509        let rail = scrollable_rail(bg, scroller, 4.0);
510
511        assert_eq!(rail.background, Some(iced::Background::Color(bg)));
512        assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
513        assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
514        assert!(rail.border.width.abs() < f32::EPSILON);
515        assert_eq!(
516            rail.scroller.border.radius,
517            iced::border::Radius::from(4.0)
518        );
519    }
520
521    #[test]
522    fn test_canvas_scrollbar_style_uses_transparent_container() {
523        let bg = Color::from_rgb(0.1, 0.2, 0.3);
524        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
525        let style = canvas_scrollbar_style(bg, scroller);
526
527        assert_eq!(
528            style.container.background,
529            Some(Background::Color(Color::TRANSPARENT))
530        );
531        let expected_rail = scrollable_rail(bg, scroller, 4.0);
532        assert_eq!(style.vertical_rail.background, expected_rail.background);
533        assert_eq!(style.horizontal_rail.background, expected_rail.background);
534    }
535}