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