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