Skip to main content

fresh/app/
types.rs

1use crate::app::file_open::SortMode;
2use crate::model::event::{BufferId, ContainerId, LeafId, SplitDirection};
3use crate::services::async_bridge::LspMessageType;
4use ratatui::layout::Rect;
5use rust_i18n::t;
6use std::collections::{HashMap, HashSet};
7use std::ops::Range;
8use std::path::{Path, PathBuf};
9
10pub const DEFAULT_BACKGROUND_FILE: &str = "scripts/landscape-wide.txt";
11
12pub const FILE_EXPLORER_CONTEXT_MENU_WIDTH: u16 = 24;
13
14/// Unique identifier for a buffer group
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct BufferGroupId(pub usize);
17
18/// Layout node for a buffer group
19#[derive(Debug, Clone)]
20pub enum GroupLayoutNode {
21    /// A scrollable panel backed by a real buffer
22    Scrollable {
23        /// Panel name (e.g., "tree", "picker")
24        id: String,
25        /// Buffer ID for this panel (set during creation)
26        buffer_id: Option<BufferId>,
27        /// Split leaf ID (set during creation)
28        split_id: Option<LeafId>,
29    },
30    /// A fixed-height panel (header, footer, toolbar)
31    Fixed {
32        /// Panel name
33        id: String,
34        /// Height in rows
35        height: u16,
36        /// Buffer ID (set during creation)
37        buffer_id: Option<BufferId>,
38        /// Split leaf ID (set during creation)
39        split_id: Option<LeafId>,
40    },
41    /// A horizontal or vertical split containing two children
42    Split {
43        direction: SplitDirection,
44        /// Ratio for the first child (0.0 to 1.0)
45        ratio: f32,
46        first: Box<GroupLayoutNode>,
47        second: Box<GroupLayoutNode>,
48    },
49}
50
51/// A buffer group: multiple splits/buffers appearing as one tab.
52///
53/// Each panel is a real buffer with its own viewport, scrollbar,
54/// and cursor. The group presents them as a single logical entity
55/// in the tab bar and buffer list.
56#[derive(Debug)]
57pub struct BufferGroup {
58    /// Unique ID
59    pub id: BufferGroupId,
60    /// Display name (shown in tab bar)
61    pub name: String,
62    /// Mode for keybindings
63    pub mode: String,
64    /// Layout tree
65    pub layout: GroupLayoutNode,
66    /// All buffer IDs in this group (panel name → buffer ID)
67    pub panel_buffers: HashMap<String, BufferId>,
68    /// All split leaf IDs in this group
69    pub panel_splits: HashMap<String, LeafId>,
70    /// The "representative" split that owns the tab entry.
71    /// This is typically the first scrollable panel.
72    pub representative_split: Option<LeafId>,
73}
74
75/// Pre-calculated line information for an event
76/// Calculated BEFORE buffer modification so line numbers are accurate
77#[derive(Debug, Clone, Default)]
78pub(super) struct EventLineInfo {
79    /// Start line (0-indexed) where the change begins
80    pub start_line: usize,
81    /// End line (0-indexed) where the change ends (in original buffer for deletes)
82    pub end_line: usize,
83    /// Number of lines added (for inserts) or removed (for deletes)
84    pub line_delta: i32,
85}
86
87/// Search state for find/replace functionality
88#[derive(Debug, Clone)]
89pub(crate) struct SearchState {
90    /// The search query
91    pub query: String,
92    /// All match positions in the buffer (byte offsets)
93    pub matches: Vec<usize>,
94    /// Match lengths parallel to `matches` (needed for viewport overlay creation)
95    pub match_lengths: Vec<usize>,
96    /// Index of the currently selected match
97    pub current_match_index: Option<usize>,
98    /// Whether search wraps around at document boundaries
99    pub wrap_search: bool,
100    /// Optional search range (for search in selection)
101    pub search_range: Option<Range<usize>>,
102    /// True if the match count was capped at MAX_MATCHES
103    #[allow(dead_code)]
104    pub capped: bool,
105}
106
107impl SearchState {
108    /// Maximum number of search matches to collect before stopping.
109    /// Prevents unbounded memory usage when searching for common patterns
110    /// in large files.
111    pub const MAX_MATCHES: usize = 100_000;
112}
113
114/// State for interactive replace (query-replace)
115#[derive(Debug, Clone)]
116pub(crate) struct InteractiveReplaceState {
117    /// The search pattern
118    pub search: String,
119    /// The replacement text
120    pub replacement: String,
121    /// Current match position (byte offset of the match we're at)
122    pub current_match_pos: usize,
123    /// Length of the current match in bytes (may differ from search.len() for regex)
124    pub current_match_len: usize,
125    /// Starting position (to detect when we've wrapped around full circle)
126    pub start_pos: usize,
127    /// Whether we've wrapped around to the beginning
128    pub has_wrapped: bool,
129    /// Number of replacements made so far
130    pub replacements_made: usize,
131    /// Compiled regex for regex-mode replace (None when regex mode is off)
132    pub regex: Option<regex::bytes::Regex>,
133}
134
135/// The kind of buffer (file-backed or virtual)
136#[derive(Debug, Clone, PartialEq)]
137pub enum BufferKind {
138    /// A buffer backed by a file on disk
139    File {
140        /// Host-side path to the file. Filesystem APIs and the
141        /// editor's own buffer state always speak in host paths.
142        path: PathBuf,
143        /// LSP-facing URI for the file. Already translated for the
144        /// active authority, so handing this to the LSP server is
145        /// always correct. See [`LspUri`] for the why.
146        uri: Option<LspUri>,
147    },
148    /// A virtual buffer (not backed by a file)
149    /// Used for special buffers like *Diagnostics*, *Grep*, etc.
150    Virtual {
151        /// The buffer's mode (e.g., "diagnostics-list", "grep-results")
152        mode: String,
153    },
154}
155
156/// Metadata associated with a buffer
157#[derive(Debug, Clone)]
158pub struct BufferMetadata {
159    /// The kind of buffer (file or virtual)
160    pub kind: BufferKind,
161
162    /// Display name for the buffer (project-relative path or filename or *BufferName*)
163    pub display_name: String,
164
165    /// Whether LSP is enabled for this buffer (always false for virtual buffers)
166    pub lsp_enabled: bool,
167
168    /// Reason LSP is disabled (if applicable)
169    pub lsp_disabled_reason: Option<String>,
170
171    /// Whether the buffer is read-only (typically true for virtual buffers)
172    pub read_only: bool,
173
174    /// Whether the buffer contains binary content
175    /// Binary buffers are automatically read-only and render unprintable chars as code points
176    pub binary: bool,
177
178    /// LSP server instance IDs that have received didOpen for this buffer.
179    /// Used to ensure didOpen is sent before any requests to a new/restarted server.
180    /// When a server restarts, it gets a new ID, so didOpen is automatically resent.
181    /// Old IDs are harmless - they just remain in the set but don't match any active server.
182    pub lsp_opened_with: HashSet<u64>,
183
184    /// Whether this buffer should be hidden from tabs (used for composite source buffers)
185    pub hidden_from_tabs: bool,
186
187    /// Whether this buffer is a synthetic placeholder created when the user
188    /// closed their last buffer with `auto_create_empty_buffer_on_last_buffer_close`
189    /// disabled. The editor's invariants require at least one buffer at all
190    /// times, so we keep this one around but render the split pane as blank
191    /// (no line numbers, no `~` filler) and hide it from tabs to give the
192    /// user a truly empty workspace.
193    pub synthetic_placeholder: bool,
194
195    /// Whether this buffer is opened in "preview" mode (ephemeral).
196    /// A preview buffer is one opened by a single-click in the file explorer
197    /// (or a similar soft-open gesture). Its tab is rendered in italic and
198    /// it is replaced the next time another file is opened the same way.
199    /// The flag is cleared ("promoted") when the user edits the buffer,
200    /// double-clicks the file, or otherwise signals commitment to the file.
201    ///
202    /// Intentionally ephemeral — never serialized into workspace or
203    /// recovery state. Restarting the editor always brings buffers back
204    /// as permanent tabs; preview status belongs to the current session's
205    /// exploration flow only.
206    pub is_preview: bool,
207
208    /// Stable recovery ID for unnamed buffers.
209    /// For file-backed buffers, recovery ID is computed from the path hash.
210    /// For unnamed buffers, this is generated once and reused across auto-saves.
211    pub recovery_id: Option<String>,
212}
213
214impl BufferMetadata {
215    /// Get the file path if this is a file-backed buffer
216    pub fn file_path(&self) -> Option<&PathBuf> {
217        match &self.kind {
218            BufferKind::File { path, .. } => Some(path),
219            BufferKind::Virtual { .. } => None,
220        }
221    }
222
223    /// Get the LSP-facing URI if this is a file-backed buffer.
224    ///
225    /// The URI is already translated for the active authority — i.e.
226    /// it carries the in-container path on a devcontainer authority
227    /// and the host path elsewhere. Hand it to the LSP server
228    /// directly; do NOT pass it to filesystem APIs (use
229    /// [`Self::file_path`] for that).
230    pub fn file_uri(&self) -> Option<&LspUri> {
231        match &self.kind {
232            BufferKind::File { uri, .. } => uri.as_ref(),
233            BufferKind::Virtual { .. } => None,
234        }
235    }
236
237    /// Check if this is a virtual buffer
238    pub fn is_virtual(&self) -> bool {
239        matches!(self.kind, BufferKind::Virtual { .. })
240    }
241
242    /// Get the mode name for virtual buffers
243    pub fn virtual_mode(&self) -> Option<&str> {
244        match &self.kind {
245            BufferKind::Virtual { mode } => Some(mode),
246            BufferKind::File { .. } => None,
247        }
248    }
249}
250
251impl Default for BufferMetadata {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257impl BufferMetadata {
258    /// Create new metadata for a buffer (unnamed, file-backed)
259    pub fn new() -> Self {
260        Self {
261            kind: BufferKind::File {
262                path: PathBuf::new(),
263                uri: None,
264            },
265            display_name: t!("buffer.no_name").to_string(),
266            lsp_enabled: true,
267            lsp_disabled_reason: None,
268            read_only: false,
269            binary: false,
270            lsp_opened_with: HashSet::new(),
271            hidden_from_tabs: false,
272            synthetic_placeholder: false,
273            is_preview: false,
274            recovery_id: None,
275        }
276    }
277
278    /// Create new metadata for an unnamed buffer with a custom display name
279    /// Used for buffers created from stdin or other non-file sources
280    pub fn new_unnamed(display_name: String) -> Self {
281        Self {
282            kind: BufferKind::File {
283                path: PathBuf::new(),
284                uri: None,
285            },
286            display_name,
287            lsp_enabled: false, // No file path, so no LSP
288            lsp_disabled_reason: Some(t!("lsp.disabled.unnamed").to_string()),
289            read_only: false,
290            binary: false,
291            lsp_opened_with: HashSet::new(),
292            hidden_from_tabs: false,
293            synthetic_placeholder: false,
294            is_preview: false,
295            recovery_id: None,
296        }
297    }
298
299    /// Create metadata for a file-backed buffer
300    ///
301    /// # Arguments
302    /// * `canonical_path` - The canonical (symlink-resolved) absolute path to the file
303    /// * `display_path` - The user-visible path before canonicalization (for library detection)
304    /// * `working_dir` - The canonical working directory for computing relative display name
305    /// * `path_translation` - Active authority's host↔remote workspace mapping;
306    ///   used to build the LSP-facing `file_uri` so an in-container LSP sees
307    ///   in-container paths. `None` for local/SSH authorities.
308    pub fn with_file(
309        canonical_path: PathBuf,
310        display_path: &Path,
311        working_dir: &Path,
312        path_translation: Option<&crate::services::authority::PathTranslation>,
313    ) -> Self {
314        // Compute URI from the absolute path. When the active authority
315        // has a host↔remote mapping (devcontainer attach), this is
316        // where the host path gets rewritten into the container path
317        // the LSP server actually understands.
318        let file_uri = LspUri::from_host_path(&canonical_path, path_translation);
319
320        // Compute display name (project-relative when under working_dir, else absolute path).
321        // Use canonicalized forms first to handle macOS /var -> /private/var differences.
322        let display_name = Self::display_name_for_path(&canonical_path, working_dir);
323
324        // Check if this is a library file (in vendor directories or standard libraries).
325        // Library files are read-only (to prevent accidental edits) but LSP stays
326        // enabled so that Goto Definition, Hover, Find References, etc. still work
327        // when the user navigates into library source code (issue #1344).
328        //
329        // A file is only considered a library file if BOTH the canonical path and the
330        // user-visible path are in a library directory. This prevents symlinked dotfiles
331        // (e.g., ~/.bash_profile -> /nix/store/...) from being marked read-only when
332        // the user explicitly opened a non-library path (issue #1469).
333        let is_library = Self::is_library_path(&canonical_path, working_dir)
334            && Self::is_library_path(display_path, working_dir);
335
336        Self {
337            kind: BufferKind::File {
338                path: canonical_path,
339                uri: file_uri,
340            },
341            display_name,
342            lsp_enabled: true,
343            lsp_disabled_reason: None,
344            read_only: is_library,
345            binary: false,
346            lsp_opened_with: HashSet::new(),
347            hidden_from_tabs: false,
348            synthetic_placeholder: false,
349            is_preview: false,
350            recovery_id: None,
351        }
352    }
353
354    /// Create metadata for a buffer fetched from inside a container.
355    ///
356    /// Used by `Editor::open_lsp_uri_target` when a Goto-Definition
357    /// (or similar) URI lands on a path that exists only inside the
358    /// container — typically a stdlib / site-packages entry that
359    /// isn't bind-mounted onto the host. The buffer is read-only
360    /// because there's no host-side writeback path; LSP stays enabled
361    /// so further navigation from the fetched buffer (hover, more
362    /// goto-defs) keeps working.
363    ///
364    /// The supplied `uri` is the wire URI the LSP returned (already
365    /// in container-side coordinates) and is cached verbatim — no
366    /// host→remote translation, because the path *is* the remote
367    /// path. The display name is the file name, since the container
368    /// path has nothing to relativize against the host working dir.
369    pub fn with_container_file(container_path: PathBuf, uri: LspUri) -> Self {
370        let display_name = container_path
371            .file_name()
372            .and_then(|n| n.to_str())
373            .map(|n| n.to_string())
374            .unwrap_or_else(|| container_path.to_string_lossy().to_string());
375        Self {
376            kind: BufferKind::File {
377                path: container_path,
378                uri: Some(uri),
379            },
380            display_name,
381            lsp_enabled: true,
382            lsp_disabled_reason: None,
383            read_only: true,
384            binary: false,
385            lsp_opened_with: HashSet::new(),
386            hidden_from_tabs: false,
387            synthetic_placeholder: false,
388            is_preview: false,
389            recovery_id: None,
390        }
391    }
392
393    /// Check if a path is a library file (in vendor directories or standard libraries)
394    ///
395    /// Library files include:
396    /// - Files in common vendor/dependency directories (.cargo, node_modules, etc.)
397    /// - Standard library / toolchain files (rustup toolchains, system includes, etc.)
398    pub fn is_library_path(path: &Path, _working_dir: &Path) -> bool {
399        // Check for common library paths
400        let path_str = path.to_string_lossy();
401
402        // Rust: .cargo directory (can be within project for vendor'd crates)
403        if path_str.contains("/.cargo/") || path_str.contains("\\.cargo\\") {
404            return true;
405        }
406
407        // Rust: rustup toolchains (standard library source files)
408        if path_str.contains("/rustup/toolchains/") || path_str.contains("\\rustup\\toolchains\\") {
409            return true;
410        }
411
412        // Node.js: node_modules
413        if path_str.contains("/node_modules/") || path_str.contains("\\node_modules\\") {
414            return true;
415        }
416
417        // Python: site-packages, dist-packages
418        if path_str.contains("/site-packages/")
419            || path_str.contains("\\site-packages\\")
420            || path_str.contains("/dist-packages/")
421            || path_str.contains("\\dist-packages\\")
422        {
423            return true;
424        }
425
426        // Go: pkg/mod
427        if path_str.contains("/pkg/mod/") || path_str.contains("\\pkg\\mod\\") {
428            return true;
429        }
430
431        // Ruby: gems
432        if path_str.contains("/gems/") || path_str.contains("\\gems\\") {
433            return true;
434        }
435
436        // Java/Gradle: .gradle
437        if path_str.contains("/.gradle/") || path_str.contains("\\.gradle\\") {
438            return true;
439        }
440
441        // Maven: .m2
442        if path_str.contains("/.m2/") || path_str.contains("\\.m2\\") {
443            return true;
444        }
445
446        // C/C++: system include directories
447        if path_str.starts_with("/usr/include/") || path_str.starts_with("/usr/local/include/") {
448            return true;
449        }
450
451        // Nix store (system-managed packages)
452        if path_str.starts_with("/nix/store/") {
453            return true;
454        }
455
456        // Homebrew (macOS system-managed packages)
457        if path_str.starts_with("/opt/homebrew/Cellar/")
458            || path_str.starts_with("/usr/local/Cellar/")
459        {
460            return true;
461        }
462
463        // .NET / C#: NuGet packages
464        if path_str.contains("/.nuget/") || path_str.contains("\\.nuget\\") {
465            return true;
466        }
467
468        // Swift / Xcode toolchains
469        if path_str.contains("/Xcode.app/Contents/Developer/")
470            || path_str.contains("/CommandLineTools/SDKs/")
471        {
472            return true;
473        }
474
475        false
476    }
477
478    /// Compute display name relative to working_dir when possible, otherwise absolute
479    pub fn display_name_for_path(path: &Path, working_dir: &Path) -> String {
480        // Canonicalize working_dir to normalize platform-specific prefixes
481        let canonical_working_dir = working_dir
482            .canonicalize()
483            .unwrap_or_else(|_| working_dir.to_path_buf());
484
485        // Try to canonicalize the file path; if it fails (e.g., new file), fall back to absolute
486        let absolute_path = if path.is_absolute() {
487            path.to_path_buf()
488        } else {
489            // If we were given a relative path, anchor it to working_dir
490            canonical_working_dir.join(path)
491        };
492        let canonical_path = absolute_path
493            .canonicalize()
494            .unwrap_or_else(|_| absolute_path.clone());
495
496        // Prefer canonical comparison first, then raw prefix as a fallback
497        let relative = canonical_path
498            .strip_prefix(&canonical_working_dir)
499            .or_else(|_| path.strip_prefix(working_dir))
500            .ok()
501            .and_then(|rel| rel.to_str().map(|s| s.to_string()));
502
503        relative
504            .or_else(|| canonical_path.to_str().map(|s| s.to_string()))
505            .unwrap_or_else(|| t!("buffer.unknown").to_string())
506    }
507
508    /// Create metadata for a virtual buffer (not backed by a file)
509    ///
510    /// # Arguments
511    /// * `name` - Display name (e.g., "*Diagnostics*")
512    /// * `mode` - Buffer mode for keybindings (e.g., "diagnostics-list")
513    /// * `read_only` - Whether the buffer should be read-only
514    pub fn virtual_buffer(name: String, mode: String, read_only: bool) -> Self {
515        Self {
516            kind: BufferKind::Virtual { mode },
517            display_name: name,
518            lsp_enabled: false, // Virtual buffers don't use LSP
519            lsp_disabled_reason: Some(t!("lsp.disabled.virtual").to_string()),
520            read_only,
521            binary: false,
522            lsp_opened_with: HashSet::new(),
523            hidden_from_tabs: false,
524            synthetic_placeholder: false,
525            is_preview: false,
526            recovery_id: None,
527        }
528    }
529
530    /// Create metadata for a hidden virtual buffer (for composite source buffers)
531    /// These buffers are not shown in tabs and are managed by their parent composite buffer.
532    /// Hidden buffers are always read-only to prevent accidental edits.
533    pub fn hidden_virtual_buffer(name: String, mode: String) -> Self {
534        Self {
535            kind: BufferKind::Virtual { mode },
536            display_name: name,
537            lsp_enabled: false,
538            lsp_disabled_reason: Some(t!("lsp.disabled.virtual").to_string()),
539            read_only: true, // Hidden buffers are always read-only
540            binary: false,
541            lsp_opened_with: HashSet::new(),
542            hidden_from_tabs: true,
543            synthetic_placeholder: false,
544            is_preview: false,
545            recovery_id: None,
546        }
547    }
548
549    /// Disable LSP for this buffer with a reason
550    pub fn disable_lsp(&mut self, reason: String) {
551        self.lsp_enabled = false;
552        self.lsp_disabled_reason = Some(reason);
553    }
554}
555
556/// LSP progress information
557#[derive(Debug, Clone)]
558pub(crate) struct LspProgressInfo {
559    pub language: String,
560    pub title: String,
561    pub message: Option<String>,
562    pub percentage: Option<u32>,
563}
564
565// `LspMenuItem` lives in `fresh_core::api` (re-exported as
566// `crate::app::LspMenuItem` for editor-internal use). See its docstring
567// there for the full design — it's both the plugin-command payload
568// and the internal storage type.
569pub use fresh_core::api::LspMenuItem;
570
571/// LSP message entry (for window messages and logs)
572#[derive(Debug, Clone)]
573#[allow(dead_code)]
574pub(crate) struct LspMessageEntry {
575    pub language: String,
576    pub message_type: LspMessageType,
577    pub message: String,
578    pub timestamp: std::time::Instant,
579}
580
581/// Types of UI elements that can be hovered over
582#[derive(Debug, Clone, PartialEq)]
583pub enum HoverTarget {
584    /// Hovering over a split separator (container_id, direction)
585    SplitSeparator(ContainerId, SplitDirection),
586    /// Hovering over a scrollbar thumb (split_id)
587    ScrollbarThumb(LeafId),
588    /// Hovering over a scrollbar track (split_id, relative_row)
589    ScrollbarTrack(LeafId, u16),
590    /// Hovering over a menu bar item (menu_index)
591    MenuBarItem(usize),
592    /// Hovering over a menu dropdown item (menu_index, item_index)
593    MenuDropdownItem(usize, usize),
594    /// Hovering over a submenu item (depth, item_index) - depth 1+ for nested submenus
595    SubmenuItem(usize, usize),
596    /// Hovering over a popup list item (popup_index in stack, item_index)
597    PopupListItem(usize, usize),
598    /// Hovering over a suggestion item (item_index)
599    SuggestionItem(usize),
600    /// Hovering over the file explorer border (for resize)
601    FileExplorerBorder,
602    /// Hovering over a file browser navigation shortcut
603    FileBrowserNavShortcut(usize),
604    /// Hovering over a file browser file/directory entry
605    FileBrowserEntry(usize),
606    /// Hovering over a file browser column header
607    FileBrowserHeader(SortMode),
608    /// Hovering over the file browser scrollbar
609    FileBrowserScrollbar,
610    /// Hovering over the file browser "Show Hidden" checkbox
611    FileBrowserShowHiddenCheckbox,
612    /// Hovering over the file browser "Detect Encoding" checkbox
613    FileBrowserDetectEncodingCheckbox,
614    /// Hovering over a tab name (target, split_id) - for non-active tabs
615    TabName(crate::view::split::TabTarget, LeafId),
616    /// Hovering over a tab close button (target, split_id)
617    TabCloseButton(crate::view::split::TabTarget, LeafId),
618    /// Hovering over a close split button (split_id)
619    CloseSplitButton(LeafId),
620    /// Hovering over a maximize/unmaximize split button (split_id)
621    MaximizeSplitButton(LeafId),
622    /// Hovering over the file explorer close button
623    FileExplorerCloseButton,
624    /// Hovering over a file explorer item's status indicator (path)
625    FileExplorerStatusIndicator(std::path::PathBuf),
626    /// Hovering over the status bar LSP indicator
627    StatusBarLspIndicator,
628    /// Hovering over the status bar remote-authority indicator
629    StatusBarRemoteIndicator,
630    /// Hovering over the status bar warning badge
631    StatusBarWarningBadge,
632    /// Hovering over the status bar line ending indicator
633    StatusBarLineEndingIndicator,
634    /// Hovering over the status bar encoding indicator
635    StatusBarEncodingIndicator,
636    /// Hovering over the status bar language indicator
637    StatusBarLanguageIndicator,
638    /// Hovering over the search options "Case Sensitive" checkbox
639    SearchOptionCaseSensitive,
640    /// Hovering over the search options "Whole Word" checkbox
641    SearchOptionWholeWord,
642    /// Hovering over the search options "Regex" checkbox
643    SearchOptionRegex,
644    /// Hovering over the search options "Confirm Each" checkbox
645    SearchOptionConfirmEach,
646    /// Hovering over a tab context menu item (item_index)
647    TabContextMenuItem(usize),
648    /// Hovering over a file explorer context menu item (item_index)
649    FileExplorerContextMenuItem(usize),
650}
651
652/// Tab context menu items
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654pub enum TabContextMenuItem {
655    /// Close this tab
656    Close,
657    /// Close all other tabs
658    CloseOthers,
659    /// Close tabs to the right
660    CloseToRight,
661    /// Close tabs to the left
662    CloseToLeft,
663    /// Close all tabs
664    CloseAll,
665    /// Copy the tab's file path relative to the workspace root
666    CopyRelativePath,
667    /// Copy the tab's absolute file path
668    CopyFullPath,
669}
670
671impl TabContextMenuItem {
672    /// Get all menu items in order
673    pub fn all() -> &'static [Self] {
674        &[
675            Self::Close,
676            Self::CloseOthers,
677            Self::CloseToRight,
678            Self::CloseToLeft,
679            Self::CloseAll,
680            Self::CopyRelativePath,
681            Self::CopyFullPath,
682        ]
683    }
684
685    /// Get the display label for this menu item
686    pub fn label(&self) -> String {
687        match self {
688            Self::Close => t!("tab.close").to_string(),
689            Self::CloseOthers => t!("tab.close_others").to_string(),
690            Self::CloseToRight => t!("tab.close_to_right").to_string(),
691            Self::CloseToLeft => t!("tab.close_to_left").to_string(),
692            Self::CloseAll => t!("tab.close_all").to_string(),
693            Self::CopyRelativePath => t!("tab.copy_relative_path").to_string(),
694            Self::CopyFullPath => t!("tab.copy_full_path").to_string(),
695        }
696    }
697}
698
699/// State for tab context menu (right-click popup on tabs)
700#[derive(Debug, Clone)]
701pub struct TabContextMenu {
702    /// The buffer ID this context menu is for
703    pub buffer_id: BufferId,
704    /// The split ID where the tab is located
705    pub split_id: LeafId,
706    /// Screen position where the menu should appear (x, y)
707    pub position: (u16, u16),
708    /// Currently highlighted menu item index
709    pub highlighted: usize,
710}
711
712impl TabContextMenu {
713    /// Create a new tab context menu
714    pub fn new(buffer_id: BufferId, split_id: LeafId, x: u16, y: u16) -> Self {
715        Self {
716            buffer_id,
717            split_id,
718            position: (x, y),
719            highlighted: 0,
720        }
721    }
722
723    /// Get the currently highlighted item
724    pub fn highlighted_item(&self) -> TabContextMenuItem {
725        TabContextMenuItem::all()[self.highlighted]
726    }
727
728    /// Move highlight down
729    pub fn next_item(&mut self) {
730        let items = TabContextMenuItem::all();
731        self.highlighted = (self.highlighted + 1) % items.len();
732    }
733
734    /// Move highlight up
735    pub fn prev_item(&mut self) {
736        let items = TabContextMenuItem::all();
737        self.highlighted = if self.highlighted == 0 {
738            items.len() - 1
739        } else {
740            self.highlighted - 1
741        };
742    }
743}
744
745/// File explorer context menu items
746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
747pub enum FileExplorerContextMenuItem {
748    NewFile,
749    NewDirectory,
750    Rename,
751    Cut,
752    Copy,
753    Paste,
754    Duplicate,
755    Delete,
756    CopyFullPath,
757    CopyRelativePath,
758}
759
760impl FileExplorerContextMenuItem {
761    pub fn all() -> &'static [Self] {
762        // Order matters: existing e2e tests address items by their index in
763        // this list (e.g. Delete is index 6 in the single-selection menu).
764        // Append-only changes here keep the older tests stable; the new
765        // entries (Duplicate, CopyFullPath, CopyRelativePath) live after
766        // Delete for that reason.
767        &[
768            Self::NewFile,
769            Self::NewDirectory,
770            Self::Rename,
771            Self::Cut,
772            Self::Copy,
773            Self::Paste,
774            Self::Delete,
775            Self::Duplicate,
776            Self::CopyFullPath,
777            Self::CopyRelativePath,
778        ]
779    }
780
781    pub fn multi_selection() -> &'static [Self] {
782        &[
783            Self::Cut,
784            Self::Copy,
785            Self::Paste,
786            Self::Delete,
787            Self::Duplicate,
788            Self::CopyFullPath,
789            Self::CopyRelativePath,
790        ]
791    }
792
793    pub fn root_single_selection() -> &'static [Self] {
794        // The root menu is intentionally narrow (VS Code parity): only
795        // creation + paste actions. Copy-path on the project root is left
796        // off because the workspace path is already exposed via other
797        // commands and adding it here would surface a "Copy …" entry on
798        // a menu that's supposed to hide destructive/copy-style actions.
799        &[Self::NewFile, Self::NewDirectory, Self::Paste]
800    }
801
802    pub fn label(&self) -> String {
803        match self {
804            Self::NewFile => t!("explorer.context.new_file").to_string(),
805            Self::NewDirectory => t!("explorer.context.new_directory").to_string(),
806            Self::Rename => t!("explorer.context.rename").to_string(),
807            Self::Cut => t!("explorer.context.cut").to_string(),
808            Self::Copy => t!("explorer.context.copy").to_string(),
809            Self::Paste => t!("explorer.context.paste").to_string(),
810            Self::Duplicate => t!("explorer.context.duplicate").to_string(),
811            Self::Delete => t!("explorer.context.delete").to_string(),
812            Self::CopyFullPath => t!("explorer.context.copy_full_path").to_string(),
813            Self::CopyRelativePath => t!("explorer.context.copy_relative_path").to_string(),
814        }
815    }
816}
817
818/// State for file explorer context menu (right-click popup in the file explorer)
819#[derive(Debug, Clone)]
820pub struct FileExplorerContextMenu {
821    /// Screen position where the menu should appear (x, y)
822    pub position: (u16, u16),
823    /// Currently highlighted menu item index
824    pub highlighted: usize,
825    /// Whether the menu was opened with multiple items selected
826    pub is_multi_selection: bool,
827    /// Whether the sole selected node is the project root
828    pub is_root_selected: bool,
829}
830
831impl FileExplorerContextMenu {
832    pub fn new(x: u16, y: u16, is_multi_selection: bool, is_root_selected: bool) -> Self {
833        Self {
834            position: (x, y),
835            highlighted: 0,
836            is_multi_selection,
837            is_root_selected,
838        }
839    }
840
841    pub fn items(&self) -> &'static [FileExplorerContextMenuItem] {
842        if self.is_multi_selection {
843            FileExplorerContextMenuItem::multi_selection()
844        } else if self.is_root_selected {
845            FileExplorerContextMenuItem::root_single_selection()
846        } else {
847            FileExplorerContextMenuItem::all()
848        }
849    }
850
851    pub fn height(&self) -> u16 {
852        self.items().len() as u16 + 2
853    }
854
855    pub fn clamped_position(&self, screen_width: u16, screen_height: u16) -> (u16, u16) {
856        let x = if self.position.0 + FILE_EXPLORER_CONTEXT_MENU_WIDTH > screen_width {
857            screen_width.saturating_sub(FILE_EXPLORER_CONTEXT_MENU_WIDTH)
858        } else {
859            self.position.0
860        };
861        let h = self.height();
862        let y = if self.position.1 + h > screen_height {
863            screen_height.saturating_sub(h)
864        } else {
865            self.position.1
866        };
867        (x, y)
868    }
869
870    pub fn next_item(&mut self) {
871        let len = self.items().len();
872        self.highlighted = (self.highlighted + 1) % len;
873    }
874
875    pub fn prev_item(&mut self) {
876        let len = self.items().len();
877        self.highlighted = if self.highlighted == 0 {
878            len - 1
879        } else {
880            self.highlighted - 1
881        };
882    }
883}
884
885/// Lightweight per-cell theme key provenance recorded during rendering.
886/// Stored in `ChromeLayout::cell_theme_map` so the theme inspector popup
887/// can look up the exact keys used for any screen position.
888#[derive(Debug, Clone, Default)]
889pub struct CellThemeInfo {
890    /// Foreground theme key (e.g. "syntax.keyword", "editor.fg")
891    pub fg_key: Option<&'static str>,
892    /// Background theme key (e.g. "editor.bg", "diagnostic.warning_bg")
893    pub bg_key: Option<&'static str>,
894    /// Short region label (e.g. "Line Numbers", "Editor Content")
895    pub region: &'static str,
896    /// Dynamic region suffix (e.g. syntax category display name appended to "Syntax: ")
897    pub syntax_category: Option<&'static str>,
898}
899
900/// Information about which theme key(s) style a specific screen position.
901/// Used by the Ctrl+Right-Click theme inspector popup.
902#[derive(Debug, Clone)]
903pub struct ThemeKeyInfo {
904    /// The foreground theme key path (e.g., "syntax.keyword", "editor.fg")
905    pub fg_key: Option<String>,
906    /// The background theme key path (e.g., "editor.bg", "editor.selection_bg")
907    pub bg_key: Option<String>,
908    /// Human-readable description of the UI region
909    pub region: String,
910    /// The actual foreground color value currently applied
911    pub fg_color: Option<ratatui::style::Color>,
912    /// The actual background color value currently applied
913    pub bg_color: Option<ratatui::style::Color>,
914    /// For syntax highlights: the HighlightCategory display name
915    pub syntax_category: Option<String>,
916}
917
918/// State for the theme inspector popup (Ctrl+Right-Click)
919#[derive(Debug, Clone)]
920pub struct ThemeInfoPopup {
921    /// Screen position where popup appears (x, y)
922    pub position: (u16, u16),
923    /// Resolved theme key information
924    pub info: ThemeKeyInfo,
925    /// Whether the "Open in Theme Editor" button is highlighted (mouse hover)
926    pub button_highlighted: bool,
927}
928
929/// Drop zone for tab drag-and-drop
930/// Indicates where a dragged tab will be placed when released
931#[derive(Debug, Clone, Copy, PartialEq, Eq)]
932pub enum TabDropZone {
933    /// Drop into an existing split's tab bar (before tab at index, or at end if None)
934    /// (target_split_id, insert_index)
935    TabBar(LeafId, Option<usize>),
936    /// Create a new split on the left edge of the target split
937    SplitLeft(LeafId),
938    /// Create a new split on the right edge of the target split
939    SplitRight(LeafId),
940    /// Create a new split on the top edge of the target split
941    SplitTop(LeafId),
942    /// Create a new split on the bottom edge of the target split
943    SplitBottom(LeafId),
944    /// Drop into the center of a split (switch to that split's tab bar)
945    SplitCenter(LeafId),
946}
947
948impl TabDropZone {
949    /// Get the split ID this drop zone is associated with
950    pub fn split_id(&self) -> LeafId {
951        match self {
952            Self::TabBar(id, _)
953            | Self::SplitLeft(id)
954            | Self::SplitRight(id)
955            | Self::SplitTop(id)
956            | Self::SplitBottom(id)
957            | Self::SplitCenter(id) => *id,
958        }
959    }
960}
961
962/// State for a tab being dragged
963#[derive(Debug, Clone)]
964pub struct TabDragState {
965    /// The buffer being dragged
966    pub buffer_id: BufferId,
967    /// The split the tab was dragged from
968    pub source_split_id: LeafId,
969    /// Starting mouse position when drag began
970    pub start_position: (u16, u16),
971    /// Current mouse position
972    pub current_position: (u16, u16),
973    /// Currently detected drop zone (if any)
974    pub drop_zone: Option<TabDropZone>,
975}
976
977impl TabDragState {
978    /// Create a new tab drag state
979    pub fn new(buffer_id: BufferId, source_split_id: LeafId, start_position: (u16, u16)) -> Self {
980        Self {
981            buffer_id,
982            source_split_id,
983            start_position,
984            current_position: start_position,
985            drop_zone: None,
986        }
987    }
988
989    /// Check if the drag has moved enough to be considered a real drag (not just a click)
990    pub fn is_dragging(&self) -> bool {
991        let dx = (self.current_position.0 as i32 - self.start_position.0 as i32).abs();
992        let dy = (self.current_position.1 as i32 - self.start_position.1 as i32).abs();
993        dx > 3 || dy > 3 // Threshold of 3 pixels before drag activates
994    }
995}
996
997/// Mouse state tracking
998#[derive(Debug, Clone, Default)]
999pub(crate) struct MouseState {
1000    /// Whether we're currently dragging a vertical scrollbar
1001    pub dragging_scrollbar: Option<LeafId>,
1002    /// Whether we're currently dragging a horizontal scrollbar
1003    pub dragging_horizontal_scrollbar: Option<LeafId>,
1004    /// Initial mouse column when starting horizontal scrollbar drag
1005    pub drag_start_hcol: Option<u16>,
1006    /// Initial left_column when starting horizontal scrollbar drag
1007    pub drag_start_left_column: Option<usize>,
1008    /// Last mouse position
1009    pub last_position: Option<(u16, u16)>,
1010    /// Mouse hover for LSP: byte position being hovered, timer start, and screen position
1011    /// Format: (byte_position, hover_start_instant, screen_x, screen_y)
1012    pub lsp_hover_state: Option<(usize, std::time::Instant, u16, u16)>,
1013    /// Whether we've already sent a hover request for the current position
1014    pub lsp_hover_request_sent: bool,
1015    /// Initial mouse row when starting to drag the scrollbar thumb
1016    /// Used to calculate relative movement rather than jumping
1017    pub drag_start_row: Option<u16>,
1018    /// Initial viewport top_byte when starting to drag the scrollbar thumb
1019    pub drag_start_top_byte: Option<usize>,
1020    /// Initial viewport top_view_line_offset when starting to drag the scrollbar thumb
1021    /// This is needed for proper visual row calculation when scrolled into a wrapped line
1022    pub drag_start_view_line_offset: Option<usize>,
1023    /// Whether we're currently dragging a split separator
1024    /// Stores (split_id, direction) for the separator being dragged
1025    pub dragging_separator: Option<(ContainerId, SplitDirection)>,
1026    /// Initial mouse position when starting to drag a separator
1027    pub drag_start_position: Option<(u16, u16)>,
1028    /// Initial split ratio when starting to drag a separator
1029    pub drag_start_ratio: Option<f32>,
1030    /// Whether we're currently dragging the file explorer border
1031    pub dragging_file_explorer: bool,
1032    /// File explorer width at the moment the drag started. Drag
1033    /// preserves the active variant: a drag that begins in `Percent`
1034    /// stays in `Percent`, and likewise for `Columns`.
1035    pub drag_start_explorer_width: Option<crate::config::ExplorerWidth>,
1036    /// Current hover target (if any)
1037    pub hover_target: Option<HoverTarget>,
1038    /// Whether we're currently doing a text selection drag
1039    pub dragging_text_selection: bool,
1040    /// The split where text selection started
1041    pub drag_selection_split: Option<LeafId>,
1042    /// The buffer byte position where the selection anchor is
1043    pub drag_selection_anchor: Option<usize>,
1044    /// When true, dragging extends selection by whole words (set by double-click)
1045    pub drag_selection_by_words: bool,
1046    /// The end of the initially double-clicked word (used as anchor when dragging backward)
1047    pub drag_selection_word_end: Option<usize>,
1048    /// Tab drag state (for drag-to-split functionality)
1049    pub dragging_tab: Option<TabDragState>,
1050    /// Whether we're currently dragging a popup scrollbar (popup index)
1051    pub dragging_popup_scrollbar: Option<usize>,
1052    /// Initial scroll offset when starting to drag popup scrollbar
1053    pub drag_start_popup_scroll: Option<usize>,
1054    /// Whether we're currently dragging the prompt's suggestion-list
1055    /// scrollbar (Live Grep floating overlay, issue #1796). The
1056    /// rect is held in `ChromeLayout::suggestions_scrollbar_rect`
1057    /// and the math is shared with the buffer-popup scrollbar via
1058    /// `view::ui::scrollbar::ScrollbarState::click_to_offset`.
1059    pub dragging_prompt_scrollbar: bool,
1060    /// Whether we're currently selecting text in a popup (popup index)
1061    pub selecting_in_popup: Option<usize>,
1062    /// Initial composite scroll_row when starting to drag the scrollbar thumb
1063    /// Used for composite buffer scrollbar drag
1064    pub drag_start_composite_scroll_row: Option<usize>,
1065}
1066
1067/// Mapping from visual row to buffer positions for mouse click handling
1068/// Each entry represents one visual row with byte position info for click handling
1069#[derive(Debug, Clone, Default)]
1070pub struct ViewLineMapping {
1071    /// Source byte offset for each character (None for injected/virtual content)
1072    pub char_source_bytes: Vec<Option<usize>>,
1073    /// Character index at each visual column (for O(1) mouse clicks)
1074    pub visual_to_char: Vec<usize>,
1075    /// Last valid byte position in this visual row (newline for real lines, last char for wrapped)
1076    /// Clicks past end of visible text position cursor here
1077    pub line_end_byte: usize,
1078    /// True iff this visual row was rendered for a plugin-injected
1079    /// virtual line (live-diff deletion overlays, markdown_compose
1080    /// borders, …) rather than for actual buffer content. Used by
1081    /// `move_visual_line` to skip past these rows without stranding
1082    /// the cursor on a position whose `line_end_byte` was inherited
1083    /// from the previous source row.
1084    pub is_plugin_virtual: bool,
1085}
1086
1087impl ViewLineMapping {
1088    /// Get source byte at a given visual column (O(1) for mouse clicks)
1089    #[inline]
1090    pub fn source_byte_at_visual_col(&self, visual_col: usize) -> Option<usize> {
1091        let char_idx = self.visual_to_char.get(visual_col).copied()?;
1092        self.char_source_bytes.get(char_idx).copied().flatten()
1093    }
1094
1095    /// Find the nearest source byte to a given visual column, searching outward.
1096    /// Returns the source byte at the closest valid visual column.
1097    pub fn nearest_source_byte(&self, goal_col: usize) -> Option<usize> {
1098        let width = self.visual_to_char.len();
1099        if width == 0 {
1100            return None;
1101        }
1102        // Search outward from goal_col: try +1, -1, +2, -2, ...
1103        for delta in 1..width {
1104            if goal_col + delta < width {
1105                if let Some(byte) = self.source_byte_at_visual_col(goal_col + delta) {
1106                    return Some(byte);
1107                }
1108            }
1109            if delta <= goal_col {
1110                if let Some(byte) = self.source_byte_at_visual_col(goal_col - delta) {
1111                    return Some(byte);
1112                }
1113            }
1114        }
1115        None
1116    }
1117
1118    /// Check if this visual row contains the given byte position
1119    #[inline]
1120    pub fn contains_byte(&self, byte_pos: usize) -> bool {
1121        // A row contains a byte if it's in the char_source_bytes range
1122        // The first valid source byte marks the start, line_end_byte marks the end
1123        if let Some(first_byte) = self.char_source_bytes.iter().find_map(|b| *b) {
1124            byte_pos >= first_byte && byte_pos <= self.line_end_byte
1125        } else {
1126            // Empty/virtual row - only matches if byte_pos equals line_end_byte
1127            byte_pos == self.line_end_byte
1128        }
1129    }
1130
1131    /// Get the first source byte position in this row (if any)
1132    #[inline]
1133    pub fn first_source_byte(&self) -> Option<usize> {
1134        self.char_source_bytes.iter().find_map(|b| *b)
1135    }
1136}
1137
1138/// Type alias for popup area layout information used in mouse hit testing.
1139/// Fields: (popup_index, rect, inner_rect, scroll_offset, num_items, scrollbar_rect, total_lines)
1140pub(crate) type PopupAreaLayout = (usize, Rect, Rect, usize, usize, Option<Rect>, usize);
1141
1142/// Editor-chrome layout cache: full-frame and chrome-region rects
1143/// (status bar, menu bar, prompt overlay, popups) plus the screen-
1144/// indexed cell-theme map. Per-window layout (split-leaf rects, tab
1145/// rects, file-explorer rects, view-line mappings) lives on
1146/// [`WindowLayoutCache`] instead.
1147#[derive(Debug, Clone, Default)]
1148pub(crate) struct ChromeLayout {
1149    /// Popup areas for mouse hit testing
1150    /// scrollbar_rect is Some if popup has a scrollbar
1151    pub popup_areas: Vec<PopupAreaLayout>,
1152    /// Editor-level popup areas (e.g. plugin action popups) for mouse hit
1153    /// testing. Stored separately from buffer popups because they're owned by
1154    /// `Editor.global_popups` rather than the active buffer's state.
1155    /// Fields: (popup_index, rect, inner_rect, scroll_offset, num_items)
1156    pub global_popup_areas: Vec<(usize, Rect, Rect, usize, usize)>,
1157    /// Suggestions area for mouse hit testing
1158    /// (inner_rect, scroll_start_idx, visible_count, total_count)
1159    pub suggestions_area: Option<(Rect, usize, usize, usize)>,
1160    /// Full outer rect of the suggestions popup (including borders).
1161    /// Used to absorb clicks on the popup chrome so they don't reach the
1162    /// buffer below while the prompt is open.
1163    pub suggestions_outer_area: Option<Rect>,
1164    /// Hit-test rect for the floating-overlay prompt's scrollbar
1165    /// (issue #1796). `None` when no overlay is open or the result
1166    /// list fits in the visible window. Click/drag handlers in
1167    /// `mouse_input.rs` read this to update `prompt.scroll_offset`.
1168    pub suggestions_scrollbar_rect: Option<Rect>,
1169    /// Settings modal layout for hit testing
1170    pub settings_layout: Option<crate::view::settings::SettingsLayout>,
1171    /// Status bar area (row, x, width)
1172    pub status_bar_area: Option<(u16, u16, u16)>,
1173    /// Status bar LSP indicator area (row, start_col, end_col)
1174    pub status_bar_lsp_area: Option<(u16, u16, u16)>,
1175    /// Status bar warning badge area (row, start_col, end_col)
1176    pub status_bar_warning_area: Option<(u16, u16, u16)>,
1177    /// Status bar line ending indicator area (row, start_col, end_col)
1178    pub status_bar_line_ending_area: Option<(u16, u16, u16)>,
1179    /// Status bar encoding indicator area (row, start_col, end_col)
1180    pub status_bar_encoding_area: Option<(u16, u16, u16)>,
1181    /// Status bar language indicator area (row, start_col, end_col)
1182    pub status_bar_language_area: Option<(u16, u16, u16)>,
1183    /// Status bar message area (row, start_col, end_col) - clickable to show status log
1184    pub status_bar_message_area: Option<(u16, u16, u16)>,
1185    /// Status bar remote-authority indicator area (row, start_col, end_col)
1186    /// — clickable to open the remote-authority context menu.
1187    pub status_bar_remote_area: Option<(u16, u16, u16)>,
1188    /// Search options layout for checkbox hit testing
1189    pub search_options_layout: Option<crate::view::ui::status_bar::SearchOptionsLayout>,
1190    /// Menu bar layout for hit testing
1191    pub menu_layout: Option<crate::view::ui::menu::MenuLayout>,
1192    /// Last frame dimensions — used by recompute_layout for macro replay
1193    pub last_frame_width: u16,
1194    pub last_frame_height: u16,
1195    /// Per-cell theme key provenance recorded during rendering.
1196    /// Flat vec indexed as `row * width + col` where `width = last_frame_width`.
1197    pub cell_theme_map: Vec<CellThemeInfo>,
1198}
1199
1200impl ChromeLayout {
1201    /// Reset the cell theme map for a new frame
1202    pub fn reset_cell_theme_map(&mut self) {
1203        let total = self.last_frame_width as usize * self.last_frame_height as usize;
1204        self.cell_theme_map.clear();
1205        self.cell_theme_map.resize(total, CellThemeInfo::default());
1206    }
1207
1208    /// Look up the theme info for a screen position
1209    pub fn cell_theme_at(&self, col: u16, row: u16) -> Option<&CellThemeInfo> {
1210        let idx = row as usize * self.last_frame_width as usize + col as usize;
1211        self.cell_theme_map.get(idx)
1212    }
1213}
1214
1215/// Per-window layout cache: hit-test rects for content scoped to a
1216/// single window (split panes, tabs, the file explorer, separators,
1217/// scrollbars) plus the per-leaf visual-row→source-byte mappings used
1218/// by mouse positioning and visual-line motion. Lives on `Window`;
1219/// editor-chrome rects live on [`ChromeLayout`].
1220#[derive(Debug, Clone, Default)]
1221pub(crate) struct WindowLayoutCache {
1222    /// File explorer area (if visible)
1223    pub file_explorer_area: Option<Rect>,
1224    /// Editor content area (excluding file explorer)
1225    pub editor_content_area: Option<Rect>,
1226    /// Individual split areas with their scrollbar areas and thumb positions
1227    /// (split_id, buffer_id, content_rect, scrollbar_rect, thumb_start, thumb_end)
1228    pub split_areas: Vec<(LeafId, BufferId, Rect, Rect, usize, usize)>,
1229    /// Horizontal scrollbar areas per split
1230    /// (split_id, buffer_id, horizontal_scrollbar_rect, max_content_width, thumb_start_col, thumb_end_col)
1231    pub horizontal_scrollbar_areas: Vec<(LeafId, BufferId, Rect, usize, usize, usize)>,
1232    /// Split separator positions for drag resize
1233    /// (container_id, direction, x, y, length)
1234    pub separator_areas: Vec<(ContainerId, SplitDirection, u16, u16, u16)>,
1235    /// Tab layouts per split for mouse interaction
1236    pub tab_layouts: HashMap<LeafId, crate::view::ui::tabs::TabLayout>,
1237    /// Close split button hit areas
1238    /// (split_id, row, start_col, end_col)
1239    pub close_split_areas: Vec<(LeafId, u16, u16, u16)>,
1240    /// Maximize split button hit areas
1241    /// (split_id, row, start_col, end_col)
1242    pub maximize_split_areas: Vec<(LeafId, u16, u16, u16)>,
1243    /// View line mappings for accurate mouse click positioning per split
1244    /// Maps visual row index to character position mappings
1245    /// Used to translate screen coordinates to buffer byte positions
1246    pub view_line_mappings: HashMap<LeafId, Vec<ViewLineMapping>>,
1247}
1248
1249impl WindowLayoutCache {
1250    /// Find which visual row contains the given byte position for a split
1251    pub fn find_visual_row(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
1252        let mappings = self.view_line_mappings.get(&split_id)?;
1253        mappings.iter().position(|m| m.contains_byte(byte_pos))
1254    }
1255
1256    /// Get the visual column of a byte position within its visual row
1257    pub fn byte_to_visual_column(&self, split_id: LeafId, byte_pos: usize) -> Option<usize> {
1258        let mappings = self.view_line_mappings.get(&split_id)?;
1259        let row_idx = self.find_visual_row(split_id, byte_pos)?;
1260        let row = mappings.get(row_idx)?;
1261
1262        // Find the visual column that maps to this byte position
1263        for (visual_col, &char_idx) in row.visual_to_char.iter().enumerate() {
1264            if let Some(source_byte) = row.char_source_bytes.get(char_idx).and_then(|b| *b) {
1265                if source_byte == byte_pos {
1266                    return Some(visual_col);
1267                }
1268                // If we've passed the byte position, return previous column
1269                if source_byte > byte_pos {
1270                    return Some(visual_col.saturating_sub(1));
1271                }
1272            }
1273        }
1274        // Byte is at or past end of row - return column after last character
1275        // This handles cursor positions at end of line (e.g., after last char before newline)
1276        Some(row.visual_to_char.len())
1277    }
1278
1279    /// Move by visual line using the cached mappings
1280    /// Returns (new_position, new_visual_column) or None if at boundary
1281    pub fn move_visual_line(
1282        &self,
1283        split_id: LeafId,
1284        current_pos: usize,
1285        goal_visual_col: usize,
1286        direction: i8, // -1 = up, 1 = down
1287    ) -> Option<(usize, usize)> {
1288        let mappings = self.view_line_mappings.get(&split_id)?;
1289        let current_row = self.find_visual_row(split_id, current_pos)?;
1290
1291        // Walk past purely-virtual rows (e.g. markdown_compose table top/
1292        // bottom borders and inter-row separators, live-diff deletion
1293        // virtual lines).  Those rows are plugin-injected and their
1294        // `line_end_byte` is inherited from the adjacent content row.
1295        // If MoveDown/MoveUp stopped on them the cursor would land on a
1296        // byte that's already at the row above's end, which in turn
1297        // causes Down-after-table to teleport back to an earlier
1298        // position (regression exposed by markdown_compose's table
1299        // border feature) or strands the cursor at the previous line's
1300        // EOL when a live-diff deletion hunk starts with a blank line
1301        // (regression exposed by the live-diff plugin).
1302        //
1303        // A row is "navigable" iff at least one of its visual columns
1304        // maps to a real source byte.  Skip entirely-virtual rows in
1305        // the move direction until we hit a navigable one or run off
1306        // the edge.
1307        let mut target_row = current_row;
1308        let navigable = |idx: usize| -> bool {
1309            mappings
1310                .get(idx)
1311                .map(|m| m.char_source_bytes.iter().any(|b| b.is_some()))
1312                .unwrap_or(false)
1313        };
1314        loop {
1315            target_row = if direction < 0 {
1316                target_row.checked_sub(1)?
1317            } else {
1318                let next = target_row + 1;
1319                if next >= mappings.len() {
1320                    return None;
1321                }
1322                next
1323            };
1324            // Either the next row has real source content, or we've reached
1325            // a legitimate non-source row that the rest of the editor
1326            // already treats as a cursor stop (trailing empty line at EOF,
1327            // implicit blank final line, empty source line between
1328            // paragraphs).  In either case stop walking.
1329            if navigable(target_row) {
1330                break;
1331            }
1332            let mapping = mappings.get(target_row)?;
1333            if mapping.is_plugin_virtual {
1334                // Plugin-injected virtual row (live-diff deletion lines,
1335                // markdown_compose table borders, …).  Its
1336                // `line_end_byte` is inherited from the previous row, so
1337                // stopping here would strand the cursor at the previous
1338                // source line's EOL.  Keep walking.
1339                continue;
1340            }
1341            // Empty mapping that isn't plugin-virtual: a real empty
1342            // source line (paragraph separator), the trailing empty
1343            // EOF row, or the implicit blank final line.  These are
1344            // legitimate cursor stops.
1345            break;
1346        }
1347
1348        let target_mapping = mappings.get(target_row)?;
1349
1350        // Try to get byte at goal visual column.  If the goal column is past
1351        // the end of visible content, land at line_end_byte (the newline or
1352        // end of buffer).  If the column exists but has no source byte (e.g.
1353        // padding on a wrapped continuation line), search outward for the
1354        // nearest valid source byte at minimal visual distance.
1355        let new_pos = if goal_visual_col >= target_mapping.visual_to_char.len() {
1356            target_mapping.line_end_byte
1357        } else {
1358            target_mapping
1359                .source_byte_at_visual_col(goal_visual_col)
1360                .or_else(|| target_mapping.nearest_source_byte(goal_visual_col))
1361                .unwrap_or(target_mapping.line_end_byte)
1362        };
1363
1364        Some((new_pos, goal_visual_col))
1365    }
1366
1367    /// Get the start byte position of the visual row containing the given byte position.
1368    /// If the cursor is already at the visual row start and this is a wrapped continuation,
1369    /// moves to the previous visual row's start (within the same logical line).
1370    /// Get the start byte position of the visual row containing the given byte position.
1371    /// When `allow_advance` is true and the cursor is already at the row start,
1372    /// moves to the previous visual row's start.
1373    pub fn visual_line_start(
1374        &self,
1375        split_id: LeafId,
1376        byte_pos: usize,
1377        allow_advance: bool,
1378    ) -> Option<usize> {
1379        let mappings = self.view_line_mappings.get(&split_id)?;
1380        let row_idx = self.find_visual_row(split_id, byte_pos)?;
1381        let row = mappings.get(row_idx)?;
1382        let row_start = row.first_source_byte()?;
1383
1384        if allow_advance && byte_pos == row_start && row_idx > 0 {
1385            let prev_row = mappings.get(row_idx - 1)?;
1386            prev_row.first_source_byte()
1387        } else {
1388            Some(row_start)
1389        }
1390    }
1391
1392    /// Get the end byte position of the visual row containing the given byte position.
1393    /// If the cursor is already at the visual row end and the next row is a wrapped continuation,
1394    /// moves to the next visual row's end (within the same logical line).
1395    /// Get the end byte position of the visual row containing the given byte position.
1396    /// When `allow_advance` is true and the cursor is already at the row end,
1397    /// advances to the next visual row's end.
1398    pub fn visual_line_end(
1399        &self,
1400        split_id: LeafId,
1401        byte_pos: usize,
1402        allow_advance: bool,
1403    ) -> Option<usize> {
1404        let mappings = self.view_line_mappings.get(&split_id)?;
1405        let row_idx = self.find_visual_row(split_id, byte_pos)?;
1406        let row = mappings.get(row_idx)?;
1407
1408        if allow_advance && byte_pos == row.line_end_byte && row_idx + 1 < mappings.len() {
1409            let next_row = mappings.get(row_idx + 1)?;
1410            Some(next_row.line_end_byte)
1411        } else {
1412            Some(row.line_end_byte)
1413        }
1414    }
1415}
1416
1417/// Convert a file path to an `lsp_types::Uri`.
1418pub fn file_path_to_lsp_uri(path: &Path) -> Option<lsp_types::Uri> {
1419    fresh_core::file_uri::path_to_lsp_uri(path)
1420}
1421
1422/// LSP-facing URI: a URI as it appears on the wire to or from a
1423/// language server. This is a newtype around `lsp_types::Uri`. The
1424/// type-system point is to force every URI that crosses the
1425/// editor↔LSP boundary through one of the two checked constructors:
1426///
1427///   * [`LspUri::from_host_path`] — given a host path and the active
1428///     authority's host↔remote translation, produces an `LspUri` that
1429///     carries the in-container path on container authorities (and
1430///     the host path everywhere else).
1431///   * [`LspUri::from_wire`] — wraps a raw `lsp_types::Uri` that was
1432///     received from the LSP server. The wrapped URI is "remote-side"
1433///     under a container authority and must be passed back through
1434///     [`LspUri::to_host_path`] before any filesystem-facing code
1435///     sees it.
1436///
1437/// Conversely, the only ways to extract a path are:
1438///
1439///   * [`LspUri::to_host_path`] — applies remote→host translation
1440///     symmetrically with `from_host_path`. This is the host-side
1441///     `PathBuf` filesystem APIs accept. Untranslated extraction
1442///     (`as_uri().path()`) is intentionally not exposed as a method —
1443///     callers that genuinely want the wire-side path string read
1444///     `as_str()` and document why a host-path interpretation isn't
1445///     wanted.
1446///
1447/// Storing buffer URIs in [`BufferMetadata`] as `LspUri` (not
1448/// `lsp_types::Uri`) keeps the cached form already translated for the
1449/// active authority, so the dozens of `metadata.file_uri()` call
1450/// sites can't accidentally ship a host URI to a container LSP.
1451#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1452pub struct LspUri(lsp_types::Uri);
1453
1454impl LspUri {
1455    /// Build an LSP-facing URI from a host path, applying the
1456    /// authority's host→remote translation when one is set. Returns
1457    /// `None` for relative paths (matches the pre-newtype helper).
1458    pub fn from_host_path(
1459        path: &Path,
1460        translation: Option<&crate::services::authority::PathTranslation>,
1461    ) -> Option<Self> {
1462        let mapped = translation
1463            .and_then(|t| t.host_to_remote(path))
1464            .unwrap_or_else(|| path.to_path_buf());
1465        fresh_core::file_uri::path_to_lsp_uri(&mapped).map(Self)
1466    }
1467
1468    /// Wrap a raw URI received from the LSP wire. The caller must
1469    /// subsequently translate via [`Self::to_host_path`] before
1470    /// opening the file or comparing with host paths — that's the
1471    /// whole point of having the newtype.
1472    pub fn from_wire(uri: lsp_types::Uri) -> Self {
1473        Self(uri)
1474    }
1475
1476    /// Borrow the underlying raw URI for serialization to the LSP
1477    /// wire (e.g. into JSON-RPC params). Only the LSP transport layer
1478    /// should call this; editor-level code never sees a bare
1479    /// `lsp_types::Uri`.
1480    pub fn as_uri(&self) -> &lsp_types::Uri {
1481        &self.0
1482    }
1483
1484    /// String form, for log messages and equality comparisons against
1485    /// other URI strings (e.g. when matching a buffer against an
1486    /// incoming notification's URI). Does not strip the
1487    /// host-vs-container ambiguity — comparisons must be between two
1488    /// `LspUri`s, not between a wire URI and a host URI.
1489    pub fn as_str(&self) -> &str {
1490        self.0.as_str()
1491    }
1492
1493    /// Decode this URI to a host path, applying the authority's
1494    /// remote→host translation when one is set. Returns `None` for
1495    /// non-`file://` URIs.
1496    pub fn to_host_path(
1497        &self,
1498        translation: Option<&crate::services::authority::PathTranslation>,
1499    ) -> Option<PathBuf> {
1500        let raw = fresh_core::file_uri::lsp_uri_to_path(&self.0)?;
1501        Some(
1502            translation
1503                .and_then(|t| t.remote_to_host(&raw))
1504                .unwrap_or(raw),
1505        )
1506    }
1507}
1508
1509/// Build the LSP-facing URI for a host-side `path`, applying the
1510/// authority's host→remote translation when one is set.
1511///
1512/// Thin shim around [`LspUri::from_host_path`] that returns the
1513/// inner [`lsp_types::Uri`] for the few callers (root_uri building
1514/// inside `LspManager`, code-action workspace folder hand-off) that
1515/// have to feed a raw `Uri` into a third-party API. New code should
1516/// prefer `LspUri::from_host_path` directly so the host-vs-LSP side
1517/// stays type-checked.
1518pub fn file_path_to_lsp_uri_with_translation(
1519    path: &Path,
1520    translation: Option<&crate::services::authority::PathTranslation>,
1521) -> Option<lsp_types::Uri> {
1522    LspUri::from_host_path(path, translation).map(|u| u.into_inner())
1523}
1524
1525impl LspUri {
1526    /// Consume `self` and return the raw `lsp_types::Uri`. Reserved
1527    /// for the wire layer (LSP transport, lsp_types interop). Editor
1528    /// code uses [`Self::as_uri`] when it just needs to borrow.
1529    pub fn into_inner(self) -> lsp_types::Uri {
1530        self.0
1531    }
1532}
1533
1534// `LspUri` translation algebra works on any platform but the unit-test
1535// fixtures use POSIX-shaped paths (the only side that ever exists for a
1536// container's interior) and a Linux-style URI without a drive letter.
1537// On Windows `lsp_types::Uri::parse(\"file:///workspaces/...\")` returns
1538// `None` for lack of a drive letter, which would make these tests fail
1539// for reasons unrelated to the algebra they're verifying. Gate to Unix
1540// — the cross-platform URI encoding is covered separately by
1541// `uri_encoding_tests`.
1542#[cfg(all(test, unix))]
1543mod lsp_uri_tests {
1544    use super::*;
1545    use crate::services::authority::PathTranslation;
1546
1547    fn translation() -> PathTranslation {
1548        PathTranslation {
1549            host_root: PathBuf::from("/tmp/.tmpA1B2"),
1550            remote_root: PathBuf::from("/workspaces/proj"),
1551        }
1552    }
1553
1554    #[test]
1555    fn from_host_path_under_workspace_translates_to_remote_uri() {
1556        let host = PathBuf::from("/tmp/.tmpA1B2/src/util.py");
1557        let lsp_uri = LspUri::from_host_path(&host, Some(&translation())).expect("absolute path");
1558        assert_eq!(lsp_uri.as_str(), "file:///workspaces/proj/src/util.py");
1559    }
1560
1561    #[test]
1562    fn from_host_path_outside_workspace_passes_through() {
1563        // System headers / library sources sit outside the mounted
1564        // workspace; translation returns `None` and the host URI is
1565        // shipped to the LSP unchanged. The point of the newtype is
1566        // just to make the decision explicit.
1567        let host = PathBuf::from("/usr/include/stdio.h");
1568        let lsp_uri = LspUri::from_host_path(&host, Some(&translation())).expect("absolute path");
1569        assert_eq!(lsp_uri.as_str(), "file:///usr/include/stdio.h");
1570    }
1571
1572    #[test]
1573    fn to_host_path_under_remote_root_translates_back() {
1574        let wire: lsp_types::Uri = "file:///workspaces/proj/src/util.py".parse().unwrap();
1575        let host = LspUri::from_wire(wire)
1576            .to_host_path(Some(&translation()))
1577            .expect("file:// URI");
1578        assert_eq!(host, PathBuf::from("/tmp/.tmpA1B2/src/util.py"));
1579    }
1580
1581    #[test]
1582    fn to_host_path_outside_remote_root_passes_through() {
1583        let wire: lsp_types::Uri = "file:///usr/include/stdio.h".parse().unwrap();
1584        let host = LspUri::from_wire(wire)
1585            .to_host_path(Some(&translation()))
1586            .expect("file:// URI");
1587        assert_eq!(host, PathBuf::from("/usr/include/stdio.h"));
1588    }
1589
1590    #[test]
1591    fn round_trip_host_to_wire_to_host_under_workspace() {
1592        // The whole point of the symmetry: anything that goes out
1593        // through `from_host_path` must come back through
1594        // `to_host_path` byte-identical. This is the property the
1595        // editor relies on so a buffer's host file_path matches the
1596        // path resolved from a server-returned `Location`.
1597        let host = PathBuf::from("/tmp/.tmpA1B2/main.py");
1598        let lsp_uri = LspUri::from_host_path(&host, Some(&translation())).unwrap();
1599        let back = lsp_uri.to_host_path(Some(&translation())).unwrap();
1600        assert_eq!(back, host);
1601    }
1602
1603    #[test]
1604    fn no_translation_is_identity() {
1605        let host = PathBuf::from("/some/host/path/file.rs");
1606        let lsp_uri = LspUri::from_host_path(&host, None).unwrap();
1607        assert_eq!(lsp_uri.as_str(), "file:///some/host/path/file.rs");
1608        let back = lsp_uri.to_host_path(None).unwrap();
1609        assert_eq!(back, host);
1610    }
1611}
1612
1613/// Self-contained state for the Live Grep floating overlay's preview
1614/// pane (issue #1796).
1615///
1616/// Owned directly by `Editor::overlay_preview_state` rather than
1617/// living in `Editor::split_view_states` keyed by a synthetic
1618/// `LeafId`. This isolation matters because ~20 sites across the
1619/// editor iterate `split_view_states` for cross-cutting work
1620/// (workspace save, viewport hooks, settings broadcasts, buffer
1621/// close cascades). The preview is a *transient render artefact*,
1622/// not a real split — none of those code paths should see it.
1623///
1624/// The phantom buffer is not in `SplitManager`'s tree either, so
1625/// it's invisible to focus rotation (`Alt+]`/`Alt+[`), tab drag
1626/// drop zones, hit testing, and `find_leaf_by_role` queries.
1627#[derive(Debug)]
1628pub struct OverlayPreviewState {
1629    /// Buffer currently displayed in the preview pane.
1630    pub buffer_id: BufferId,
1631    /// View state (cursor, viewport, folds, view mode, …) used by
1632    /// the renderer's per-leaf pipeline.
1633    pub view_state: crate::view::split::SplitViewState,
1634    /// Buffers we loaded only to feed the preview pane. On overlay
1635    /// close we close these via the standard `close_buffer` path.
1636    /// Buffers the user already had open are *not* in this set —
1637    /// dismissing the overlay never disturbs them.
1638    pub loaded_buffers: HashSet<BufferId>,
1639}
1640
1641#[cfg(test)]
1642mod uri_encoding_tests {
1643    use super::*;
1644
1645    /// Helper to get a platform-appropriate absolute path for testing.
1646    fn abs_path(suffix: &str) -> PathBuf {
1647        std::env::temp_dir().join(suffix)
1648    }
1649
1650    #[test]
1651    fn test_brackets_in_path() {
1652        let path = abs_path("MY_PROJECTS [temp]/gogame/main.go");
1653        let uri = file_path_to_lsp_uri(&path);
1654        assert!(
1655            uri.is_some(),
1656            "URI should be computed for path with brackets"
1657        );
1658        let uri = uri.unwrap();
1659        assert!(
1660            uri.as_str().contains("%5Btemp%5D"),
1661            "Brackets should be percent-encoded: {}",
1662            uri.as_str()
1663        );
1664    }
1665
1666    #[test]
1667    fn test_spaces_in_path() {
1668        let path = abs_path("My Projects/src/main.go");
1669        let uri = file_path_to_lsp_uri(&path);
1670        assert!(uri.is_some(), "URI should be computed for path with spaces");
1671    }
1672
1673    #[test]
1674    fn test_normal_path() {
1675        let path = abs_path("project/main.go");
1676        let uri = file_path_to_lsp_uri(&path);
1677        assert!(uri.is_some(), "URI should be computed for normal path");
1678        let s = uri.unwrap().as_str().to_string();
1679        assert!(s.starts_with("file:///"), "Should be a file URI: {}", s);
1680        assert!(
1681            s.ends_with("project/main.go"),
1682            "Should end with the path: {}",
1683            s
1684        );
1685    }
1686
1687    #[test]
1688    fn test_relative_path_returns_none() {
1689        let path = PathBuf::from("main.go");
1690        assert!(file_path_to_lsp_uri(&path).is_none());
1691    }
1692
1693    #[test]
1694    fn test_all_special_chars() {
1695        let path = abs_path("a[b]c{d}e^g`h/file.rs");
1696        let uri = file_path_to_lsp_uri(&path);
1697        assert!(uri.is_some(), "Should handle all special characters");
1698        let s = uri.unwrap().as_str().to_string();
1699        assert!(!s.contains('['), "[ should be encoded in {}", s);
1700        assert!(!s.contains(']'), "] should be encoded in {}", s);
1701        assert!(!s.contains('{'), "{{ should be encoded in {}", s);
1702        assert!(!s.contains('}'), "}} should be encoded in {}", s);
1703        assert!(!s.contains('^'), "^ should be encoded in {}", s);
1704        assert!(!s.contains('`'), "` should be encoded in {}", s);
1705    }
1706}