Skip to main content

iced_code_editor/canvas_editor/render/
view.rs

1//! Iced UI view and rendering logic.
2
3use iced::Size;
4use iced::alignment;
5use iced::mouse;
6use iced::widget::canvas::Canvas;
7use iced::widget::{
8    Column, MouseArea, Row, Scrollable, Space, container, scrollable, text,
9};
10use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
11use iced_aw::ContextMenu;
12
13use super::text::{expand_tabs, expand_tabs_visible};
14use super::wrapping::{self, WrappingCalculator};
15use crate::canvas_editor::features::command_palette::dialog as command_palette_dialog;
16use crate::canvas_editor::features::context_menu;
17use crate::canvas_editor::features::goto_line::dialog as goto_line_dialog;
18use crate::canvas_editor::features::search::dialog as search_dialog;
19use crate::canvas_editor::features::sticky_scroll;
20use crate::canvas_editor::input::ime_requester::ImeRequester;
21use crate::canvas_editor::{CodeEditor, Message, TAB_WIDTH};
22use std::rc::Rc;
23
24/// Horizontal gap in pixels between the gutter and the code text, matching the
25/// offset the canvas text layer uses so pinned headers line up with the code.
26const CODE_TEXT_LEFT_PADDING: f32 = 5.0;
27
28/// Thickness in pixels of the separator drawn under the sticky-scroll headers.
29const STICKY_SEPARATOR_WIDTH: f32 = 1.0;
30
31/// Rail width in pixels of the canvas editor's scrollbars (the area that takes
32/// the mouse).
33const SCROLLBAR_WIDTH: f32 = 8.0;
34/// Width in pixels of the scroller (thumb) inside the rail.
35const SCROLLER_WIDTH: f32 = 6.0;
36/// Space in pixels between the scrollbar and the editor's edge.
37const SCROLLBAR_MARGIN: f32 = 2.0;
38
39/// The canvas editor's scrollbar: a thin pill, away from the edge.
40fn canvas_scrollbar() -> scrollable::Scrollbar {
41    scrollable::Scrollbar::new()
42        .width(SCROLLBAR_WIDTH)
43        .scroller_width(SCROLLER_WIDTH)
44        .margin(SCROLLBAR_MARGIN)
45}
46
47/// How opaque the scroller is: faint with the mouse away from the editor,
48/// plain over it, solid over the scrollbar or while dragging it. Returns the
49/// (vertical, horizontal) factors.
50fn scroller_alpha(status: scrollable::Status) -> (f32, f32) {
51    let pick = |on_bar: bool| if on_bar { 1.0 / 0.6 } else { 1.0 };
52    match status {
53        scrollable::Status::Active { .. } => (0.6, 0.6),
54        scrollable::Status::Hovered {
55            is_vertical_scrollbar_hovered: v,
56            is_horizontal_scrollbar_hovered: h,
57            ..
58        } => (pick(v), pick(h)),
59        scrollable::Status::Dragged {
60            is_vertical_scrollbar_dragged: v,
61            is_horizontal_scrollbar_dragged: h,
62            ..
63        } => (pick(v), pick(h)),
64    }
65}
66
67/// Builds the transparent-container scrollable style shared by the canvas
68/// editor's vertical and horizontal scrollbars: pill-shaped scrollers whose
69/// opacity follows the mouse (see [`scroller_alpha`]).
70fn canvas_scrollbar_style(
71    scrollbar_bg: Color,
72    scroller_color: Color,
73    status: scrollable::Status,
74) -> scrollable::Style {
75    let (v, h) = scroller_alpha(status);
76    let scale =
77        |a: f32| Color { a: (scroller_color.a * a).min(1.0), ..scroller_color };
78    // A radius larger than the scroller: the renderer caps it at half the
79    // side, so the ends are round.
80    let pill = SCROLLBAR_WIDTH * 10.0;
81    scrollable::Style {
82        container: container::Style {
83            background: Some(Background::Color(Color::TRANSPARENT)),
84            ..container::Style::default()
85        },
86        vertical_rail: scrollable_rail(scrollbar_bg, scale(v), pill),
87        horizontal_rail: scrollable_rail(scrollbar_bg, scale(h), pill),
88        gap: None,
89        auto_scroll: scrollable::AutoScroll {
90            background: Color::TRANSPARENT.into(),
91            border: Border::default(),
92            shadow: Shadow::default(),
93            icon: Color::TRANSPARENT,
94        },
95    }
96}
97
98impl CodeEditor {
99    /// Calculates visual lines and canvas height for the editor.
100    ///
101    /// Returns a tuple of (visual_lines, canvas_height) where:
102    /// - visual_lines: The visual line mapping with wrapping applied
103    /// - canvas_height: The total height needed for the canvas
104    fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
105        // Reuse memoized visual lines so view layout (canvas height + IME cursor rect)
106        // does not trigger repeated wrapping computation.
107        let visual_lines = self.visual_lines_cached(self.viewport_width);
108        let total_visual_lines = visual_lines.len();
109        let content_height = total_visual_lines as f32 * self.line_height;
110
111        // Use max of content height and viewport height to ensure the canvas
112        // always covers the visible area (prevents visual artifacts when
113        // content is shorter than viewport after reset/file change)
114        let canvas_height = content_height.max(self.viewport_height);
115
116        (visual_lines, canvas_height)
117    }
118
119    /// Creates the scrollable style function with custom colors.
120    ///
121    /// Returns a style function that configures the scrollbar appearance.
122    fn create_scrollable_style(
123        &self,
124    ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
125        let scrollbar_bg = self.style.scrollbar_background;
126        let scroller_color = self.style.scroller_color;
127
128        move |_theme, status| {
129            canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
130        }
131    }
132
133    /// Creates the canvas widget wrapped in a scrollable container.
134    ///
135    /// # Arguments
136    ///
137    /// * `canvas_height` - The total height of the canvas
138    ///
139    /// # Returns
140    ///
141    /// A configured scrollable widget containing the canvas
142    fn create_canvas_with_scrollable(
143        &self,
144        canvas_height: f32,
145    ) -> Scrollable<'_, Message> {
146        let canvas = Canvas::new(self)
147            .width(Length::Fill)
148            .height(Length::Fixed(canvas_height));
149
150        Scrollable::new(canvas)
151            .id(self.scrollable_id.clone())
152            .width(Length::Fill)
153            .height(Length::Fill)
154            .direction(scrollable::Direction::Vertical(canvas_scrollbar()))
155            .on_scroll(Message::Scrolled)
156            .style(self.create_scrollable_style())
157    }
158
159    /// Decides whether the horizontal scrollbar should be shown: wrap must be
160    /// disabled, and the widest line must not fit in the real, last-observed
161    /// canvas width (`last_canvas_width`, refreshed every `draw()` call).
162    ///
163    /// This intentionally does not use `viewport_width`, which is only
164    /// corrected via vertical-scroll notifications and can stay stuck at its
165    /// default for content that never overflows vertically — e.g. right after
166    /// [`CodeEditor::reset`] loads a short file with a very wide line (issue #26).
167    ///
168    /// # Arguments
169    ///
170    /// * `max_content_width` - The total pixel width of the widest line
171    ///
172    /// # Returns
173    ///
174    /// `true` if a horizontal scrollbar is needed, `false` otherwise
175    pub(crate) fn should_show_horizontal_scrollbar(
176        &self,
177        max_content_width: f32,
178    ) -> bool {
179        !self.wrap_enabled && max_content_width > self.last_canvas_width.get()
180    }
181
182    /// Creates the horizontal scrollbar element when wrap is disabled and content overflows.
183    ///
184    /// # Arguments
185    ///
186    /// * `max_content_width` - The total pixel width of the widest line
187    ///
188    /// # Returns
189    ///
190    /// `Some(element)` if a horizontal scrollbar is needed, `None` otherwise
191    fn create_horizontal_scrollbar(
192        &self,
193        max_content_width: f32,
194    ) -> Option<Element<'_, Message>> {
195        if !self.should_show_horizontal_scrollbar(max_content_width) {
196            return None;
197        }
198
199        let scrollbar_bg = self.style.scrollbar_background;
200        let scroller_color = self.style.scroller_color;
201
202        let h_scrollable = Scrollable::new(
203            Space::new().width(Length::Fixed(max_content_width)).height(0.0),
204        )
205        .id(self.horizontal_scrollable_id.clone())
206        .width(Length::Fill)
207        .height(Length::Fixed(12.0))
208        .direction(scrollable::Direction::Horizontal(canvas_scrollbar()))
209        .on_scroll(Message::HorizontalScrolled)
210        .style(move |_theme, status| {
211            canvas_scrollbar_style(scrollbar_bg, scroller_color, status)
212        });
213
214        Some(h_scrollable.into())
215    }
216
217    /// Creates the gutter background container if line numbers are enabled.
218    ///
219    /// # Returns
220    ///
221    /// Some(container) if line numbers are enabled, None otherwise
222    fn create_gutter_container(
223        &self,
224    ) -> Option<container::Container<'_, Message>> {
225        if self.line_numbers_enabled {
226            let gutter_background = self.style.gutter_background;
227            Some(
228                container(
229                    Space::new().width(Length::Fill).height(Length::Fill),
230                )
231                // Spans the fold margin too when it comes first, so the
232                // whole gutter left of the numbers shares one background.
233                .width(Length::Fixed(self.gutter_columns().line_numbers.end))
234                .height(Length::Fill)
235                .style(move |_| container::Style {
236                    background: Some(Background::Color(gutter_background)),
237                    ..container::Style::default()
238                }),
239            )
240        } else {
241            None
242        }
243    }
244
245    /// Creates the code area background container.
246    ///
247    /// # Returns
248    ///
249    /// The code background container widget
250    fn create_code_background_container(
251        &self,
252    ) -> container::Container<'_, Message> {
253        let background_color = self.style.background;
254        container(Space::new().width(Length::Fill).height(Length::Fill))
255            .width(Length::Fill)
256            .height(Length::Fill)
257            .style(move |_| container::Style {
258                background: Some(Background::Color(background_color)),
259                ..container::Style::default()
260            })
261    }
262
263    /// Creates the fixed Vim status and command line shown below the editor.
264    fn create_vim_status_bar(&self) -> Element<'_, Message> {
265        let (left_text, right_text) = self.vim_state.status_line_text();
266        let background = self.style.gutter_background;
267        let text_color = self.style.text_color;
268
269        container(
270            Row::new()
271                .push(
272                    text(left_text).size(self.font_size).style(move |_| {
273                        text::Style { color: Some(text_color) }
274                    }),
275                )
276                .push(Space::new().width(Length::Fill))
277                .push(
278                    text(right_text).size(self.font_size).style(move |_| {
279                        text::Style { color: Some(text_color) }
280                    }),
281                ),
282        )
283        .padding([2, 8])
284        .width(Length::Fill)
285        .height(Length::Fixed(self.line_height.max(20.0)))
286        .style(move |_| container::Style {
287            background: Some(Background::Color(background)),
288            ..container::Style::default()
289        })
290        .into()
291    }
292
293    /// Creates the background layer combining gutter and code backgrounds.
294    ///
295    /// # Returns
296    ///
297    /// A row containing the background elements
298    fn create_background_layer(&self) -> Row<'_, Message> {
299        let gutter_container = self.create_gutter_container();
300        let code_background_container = self.create_code_background_container();
301
302        if let Some(gutter) = gutter_container {
303            Row::new().push(gutter).push(code_background_container)
304        } else {
305            Row::new().push(code_background_container)
306        }
307    }
308
309    /// Calculates the IME cursor rectangle for the current cursor position.
310    ///
311    /// # Arguments
312    ///
313    /// * `visual_lines` - The visual line mapping
314    ///
315    /// # Returns
316    ///
317    /// A rectangle representing the cursor position for IME
318    fn calculate_ime_cursor_rect(
319        &self,
320        visual_lines: &[wrapping::VisualLine],
321    ) -> Rectangle {
322        let ime_enabled = self.is_focused() && self.has_canvas_focus;
323
324        if !ime_enabled {
325            return Rectangle::new(
326                iced::Point::new(0.0, 0.0),
327                Size::new(0.0, 0.0),
328            );
329        }
330
331        if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
332            visual_lines,
333            self.cursors.primary_position().0,
334            self.cursors.primary_position().1,
335        ) {
336            let vl = &visual_lines[cursor_visual];
337            let line_content = self.buffer.line(vl.logical_line);
338            let prefix_len =
339                self.cursors.primary_position().1.saturating_sub(vl.start_col);
340            let prefix_text: String = line_content
341                .chars()
342                .skip(vl.start_col)
343                .take(prefix_len)
344                .collect();
345            let cursor_x = self.gutter_width()
346                + 5.0
347                + crate::canvas_editor::measure_text_width(
348                    &prefix_text,
349                    self.full_char_width,
350                    self.char_width,
351                )
352                - self.horizontal_scroll_offset;
353
354            // Calculate visual Y position relative to the viewport
355            // We subtract viewport_scroll because the content is scrolled up/down
356            // but the cursor position sent to IME must be relative to the visible area
357            let cursor_y = (cursor_visual as f32 * self.line_height)
358                - self.viewport_scroll;
359
360            Rectangle::new(
361                iced::Point::new(cursor_x, cursor_y + 2.0),
362                Size::new(2.0, self.line_height - 4.0),
363            )
364        } else {
365            Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
366        }
367    }
368
369    /// Builds one pinned header row: its line number, then its colored text.
370    ///
371    /// The row reuses the memoized per-line highlight spans, so pinning a header
372    /// costs no extra syntect work. Unlike the canvas text layer, it ignores
373    /// `horizontal_scroll_offset`: a pinned header exists to be read, and would
374    /// be useless if it scrolled out of view sideways.
375    ///
376    /// # Arguments
377    ///
378    /// * `line` - Index of the logical header line to render
379    /// * `syntax_set` - The syntax set `syntax` belongs to
380    /// * `syntax` - The syntect syntax definition to tokenize with
381    /// * `theme` - The syntect theme providing token colors
382    fn create_sticky_header_row(
383        &self,
384        line: usize,
385        syntax_set: &syntect::parsing::SyntaxSet,
386        syntax: &syntect::parsing::SyntaxReference,
387        theme: &syntect::highlighting::Theme,
388    ) -> Element<'_, Message> {
389        let font = self.font;
390        let font_size = self.font_size;
391        let line_number_color = self.style.line_number_color;
392
393        let mut row = Row::new();
394
395        // Keep the fold margin empty: a pinned header is not where the user
396        // folds, and a chevron there would invite a click that does nothing.
397        let fold_margin_width = self.fold_margin_width();
398        let fold_margin =
399            || Space::new().width(Length::Fixed(fold_margin_width));
400        let markers_first = self.fold_marker_position
401            == crate::FoldMarkerPosition::BeforeLineNumbers;
402        if markers_first {
403            row = row.push(fold_margin());
404        }
405
406        if self.line_numbers_enabled {
407            row = row.push(
408                container(
409                    text(format!("{}", line + 1))
410                        .size(font_size)
411                        .font(font)
412                        .style(move |_| text::Style {
413                            color: Some(line_number_color),
414                        }),
415                )
416                .width(Length::Fixed(self.line_number_gutter_width()))
417                .align_x(alignment::Horizontal::Center),
418            );
419        }
420
421        if !markers_first {
422            row = row.push(fold_margin());
423        }
424        row =
425            row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));
426
427        let spans =
428            self.highlighted_line_cached(line, syntax, theme, syntax_set);
429        let mut code = Row::new();
430        for (color, content) in spans.iter() {
431            let color = *color;
432            // Match the canvas text layer, so a pinned header shows the same
433            // whitespace glyphs as the line it mirrors.
434            let content = if self.show_whitespace {
435                expand_tabs_visible(content, TAB_WIDTH)
436            } else {
437                expand_tabs(content, TAB_WIDTH).into_owned()
438            };
439            // Unicode headers need the same fallback as the canvas text layer.
440            let span_font =
441                if content.is_ascii() { font } else { iced::Font::DEFAULT };
442            code = code.push(
443                text(content)
444                    .size(font_size)
445                    .font(span_font)
446                    .wrapping(text::Wrapping::None)
447                    .style(move |_| text::Style { color: Some(color) }),
448            );
449        }
450        row = row.push(code);
451
452        MouseArea::new(
453            container(row)
454                .width(Length::Fill)
455                .height(Length::Fixed(self.line_height))
456                .clip(true),
457        )
458        .interaction(mouse::Interaction::Pointer)
459        .on_press(Message::StickyScrollJump(line))
460        .into()
461    }
462
463    /// Creates the sticky-scroll layer: the headers of the blocks enclosing the
464    /// topmost visible line, pinned above the viewport.
465    ///
466    /// # Arguments
467    ///
468    /// * `visual_lines` - The visual line mapping, used to resolve the topmost
469    ///   visible visual line back to its logical line
470    ///
471    /// # Returns
472    ///
473    /// `Some(layer)` when at least one header must be pinned, `None` when the
474    /// feature is disabled or the topmost visible line sits at the top level
475    fn create_sticky_scroll_layer(
476        &self,
477        visual_lines: &[wrapping::VisualLine],
478    ) -> Option<Element<'_, Message>> {
479        if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
480            return None;
481        }
482
483        // Same first-visible-line formula the canvas layer uses. The topmost
484        // entry is a *visual* line, so it must be mapped back to a logical one:
485        // wrapping and collapsed folds make the two indices diverge.
486        let first_visible =
487            (self.viewport_scroll / self.line_height).floor() as usize;
488        let top_line = visual_lines.get(first_visible)?.logical_line;
489
490        // `block_regions`, not `foldable_regions`: the blocks a line sits in
491        // are a property of the buffer, not of whether the user may collapse
492        // them. Sticky scroll keeps working with code folding turned off.
493        let regions = self.block_regions();
494        let headers = sticky_scroll::sticky_headers(
495            &regions,
496            top_line,
497            sticky_scroll::DEFAULT_MAX_STICKY_LINES,
498        );
499        if headers.is_empty() {
500            return None;
501        }
502
503        let (syntax_set, syntax, theme) = self.resolve_syntax();
504        let (Some(syntax), Some(theme)) = (syntax, theme) else {
505            return None;
506        };
507
508        let mut column = Column::new();
509        for line in headers {
510            column = column.push(
511                self.create_sticky_header_row(line, syntax_set, syntax, theme),
512            );
513        }
514
515        let background = self.style.gutter_background;
516        let border_color = self.style.gutter_border;
517
518        // An explicit rule rather than a container shadow: it must sit exactly
519        // one pixel under the last header, on top of the code scrolling beneath.
520        let column = column.push(
521            container(Space::new().width(Length::Fill).height(Length::Fill))
522                .width(Length::Fill)
523                .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
524                .style(move |_| container::Style {
525                    background: Some(Background::Color(border_color)),
526                    ..container::Style::default()
527                }),
528        );
529
530        Some(
531            container(column)
532                .width(Length::Fill)
533                .height(Length::Shrink)
534                .style(move |_| container::Style {
535                    background: Some(Background::Color(background)),
536                    ..container::Style::default()
537                })
538                .into(),
539        )
540    }
541
542    /// Creates the IME (Input Method Editor) layer widget.
543    ///
544    /// # Arguments
545    ///
546    /// * `cursor_rect` - The rectangle representing the cursor position
547    ///
548    /// # Returns
549    ///
550    /// An element containing the IME requester widget
551    fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
552        let ime_enabled = self.is_focused() && self.has_canvas_focus;
553
554        // The canvas draws preedit on the spot. Supplying it here would also
555        // create Iced's over-the-spot paragraph with unbounded layout.
556        let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, None);
557        iced::Element::new(ime_layer)
558    }
559
560    /// Wraps the canvas scrollable in the right-click context menu.
561    ///
562    /// The menu owns its transient open/close state and positions itself at
563    /// the right-click location. Its widget *captures* the right press before
564    /// forwarding it to its underlay, and a `Stack` stops delivering a
565    /// captured event after its topmost layer. Wrapping the whole editor stack
566    /// therefore hid the press from the canvas, which sits below the IME and
567    /// dialog layers: no `ContextMenuRequested` was published, so the caret
568    /// and selection handling for context clicks never ran.
569    ///
570    /// A scrollable forwards events to its content whether or not they were
571    /// captured, so wrapping only the scrollable keeps the menu over the same
572    /// area while the canvas still sees the press.
573    fn with_context_menu<'a>(
574        &self,
575        underlay: impl Into<Element<'a, Message>>,
576    ) -> Element<'a, Message> {
577        let action_context = self.action_context();
578        let custom_context_menu_entries =
579            self.custom_context_menu_entries().to_vec();
580        let default_context_menu_enabled = self.default_context_menu_enabled();
581        let translations = self.translations;
582        ContextMenu::new(underlay, move || {
583            context_menu::view(
584                &custom_context_menu_entries,
585                default_context_menu_enabled,
586                action_context,
587                translations,
588            )
589        })
590        .into()
591    }
592
593    /// Creates the view element with scrollable wrapper.
594    ///
595    /// The backgrounds (editor and gutter) are handled by container styles
596    /// to ensure proper clipping when the pane is resized.
597    ///
598    /// Call this from the host application's `view`, mapping the editor's
599    /// [`Message`] into the host's own message type.
600    ///
601    /// # Returns
602    ///
603    /// An `Element` rendering the editor, its gutter, and any open overlay
604    ///
605    /// # Example
606    ///
607    /// ```
608    /// use iced::Element;
609    /// use iced_code_editor::{CodeEditor, Message};
610    ///
611    /// /// The host application's own message type.
612    /// #[derive(Debug, Clone)]
613    /// enum AppMessage {
614    ///     Editor(Message),
615    /// }
616    ///
617    /// fn view(editor: &CodeEditor) -> Element<'_, AppMessage> {
618    ///     editor.view().map(AppMessage::Editor)
619    /// }
620    /// ```
621    pub fn view(&self) -> Element<'_, Message> {
622        // Calculate canvas height and visual lines
623        let (visual_lines, canvas_height) = self.calculate_canvas_height();
624
625        // Create scrollable containing the canvas, with the right-click menu
626        // wrapped directly around it (see `with_context_menu`).
627        let scrollable = self.with_context_menu(
628            self.create_canvas_with_scrollable(canvas_height),
629        );
630
631        // Create background layer with gutter and code backgrounds
632        let background_row = self.create_background_layer();
633
634        // Build editor stack: backgrounds + scrollable
635        let mut editor_stack =
636            iced::widget::Stack::new().push(background_row).push(scrollable);
637
638        // Keep a slot for sticky headers even when there are none. Stack diffs
639        // children by position: inserting/removing this layer would recreate
640        // the dialogs above it, losing their text input focus and selection
641        // whenever a search result scrolls across a block boundary.
642        editor_stack = editor_stack.push(
643            self.create_sticky_scroll_layer(visual_lines.as_ref())
644                .unwrap_or_else(|| Space::new().into()),
645        );
646
647        // Add IME layer for input method support.
648        // The IME requester needs the cursor rect in viewport coordinates, which
649        // depends on the current logical↔visual mapping.
650        let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
651        let ime_layer = self.create_ime_layer(cursor_rect);
652        editor_stack = editor_stack.push(ime_layer);
653
654        // Add the compact go-to-line dialog in the top center.
655        if self.goto_line_state.is_open {
656            let goto_line_dialog = goto_line_dialog::view(
657                &self.goto_line_state,
658                self.buffer.line_count(),
659            );
660            let positioned_dialog = container(
661                Row::new()
662                    .push(Space::new().width(Length::Fill))
663                    .push(goto_line_dialog)
664                    .push(Space::new().width(Length::Fill)),
665            )
666            .padding(20)
667            .width(Length::Fill)
668            .height(Length::Shrink);
669
670            editor_stack = editor_stack.push(positioned_dialog);
671        }
672
673        // Add the command palette in the top center, above every other
674        // dialog: opening it closes the others, so it is always innermost.
675        if self.command_palette_state.is_open {
676            let entries = self.command_palette_entries();
677            let palette = command_palette_dialog::view(
678                &self.command_palette_state,
679                &entries,
680                &self.translations,
681            );
682            let positioned_palette = container(
683                Row::new()
684                    .push(Space::new().width(Length::Fill))
685                    .push(palette)
686                    .push(Space::new().width(Length::Fill)),
687            )
688            .padding(20)
689            .width(Length::Fill)
690            .height(Length::Shrink);
691
692            editor_stack = editor_stack.push(positioned_palette);
693        }
694
695        // Wrap the editor stack in a container with clip
696        let editor_container = container(editor_stack)
697            .width(Length::Fill)
698            .height(Length::Fill)
699            .clip(true);
700
701        // When wrap is disabled, add a horizontal scrollbar below the editor.
702        let editor_body: Element<'_, Message> = if self.wrap_enabled {
703            editor_container.into()
704        } else {
705            // Measuring the widest line scans the entire buffer. It is only
706            // needed for the horizontal scrollbar, so never do that work while
707            // wrapping is enabled (the default), especially after every edit in
708            // a large file.
709            let max_content_width = self.max_content_width();
710            if let Some(h_scrollbar) =
711                self.create_horizontal_scrollbar(max_content_width)
712            {
713                Column::new().push(editor_container).push(h_scrollbar).into()
714            } else {
715                editor_container.into()
716            }
717        };
718
719        let editor_body = if self.search_state.is_open {
720            Column::new()
721                .push(search_dialog::view(
722                    &self.search_state,
723                    &self.translations,
724                    !self.vim_enabled,
725                    !self.goto_line_state.is_open
726                        && !self.command_palette_state.is_open,
727                ))
728                .push(editor_body)
729                .width(Length::Fill)
730                .height(Length::Fill)
731                .into()
732        } else {
733            editor_body
734        };
735
736        if self.vim_enabled {
737            Column::new()
738                .push(editor_body)
739                .push(self.create_vim_status_bar())
740                .width(Length::Fill)
741                .height(Length::Fill)
742                .into()
743        } else {
744            editor_body
745        }
746    }
747}
748
749/// Builds a plain-color scrollable rail: a solid background track with a
750/// solid-color scroller, square corners of `radius`, and no border.
751///
752/// Shared by the canvas editor's own scrollbars ([`view`]) and the LSP
753/// overlay panels ([`lsp::process::overlay`]), which derive their colors from
754/// a theme palette instead of plain [`Color`]s.
755///
756/// # Examples
757///
758/// ```text
759/// let rail = scrollable_rail(Color::BLACK, Color::WHITE, 4.0);
760/// ```
761pub(crate) fn scrollable_rail(
762    background: Color,
763    scroller: Color,
764    radius: f32,
765) -> iced::widget::scrollable::Rail {
766    iced::widget::scrollable::Rail {
767        background: Some(background.into()),
768        border: iced::Border {
769            radius: radius.into(),
770            width: 0.0,
771            color: Color::TRANSPARENT,
772        },
773        scroller: iced::widget::scrollable::Scroller {
774            background: scroller.into(),
775            border: iced::Border {
776                radius: radius.into(),
777                width: 0.0,
778                color: Color::TRANSPARENT,
779            },
780        },
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787
788    #[test]
789    fn ime_uses_canvas_preedit_without_a_duplicate_runtime_overlay()
790    -> Result<(), &'static str> {
791        use iced::advanced::input_method::InputMethod;
792        use iced::advanced::{Layout, Shell, layout, renderer::Headless};
793
794        let renderer = iced::futures::executor::block_on(iced::Renderer::new(
795            iced::Font::DEFAULT,
796            iced::Pixels(13.0),
797            Some("tiny-skia"),
798        ))
799        .ok_or("headless software renderer unavailable")?;
800        let mut editor = CodeEditor::new("", "txt");
801        editor.focus_for_test();
802        let _ = editor.handle_ime_preedit_msg("中文", &Some(0..3));
803        let cursor =
804            Rectangle::new(iced::Point::new(40.0, 20.0), Size::new(2.0, 18.0));
805        let mut layer = editor.create_ime_layer(cursor);
806        let mut tree = iced::advanced::widget::Tree::new(&layer);
807        let node = layer.as_widget_mut().layout(
808            &mut tree,
809            &renderer,
810            &layout::Limits::new(Size::ZERO, Size::new(500.0, 300.0)),
811        );
812        let mut messages = Vec::new();
813        let mut shell = Shell::new(&mut messages);
814        layer.as_widget_mut().update(
815            &mut tree,
816            &iced::Event::Window(iced::window::Event::RedrawRequested(
817                iced::time::Instant::now(),
818            )),
819            Layout::new(&node),
820            mouse::Cursor::Unavailable,
821            &renderer,
822            &mut iced::advanced::clipboard::Null,
823            &mut shell,
824            &Rectangle::with_size(Size::new(500.0, 300.0)),
825        );
826        assert!(matches!(shell.input_method(), InputMethod::Enabled {
827            cursor: requested, preedit: None, ..
828        } if *requested == cursor));
829        Ok(())
830    }
831
832    type InputState = iced::widget::text_input::State<
833        <iced::Renderer as iced::advanced::text::Renderer>::Paragraph,
834    >;
835
836    fn input_states(
837        tree: &mut iced::advanced::widget::Tree,
838    ) -> Vec<&mut InputState> {
839        if tree.tag == iced::advanced::widget::tree::Tag::of::<InputState>() {
840            vec![tree.state.downcast_mut::<InputState>()]
841        } else {
842            tree.children.iter_mut().flat_map(input_states).collect()
843        }
844    }
845
846    #[test]
847    fn search_input_focus_survives_sticky_header_transitions()
848    -> Result<(), &'static str> {
849        assert_dialog_focus_survives_sticky_header_transitions(false, 0)
850    }
851
852    #[test]
853    fn replace_input_focus_survives_sticky_header_transitions()
854    -> Result<(), &'static str> {
855        assert_dialog_focus_survives_sticky_header_transitions(true, 1)
856    }
857
858    fn assert_dialog_focus_survives_sticky_header_transitions(
859        replace: bool,
860        focused_input: usize,
861    ) -> Result<(), &'static str> {
862        use iced::advanced::{Layout, Shell, layout, renderer::Headless};
863        use iced::keyboard::{self, Key, key::Named};
864
865        let renderer = iced::futures::executor::block_on(iced::Renderer::new(
866            iced::Font::DEFAULT,
867            iced::Pixels(13.0),
868            Some("tiny-skia"),
869        ))
870        .ok_or("headless software renderer unavailable")?;
871        let mut editor = CodeEditor::new(
872            "fn main() {\n    let needle = 1;\n    let value = needle;\n}",
873            "rs",
874        );
875        let _ = editor.handle_open_search(replace);
876        editor.search_state.set_query("needle".into(), &editor.buffer);
877        editor.search_state.set_replace_with("replacement".into());
878        let mut tree = iced::advanced::widget::Tree::new(editor.view());
879        let mut inputs = input_states(&mut tree);
880        inputs[focused_input].focus();
881        inputs[focused_input].select_range(1, 3);
882        let selection = inputs[focused_input].cursor();
883
884        // Searching/navigating to a match scrolls across block boundaries.
885        // The sticky header appears and disappears ahead of the dialog.
886        for (scroll, key, text) in [
887            (editor.line_height(), Key::Named(Named::Backspace), None),
888            (0.0, Key::Named(Named::Enter), None),
889            (
890                editor.line_height(),
891                Key::Character("x".into()),
892                Some("x".into()),
893            ),
894        ] {
895            editor.viewport_scroll = scroll;
896            let visual_lines =
897                editor.visual_lines_cached(editor.viewport_width);
898            assert_eq!(
899                editor.create_sticky_scroll_layer(&visual_lines).is_some(),
900                scroll > 0.0,
901            );
902            let mut view = editor.view();
903            tree.diff(&view);
904            let inputs = input_states(&mut tree);
905            assert!(
906                inputs[focused_input].is_focused(),
907                "dialog lost focus after scroll"
908            );
909            assert_eq!(inputs[focused_input].cursor(), selection);
910
911            let node = view.as_widget_mut().layout(
912                &mut tree,
913                &renderer,
914                &layout::Limits::new(Size::ZERO, Size::new(800.0, 400.0)),
915            );
916            let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
917                key: key.clone(),
918                modified_key: key.clone(),
919                physical_key: keyboard::key::Physical::Unidentified(
920                    keyboard::key::NativeCode::Unidentified,
921                ),
922                location: keyboard::Location::Standard,
923                modifiers: keyboard::Modifiers::empty(),
924                text,
925                repeat: false,
926            });
927            let mut messages = Vec::new();
928            let mut shell = Shell::new(&mut messages);
929            view.as_widget_mut().update(
930                &mut tree,
931                &event,
932                Layout::new(&node),
933                mouse::Cursor::Unavailable,
934                &renderer,
935                &mut iced::advanced::clipboard::Null,
936                &mut shell,
937                &node.bounds(),
938            );
939            assert!(shell.is_event_captured());
940            assert_eq!(messages.len(), 1);
941            assert!(
942                matches!(
943                    (&messages[0], replace, key),
944                    (Message::FindNext, false, Key::Named(Named::Enter))
945                        | (
946                            Message::ReplaceNext,
947                            true,
948                            Key::Named(Named::Enter)
949                        )
950                        | (Message::SearchQueryChanged(_), false, _)
951                        | (Message::ReplaceQueryChanged(_), true, _)
952                ),
953                "key escaped the dialog: {messages:?}"
954            );
955            input_states(&mut tree)[focused_input].select_range(1, 3);
956        }
957        Ok(())
958    }
959
960    #[test]
961    fn test_should_show_horizontal_scrollbar_after_reset_with_known_canvas_width()
962     {
963        // Regression test for issue #26: a prior real `draw()` call already
964        // recorded the true (narrow) canvas width before `reset()` swaps in
965        // wide content that never overflows vertically. The decision must use
966        // that observed width, not the stale `viewport_width` default.
967        let mut editor = CodeEditor::new("short\n", "rs");
968        editor.wrap_enabled = false;
969        editor.last_canvas_width.set(200.0);
970
971        let _ = editor
972            .reset("a very very very long single line that clearly exceeds two hundred pixels of rendered width");
973
974        let max_content_width = editor.max_content_width();
975        assert!(
976            editor.should_show_horizontal_scrollbar(max_content_width),
977            "wide content narrower canvas should require a horizontal scrollbar after reset()"
978        );
979    }
980
981    #[test]
982    fn test_should_show_horizontal_scrollbar_false_when_content_fits() {
983        let mut editor = CodeEditor::new("short", "rs");
984        editor.wrap_enabled = false;
985        editor.last_canvas_width.set(800.0);
986
987        let max_content_width = editor.max_content_width();
988        assert!(
989            !editor.should_show_horizontal_scrollbar(max_content_width),
990            "content narrower than the canvas should not need a horizontal scrollbar"
991        );
992    }
993
994    #[test]
995    fn test_should_show_horizontal_scrollbar_false_when_wrap_enabled() {
996        let mut editor = CodeEditor::new(
997            "a very very very long single line that clearly exceeds two hundred pixels of rendered width",
998            "rs",
999        );
1000        editor.wrap_enabled = true;
1001        editor.last_canvas_width.set(50.0);
1002
1003        let max_content_width = editor.max_content_width();
1004        assert!(
1005            !editor.should_show_horizontal_scrollbar(max_content_width),
1006            "wrapped content never needs a horizontal scrollbar regardless of width"
1007        );
1008    }
1009
1010    #[test]
1011    fn test_scrollable_rail_sets_background_scroller_and_radius() {
1012        let bg = Color::from_rgb(0.1, 0.2, 0.3);
1013        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
1014        let rail = scrollable_rail(bg, scroller, 4.0);
1015
1016        assert_eq!(rail.background, Some(iced::Background::Color(bg)));
1017        assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
1018        assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
1019        assert!(rail.border.width.abs() < f32::EPSILON);
1020        assert_eq!(
1021            rail.scroller.border.radius,
1022            iced::border::Radius::from(4.0)
1023        );
1024    }
1025
1026    #[test]
1027    fn test_sticky_layer_absent_when_disabled() {
1028        let mut editor =
1029            CodeEditor::new("fn main() {\n    let x = 1;\n}", "rs");
1030        editor.set_sticky_scroll_enabled(false);
1031        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1032
1033        assert!(
1034            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1035        );
1036    }
1037
1038    #[test]
1039    fn test_sticky_layer_absent_without_enclosing_block() {
1040        // A flat buffer has no fold region, so nothing can be pinned.
1041        let editor = CodeEditor::new("a\nb\nc", "rs");
1042        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1043
1044        assert!(
1045            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1046        );
1047    }
1048
1049    #[test]
1050    fn test_sticky_layer_absent_at_top_of_file() {
1051        // Scrolled to the top, the header is on screen and must not be pinned.
1052        let editor = CodeEditor::new(
1053            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
1054            "rs",
1055        );
1056        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1057
1058        assert!(
1059            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
1060        );
1061    }
1062
1063    #[test]
1064    fn test_sticky_layer_survives_code_folding_being_disabled() {
1065        // End-to-end counterpart of
1066        // `sticky_scroll::tests::test_headroom_survives_code_folding_being_disabled`:
1067        // the layer is built from `block_regions`, so turning folding off
1068        // removes the chevrons and leaves the pinned headers alone.
1069        let mut editor = CodeEditor::new(
1070            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
1071            "rs",
1072        );
1073        editor.set_folding_enabled(false);
1074        editor.viewport_scroll = editor.line_height();
1075        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1076
1077        assert!(
1078            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
1079        );
1080    }
1081
1082    #[test]
1083    fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
1084        // The subtlest line in the feature: the topmost entry of the viewport
1085        // is a *visual* line, and soft wrapping makes visual and logical
1086        // indices diverge. Here the body of the `if` wraps into several
1087        // segments, so scrolling onto one of its continuations puts the
1088        // topmost visual index well past any logical line index.
1089        //
1090        // The fixture discriminates: reading the visual index as a logical one
1091        // would land on `}` or past the end of the buffer, where nothing
1092        // encloses anything and the layer would be `None`.
1093        let mut editor = CodeEditor::new(
1094            "fn main() {\n    if a {\n        let x = 1; let y = 2; let z = 3; let w = 4;\n    }\n}",
1095            "rs",
1096        )
1097        .with_wrap_column(Some(20));
1098
1099        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1100        let continuation = visual_lines
1101            .iter()
1102            .position(|line| line.logical_line == 2 && line.segment_index == 1)
1103            .unwrap_or_default();
1104        assert!(
1105            continuation > 2,
1106            "the fixture must wrap far enough for the two indices to diverge"
1107        );
1108
1109        editor.viewport_scroll = continuation as f32 * editor.line_height();
1110        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1111
1112        assert!(
1113            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
1114            "a continuation segment is still inside both enclosing blocks"
1115        );
1116        // Both headers, so the layer really resolved logical line 2 and not
1117        // whatever line the raw visual index points at.
1118        assert_eq!(editor.sticky_headroom(2), 2);
1119    }
1120
1121    #[test]
1122    fn test_sticky_layer_present_when_scrolled_into_block() {
1123        let mut editor = CodeEditor::new(
1124            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
1125            "rs",
1126        );
1127        // Scroll so the second line is the topmost visible one, putting the
1128        // viewport inside the `fn` block.
1129        editor.viewport_scroll = editor.line_height();
1130        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1131
1132        assert!(
1133            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
1134        );
1135    }
1136
1137    #[test]
1138    fn test_canvas_scrollbar_style_uses_transparent_container() {
1139        let bg = Color::from_rgb(0.1, 0.2, 0.3);
1140        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
1141        let active = scrollable::Status::Active {
1142            is_horizontal_scrollbar_disabled: false,
1143            is_vertical_scrollbar_disabled: false,
1144        };
1145        let style = canvas_scrollbar_style(bg, scroller, active);
1146
1147        assert_eq!(
1148            style.container.background,
1149            Some(Background::Color(Color::TRANSPARENT))
1150        );
1151        let expected_rail = scrollable_rail(bg, scroller, 4.0);
1152        assert_eq!(style.vertical_rail.background, expected_rail.background);
1153        assert_eq!(style.horizontal_rail.background, expected_rail.background);
1154    }
1155
1156    #[test]
1157    fn test_canvas_scroller_is_faint_away_and_solid_on_the_bar() {
1158        let bg = Color::TRANSPARENT;
1159        let scroller = Color::from_rgba(0.4, 0.5, 0.6, 0.6);
1160        let alpha = |status| match canvas_scrollbar_style(bg, scroller, status)
1161            .vertical_rail
1162            .scroller
1163            .background
1164        {
1165            Background::Color(c) => c.a,
1166            // Not a solid color: NaN makes every comparison below fail.
1167            _ => f32::NAN,
1168        };
1169        let away = alpha(scrollable::Status::Active {
1170            is_horizontal_scrollbar_disabled: false,
1171            is_vertical_scrollbar_disabled: false,
1172        });
1173        let over = alpha(scrollable::Status::Hovered {
1174            is_horizontal_scrollbar_hovered: false,
1175            is_vertical_scrollbar_hovered: false,
1176            is_horizontal_scrollbar_disabled: false,
1177            is_vertical_scrollbar_disabled: false,
1178        });
1179        let on_bar = alpha(scrollable::Status::Dragged {
1180            is_horizontal_scrollbar_dragged: false,
1181            is_vertical_scrollbar_dragged: true,
1182            is_horizontal_scrollbar_disabled: false,
1183            is_vertical_scrollbar_disabled: false,
1184        });
1185        assert!(away < over && over < on_bar, "{away} {over} {on_bar}");
1186        assert!((on_bar - 1.0).abs() < 1e-6);
1187    }
1188}
1189
1190#[cfg(test)]
1191#[path = "../option_sticky_tests.rs"]
1192mod option_sticky_tests;
1193
1194#[cfg(test)]
1195#[path = "search_focus_tests.rs"]
1196mod search_focus_tests;