iced-code-editor 0.7.0

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Canvas rendering implementation using Iced's `canvas::Program`.

use iced::mouse;
use iced::widget::canvas::{self, Action, Geometry};
use iced::{Event, Rectangle, Theme, keyboard};
use std::rc::Rc;

use super::text::RenderContext;
use super::wrapping::VisualLine;
use crate::canvas_editor::features::color_preview;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_time::Instant;

use crate::canvas_editor::{
    CodeEditor, HIGHLIGHT_LINES_PER_FRAME, HIGHLIGHT_TIME_PER_FRAME, Message,
};

impl canvas::Program<Message> for CodeEditor {
    type State = Option<iced::time::Instant>;

    /// Renders the code editor's visual elements on the canvas, including text layout, syntax highlighting,
    /// cursor positioning, and other graphical aspects.
    ///
    /// # Arguments
    ///
    /// * `state` - The current state of the canvas
    /// * `renderer` - The renderer used for drawing
    /// * `theme` - The theme for styling
    /// * `bounds` - The rectangle bounds of the canvas
    /// * `cursor` - The mouse cursor position
    ///
    /// # Returns
    ///
    /// A vector of `Geometry` objects representing the drawn elements
    fn draw(
        &self,
        _state: &Self::State,
        renderer: &iced::Renderer,
        _theme: &Theme,
        bounds: Rectangle,
        _cursor: mouse::Cursor,
    ) -> Vec<Geometry> {
        // Track the real, live canvas width every frame, independent of the
        // vertical-scroll-driven `viewport_width` (which never gets corrected
        // for content that doesn't overflow vertically — see issue #26).
        self.last_canvas_width.set(bounds.width);

        let visual_lines: Rc<Vec<VisualLine>> =
            self.visual_lines_cached(bounds.width);

        // Prefer the tracked viewport height when available, but fall back to
        // the current bounds during initial layout when viewport metrics have
        // not been populated yet.
        let effective_viewport_height = if self.viewport_height > 0.0 {
            self.viewport_height
        } else {
            bounds.height
        };
        let first_visible_line =
            (self.viewport_scroll / self.line_height).floor() as usize;
        let visible_lines_count =
            (effective_viewport_height / self.line_height).ceil() as usize + 2;
        let last_visible_line =
            (first_visible_line + visible_lines_count).min(visual_lines.len());

        let (start_idx, end_idx) =
            if self.cache_window_end_line > self.cache_window_start_line {
                let s = self.cache_window_start_line.min(visual_lines.len());
                let e = self.cache_window_end_line.min(visual_lines.len());
                (s, e)
            } else {
                (first_visible_line, last_visible_line)
            };

        // Split rendering into two cached layers:
        // - content: expensive, mostly static text/gutter rendering
        // - overlay: frequently changing highlights/cursor/IME
        //
        // This keeps selection dragging and cursor blinking smooth by avoiding
        // invalidation of the text layer on every overlay update.
        let visual_lines_for_content = visual_lines.clone();
        // A previous frame ran out of highlight budget: redraw the content
        // layer so this frame refills the budget and advances the parse.
        if self.highlight_catch_up_pending.replace(false) {
            self.content_cache.clear();
        }
        let content_geometry =
            self.content_cache.draw(renderer, bounds.size(), |frame| {
                // Bound sequential syntect catch-up work for this frame, in
                // lines and in time. This keeps a deep jump or a cache
                // truncation in a huge file from blocking the UI while parsing
                // every preceding line.
                self.highlight_lines_remaining.set(HIGHLIGHT_LINES_PER_FRAME);
                self.highlight_deadline
                    .set(Some(Instant::now() + HIGHLIGHT_TIME_PER_FRAME));

                // Shared with the sticky-scroll layer, which colors the same
                // lines outside the canvas.
                let (syntax_set, syntax_ref, syntax_theme) =
                    self.resolve_syntax();

                let ctx = RenderContext {
                    visual_lines: visual_lines_for_content.as_ref(),
                    bounds_width: bounds.width,
                    gutter_width: self.gutter_width(),
                    line_height: self.line_height,
                    font_size: self.font_size,
                    full_char_width: self.full_char_width,
                    char_width: self.char_width,
                    font: self.font,
                    horizontal_scroll_offset: self.horizontal_scroll_offset,
                };

                // Clip code text to the code area (right of gutter) so that
                // horizontal scrolling cannot cause text to bleed into the gutter.
                // Note: iced renders ALL text on top of ALL geometry, so a
                // fill_rectangle cannot mask text bleed — with_clip is required.
                let code_clip = Rectangle {
                    x: ctx.gutter_width,
                    y: 0.0,
                    width: (bounds.width - ctx.gutter_width).max(0.0),
                    height: bounds.height,
                };
                frame.with_clip(code_clip, |f| {
                    // Scoped to this pass: the memo is keyed on line index
                    // alone, so it must not outlive a buffer that cannot
                    // change underneath it.
                    let mut color_literals =
                        color_preview::LineLiterals::default();

                    for (idx, visual_line) in visual_lines_for_content
                        .iter()
                        .enumerate()
                        .skip(start_idx)
                        .take(end_idx.saturating_sub(start_idx))
                    {
                        let y = idx as f32 * self.line_height;
                        self.draw_indent_guides(f, &ctx, visual_line, y);
                        self.draw_text_with_syntax_highlighting(
                            f,
                            &ctx,
                            visual_line,
                            y,
                            syntax_ref,
                            syntax_set,
                            syntax_theme,
                        );
                        self.draw_bracket_pair_colors(f, &ctx, visual_line, y);
                        self.draw_color_swatches(
                            f,
                            &ctx,
                            visual_line,
                            y,
                            &mut color_literals,
                        );
                        self.draw_fold_collapsed_marker(
                            f,
                            &ctx,
                            visual_line,
                            y,
                        );
                    }
                });

                // Draw line numbers in the gutter (no clip — fixed position)
                for (idx, visual_line) in visual_lines_for_content
                    .iter()
                    .enumerate()
                    .skip(start_idx)
                    .take(end_idx.saturating_sub(start_idx))
                {
                    let y = idx as f32 * self.line_height;
                    self.draw_line_numbers(frame, &ctx, visual_line, y);
                }

                // Highlighting outside a content render (sticky headers) is
                // not bound by this frame's clock.
                self.highlight_deadline.set(None);
            });

        let visual_lines_for_overlay = visual_lines;
        let overlay_geometry =
            self.overlay_cache.draw(renderer, bounds.size(), |frame| {
                // The overlay layer shares the same visual lines, but draws only
                // elements that change without modifying the buffer content.
                let ctx = RenderContext {
                    visual_lines: visual_lines_for_overlay.as_ref(),
                    bounds_width: bounds.width,
                    gutter_width: self.gutter_width(),
                    line_height: self.line_height,
                    font_size: self.font_size,
                    full_char_width: self.full_char_width,
                    char_width: self.char_width,
                    font: self.font,
                    horizontal_scroll_offset: self.horizontal_scroll_offset,
                };

                for (idx, visual_line) in visual_lines_for_overlay
                    .iter()
                    .enumerate()
                    .skip(start_idx)
                    .take(end_idx.saturating_sub(start_idx))
                {
                    let y = idx as f32 * self.line_height;
                    self.draw_current_line_highlight(
                        frame,
                        &ctx,
                        visual_line,
                        y,
                    );
                }

                self.draw_search_highlights(frame, &ctx, start_idx, end_idx);
                self.draw_matching_bracket_highlight(frame, &ctx);
                self.draw_selection_highlight(frame, &ctx, start_idx..end_idx);
                self.draw_diagnostics(frame, &ctx, start_idx, end_idx);
                self.draw_jump_link_highlight(frame, &ctx, bounds, _cursor);
                self.draw_cursor(frame, &ctx);
            });

        vec![content_geometry, overlay_geometry]
    }

    /// Handles Canvas trait events, specifically keyboard input events and focus management for the code editor widget.
    ///
    /// # Arguments
    ///
    /// * `_state` - The mutable state of the canvas (unused in this implementation)
    /// * `event` - The input event to handle, such as keyboard presses
    /// * `bounds` - The rectangle bounds of the canvas widget
    /// * `cursor` - The current mouse cursor position and status
    ///
    /// # Returns
    ///
    /// An optional `Action<Message>` to perform, such as sending a message or redrawing the canvas
    fn update(
        &self,
        state: &mut Self::State,
        event: &Event,
        bounds: Rectangle,
        cursor: mouse::Cursor,
    ) -> Option<Action<Message>> {
        if let Event::Window(iced::window::Event::RedrawRequested(now)) = event
        {
            if self.has_focus()
                && self.selection_scroll_speed().abs() > f32::EPSILON
            {
                let previous = state.get_or_insert(*now);
                let elapsed = now.duration_since(*previous);
                let interval = std::time::Duration::from_millis(8);
                if elapsed >= interval {
                    *previous = *now;
                    return Some(Action::publish(
                        Message::SelectionAutoScroll(elapsed.as_secs_f32()),
                    ));
                }
                return Some(Action::request_redraw_at(*previous + interval));
            }
            *state = None;
            // Keep sequential highlight catch-up going: each content frame
            // parses a bounded slice, and nothing else asks for the next
            // frame while the user is idle.
            if self.highlight_catch_up_pending.get() {
                return Some(Action::request_redraw());
            }
        }
        match event {
            Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
                self.modifiers.set(*modifiers);
                None
            }
            Event::Keyboard(keyboard::Event::KeyPressed {
                key,
                modified_key,
                modifiers,
                text,
                ..
            }) => {
                self.modifiers.set(*modifiers);
                self.handle_keyboard_event(
                    key,
                    modified_key,
                    modifiers,
                    text,
                    bounds,
                    &cursor,
                )
            }
            Event::Keyboard(keyboard::Event::KeyReleased {
                modifiers, ..
            }) => {
                self.modifiers.set(*modifiers);
                None
            }
            Event::Mouse(mouse_event) => {
                self.handle_mouse_event(mouse_event, bounds, &cursor)
            }
            Event::InputMethod(ime_event) => {
                self.handle_ime_event(ime_event, bounds, &cursor)
            }
            _ => None,
        }
    }

    /// Uses the text-selection cursor over the editable code area.
    ///
    /// The gutter keeps the default cursor, except for an interactive fold
    /// chevron. Checking the cursor against `bounds` is important because a
    /// canvas program's interaction can otherwise remain active out of bounds.
    fn mouse_interaction(
        &self,
        _state: &Self::State,
        bounds: Rectangle,
        cursor: mouse::Cursor,
    ) -> mouse::Interaction {
        let Some(position) = cursor.position_in(bounds) else {
            return mouse::Interaction::default();
        };

        if self.fold_header_at_point(position).is_some() {
            mouse::Interaction::Pointer
        } else if position.x >= self.gutter_width() {
            mouse::Interaction::Text
        } else {
            mouse::Interaction::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use iced::{Point, Size};

    use super::*;

    fn editor_mouse_interaction(
        editor: &CodeEditor,
        bounds: Rectangle,
        cursor: mouse::Cursor,
    ) -> mouse::Interaction {
        canvas::Program::<Message>::mouse_interaction(
            editor, &None, bounds, cursor,
        )
    }

    /// A JSON document comfortably longer than one frame's line budget.
    fn large_json_editor() -> (CodeEditor, usize) {
        let line_count = HIGHLIGHT_LINES_PER_FRAME * 2 + 500;
        let content = (0..line_count)
            .map(|i| format!("{{\"key{i}\": {i}}}"))
            .collect::<Vec<_>>()
            .join("\n");
        (CodeEditor::new(&content, "json"), line_count - 1)
    }

    /// Highlights `line` with one frame's worth of budget, as `draw` does:
    /// the pending flag is consumed at the start of the frame and the line
    /// budget refilled.
    fn highlight_one_frame(editor: &CodeEditor, line: usize) -> usize {
        editor.highlight_catch_up_pending.set(false);
        editor.highlight_lines_remaining.set(HIGHLIGHT_LINES_PER_FRAME);
        let (syntax_set, syntax, theme) = editor.resolve_syntax();
        let (Some(syntax), Some(theme)) = (syntax, theme) else {
            return 0;
        };
        editor.highlighted_line_cached(line, syntax, theme, syntax_set).len()
    }

    /// Feeds a `RedrawRequested` event to the canvas program.
    fn redraw_requested(editor: &CodeEditor) -> Option<Action<Message>> {
        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
        let event = Event::Window(iced::window::Event::RedrawRequested(
            iced::time::Instant::now(),
        ));
        canvas::Program::<Message>::update(
            editor,
            &mut None,
            &event,
            bounds,
            mouse::Cursor::Unavailable,
        )
    }

    #[test]
    fn test_unfinished_highlighting_schedules_another_frame() {
        let (editor, deep_line) = large_json_editor();

        // One frame cannot reach the deep line: it falls back to plain text.
        assert_eq!(highlight_one_frame(&editor, deep_line), 1);

        // Nothing else may redraw the editor (no typing, no scrolling), so
        // the canvas itself must ask for the next frame; otherwise the rest
        // of the document stays uncolored indefinitely.
        assert!(
            redraw_requested(&editor).is_some(),
            "a budget-limited frame must schedule the next one"
        );
    }

    #[test]
    fn test_highlight_catch_up_converges_then_goes_quiet() {
        let (editor, deep_line) = large_json_editor();

        let mut frames = 0;
        let mut spans = highlight_one_frame(&editor, deep_line);
        while redraw_requested(&editor).is_some() {
            spans = highlight_one_frame(&editor, deep_line);
            frames += 1;
            assert!(frames < 10_000, "catch-up must converge");
        }

        assert!(spans > 1, "the deep line must end up highlighted");
        assert!(
            redraw_requested(&editor).is_none(),
            "a fully highlighted editor must stop requesting frames"
        );
    }

    #[test]
    fn test_mouse_interaction_uses_text_cursor_in_editable_area() {
        let editor = CodeEditor::new("fn main() {}", "rs");
        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));
        let cursor = mouse::Cursor::Available(Point::new(
            editor.gutter_width() + 10.0,
            10.0,
        ));

        assert_eq!(
            editor_mouse_interaction(&editor, bounds, cursor),
            mouse::Interaction::Text
        );
    }

    #[test]
    fn test_mouse_interaction_keeps_default_cursor_in_gutter_and_outside() {
        let editor = CodeEditor::new("fn main() {}", "rs");
        let bounds = Rectangle::new(Point::ORIGIN, Size::new(800.0, 600.0));

        assert_eq!(
            editor_mouse_interaction(
                &editor,
                bounds,
                mouse::Cursor::Available(Point::new(5.0, 10.0)),
            ),
            mouse::Interaction::default()
        );
        assert_eq!(
            editor_mouse_interaction(
                &editor,
                bounds,
                mouse::Cursor::Available(Point::new(900.0, 10.0)),
            ),
            mouse::Interaction::default()
        );
    }
}