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