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