Skip to main content

iced_code_editor/canvas_editor/render/
canvas.rs

1//! Canvas rendering implementation using Iced's `canvas::Program`.
2
3use iced::mouse;
4use iced::widget::canvas::{self, Action, Geometry};
5use iced::{Event, Rectangle, Theme, keyboard};
6use std::rc::Rc;
7
8use super::text::RenderContext;
9use super::wrapping::VisualLine;
10use crate::canvas_editor::features::color_preview;
11use crate::canvas_editor::{CodeEditor, HIGHLIGHT_LINES_PER_FRAME, Message};
12
13impl canvas::Program<Message> for CodeEditor {
14    type State = ();
15
16    /// Renders the code editor's visual elements on the canvas, including text layout, syntax highlighting,
17    /// cursor positioning, and other graphical aspects.
18    ///
19    /// # Arguments
20    ///
21    /// * `state` - The current state of the canvas
22    /// * `renderer` - The renderer used for drawing
23    /// * `theme` - The theme for styling
24    /// * `bounds` - The rectangle bounds of the canvas
25    /// * `cursor` - The mouse cursor position
26    ///
27    /// # Returns
28    ///
29    /// A vector of `Geometry` objects representing the drawn elements
30    fn draw(
31        &self,
32        _state: &Self::State,
33        renderer: &iced::Renderer,
34        _theme: &Theme,
35        bounds: Rectangle,
36        _cursor: mouse::Cursor,
37    ) -> Vec<Geometry> {
38        let visual_lines: Rc<Vec<VisualLine>> =
39            self.visual_lines_cached(bounds.width);
40
41        // Prefer the tracked viewport height when available, but fall back to
42        // the current bounds during initial layout when viewport metrics have
43        // not been populated yet.
44        let effective_viewport_height = if self.viewport_height > 0.0 {
45            self.viewport_height
46        } else {
47            bounds.height
48        };
49        let first_visible_line =
50            (self.viewport_scroll / self.line_height).floor() as usize;
51        let visible_lines_count =
52            (effective_viewport_height / self.line_height).ceil() as usize + 2;
53        let last_visible_line =
54            (first_visible_line + visible_lines_count).min(visual_lines.len());
55
56        let (start_idx, end_idx) =
57            if self.cache_window_end_line > self.cache_window_start_line {
58                let s = self.cache_window_start_line.min(visual_lines.len());
59                let e = self.cache_window_end_line.min(visual_lines.len());
60                (s, e)
61            } else {
62                (first_visible_line, last_visible_line)
63            };
64
65        // Split rendering into two cached layers:
66        // - content: expensive, mostly static text/gutter rendering
67        // - overlay: frequently changing highlights/cursor/IME
68        //
69        // This keeps selection dragging and cursor blinking smooth by avoiding
70        // invalidation of the text layer on every overlay update.
71        let visual_lines_for_content = visual_lines.clone();
72        let content_geometry =
73            self.content_cache.draw(renderer, bounds.size(), |frame| {
74                // Bound sequential syntect catch-up work for this frame. This
75                // keeps a deep jump or a cache truncation in a huge file from
76                // blocking the UI while parsing every preceding line.
77                self.highlight_lines_remaining.set(HIGHLIGHT_LINES_PER_FRAME);
78
79                // Shared with the sticky-scroll layer, which colors the same
80                // lines outside the canvas.
81                let (syntax_set, syntax_ref, syntax_theme) =
82                    self.resolve_syntax();
83
84                let ctx = RenderContext {
85                    visual_lines: visual_lines_for_content.as_ref(),
86                    bounds_width: bounds.width,
87                    gutter_width: self.gutter_width(),
88                    line_height: self.line_height,
89                    font_size: self.font_size,
90                    full_char_width: self.full_char_width,
91                    char_width: self.char_width,
92                    font: self.font,
93                    horizontal_scroll_offset: self.horizontal_scroll_offset,
94                };
95
96                // Clip code text to the code area (right of gutter) so that
97                // horizontal scrolling cannot cause text to bleed into the gutter.
98                // Note: iced renders ALL text on top of ALL geometry, so a
99                // fill_rectangle cannot mask text bleed — with_clip is required.
100                let code_clip = Rectangle {
101                    x: ctx.gutter_width,
102                    y: 0.0,
103                    width: (bounds.width - ctx.gutter_width).max(0.0),
104                    height: bounds.height,
105                };
106                frame.with_clip(code_clip, |f| {
107                    // Scoped to this pass: the memo is keyed on line index
108                    // alone, so it must not outlive a buffer that cannot
109                    // change underneath it.
110                    let mut color_literals =
111                        color_preview::LineLiterals::default();
112
113                    for (idx, visual_line) in visual_lines_for_content
114                        .iter()
115                        .enumerate()
116                        .skip(start_idx)
117                        .take(end_idx.saturating_sub(start_idx))
118                    {
119                        let y = idx as f32 * self.line_height;
120                        self.draw_indent_guides(f, &ctx, visual_line, y);
121                        self.draw_text_with_syntax_highlighting(
122                            f,
123                            &ctx,
124                            visual_line,
125                            y,
126                            syntax_ref,
127                            syntax_set,
128                            syntax_theme,
129                        );
130                        self.draw_bracket_pair_colors(f, &ctx, visual_line, y);
131                        self.draw_color_swatches(
132                            f,
133                            &ctx,
134                            visual_line,
135                            y,
136                            &mut color_literals,
137                        );
138                        self.draw_fold_collapsed_marker(
139                            f,
140                            &ctx,
141                            visual_line,
142                            y,
143                        );
144                    }
145                });
146
147                // Draw line numbers in the gutter (no clip — fixed position)
148                for (idx, visual_line) in visual_lines_for_content
149                    .iter()
150                    .enumerate()
151                    .skip(start_idx)
152                    .take(end_idx.saturating_sub(start_idx))
153                {
154                    let y = idx as f32 * self.line_height;
155                    self.draw_line_numbers(frame, &ctx, visual_line, y);
156                }
157            });
158
159        let visual_lines_for_overlay = visual_lines;
160        let overlay_geometry =
161            self.overlay_cache.draw(renderer, bounds.size(), |frame| {
162                // The overlay layer shares the same visual lines, but draws only
163                // elements that change without modifying the buffer content.
164                let ctx = RenderContext {
165                    visual_lines: visual_lines_for_overlay.as_ref(),
166                    bounds_width: bounds.width,
167                    gutter_width: self.gutter_width(),
168                    line_height: self.line_height,
169                    font_size: self.font_size,
170                    full_char_width: self.full_char_width,
171                    char_width: self.char_width,
172                    font: self.font,
173                    horizontal_scroll_offset: self.horizontal_scroll_offset,
174                };
175
176                for (idx, visual_line) in visual_lines_for_overlay
177                    .iter()
178                    .enumerate()
179                    .skip(start_idx)
180                    .take(end_idx.saturating_sub(start_idx))
181                {
182                    let y = idx as f32 * self.line_height;
183                    self.draw_current_line_highlight(
184                        frame,
185                        &ctx,
186                        visual_line,
187                        y,
188                    );
189                }
190
191                self.draw_search_highlights(frame, &ctx, start_idx, end_idx);
192                self.draw_matching_bracket_highlight(frame, &ctx);
193                self.draw_selection_highlight(frame, &ctx);
194                self.draw_jump_link_highlight(frame, &ctx, bounds, _cursor);
195                self.draw_cursor(frame, &ctx);
196            });
197
198        vec![content_geometry, overlay_geometry]
199    }
200
201    /// Handles Canvas trait events, specifically keyboard input events and focus management for the code editor widget.
202    ///
203    /// # Arguments
204    ///
205    /// * `_state` - The mutable state of the canvas (unused in this implementation)
206    /// * `event` - The input event to handle, such as keyboard presses
207    /// * `bounds` - The rectangle bounds of the canvas widget
208    /// * `cursor` - The current mouse cursor position and status
209    ///
210    /// # Returns
211    ///
212    /// An optional `Action<Message>` to perform, such as sending a message or redrawing the canvas
213    fn update(
214        &self,
215        _state: &mut Self::State,
216        event: &Event,
217        bounds: Rectangle,
218        cursor: mouse::Cursor,
219    ) -> Option<Action<Message>> {
220        match event {
221            Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
222                self.modifiers.set(*modifiers);
223                None
224            }
225            Event::Keyboard(keyboard::Event::KeyPressed {
226                key,
227                modified_key,
228                modifiers,
229                text,
230                ..
231            }) => {
232                self.modifiers.set(*modifiers);
233                self.handle_keyboard_event(
234                    key,
235                    modified_key,
236                    modifiers,
237                    text,
238                    bounds,
239                    &cursor,
240                )
241            }
242            Event::Keyboard(keyboard::Event::KeyReleased {
243                modifiers, ..
244            }) => {
245                self.modifiers.set(*modifiers);
246                None
247            }
248            Event::Mouse(mouse_event) => {
249                self.handle_mouse_event(mouse_event, bounds, &cursor)
250            }
251            Event::InputMethod(ime_event) => {
252                self.handle_ime_event(ime_event, bounds, &cursor)
253            }
254            _ => None,
255        }
256    }
257
258    /// Uses the text-selection cursor over the editable code area.
259    ///
260    /// The gutter keeps the default cursor, except for an interactive fold
261    /// chevron. Checking the cursor against `bounds` is important because a
262    /// canvas program's interaction can otherwise remain active out of bounds.
263    fn mouse_interaction(
264        &self,
265        _state: &Self::State,
266        bounds: Rectangle,
267        cursor: mouse::Cursor,
268    ) -> mouse::Interaction {
269        let Some(position) = cursor.position_in(bounds) else {
270            return mouse::Interaction::default();
271        };
272
273        if self.fold_header_at_point(position).is_some() {
274            mouse::Interaction::Pointer
275        } else if position.x >= self.gutter_width() {
276            mouse::Interaction::Text
277        } else {
278            mouse::Interaction::default()
279        }
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use iced::{Point, Size};
286
287    use super::*;
288
289    fn editor_mouse_interaction(
290        editor: &CodeEditor,
291        bounds: Rectangle,
292        cursor: mouse::Cursor,
293    ) -> mouse::Interaction {
294        canvas::Program::<Message>::mouse_interaction(
295            editor,
296            &(),
297            bounds,
298            cursor,
299        )
300    }
301
302    #[test]
303    fn test_mouse_interaction_uses_text_cursor_in_editable_area() {
304        let editor = CodeEditor::new("fn main() {}", "rs");
305        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
306        let cursor = mouse::Cursor::Available(Point::new(
307            editor.gutter_width() + 10.0,
308            10.0,
309        ));
310
311        assert_eq!(
312            editor_mouse_interaction(&editor, bounds, cursor),
313            mouse::Interaction::Text
314        );
315    }
316
317    #[test]
318    fn test_mouse_interaction_keeps_default_cursor_in_gutter_and_outside() {
319        let editor = CodeEditor::new("fn main() {}", "rs");
320        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
321
322        assert_eq!(
323            editor_mouse_interaction(
324                &editor,
325                bounds,
326                mouse::Cursor::Available(Point::new(5.0, 10.0)),
327            ),
328            mouse::Interaction::default()
329        );
330        assert_eq!(
331            editor_mouse_interaction(
332                &editor,
333                bounds,
334                mouse::Cursor::Available(Point::new(900.0, 10.0)),
335            ),
336            mouse::Interaction::default()
337        );
338    }
339}