Skip to main content

fresh/app/types/
layout.rs

1use super::theme::CellThemeInfo;
2use crate::model::event::{BufferId, ContainerId, LeafId, SplitDirection};
3use ratatui::layout::Rect;
4use std::collections::{HashMap, HashSet};
5
6/// Mapping from visual row to buffer positions for mouse click handling
7/// Each entry represents one visual row with byte position info for click handling
8#[derive(Debug, Clone, Default)]
9pub struct ViewLineMapping {
10    /// Source byte offset for each character (None for injected/virtual content)
11    pub char_source_bytes: Vec<Option<usize>>,
12    /// Character index at each visual column (for O(1) mouse clicks)
13    pub visual_to_char: Vec<usize>,
14    /// Last valid byte position in this visual row (newline for real lines, last char for wrapped)
15    /// Clicks past end of visible text position cursor here
16    pub line_end_byte: usize,
17    /// True iff this visual row was rendered for a plugin-injected
18    /// virtual line (live-diff deletion overlays, markdown_compose
19    /// borders, …) rather than for actual buffer content. Used by
20    /// `move_visual_line` to skip past these rows without stranding
21    /// the cursor on a position whose `line_end_byte` was inherited
22    /// from the previous source row.
23    pub is_plugin_virtual: bool,
24}
25
26impl ViewLineMapping {
27    /// Get source byte at a given visual column (O(1) for mouse clicks)
28    #[inline]
29    pub fn source_byte_at_visual_col(&self, visual_col: usize) -> Option<usize> {
30        let char_idx = self.visual_to_char.get(visual_col).copied()?;
31        self.char_source_bytes.get(char_idx).copied().flatten()
32    }
33
34    /// Find the nearest source byte to a given visual column, searching outward.
35    /// Returns the source byte at the closest valid visual column.
36    pub fn nearest_source_byte(&self, goal_col: usize) -> Option<usize> {
37        let width = self.visual_to_char.len();
38        if width == 0 {
39            return None;
40        }
41        // Search outward from goal_col: try +1, -1, +2, -2, ...
42        for delta in 1..width {
43            if goal_col + delta < width {
44                if let Some(byte) = self.source_byte_at_visual_col(goal_col + delta) {
45                    return Some(byte);
46                }
47            }
48            if delta <= goal_col {
49                if let Some(byte) = self.source_byte_at_visual_col(goal_col - delta) {
50                    return Some(byte);
51                }
52            }
53        }
54        None
55    }
56
57    /// Check if this visual row contains the given byte position
58    #[inline]
59    pub fn contains_byte(&self, byte_pos: usize) -> bool {
60        // A row contains a byte if it's in the char_source_bytes range
61        // The first valid source byte marks the start, line_end_byte marks the end
62        if let Some(first_byte) = self.char_source_bytes.iter().find_map(|b| *b) {
63            byte_pos >= first_byte && byte_pos <= self.line_end_byte
64        } else {
65            // Empty/virtual row - only matches if byte_pos equals line_end_byte
66            byte_pos == self.line_end_byte
67        }
68    }
69
70    /// Get the first source byte position in this row (if any)
71    #[inline]
72    pub fn first_source_byte(&self) -> Option<usize> {
73        self.char_source_bytes.iter().find_map(|b| *b)
74    }
75}
76
77/// Type alias for popup area layout information used in mouse hit testing.
78/// Fields: (popup_index, rect, inner_rect, scroll_offset, num_items, scrollbar_rect, total_lines)
79pub(crate) type PopupAreaLayout = (usize, Rect, Rect, usize, usize, Option<Rect>, usize);
80
81/// Editor-chrome layout cache: full-frame and chrome-region rects
82/// (status bar, menu bar, prompt overlay, popups) plus the screen-
83/// indexed cell-theme map. Per-window layout (split-leaf rects, tab
84/// rects, file-explorer rects, view-line mappings) lives on
85/// [`WindowLayoutCache`] instead.
86#[derive(Debug, Clone, Default)]
87pub(crate) struct ChromeLayout {
88    /// Popup areas for mouse hit testing
89    /// scrollbar_rect is Some if popup has a scrollbar
90    pub popup_areas: Vec<PopupAreaLayout>,
91    /// Editor-level popup areas (e.g. plugin action popups) for mouse hit
92    /// testing. Stored separately from buffer popups because they're owned by
93    /// `Editor.global_popups` rather than the active buffer's state.
94    /// Fields: (popup_index, rect, inner_rect, scroll_offset, num_items)
95    pub global_popup_areas: Vec<(usize, Rect, Rect, usize, usize)>,
96    /// Suggestions area for mouse hit testing
97    /// (inner_rect, scroll_start_idx, visible_count, total_count)
98    pub suggestions_area: Option<(Rect, usize, usize, usize)>,
99    /// Full outer rect of the suggestions popup (including borders).
100    /// Used to absorb clicks on the popup chrome so they don't reach the
101    /// buffer below while the prompt is open.
102    pub suggestions_outer_area: Option<Rect>,
103    /// Hit-test rect for the floating-overlay prompt's scrollbar
104    /// (issue #1796). `None` when no overlay is open or the result
105    /// list fits in the visible window. Click/drag handlers in
106    /// `mouse_input.rs` read this to update `prompt.scroll_offset`.
107    pub suggestions_scrollbar_rect: Option<Rect>,
108    /// Hit rects for the floating-overlay prompt's widget toolbar, as
109    /// (widget_key, screen_rect) pairs. Populated when the prompt carries a
110    /// `toolbar_widget`; a click inside one fires the matching
111    /// `live_grep_toggle_<key>` action. Empty otherwise.
112    pub prompt_toolbar_hits: Vec<(String, Rect)>,
113    /// Screen rect of the floating-overlay prompt's results list (issue
114    /// #2119). `None` when no overlay is open. The mouse-wheel handler reads
115    /// this to scroll the result list (without moving the selection) when the
116    /// pointer is over it.
117    pub prompt_results_area: Option<Rect>,
118    /// Screen rect of the floating-overlay prompt's preview pane (issue
119    /// #2119). `None` when no overlay is open or the overlay is too narrow to
120    /// show a preview. The mouse-wheel handler reads this to scroll the
121    /// preview (rather than the result list) when the pointer is over it.
122    pub prompt_preview_area: Option<Rect>,
123    /// Settings modal layout for hit testing
124    pub settings_layout: Option<crate::view::settings::SettingsLayout>,
125    /// Workspace-trust dialog click layout (radios + OK/Quit) for hit testing.
126    pub workspace_trust_dialog: Option<crate::view::workspace_trust_dialog::TrustDialogLayout>,
127    /// Status bar area (row, x, width)
128    pub status_bar_area: Option<(u16, u16, u16)>,
129    /// Status bar LSP indicator area (row, start_col, end_col)
130    pub status_bar_lsp_area: Option<(u16, u16, u16)>,
131    /// Status bar warning badge area (row, start_col, end_col)
132    pub status_bar_warning_area: Option<(u16, u16, u16)>,
133    /// Status bar line ending indicator area (row, start_col, end_col)
134    pub status_bar_line_ending_area: Option<(u16, u16, u16)>,
135    /// Status bar encoding indicator area (row, start_col, end_col)
136    pub status_bar_encoding_area: Option<(u16, u16, u16)>,
137    /// Status bar language indicator area (row, start_col, end_col)
138    pub status_bar_language_area: Option<(u16, u16, u16)>,
139    /// Status bar message area (row, start_col, end_col) - clickable to show status log
140    pub status_bar_message_area: Option<(u16, u16, u16)>,
141    /// Status bar remote-authority indicator area (row, start_col, end_col)
142    /// — clickable to open the remote-authority context menu.
143    pub status_bar_remote_area: Option<(u16, u16, u16)>,
144    /// Search options layout for checkbox hit testing
145    pub search_options_layout: Option<crate::view::ui::status_bar::SearchOptionsLayout>,
146    /// Menu bar layout for hit testing
147    pub menu_layout: Option<crate::view::ui::menu::MenuLayout>,
148    /// Last frame dimensions — used by recompute_layout for macro replay
149    pub last_frame_width: u16,
150    pub last_frame_height: u16,
151    /// Per-cell theme key provenance recorded during rendering.
152    /// Flat vec indexed as `row * width + col` where `width = last_frame_width`.
153    pub cell_theme_map: Vec<CellThemeInfo>,
154}
155
156impl ChromeLayout {
157    /// Reset the cell theme map for a new frame
158    pub fn reset_cell_theme_map(&mut self) {
159        let total = self.last_frame_width as usize * self.last_frame_height as usize;
160        self.cell_theme_map.clear();
161        self.cell_theme_map.resize(total, CellThemeInfo::default());
162    }
163
164    /// Look up the theme info for a screen position
165    pub fn cell_theme_at(&self, col: u16, row: u16) -> Option<&CellThemeInfo> {
166        let idx = row as usize * self.last_frame_width as usize + col as usize;
167        self.cell_theme_map.get(idx)
168    }
169}
170
171/// Per-window layout cache: hit-test rects for content scoped to a
172/// single window (split panes, tabs, the file explorer, separators,
173/// scrollbars) plus the per-leaf visual-row→source-byte mappings used
174/// by mouse positioning and visual-line motion. Lives on `Window`;
175/// editor-chrome rects live on [`ChromeLayout`].
176#[derive(Debug, Clone, Default)]
177pub(crate) struct WindowLayoutCache {
178    /// File explorer area (if visible)
179    pub file_explorer_area: Option<Rect>,
180    /// Editor content area (excluding file explorer)
181    pub editor_content_area: Option<Rect>,
182    /// Individual split areas with their scrollbar areas and thumb positions
183    /// (split_id, buffer_id, content_rect, scrollbar_rect, thumb_start, thumb_end)
184    pub split_areas: Vec<(LeafId, BufferId, Rect, Rect, usize, usize)>,
185    /// Horizontal scrollbar areas per split
186    /// (split_id, buffer_id, horizontal_scrollbar_rect, max_content_width, thumb_start_col, thumb_end_col)
187    pub horizontal_scrollbar_areas: Vec<(LeafId, BufferId, Rect, usize, usize, usize)>,
188    /// Split separator positions for drag resize
189    /// (container_id, direction, x, y, length)
190    pub separator_areas: Vec<(ContainerId, SplitDirection, u16, u16, u16)>,
191    /// Tab layouts per split for mouse interaction
192    pub tab_layouts: HashMap<LeafId, crate::view::ui::tabs::TabLayout>,
193    /// Close split button hit areas
194    /// (split_id, row, start_col, end_col)
195    pub close_split_areas: Vec<(LeafId, u16, u16, u16)>,
196    /// Maximize split button hit areas
197    /// (split_id, row, start_col, end_col)
198    pub maximize_split_areas: Vec<(LeafId, u16, u16, u16)>,
199    /// View line mappings for accurate mouse click positioning per split
200    /// Maps visual row index to character position mappings
201    /// Used to translate screen coordinates to buffer byte positions
202    pub view_line_mappings: HashMap<LeafId, Vec<ViewLineMapping>>,
203}
204
205impl WindowLayoutCache {
206    /// Find which visual row contains the given byte position for a split
207    pub fn find_visual_row(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
208        let mappings = self.view_line_mappings.get(&split_id)?;
209        mappings.iter().position(|m| m.contains_byte(byte_pos))
210    }
211
212    /// Get the visual column of a byte position within its visual row
213    pub fn byte_to_visual_column(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
214        let mappings = self.view_line_mappings.get(&split_id)?;
215        let row_idx = self.find_visual_row(split_id, byte_pos)?;
216        let row = mappings.get(row_idx)?;
217
218        // Find the visual column that maps to this byte position
219        for (visual_col, &char_idx) in row.visual_to_char.iter().enumerate() {
220            if let Some(source_byte) = row.char_source_bytes.get(char_idx).and_then(|b| *b) {
221                if source_byte == byte_pos {
222                    return Some(visual_col);
223                }
224                // If we've passed the byte position, return previous column
225                if source_byte > byte_pos {
226                    return Some(visual_col.saturating_sub(1));
227                }
228            }
229        }
230        // Byte is at or past end of row - return column after last character
231        // This handles cursor positions at end of line (e.g., after last char before newline)
232        Some(row.visual_to_char.len())
233    }
234
235    /// Move by visual line using the cached mappings
236    /// Returns (new_position, new_visual_column) or None if at boundary
237    pub fn move_visual_line(
238        &self,
239        split_id: LeafId,
240        current_pos: usize,
241        goal_visual_col: usize,
242        direction: i8, // -1 = up, 1 = down
243    ) -> Option<(usize, usize)> {
244        let mappings = self.view_line_mappings.get(&split_id)?;
245        let current_row = self.find_visual_row(split_id, current_pos)?;
246
247        // Walk past purely-virtual rows (e.g. markdown_compose table top/
248        // bottom borders and inter-row separators, live-diff deletion
249        // virtual lines).  Those rows are plugin-injected and their
250        // `line_end_byte` is inherited from the adjacent content row.
251        // If MoveDown/MoveUp stopped on them the cursor would land on a
252        // byte that's already at the row above's end, which in turn
253        // causes Down-after-table to teleport back to an earlier
254        // position (regression exposed by markdown_compose's table
255        // border feature) or strands the cursor at the previous line's
256        // EOL when a live-diff deletion hunk starts with a blank line
257        // (regression exposed by the live-diff plugin).
258        //
259        // A row is "navigable" iff at least one of its visual columns
260        // maps to a real source byte.  Skip entirely-virtual rows in
261        // the move direction until we hit a navigable one or run off
262        // the edge.
263        let mut target_row = current_row;
264        let navigable = |idx: usize| -> bool {
265            mappings
266                .get(idx)
267                .map(|m| m.char_source_bytes.iter().any(|b| b.is_some()))
268                .unwrap_or(false)
269        };
270        loop {
271            target_row = if direction < 0 {
272                target_row.checked_sub(1)?
273            } else {
274                let next = target_row + 1;
275                if next >= mappings.len() {
276                    return None;
277                }
278                next
279            };
280            // Either the next row has real source content, or we've reached
281            // a legitimate non-source row that the rest of the editor
282            // already treats as a cursor stop (trailing empty line at EOF,
283            // implicit blank final line, empty source line between
284            // paragraphs).  In either case stop walking.
285            if navigable(target_row) {
286                break;
287            }
288            let mapping = mappings.get(target_row)?;
289            if mapping.is_plugin_virtual {
290                // Plugin-injected virtual row (live-diff deletion lines,
291                // markdown_compose table borders, …).  Its
292                // `line_end_byte` is inherited from the previous row, so
293                // stopping here would strand the cursor at the previous
294                // source line's EOL.  Keep walking.
295                continue;
296            }
297            // Empty mapping that isn't plugin-virtual: a real empty
298            // source line (paragraph separator), the trailing empty
299            // EOF row, or the implicit blank final line.  These are
300            // legitimate cursor stops.
301            break;
302        }
303
304        let target_mapping = mappings.get(target_row)?;
305
306        // Try to get byte at goal visual column.  If the goal column is past
307        // the end of visible content, land at line_end_byte (the newline or
308        // end of buffer).  If the column exists but has no source byte (e.g.
309        // padding on a wrapped continuation line), search outward for the
310        // nearest valid source byte at minimal visual distance.
311        let new_pos = if goal_visual_col >= target_mapping.visual_to_char.len() {
312            target_mapping.line_end_byte
313        } else {
314            target_mapping
315                .source_byte_at_visual_col(goal_visual_col)
316                .or_else(|| target_mapping.nearest_source_byte(goal_visual_col))
317                .unwrap_or(target_mapping.line_end_byte)
318        };
319
320        Some((new_pos, goal_visual_col))
321    }
322
323    /// Get the start byte position of the visual row containing the given byte position.
324    /// If the cursor is already at the visual row start and this is a wrapped continuation,
325    /// moves to the previous visual row's start (within the same logical line).
326    /// Get the start byte position of the visual row containing the given byte position.
327    /// When `allow_advance` is true and the cursor is already at the row start,
328    /// moves to the previous visual row's start.
329    pub fn visual_line_start(
330        &self,
331        split_id: LeafId,
332        byte_pos: usize,
333        allow_advance: bool,
334    ) -> Option<usize> {
335        let mappings = self.view_line_mappings.get(&split_id)?;
336        let row_idx = self.find_visual_row(split_id, byte_pos)?;
337        let row = mappings.get(row_idx)?;
338        let row_start = row.first_source_byte()?;
339
340        if allow_advance && byte_pos == row_start && row_idx > 0 {
341            let prev_row = mappings.get(row_idx - 1)?;
342            prev_row.first_source_byte()
343        } else {
344            Some(row_start)
345        }
346    }
347
348    /// Get the end byte position of the visual row containing the given byte position.
349    /// If the cursor is already at the visual row end and the next row is a wrapped continuation,
350    /// moves to the next visual row's end (within the same logical line).
351    /// Get the end byte position of the visual row containing the given byte position.
352    /// When `allow_advance` is true and the cursor is already at the row end,
353    /// advances to the next visual row's end.
354    pub fn visual_line_end(
355        &self,
356        split_id: LeafId,
357        byte_pos: usize,
358        allow_advance: bool,
359    ) -> Option<usize> {
360        let mappings = self.view_line_mappings.get(&split_id)?;
361        let row_idx = self.find_visual_row(split_id, byte_pos)?;
362        let row = mappings.get(row_idx)?;
363
364        if allow_advance && byte_pos == row.line_end_byte && row_idx + 1 < mappings.len() {
365            let next_row = mappings.get(row_idx + 1)?;
366            Some(next_row.line_end_byte)
367        } else {
368            Some(row.line_end_byte)
369        }
370    }
371}
372
373/// Self-contained state for the Live Grep floating overlay's preview
374/// pane (issue #1796).
375///
376/// Owned directly by `Editor::overlay_preview_state` rather than
377/// living in `Editor::split_view_states` keyed by a synthetic
378/// `LeafId`. This isolation matters because ~20 sites across the
379/// editor iterate `split_view_states` for cross-cutting work
380/// (workspace save, viewport hooks, settings broadcasts, buffer
381/// close cascades). The preview is a *transient render artefact*,
382/// not a real split — none of those code paths should see it.
383///
384/// The phantom buffer is not in `SplitManager`'s tree either, so
385/// it's invisible to focus rotation (`Alt+]`/`Alt+[`), tab drag
386/// drop zones, hit testing, and `find_leaf_by_role` queries.
387#[derive(Debug)]
388pub struct OverlayPreviewState {
389    /// Buffer currently displayed in the preview pane.
390    pub buffer_id: BufferId,
391    /// View state (cursor, viewport, folds, view mode, …) used by
392    /// the renderer's per-leaf pipeline.
393    pub view_state: crate::view::split::SplitViewState,
394    /// Buffers we loaded only to feed the preview pane. On overlay
395    /// close we close these via the standard `close_buffer` path.
396    /// Buffers the user already had open are *not* in this set —
397    /// dismissing the overlay never disturbs them.
398    pub loaded_buffers: HashSet<BufferId>,
399    /// When true, the preview pane renders empty (just its frame). Set
400    /// when the current query has no selectable result so a stale match
401    /// doesn't keep showing after the result list clears. Kept as a flag
402    /// (rather than dropping the whole state) so `loaded_buffers` stays
403    /// tracked for cleanup and the buffer can be re-shown on the next
404    /// match without reloading.
405    pub blanked: bool,
406    /// The match byte-offset the preview viewport was last centred on
407    /// (issue #2119). The renderer recentres only when this changes (a new
408    /// selected result), so a mouse-wheel scroll of the preview isn't undone
409    /// by the next frame's recenter.
410    pub centered_byte: Option<usize>,
411}