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