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