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