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