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;
11#[cfg(not(target_arch = "wasm32"))]
12use std::time::Instant;
13#[cfg(target_arch = "wasm32")]
14use web_time::Instant;
15
16use crate::canvas_editor::{
17    CodeEditor, HIGHLIGHT_LINES_PER_FRAME, HIGHLIGHT_TIME_PER_FRAME, Message,
18};
19
20impl canvas::Program<Message> for CodeEditor {
21    type State = Option<iced::time::Instant>;
22
23    /// Renders the code editor's visual elements on the canvas, including text layout, syntax highlighting,
24    /// cursor positioning, and other graphical aspects.
25    ///
26    /// # Arguments
27    ///
28    /// * `state` - The current state of the canvas
29    /// * `renderer` - The renderer used for drawing
30    /// * `theme` - The theme for styling
31    /// * `bounds` - The rectangle bounds of the canvas
32    /// * `cursor` - The mouse cursor position
33    ///
34    /// # Returns
35    ///
36    /// A vector of `Geometry` objects representing the drawn elements
37    fn draw(
38        &self,
39        _state: &Self::State,
40        renderer: &iced::Renderer,
41        _theme: &Theme,
42        bounds: Rectangle,
43        _cursor: mouse::Cursor,
44    ) -> Vec<Geometry> {
45        // Track the real, live canvas width every frame, independent of the
46        // vertical-scroll-driven `viewport_width` (which never gets corrected
47        // for content that doesn't overflow vertically — see issue #26).
48        self.last_canvas_width.set(bounds.width);
49
50        let visual_lines: Rc<Vec<VisualLine>> =
51            self.visual_lines_cached(bounds.width);
52
53        // Prefer the tracked viewport height when available, but fall back to
54        // the current bounds during initial layout when viewport metrics have
55        // not been populated yet.
56        let effective_viewport_height = if self.viewport_height > 0.0 {
57            self.viewport_height
58        } else {
59            bounds.height
60        };
61        let first_visible_line =
62            (self.viewport_scroll / self.line_height).floor() as usize;
63        let visible_lines_count =
64            (effective_viewport_height / self.line_height).ceil() as usize + 2;
65        let last_visible_line =
66            (first_visible_line + visible_lines_count).min(visual_lines.len());
67
68        let (start_idx, end_idx) =
69            if self.cache_window_end_line > self.cache_window_start_line {
70                let s = self.cache_window_start_line.min(visual_lines.len());
71                let e = self.cache_window_end_line.min(visual_lines.len());
72                (s, e)
73            } else {
74                (first_visible_line, last_visible_line)
75            };
76
77        // Split rendering into two cached layers:
78        // - content: expensive, mostly static text/gutter rendering
79        // - overlay: frequently changing highlights/cursor/IME
80        //
81        // This keeps selection dragging and cursor blinking smooth by avoiding
82        // invalidation of the text layer on every overlay update.
83        let visual_lines_for_content = visual_lines.clone();
84        // A previous frame ran out of highlight budget: redraw the content
85        // layer so this frame refills the budget and advances the parse.
86        if self.highlight_catch_up_pending.replace(false) {
87            self.content_cache.clear();
88        }
89        let content_geometry =
90            self.content_cache.draw(renderer, bounds.size(), |frame| {
91                // Bound sequential syntect catch-up work for this frame, in
92                // lines and in time. This keeps a deep jump or a cache
93                // truncation in a huge file from blocking the UI while parsing
94                // every preceding line.
95                self.highlight_lines_remaining.set(HIGHLIGHT_LINES_PER_FRAME);
96                self.highlight_deadline
97                    .set(Some(Instant::now() + HIGHLIGHT_TIME_PER_FRAME));
98
99                // Shared with the sticky-scroll layer, which colors the same
100                // lines outside the canvas.
101                let (syntax_set, syntax_ref, syntax_theme) =
102                    self.resolve_syntax();
103
104                let ctx = RenderContext {
105                    visual_lines: visual_lines_for_content.as_ref(),
106                    bounds_width: bounds.width,
107                    gutter_width: self.gutter_width(),
108                    line_height: self.line_height,
109                    font_size: self.font_size,
110                    full_char_width: self.full_char_width,
111                    char_width: self.char_width,
112                    font: self.font,
113                    horizontal_scroll_offset: self.horizontal_scroll_offset,
114                };
115
116                // Clip code text to the code area (right of gutter) so that
117                // horizontal scrolling cannot cause text to bleed into the gutter.
118                // Note: iced renders ALL text on top of ALL geometry, so a
119                // fill_rectangle cannot mask text bleed — with_clip is required.
120                let code_clip = Rectangle {
121                    x: ctx.gutter_width,
122                    y: 0.0,
123                    width: (bounds.width - ctx.gutter_width).max(0.0),
124                    height: bounds.height,
125                };
126                frame.with_clip(code_clip, |f| {
127                    // Scoped to this pass: the memo is keyed on line index
128                    // alone, so it must not outlive a buffer that cannot
129                    // change underneath it.
130                    let mut color_literals =
131                        color_preview::LineLiterals::default();
132
133                    for (idx, visual_line) in visual_lines_for_content
134                        .iter()
135                        .enumerate()
136                        .skip(start_idx)
137                        .take(end_idx.saturating_sub(start_idx))
138                    {
139                        let y = idx as f32 * self.line_height;
140                        self.draw_indent_guides(f, &ctx, visual_line, y);
141                        self.draw_text_with_syntax_highlighting(
142                            f,
143                            &ctx,
144                            visual_line,
145                            y,
146                            syntax_ref,
147                            syntax_set,
148                            syntax_theme,
149                        );
150                        self.draw_bracket_pair_colors(f, &ctx, visual_line, y);
151                        self.draw_color_swatches(
152                            f,
153                            &ctx,
154                            visual_line,
155                            y,
156                            &mut color_literals,
157                        );
158                        self.draw_fold_collapsed_marker(
159                            f,
160                            &ctx,
161                            visual_line,
162                            y,
163                        );
164                    }
165                });
166
167                // Draw line numbers in the gutter (no clip — fixed position)
168                for (idx, visual_line) in visual_lines_for_content
169                    .iter()
170                    .enumerate()
171                    .skip(start_idx)
172                    .take(end_idx.saturating_sub(start_idx))
173                {
174                    let y = idx as f32 * self.line_height;
175                    self.draw_line_numbers(frame, &ctx, visual_line, y);
176                }
177
178                // Highlighting outside a content render (sticky headers) is
179                // not bound by this frame's clock.
180                self.highlight_deadline.set(None);
181            });
182
183        let visual_lines_for_overlay = visual_lines;
184        let overlay_geometry =
185            self.overlay_cache.draw(renderer, bounds.size(), |frame| {
186                // The overlay layer shares the same visual lines, but draws only
187                // elements that change without modifying the buffer content.
188                let ctx = RenderContext {
189                    visual_lines: visual_lines_for_overlay.as_ref(),
190                    bounds_width: bounds.width,
191                    gutter_width: self.gutter_width(),
192                    line_height: self.line_height,
193                    font_size: self.font_size,
194                    full_char_width: self.full_char_width,
195                    char_width: self.char_width,
196                    font: self.font,
197                    horizontal_scroll_offset: self.horizontal_scroll_offset,
198                };
199
200                for (idx, visual_line) in visual_lines_for_overlay
201                    .iter()
202                    .enumerate()
203                    .skip(start_idx)
204                    .take(end_idx.saturating_sub(start_idx))
205                {
206                    let y = idx as f32 * self.line_height;
207                    self.draw_current_line_highlight(
208                        frame,
209                        &ctx,
210                        visual_line,
211                        y,
212                    );
213                }
214
215                self.draw_search_highlights(frame, &ctx, start_idx, end_idx);
216                self.draw_matching_bracket_highlight(frame, &ctx);
217                self.draw_selection_highlight(frame, &ctx, start_idx..end_idx);
218                self.draw_diagnostics(frame, &ctx, start_idx, end_idx);
219                self.draw_jump_link_highlight(frame, &ctx, bounds, _cursor);
220                self.draw_cursor(frame, &ctx);
221            });
222
223        vec![content_geometry, overlay_geometry]
224    }
225
226    /// Handles Canvas trait events, specifically keyboard input events and focus management for the code editor widget.
227    ///
228    /// # Arguments
229    ///
230    /// * `_state` - The mutable state of the canvas (unused in this implementation)
231    /// * `event` - The input event to handle, such as keyboard presses
232    /// * `bounds` - The rectangle bounds of the canvas widget
233    /// * `cursor` - The current mouse cursor position and status
234    ///
235    /// # Returns
236    ///
237    /// An optional `Action<Message>` to perform, such as sending a message or redrawing the canvas
238    fn update(
239        &self,
240        state: &mut Self::State,
241        event: &Event,
242        bounds: Rectangle,
243        cursor: mouse::Cursor,
244    ) -> Option<Action<Message>> {
245        if let Event::Window(iced::window::Event::RedrawRequested(now)) = event
246        {
247            if self.has_focus()
248                && self.selection_scroll_speed().abs() > f32::EPSILON
249            {
250                let previous = state.get_or_insert(*now);
251                let elapsed = now.duration_since(*previous);
252                let interval = std::time::Duration::from_millis(8);
253                if elapsed >= interval {
254                    *previous = *now;
255                    return Some(Action::publish(
256                        Message::SelectionAutoScroll(elapsed.as_secs_f32()),
257                    ));
258                }
259                return Some(Action::request_redraw_at(*previous + interval));
260            }
261            *state = None;
262            // Keep sequential highlight catch-up going: each content frame
263            // parses a bounded slice, and nothing else asks for the next
264            // frame while the user is idle.
265            if self.highlight_catch_up_pending.get() {
266                return Some(Action::request_redraw());
267            }
268        }
269        match event {
270            Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
271                self.modifiers.set(*modifiers);
272                None
273            }
274            Event::Keyboard(keyboard::Event::KeyPressed {
275                key,
276                modified_key,
277                modifiers,
278                text,
279                ..
280            }) => {
281                self.modifiers.set(*modifiers);
282                self.handle_keyboard_event(
283                    key,
284                    modified_key,
285                    modifiers,
286                    text,
287                    bounds,
288                    &cursor,
289                )
290            }
291            Event::Keyboard(keyboard::Event::KeyReleased {
292                modifiers, ..
293            }) => {
294                self.modifiers.set(*modifiers);
295                None
296            }
297            Event::Mouse(mouse_event) => {
298                self.handle_mouse_event(mouse_event, bounds, &cursor)
299            }
300            Event::InputMethod(ime_event) => {
301                self.handle_ime_event(ime_event, bounds, &cursor)
302            }
303            _ => None,
304        }
305    }
306
307    /// Uses the text-selection cursor over the editable code area.
308    ///
309    /// The gutter keeps the default cursor, except for an interactive fold
310    /// chevron. Checking the cursor against `bounds` is important because a
311    /// canvas program's interaction can otherwise remain active out of bounds.
312    fn mouse_interaction(
313        &self,
314        _state: &Self::State,
315        bounds: Rectangle,
316        cursor: mouse::Cursor,
317    ) -> mouse::Interaction {
318        let Some(position) = cursor.position_in(bounds) else {
319            return mouse::Interaction::default();
320        };
321
322        if self.fold_header_at_point(position).is_some() {
323            mouse::Interaction::Pointer
324        } else if position.x >= self.gutter_width() {
325            mouse::Interaction::Text
326        } else {
327            mouse::Interaction::default()
328        }
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use iced::{Point, Size};
335
336    use super::*;
337
338    fn editor_mouse_interaction(
339        editor: &CodeEditor,
340        bounds: Rectangle,
341        cursor: mouse::Cursor,
342    ) -> mouse::Interaction {
343        canvas::Program::<Message>::mouse_interaction(
344            editor, &None, bounds, cursor,
345        )
346    }
347
348    /// A JSON document comfortably longer than one frame's line budget.
349    fn large_json_editor() -> (CodeEditor, usize) {
350        let line_count = HIGHLIGHT_LINES_PER_FRAME * 2 + 500;
351        let content = (0..line_count)
352            .map(|i| format!("{{\"key{i}\": {i}}}"))
353            .collect::<Vec<_>>()
354            .join("\n");
355        (CodeEditor::new(&content, "json"), line_count - 1)
356    }
357
358    /// Highlights `line` with one frame's worth of budget, as `draw` does:
359    /// the pending flag is consumed at the start of the frame and the line
360    /// budget refilled.
361    fn highlight_one_frame(editor: &CodeEditor, line: usize) -> usize {
362        editor.highlight_catch_up_pending.set(false);
363        editor.highlight_lines_remaining.set(HIGHLIGHT_LINES_PER_FRAME);
364        let (syntax_set, syntax, theme) = editor.resolve_syntax();
365        let (Some(syntax), Some(theme)) = (syntax, theme) else {
366            return 0;
367        };
368        editor.highlighted_line_cached(line, syntax, theme, syntax_set).len()
369    }
370
371    /// Feeds a `RedrawRequested` event to the canvas program.
372    fn redraw_requested(editor: &CodeEditor) -> Option<Action<Message>> {
373        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
374        let event = Event::Window(iced::window::Event::RedrawRequested(
375            iced::time::Instant::now(),
376        ));
377        canvas::Program::<Message>::update(
378            editor,
379            &mut None,
380            &event,
381            bounds,
382            mouse::Cursor::Unavailable,
383        )
384    }
385
386    #[test]
387    fn test_unfinished_highlighting_schedules_another_frame() {
388        let (editor, deep_line) = large_json_editor();
389
390        // One frame cannot reach the deep line: it falls back to plain text.
391        assert_eq!(highlight_one_frame(&editor, deep_line), 1);
392
393        // Nothing else may redraw the editor (no typing, no scrolling), so
394        // the canvas itself must ask for the next frame; otherwise the rest
395        // of the document stays uncolored indefinitely.
396        assert!(
397            redraw_requested(&editor).is_some(),
398            "a budget-limited frame must schedule the next one"
399        );
400    }
401
402    #[test]
403    fn test_highlight_catch_up_converges_then_goes_quiet() {
404        let (editor, deep_line) = large_json_editor();
405
406        let mut frames = 0;
407        let mut spans = highlight_one_frame(&editor, deep_line);
408        while redraw_requested(&editor).is_some() {
409            spans = highlight_one_frame(&editor, deep_line);
410            frames += 1;
411            assert!(frames < 10_000, "catch-up must converge");
412        }
413
414        assert!(spans > 1, "the deep line must end up highlighted");
415        assert!(
416            redraw_requested(&editor).is_none(),
417            "a fully highlighted editor must stop requesting frames"
418        );
419    }
420
421    #[test]
422    fn test_mouse_interaction_uses_text_cursor_in_editable_area() {
423        let editor = CodeEditor::new("fn main() {}", "rs");
424        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
425        let cursor = mouse::Cursor::Available(Point::new(
426            editor.gutter_width() + 10.0,
427            10.0,
428        ));
429
430        assert_eq!(
431            editor_mouse_interaction(&editor, bounds, cursor),
432            mouse::Interaction::Text
433        );
434    }
435
436    #[test]
437    fn test_mouse_interaction_keeps_default_cursor_in_gutter_and_outside() {
438        let editor = CodeEditor::new("fn main() {}", "rs");
439        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
440
441        assert_eq!(
442            editor_mouse_interaction(
443                &editor,
444                bounds,
445                mouse::Cursor::Available(Point::new(5.0, 10.0)),
446            ),
447            mouse::Interaction::default()
448        );
449        assert_eq!(
450            editor_mouse_interaction(
451                &editor,
452                bounds,
453                mouse::Cursor::Available(Point::new(900.0, 10.0)),
454            ),
455            mouse::Interaction::default()
456        );
457    }
458}