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    /// Status bar workspace-trust indicator area (row, start_col, end_col)
145    /// — clickable to open the workspace-trust prompt.
146    pub status_bar_trust_area: Option<(u16, u16, u16)>,
147    /// Plugin-registered status-bar token areas, keyed by
148    /// `"<plugin>:<token>"`. Populated by `render_status_bar`; consumed
149    /// by `handle_click_status_bar` which fires the
150    /// `status_bar_token_clicked` hook on a hit so the registering
151    /// plugin can react (typically by re-opening a deferred prompt).
152    /// See `docs/internal/trust-env-devcontainer-ux-plan.md` for the
153    /// design context.
154    pub status_bar_plugin_token_areas: std::collections::HashMap<String, (u16, u16, u16)>,
155    /// Search options layout for checkbox hit testing
156    pub search_options_layout: Option<crate::view::ui::status_bar::SearchOptionsLayout>,
157    /// Menu bar layout for hit testing
158    pub menu_layout: Option<crate::view::ui::menu::MenuLayout>,
159    /// Last frame dimensions — used by recompute_layout for macro replay
160    pub last_frame_width: u16,
161    pub last_frame_height: u16,
162    /// Per-cell theme key provenance recorded during rendering.
163    /// Flat vec indexed as `row * width + col` where `width = last_frame_width`.
164    pub cell_theme_map: Vec<CellThemeInfo>,
165}
166
167impl ChromeLayout {
168    /// Reset the cell theme map for a new frame
169    pub fn reset_cell_theme_map(&mut self) {
170        let total = self.last_frame_width as usize * self.last_frame_height as usize;
171        self.cell_theme_map.clear();
172        self.cell_theme_map.resize(total, CellThemeInfo::default());
173    }
174
175    /// Look up the theme info for a screen position
176    pub fn cell_theme_at(&self, col: u16, row: u16) -> Option<&CellThemeInfo> {
177        let idx = row as usize * self.last_frame_width as usize + col as usize;
178        self.cell_theme_map.get(idx)
179    }
180}
181
182/// Per-window layout cache: hit-test rects for content scoped to a
183/// single window (split panes, tabs, the file explorer, separators,
184/// scrollbars) plus the per-leaf visual-row→source-byte mappings used
185/// by mouse positioning and visual-line motion. Lives on `Window`;
186/// editor-chrome rects live on [`ChromeLayout`].
187#[derive(Debug, Clone, Default)]
188pub(crate) struct WindowLayoutCache {
189    /// File explorer area (if visible)
190    pub file_explorer_area: Option<Rect>,
191    /// Editor content area (excluding file explorer)
192    pub editor_content_area: Option<Rect>,
193    /// Individual split areas with their scrollbar areas and thumb positions
194    /// (split_id, buffer_id, content_rect, scrollbar_rect, thumb_start, thumb_end)
195    pub split_areas: Vec<(LeafId, BufferId, Rect, Rect, usize, usize)>,
196    /// Horizontal scrollbar areas per split
197    /// (split_id, buffer_id, horizontal_scrollbar_rect, max_content_width, thumb_start_col, thumb_end_col)
198    pub horizontal_scrollbar_areas: Vec<(LeafId, BufferId, Rect, usize, usize, usize)>,
199    /// Split separator positions for drag resize
200    /// (container_id, direction, x, y, length)
201    pub separator_areas: Vec<(ContainerId, SplitDirection, u16, u16, u16)>,
202    /// Tab layouts per split for mouse interaction
203    pub tab_layouts: HashMap<LeafId, crate::view::ui::tabs::TabLayout>,
204    /// Close split button hit areas
205    /// (split_id, row, start_col, end_col)
206    pub close_split_areas: Vec<(LeafId, u16, u16, u16)>,
207    /// Maximize split button hit areas
208    /// (split_id, row, start_col, end_col)
209    pub maximize_split_areas: Vec<(LeafId, u16, u16, u16)>,
210    /// View line mappings for accurate mouse click positioning per split
211    /// Maps visual row index to character position mappings
212    /// Used to translate screen coordinates to buffer byte positions
213    pub view_line_mappings: HashMap<LeafId, Vec<ViewLineMapping>>,
214}
215
216impl WindowLayoutCache {
217    /// Find which visual row contains the given byte position for a split
218    pub fn find_visual_row(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
219        let mappings = self.view_line_mappings.get(&split_id)?;
220        mappings.iter().position(|m| m.contains_byte(byte_pos))
221    }
222
223    /// Get the visual column of a byte position within its visual row
224    pub fn byte_to_visual_column(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
225        let mappings = self.view_line_mappings.get(&split_id)?;
226        let row_idx = self.find_visual_row(split_id, byte_pos)?;
227        let row = mappings.get(row_idx)?;
228
229        // Find the visual column that maps to this byte position
230        for (visual_col, &char_idx) in row.visual_to_char.iter().enumerate() {
231            if let Some(source_byte) = row.char_source_bytes.get(char_idx).and_then(|b| *b) {
232                if source_byte == byte_pos {
233                    return Some(visual_col);
234                }
235                // If we've passed the byte position, return previous column
236                if source_byte > byte_pos {
237                    return Some(visual_col.saturating_sub(1));
238                }
239            }
240        }
241        // Byte is at or past end of row - return column after last character
242        // This handles cursor positions at end of line (e.g., after last char before newline)
243        Some(row.visual_to_char.len())
244    }
245
246    /// Move by visual line using the cached mappings
247    /// Returns (new_position, new_visual_column) or None if at boundary
248    pub fn move_visual_line(
249        &self,
250        split_id: LeafId,
251        current_pos: usize,
252        goal_visual_col: usize,
253        direction: i8, // -1 = up, 1 = down
254    ) -> Option<(usize, usize)> {
255        let mappings = self.view_line_mappings.get(&split_id)?;
256        let current_row = self.find_visual_row(split_id, current_pos)?;
257
258        // Walk past purely-virtual rows (e.g. markdown_compose table top/
259        // bottom borders and inter-row separators, live-diff deletion
260        // virtual lines).  Those rows are plugin-injected and their
261        // `line_end_byte` is inherited from the adjacent content row.
262        // If MoveDown/MoveUp stopped on them the cursor would land on a
263        // byte that's already at the row above's end, which in turn
264        // causes Down-after-table to teleport back to an earlier
265        // position (regression exposed by markdown_compose's table
266        // border feature) or strands the cursor at the previous line's
267        // EOL when a live-diff deletion hunk starts with a blank line
268        // (regression exposed by the live-diff plugin).
269        //
270        // A row is "navigable" iff at least one of its visual columns
271        // maps to a real source byte.  Skip entirely-virtual rows in
272        // the move direction until we hit a navigable one or run off
273        // the edge.
274        let mut target_row = current_row;
275        let navigable = |idx: usize| -> bool {
276            mappings
277                .get(idx)
278                .map(|m| m.char_source_bytes.iter().any(|b| b.is_some()))
279                .unwrap_or(false)
280        };
281        loop {
282            target_row = if direction < 0 {
283                target_row.checked_sub(1)?
284            } else {
285                let next = target_row + 1;
286                if next >= mappings.len() {
287                    return None;
288                }
289                next
290            };
291            // Either the next row has real source content, or we've reached
292            // a legitimate non-source row that the rest of the editor
293            // already treats as a cursor stop (trailing empty line at EOF,
294            // implicit blank final line, empty source line between
295            // paragraphs).  In either case stop walking.
296            if navigable(target_row) {
297                break;
298            }
299            let mapping = mappings.get(target_row)?;
300            if mapping.is_plugin_virtual {
301                // Plugin-injected virtual row (live-diff deletion lines,
302                // markdown_compose table borders, …).  Its
303                // `line_end_byte` is inherited from the previous row, so
304                // stopping here would strand the cursor at the previous
305                // source line's EOL.  Keep walking.
306                continue;
307            }
308            // Empty mapping that isn't plugin-virtual: a real empty
309            // source line (paragraph separator), the trailing empty
310            // EOF row, or the implicit blank final line.  These are
311            // legitimate cursor stops.
312            break;
313        }
314
315        let target_mapping = mappings.get(target_row)?;
316
317        // Try to get byte at goal visual column.  If the goal column is past
318        // the end of visible content, land at line_end_byte (the newline or
319        // end of buffer).  If the column exists but has no source byte (e.g.
320        // padding on a wrapped continuation line), search outward for the
321        // nearest valid source byte at minimal visual distance.
322        let new_pos = if goal_visual_col >= target_mapping.visual_to_char.len() {
323            target_mapping.line_end_byte
324        } else {
325            target_mapping
326                .source_byte_at_visual_col(goal_visual_col)
327                .or_else(|| target_mapping.nearest_source_byte(goal_visual_col))
328                .unwrap_or(target_mapping.line_end_byte)
329        };
330
331        Some((new_pos, goal_visual_col))
332    }
333
334    /// Get the start byte position of the visual row containing the given byte position.
335    /// If the cursor is already at the visual row start and this is a wrapped continuation,
336    /// moves to the previous visual row's start (within the same logical line).
337    /// Get the start byte position of the visual row containing the given byte position.
338    /// When `allow_advance` is true and the cursor is already at the row start,
339    /// moves to the previous visual row's start.
340    pub fn visual_line_start(
341        &self,
342        split_id: LeafId,
343        byte_pos: usize,
344        allow_advance: bool,
345    ) -> Option<usize> {
346        let mappings = self.view_line_mappings.get(&split_id)?;
347        let row_idx = self.find_visual_row(split_id, byte_pos)?;
348        let row = mappings.get(row_idx)?;
349        let row_start = row.first_source_byte()?;
350
351        if allow_advance && byte_pos == row_start && row_idx > 0 {
352            let prev_row = mappings.get(row_idx - 1)?;
353            prev_row.first_source_byte()
354        } else {
355            Some(row_start)
356        }
357    }
358
359    /// Get the end byte position of the visual row containing the given byte position.
360    /// If the cursor is already at the visual row end and the next row is a wrapped continuation,
361    /// moves to the next visual row's end (within the same logical line).
362    /// Get the end byte position of the visual row containing the given byte position.
363    /// When `allow_advance` is true and the cursor is already at the row end,
364    /// advances to the next visual row's end.
365    pub fn visual_line_end(
366        &self,
367        split_id: LeafId,
368        byte_pos: usize,
369        allow_advance: bool,
370    ) -> Option<usize> {
371        let mappings = self.view_line_mappings.get(&split_id)?;
372        let row_idx = self.find_visual_row(split_id, byte_pos)?;
373        let row = mappings.get(row_idx)?;
374
375        if allow_advance && byte_pos == row.line_end_byte && row_idx + 1 < mappings.len() {
376            let next_row = mappings.get(row_idx + 1)?;
377            Some(next_row.line_end_byte)
378        } else {
379            Some(row.line_end_byte)
380        }
381    }
382}
383
384/// Self-contained state for the Live Grep floating overlay's preview
385/// pane (issue #1796).
386///
387/// Owned directly by `Editor::overlay_preview_state` rather than
388/// living in `Editor::split_view_states` keyed by a synthetic
389/// `LeafId`. This isolation matters because ~20 sites across the
390/// editor iterate `split_view_states` for cross-cutting work
391/// (workspace save, viewport hooks, settings broadcasts, buffer
392/// close cascades). The preview is a *transient render artefact*,
393/// not a real split — none of those code paths should see it.
394///
395/// The phantom buffer is not in `SplitManager`'s tree either, so
396/// it's invisible to focus rotation (`Alt+]`/`Alt+[`), tab drag
397/// drop zones, hit testing, and `find_leaf_by_role` queries.
398#[derive(Debug)]
399pub struct OverlayPreviewState {
400    /// Buffer currently displayed in the preview pane.
401    pub buffer_id: BufferId,
402    /// View state (cursor, viewport, folds, view mode, …) used by
403    /// the renderer's per-leaf pipeline.
404    pub view_state: crate::view::split::SplitViewState,
405    /// Buffers we loaded only to feed the preview pane. On overlay
406    /// close we close these via the standard `close_buffer` path.
407    /// Buffers the user already had open are *not* in this set —
408    /// dismissing the overlay never disturbs them.
409    pub loaded_buffers: HashSet<BufferId>,
410    /// When true, the preview pane renders empty (just its frame). Set
411    /// when the current query has no selectable result so a stale match
412    /// doesn't keep showing after the result list clears. Kept as a flag
413    /// (rather than dropping the whole state) so `loaded_buffers` stays
414    /// tracked for cleanup and the buffer can be re-shown on the next
415    /// match without reloading.
416    pub blanked: bool,
417    /// The match byte-offset the preview viewport was last centred on
418    /// (issue #2119). The renderer recentres only when this changes (a new
419    /// selected result), so a mouse-wheel scroll of the preview isn't undone
420    /// by the next frame's recenter.
421    pub centered_byte: Option<usize>,
422}