Skip to main content

fresh/app/
render.rs

1use super::lsp_status::compose_lsp_status;
2use super::*;
3use crate::config::FileExplorerSide;
4
5impl Editor {
6    /// Render the topmost global popup at its computed area and register its
7    /// click region in `global_popup_areas`. Shared by the generic
8    /// global-popup slot and the workspace-trust modal band so the area math
9    /// lives in exactly one place.
10    fn render_top_global_popup(
11        &mut self,
12        frame: &mut Frame,
13        size: ratatui::layout::Rect,
14        theme: &crate::view::theme::Theme,
15        hover_target: Option<&crate::app::HoverTarget>,
16    ) {
17        let Some(popup) = self.global_popups.top() else {
18            return;
19        };
20        let top_idx = self.global_popups.all().len() - 1;
21        let popup_area = popup.calculate_area(size, None);
22        let desc_height = popup.description_height();
23        let inner_area = if popup.bordered {
24            ratatui::layout::Rect {
25                x: popup_area.x + 1,
26                y: popup_area.y + 1 + desc_height,
27                width: popup_area.width.saturating_sub(2),
28                height: popup_area.height.saturating_sub(2 + desc_height),
29            }
30        } else {
31            ratatui::layout::Rect {
32                x: popup_area.x,
33                y: popup_area.y + desc_height,
34                width: popup_area.width,
35                height: popup_area.height.saturating_sub(desc_height),
36            }
37        };
38        let num_items = match &popup.content {
39            crate::view::popup::PopupContent::List { items, .. } => items.len(),
40            _ => 0,
41        };
42        let scroll_offset = popup.scroll_offset;
43        popup.render_with_hover(frame, popup_area, theme, hover_target);
44        self.active_chrome_mut().global_popup_areas.push((
45            top_idx,
46            popup_area,
47            inner_area,
48            scroll_offset,
49            num_items,
50        ));
51    }
52
53    /// Render the editor to the terminal
54    pub fn render(&mut self, frame: &mut Frame) {
55        let _span = tracing::info_span!("render").entered();
56        let size = frame.area();
57
58        // Let active animations snapshot the previous frame's buffer
59        // from the runner's own cache. We can't read the live
60        // `frame.buffer_mut()` — ratatui resets it before each draw —
61        // so the runner keeps a post-apply clone from the last frame.
62        self.active_window_mut().animations.capture_before_all();
63
64        // Save frame dimensions for recompute_layout (used by macro replay)
65        self.active_chrome_mut().last_frame_width = size.width;
66        self.active_chrome_mut().last_frame_height = size.height;
67
68        // Reset per-cell theme key map for this frame
69        self.active_chrome_mut().reset_cell_theme_map();
70
71        // For scroll sync groups, we need to update the active split's viewport position BEFORE
72        // calling sync_scroll_groups, so that the sync reads the correct position.
73        // Otherwise, cursor movements like 'G' (go to end) won't sync properly because
74        // viewport.top_byte hasn't been updated yet.
75        let active_split = self
76            .windows
77            .get(&self.active_window)
78            .and_then(|w| w.buffers.splits())
79            .map(|(mgr, _)| mgr)
80            .expect("active window must have a populated split layout")
81            .active_split();
82        {
83            let _span = tracing::info_span!("pre_sync_ensure_visible").entered();
84            self.active_window_mut()
85                .pre_sync_ensure_visible(active_split);
86        }
87
88        // Synchronize scroll sync groups (anchor-based scroll for side-by-side diffs)
89        // This sets viewport positions based on the authoritative scroll_line in each group
90        {
91            let _span = tracing::info_span!("sync_scroll_groups").entered();
92            self.active_window_mut().sync_scroll_groups();
93        }
94
95        // NOTE: Viewport sync with cursor is handled by split_rendering.rs which knows the
96        // correct content area dimensions. Don't sync here with incorrect EditorState viewport size.
97
98        // Prepare all buffers for rendering (pre-load viewport data for lazy loading)
99        // Each split may have a different viewport position on the same buffer
100        let mut semantic_ranges: std::collections::HashMap<BufferId, (usize, usize)> =
101            std::collections::HashMap::new();
102        {
103            let _span = tracing::info_span!("compute_semantic_ranges").entered();
104            for (split_id, view_state) in self
105                .windows
106                .get(&self.active_window)
107                .and_then(|w| w.buffers.splits())
108                .map(|(_, vs)| vs)
109                .expect("active window must have a populated split layout")
110            {
111                if let Some(buffer_id) = self
112                    .windows
113                    .get(&self.active_window)
114                    .and_then(|w| w.buffers.splits())
115                    .map(|(mgr, _)| mgr)
116                    .expect("active window must have a populated split layout")
117                    .get_buffer_id((*split_id).into())
118                {
119                    if let Some(state) = self
120                        .windows
121                        .get(&self.active_window)
122                        .map(|w| &w.buffers)
123                        .expect("active window present")
124                        .get(&buffer_id)
125                    {
126                        let start_line = state.buffer.get_line_number(view_state.viewport.top_byte);
127                        let visible_lines =
128                            view_state.viewport.visible_line_count().saturating_sub(1);
129                        let end_line = start_line.saturating_add(visible_lines);
130                        semantic_ranges
131                            .entry(buffer_id)
132                            .and_modify(|(min_start, max_end)| {
133                                *min_start = (*min_start).min(start_line);
134                                *max_end = (*max_end).max(end_line);
135                            })
136                            .or_insert((start_line, end_line));
137                    }
138                }
139            }
140        }
141        for (buffer_id, (start_line, end_line)) in semantic_ranges {
142            self.maybe_request_semantic_tokens_range(buffer_id, start_line, end_line);
143            self.maybe_request_semantic_tokens_full_debounced(buffer_id);
144            self.maybe_request_folding_ranges_debounced(buffer_id);
145        }
146
147        {
148            let _span = tracing::info_span!("prepare_for_render").entered();
149            // Pre-collect (split_id, top_byte, height, buffer_id) so we
150            // can mutate buffers below without holding a read borrow on
151            // self.windows.
152            let active_id = self.active_window;
153            let prep_targets: Vec<(BufferId, usize, u16)> = {
154                let win = self
155                    .windows
156                    .get(&active_id)
157                    .expect("active window must exist");
158                let (mgr, vs_map) = win
159                    .buffers
160                    .splits()
161                    .expect("active window must have a populated split layout");
162                vs_map
163                    .iter()
164                    .filter_map(|(split_id, vs)| {
165                        mgr.get_buffer_id((*split_id).into())
166                            .map(|bid| (bid, vs.viewport.top_byte, vs.viewport.height))
167                    })
168                    .collect()
169            };
170            let win_buffers = &mut self
171                .windows
172                .get_mut(&active_id)
173                .expect("active window must exist")
174                .buffers;
175            for (buffer_id, top_byte, height) in prep_targets {
176                if let Some(state) = win_buffers.get_mut(&buffer_id) {
177                    if let Err(e) = state.prepare_for_render(top_byte, height) {
178                        tracing::error!("Failed to prepare buffer for render: {}", e);
179                    }
180                }
181            }
182        }
183
184        // Refresh search highlights only during incremental search (when prompt is active)
185        // After search is confirmed, overlays exist for ALL matches and shouldn't be overwritten
186        let is_search_prompt_active = self.active_window().prompt.as_ref().is_some_and(|p| {
187            matches!(
188                p.prompt_type,
189                PromptType::Search | PromptType::ReplaceSearch | PromptType::QueryReplaceSearch
190            )
191        });
192        if is_search_prompt_active {
193            if let Some(ref search_state) = self.active_window().search_state {
194                let query = search_state.query.clone();
195                self.update_search_highlights(&query);
196            }
197        }
198
199        // Determine if we need to show search options bar.
200        // (Held in mutable bindings because the in-render
201        // `process_commands` block below can dispatch commands —
202        // e.g. `StartPromptAsync`, `SetPromptSuggestions` — that
203        // mutate `self.active_window_mut().prompt`. When that happens we recompute these
204        // flags and re-split `main_chunks` so the bottom-row
205        // rendering uses an up-to-date layout. See the
206        // "Recompute layout if mid-render commands changed state"
207        // block below.)
208        let mut show_search_options = self.active_window().prompt.as_ref().is_some_and(|p| {
209            matches!(
210                p.prompt_type,
211                PromptType::Search
212                    | PromptType::ReplaceSearch
213                    | PromptType::Replace { .. }
214                    | PromptType::QueryReplaceSearch
215                    | PromptType::QueryReplace { .. }
216            )
217        });
218
219        // Hide status bar when suggestions popup or file browser
220        // popup is shown — those popups float just above the prompt
221        // line, and a visible status bar wedged between them looks
222        // wrong. Floating-overlay prompts (Live Grep, issue #1796)
223        // are exempt because their suggestions live inside the
224        // centred frame, not above the bottom row.
225        let mut prompt_is_overlay = self
226            .active_window()
227            .prompt
228            .as_ref()
229            .is_some_and(|p| p.overlay);
230        let mut has_suggestions = self
231            .active_window()
232            .prompt
233            .as_ref()
234            .is_some_and(|p| !p.suggestions.is_empty())
235            && !prompt_is_overlay;
236        let mut has_file_browser = self.active_window().prompt.as_ref().is_some_and(|p| {
237            matches!(
238                p.prompt_type,
239                PromptType::OpenFile | PromptType::SwitchProject | PromptType::SaveFileAs
240            )
241        }) && self.active_window_mut().file_open_state.is_some();
242
243        // Build main vertical layout: [menu_bar, main_content, status_bar, search_options, prompt_line]
244        // Status bar is hidden when suggestions popup is shown
245        // Search options bar is shown when in search prompt
246        let mut main_chunks = Layout::default()
247            .direction(Direction::Vertical)
248            .constraints(vec![
249                Constraint::Length(if self.active_window_mut().menu_bar_visible {
250                    1
251                } else {
252                    0
253                }), // Menu bar
254                Constraint::Min(0), // Main content area
255                Constraint::Length(
256                    if !self.active_window_mut().status_bar_visible
257                        || has_suggestions
258                        || has_file_browser
259                    {
260                        0
261                    } else {
262                        1
263                    },
264                ), // Status bar (hidden when toggled off or with popups)
265                Constraint::Length(if show_search_options { 1 } else { 0 }), // Search options bar
266                Constraint::Length(
267                    // Prompt line is auto-hidden when no prompt active.
268                    // Overlay prompts (Live Grep, issue #1796) host the
269                    // input row inside the centred frame, so the
270                    // bottom row stays available for editor content
271                    // rather than being reserved as dead space.
272                    if (self.active_window_mut().prompt_line_visible
273                        || self.active_window().prompt.is_some())
274                        && !prompt_is_overlay
275                    {
276                        1
277                    } else {
278                        0
279                    },
280                ), // Prompt line
281            ])
282            .split(size);
283
284        let menu_bar_area = main_chunks[0];
285        let main_content_area = main_chunks[1];
286        let status_bar_idx = 2;
287        let search_options_idx = 3;
288        let prompt_line_idx = 4;
289
290        // Split main content area based on file explorer visibility
291        // Also keep the layout split if a sync is in progress (to avoid flicker)
292        let editor_content_area;
293        let file_explorer_should_show = self.file_explorer_visible()
294            && (self.file_explorer().is_some()
295                || self.active_window().file_explorer_sync_in_progress);
296
297        if file_explorer_should_show {
298            // Split horizontally based on side placement
299            tracing::trace!(
300                "render: file explorer layout active (present={}, sync_in_progress={}, side={:?})",
301                self.file_explorer().is_some(),
302                self.active_window().file_explorer_sync_in_progress,
303                self.active_window().file_explorer_side
304            );
305            let explorer_cols = self
306                .active_window()
307                .file_explorer_width
308                .to_cols(main_content_area.width);
309
310            let (explorer_area, editor_area) = match self.active_window().file_explorer_side {
311                FileExplorerSide::Left => {
312                    let chunks = Layout::default()
313                        .direction(Direction::Horizontal)
314                        .constraints([Constraint::Length(explorer_cols), Constraint::Min(0)])
315                        .split(main_content_area);
316                    (chunks[0], chunks[1])
317                }
318                FileExplorerSide::Right => {
319                    let chunks = Layout::default()
320                        .direction(Direction::Horizontal)
321                        .constraints([Constraint::Min(0), Constraint::Length(explorer_cols)])
322                        .split(main_content_area);
323                    (chunks[1], chunks[0])
324                }
325            };
326
327            self.active_layout_mut().file_explorer_area = Some(explorer_area);
328            editor_content_area = editor_area;
329
330            // Get connection string before mutable borrow of file_explorer.
331            let remote_connection = self.connection_display_string();
332
333            // Render file explorer (only if we have it - during sync we just keep the area reserved).
334            // Uses direct `self.windows.get_mut(...)` (not `file_explorer_mut()`) so the body
335            // can keep reading other Editor fields (buffers, theme, keybindings, …) — Rust
336            // splits the borrow on `self.windows` from the borrows on those other fields.
337            let active_id = self.active_window;
338            // Read window-state inputs before taking the &mut borrow on the
339            // window for the explorer/buffer access below.
340            let is_focused = self.active_window().key_context == KeyContext::FileExplorer;
341            let key_context_clone = self.active_window().key_context.clone();
342            let close_button_hovered = matches!(
343                &self.active_window().mouse_state.hover_target,
344                Some(HoverTarget::FileExplorerCloseButton)
345            );
346            // Take one &mut on the active window; the explorer + buffers
347            // come from disjoint sub-fields so they can coexist.
348            let __win = self
349                .windows
350                .get_mut(&active_id)
351                .expect("active window must exist");
352            let __buffers_ref: &crate::app::window::WindowBuffers = &__win.buffers;
353            if let Some(explorer) = __win.file_explorer.as_mut() {
354                // Build set of files with unsaved changes
355                let mut files_with_unsaved_changes = std::collections::HashSet::new();
356                for (buffer_id, state) in __buffers_ref {
357                    if state.buffer.is_modified() {
358                        if let Some(metadata) = __win.buffer_metadata.get(buffer_id) {
359                            if let Some(file_path) = metadata.file_path() {
360                                files_with_unsaved_changes.insert(file_path.clone());
361                            }
362                        }
363                    }
364                }
365
366                let keybindings = self.keybindings.read().unwrap();
367                let empty: Vec<std::path::PathBuf> = Vec::new();
368                let cut_paths = __win
369                    .file_explorer_clipboard
370                    .as_ref()
371                    .filter(|cb| cb.is_cut)
372                    .map(|cb| cb.paths.as_slice())
373                    .unwrap_or(empty.as_slice());
374                FileExplorerRenderer::render(
375                    explorer,
376                    frame,
377                    explorer_area,
378                    is_focused,
379                    &files_with_unsaved_changes,
380                    &__win.file_explorer_decoration_cache,
381                    &keybindings,
382                    key_context_clone,
383                    &*self.theme.read().unwrap(),
384                    close_button_hovered,
385                    remote_connection.as_deref(),
386                    cut_paths,
387                    &self.config.file_explorer.tree_indicator_collapsed,
388                    &self.config.file_explorer.tree_indicator_expanded,
389                );
390            }
391            // Note: if file_explorer is None but sync_in_progress is true,
392            // we just leave the area blank (or could render a placeholder)
393        } else {
394            // No file explorer: use entire main content area for editor
395            self.active_layout_mut().file_explorer_area = None;
396            editor_content_area = main_content_area;
397        }
398
399        // Note: Tabs are now rendered within each split by SplitRenderer
400
401        // Trigger lines_changed hooks for newly visible lines in all visible buffers
402        // This allows plugins to add overlays before rendering
403        // Only lines that haven't been seen before are sent (batched for efficiency)
404        // Use non-blocking hooks to avoid deadlock when actions are awaiting
405        if self.plugin_manager.read().unwrap().is_active() {
406            let hooks_start = std::time::Instant::now();
407            // Get visible buffers and their areas
408            let visible_buffers = self
409                .windows
410                .get(&self.active_window)
411                .and_then(|w| w.buffers.splits())
412                .map(|(mgr, _)| mgr)
413                .expect("active window must have a populated split layout")
414                .get_visible_buffers(editor_content_area);
415
416            let mut total_new_lines = 0usize;
417            for (split_id, buffer_id, split_area) in visible_buffers {
418                // Get viewport from SplitViewState (the authoritative source)
419                let viewport_top_byte = self
420                    .windows
421                    .get(&self.active_window)
422                    .and_then(|w| w.buffers.splits())
423                    .map(|(_, vs)| vs)
424                    .expect("active window must have a populated split layout")
425                    .get(&split_id)
426                    .map(|vs| vs.viewport.top_byte)
427                    .unwrap_or(0);
428
429                let __active_id = self.active_window;
430                let __win = self
431                    .windows
432                    .get_mut(&__active_id)
433                    .expect("active window must exist");
434                // Take a disjoint mut borrow on `seen_byte_ranges` (a sibling
435                // field on Window, not part of WindowBuffers) so the closure
436                // below can update it alongside the buffer + view-state
437                // mutations.
438                let seen_ranges_for_win = &mut __win.seen_byte_ranges;
439                let plugin_manager = &self.plugin_manager;
440                let estimated_line_length = self.config.editor.estimated_line_length;
441                let added = __win
442                    .buffers
443                    .with_buffer_and_view_states(buffer_id, |state, vs_map| {
444                        // `render_start` has a tiny payload (just the
445                        // buffer id) — fire unconditionally so third-party
446                        // plugins listening for it still work.
447                        let pm_guard = plugin_manager.read().unwrap();
448                        pm_guard.run_hook(
449                            "render_start",
450                            crate::services::plugins::hooks::HookArgs::RenderStart { buffer_id },
451                        );
452
453                        let visible_count = split_area.height as usize;
454
455                        // `view_transform_request` carries the full
456                        // tokenized viewport in its args. Building those
457                        // tokens (`build_base_tokens_for_hook`) is the
458                        // expensive part — see #2009. Skip the whole
459                        // pipeline when no plugin subscribes.
460                        if pm_guard.has_subscribers("view_transform_request") {
461                            let is_binary = state.buffer.is_binary();
462                            let line_ending = state.buffer.line_ending();
463                            let base_tokens =
464                                crate::view::ui::split_rendering::SplitRenderer::build_base_tokens_for_hook(
465                                    &mut state.buffer,
466                                    viewport_top_byte,
467                                    estimated_line_length,
468                                    visible_count,
469                                    is_binary,
470                                    line_ending,
471                                );
472                            let viewport_start = viewport_top_byte;
473                            let viewport_end = base_tokens
474                                .last()
475                                .and_then(|t| t.source_offset)
476                                .unwrap_or(viewport_start);
477                            let cursor_positions: Vec<usize> = vs_map
478                                .get(&split_id)
479                                .map(|vs| vs.cursors.iter().map(|(_, c)| c.position).collect())
480                                .unwrap_or_default();
481                            pm_guard.run_hook(
482                                "view_transform_request",
483                                crate::services::plugins::hooks::HookArgs::ViewTransformRequest {
484                                    buffer_id,
485                                    split_id: split_id.into(),
486                                    viewport_start,
487                                    viewport_end,
488                                    tokens: base_tokens,
489                                    cursor_positions,
490                                },
491                            );
492
493                            // Plugin saw fresh base tokens; future
494                            // SubmitViewTransform from this request is valid.
495                            if let Some(vs) = vs_map.get_mut(&split_id) {
496                                vs.view_transform_stale = false;
497                            }
498                        }
499                        drop(pm_guard);
500
501                        let top_byte = viewport_top_byte;
502                        let seen_byte_ranges =
503                            seen_ranges_for_win.entry(buffer_id).or_default();
504
505                        let mut new_lines: Vec<
506                            crate::services::plugins::hooks::LineInfo,
507                        > = Vec::new();
508                        let mut line_number = state.buffer.get_line_number(top_byte);
509                        let mut iter = state
510                            .buffer
511                            .line_iterator(top_byte, estimated_line_length);
512
513                        for _ in 0..visible_count {
514                            if let Some((line_start, line_content)) = iter.next_line() {
515                                let byte_end = line_start + line_content.len();
516                                let byte_range = (line_start, byte_end);
517
518                                if !seen_byte_ranges.contains(&byte_range) {
519                                    new_lines.push(
520                                        crate::services::plugins::hooks::LineInfo {
521                                            line_number,
522                                            byte_start: line_start,
523                                            byte_end,
524                                            content: line_content,
525                                        },
526                                    );
527                                    seen_byte_ranges.insert(byte_range);
528                                }
529                                line_number += 1;
530                            } else {
531                                break;
532                            }
533                        }
534
535                        let count = new_lines.len();
536                        if !new_lines.is_empty() {
537                            plugin_manager.read().unwrap().run_hook(
538                                "lines_changed",
539                                crate::services::plugins::hooks::HookArgs::LinesChanged {
540                                    buffer_id,
541                                    lines: new_lines,
542                                },
543                            );
544                        }
545                        count
546                    })
547                    .unwrap_or(0);
548                total_new_lines += added;
549            }
550            let hooks_elapsed = hooks_start.elapsed();
551            tracing::trace!(
552                new_lines = total_new_lines,
553                elapsed_ms = hooks_elapsed.as_millis(),
554                elapsed_us = hooks_elapsed.as_micros(),
555                "lines_changed hooks total"
556            );
557
558            // Process any plugin commands (like AddOverlay) that resulted from the hooks.
559            //
560            // This is non-blocking: we collect whatever the plugin has sent so far.
561            // The plugin thread runs in parallel, and because we proactively call
562            // handle_refresh_lines after cursor_moved (in fire_cursor_hooks), the
563            // lines_changed hook fires early in the render cycle. By the time we
564            // reach this point, the plugin has typically already processed all hooks
565            // and sent back conceal/overlay commands. On rare occasions (high CPU
566            // load), the response arrives one frame late, which is imperceptible
567            // at 60fps. The plugin's own refreshLines() call from cursor_moved
568            // ensures a follow-up render cycle picks up any missed commands.
569            let commands = self.plugin_manager.write().unwrap().process_commands();
570            let dispatched_any = !commands.is_empty();
571            if dispatched_any {
572                let cmd_names: Vec<String> =
573                    commands.iter().map(|c| c.debug_variant_name()).collect();
574                tracing::trace!(count = commands.len(), cmds = ?cmd_names, "process_commands during render");
575            }
576            for command in commands {
577                if let Err(e) = self.handle_plugin_command(command) {
578                    tracing::error!("Error handling plugin command: {}", e);
579                }
580            }
581
582            // Flush any deferred grammar rebuilds as a single batch
583            self.flush_pending_grammars();
584
585            // Recompute the bottom-row layout if the in-render command
586            // dispatch above mutated state that affects it. Without
587            // this, a `StartPromptAsync` (or similar) processed
588            // mid-render leaves `main_chunks` reflecting the prior
589            // `self.active_window_mut().prompt = None` shape — the prompt slot ends up at
590            // (y = size.height, h = 0) and the status bar paints the
591            // bottom row in place of the prompt input. Conservative:
592            // we recompute on *any* dispatched commands rather than
593            // enumerating layout-affecting variants — Layout::split is
594            // cheap, and this avoids a maintenance-burden whitelist
595            // that would silently regress as new `PluginCommand`
596            // variants are added.
597            //
598            // Bounded — single drain + single recompute. We do not
599            // call `process_commands` again, so commands queued by
600            // hooks fired inside the dispatch above wait for the next
601            // render or `editor_tick` (the existing one-frame-late
602            // behaviour the comment above already accepts).
603            //
604            // `main_content_area` (and the file-explorer / split
605            // rendering derived from it earlier in this render) is
606            // intentionally NOT re-derived: those areas were already
607            // painted, and the bottom-row recompute may overwrite a
608            // single row of main content where the new status bar /
609            // prompt now sits. That brief overlap self-corrects on
610            // the next frame, where the layout is built consistently
611            // from the start.
612            if dispatched_any {
613                show_search_options = self.active_window().prompt.as_ref().is_some_and(|p| {
614                    matches!(
615                        p.prompt_type,
616                        PromptType::Search
617                            | PromptType::ReplaceSearch
618                            | PromptType::Replace { .. }
619                            | PromptType::QueryReplaceSearch
620                            | PromptType::QueryReplace { .. }
621                    )
622                });
623                prompt_is_overlay = self
624                    .active_window()
625                    .prompt
626                    .as_ref()
627                    .is_some_and(|p| p.overlay);
628                has_suggestions = self
629                    .active_window()
630                    .prompt
631                    .as_ref()
632                    .is_some_and(|p| !p.suggestions.is_empty())
633                    && !prompt_is_overlay;
634                has_file_browser = self.active_window().prompt.as_ref().is_some_and(|p| {
635                    matches!(
636                        p.prompt_type,
637                        PromptType::OpenFile | PromptType::SwitchProject | PromptType::SaveFileAs
638                    )
639                }) && self.active_window_mut().file_open_state.is_some();
640                main_chunks = Layout::default()
641                    .direction(Direction::Vertical)
642                    .constraints(vec![
643                        Constraint::Length(if self.active_window_mut().menu_bar_visible {
644                            1
645                        } else {
646                            0
647                        }),
648                        Constraint::Min(0),
649                        Constraint::Length(
650                            if !self.active_window_mut().status_bar_visible
651                                || has_suggestions
652                                || has_file_browser
653                            {
654                                0
655                            } else {
656                                1
657                            },
658                        ),
659                        Constraint::Length(if show_search_options { 1 } else { 0 }),
660                        Constraint::Length(
661                            if (self.active_window_mut().prompt_line_visible
662                                || self.active_window().prompt.is_some())
663                                && !prompt_is_overlay
664                            {
665                                1
666                            } else {
667                                0
668                            },
669                        ),
670                    ])
671                    .split(size);
672            }
673        }
674
675        // Render editor content (same for both layouts)
676        let lsp_waiting = !self.active_window().pending_completion_requests.is_empty()
677            || self
678                .active_window()
679                .pending_goto_definition_request
680                .is_some();
681
682        // Hide the hardware cursor when menu is open, file explorer is focused, terminal mode,
683        // or settings UI is open
684        // (the file explorer will set its own cursor position when focused)
685        // (terminal mode renders its own cursor via the terminal emulator)
686        // (settings UI is a modal that doesn't need the editor cursor)
687        // This also causes visual cursor indicators in the editor to be dimmed
688        let settings_visible = self.settings_state.as_ref().is_some_and(|s| s.visible);
689        let hide_cursor = self.menu_state.active_menu.is_some()
690            || self.active_window_mut().key_context == KeyContext::FileExplorer
691            || self.active_window().terminal_mode
692            || settings_visible
693            || self.keybinding_editor.is_some();
694
695        // Convert HoverTarget to tab hover info for rendering
696        let hovered_tab = match &self.active_window_mut().mouse_state.hover_target {
697            Some(HoverTarget::TabName(target, split_id)) => Some((*target, *split_id, false)),
698            Some(HoverTarget::TabCloseButton(target, split_id)) => Some((*target, *split_id, true)),
699            _ => None,
700        };
701
702        // Get hovered close split button
703        let hovered_close_split = match &self.active_window_mut().mouse_state.hover_target {
704            Some(HoverTarget::CloseSplitButton(split_id)) => Some(*split_id),
705            _ => None,
706        };
707
708        // Get hovered maximize split button
709        let hovered_maximize_split = match &self.active_window_mut().mouse_state.hover_target {
710            Some(HoverTarget::MaximizeSplitButton(split_id)) => Some(*split_id),
711            _ => None,
712        };
713
714        let is_maximized = self
715            .windows
716            .get(&self.active_window)
717            .and_then(|w| w.buffers.splits())
718            .map(|(mgr, _)| mgr)
719            .expect("active window must have a populated split layout")
720            .is_maximized();
721
722        // The active split's buffer renderer records where the hardware
723        // cursor *wants* to appear here; we only commit it to the frame at
724        // the very end of this draw pass, after popups have been rendered,
725        // so a popup covering the cursor cell causes the cursor to be
726        // hidden (otherwise the hardware caret would bleed through the
727        // popup).
728        let mut pending_hardware_cursor: Option<(u16, u16)> = None;
729
730        let _content_span = tracing::info_span!("render_content").entered();
731        // Take a single mutable borrow on the active window's splits and
732        // split it into (&SplitManager, &mut HashMap<...>) — Rust can
733        // destructure the tuple, but we can't make two separate
734        // `windows.get`/`windows.get_mut` calls in the same expression.
735        let active_window_id = self.active_window;
736        // Take one &mut on the active window. Split-borrow into
737        // buffers (mut), split_mgr (immutable view of mgr), and
738        // split_view_states (mut) — all disjoint sub-fields.
739        let __win = self
740            .windows
741            .get_mut(&active_window_id)
742            .expect("active window must exist");
743        let __metadata_ref = &__win.buffer_metadata;
744        let __event_logs_mut = &mut __win.event_logs;
745        let __grouped_ref = &__win.grouped_subtrees;
746        let __composite_buffers_mut = &mut __win.composite_buffers;
747        let __composite_view_states_mut = &mut __win.composite_view_states;
748        let __cell_theme_map_mut = &mut __win.chrome_layout.cell_theme_map;
749        let __tab_bar_visible = __win.tab_bar_visible;
750        let (
751            split_areas,
752            tab_layouts,
753            close_split_areas,
754            maximize_split_areas,
755            view_line_mappings,
756            horizontal_scrollbar_areas,
757            grouped_separator_areas,
758        ) = __win
759            .buffers
760            .with_all_mut(|__buffers_mut, __mgr, __vs_map| {
761                SplitRenderer::render_content(
762                    frame,
763                    editor_content_area,
764                    &*__mgr,
765                    __buffers_mut,
766                    __metadata_ref,
767                    __event_logs_mut,
768                    __composite_buffers_mut,
769                    __composite_view_states_mut,
770                    &*self.theme.read().unwrap(),
771                    self.ansi_background.as_ref(),
772                    self.background_fade,
773                    lsp_waiting,
774                    self.config.editor.large_file_threshold_bytes,
775                    self.config.editor.line_wrap,
776                    self.config.editor.estimated_line_length,
777                    self.config.editor.highlight_context_bytes,
778                    Some(__vs_map),
779                    __grouped_ref,
780                    hide_cursor,
781                    hovered_tab,
782                    hovered_close_split,
783                    hovered_maximize_split,
784                    is_maximized,
785                    self.config.editor.relative_line_numbers,
786                    __tab_bar_visible,
787                    self.config.editor.use_terminal_bg,
788                    self.session_mode || !self.software_cursor_only,
789                    self.software_cursor_only,
790                    self.config.editor.show_vertical_scrollbar,
791                    self.config.editor.show_horizontal_scrollbar,
792                    self.config.editor.diagnostics_inline_text,
793                    self.config.editor.show_tilde,
794                    self.config.editor.highlight_current_column,
795                    __cell_theme_map_mut,
796                    size.width,
797                    &mut pending_hardware_cursor,
798                )
799            })
800            .expect("active window must have a populated split layout");
801
802        drop(_content_span);
803
804        // Cursor-jump animation: compare the cursor's screen position to
805        // the prior frame and animate either when the cursor crossed split
806        // panes or moved more than two rows within the same pane. The
807        // trail crosses pane separators when the jump is across splits —
808        // that's the intended "follow the focus" cue.
809        self.maybe_start_cursor_jump_animation(pending_hardware_cursor, active_split);
810
811        // Detect viewport changes and fire hooks
812        // Compare against previous frame's viewport state (stored in self.active_window().previous_viewports)
813        // This correctly detects changes from scroll events that happen before render()
814        if self.plugin_manager.read().unwrap().is_active() {
815            for (split_id, view_state) in self
816                .windows
817                .get(&self.active_window)
818                .and_then(|w| w.buffers.splits())
819                .map(|(_, vs)| vs)
820                .expect("active window must have a populated split layout")
821            {
822                let current = (
823                    view_state.viewport.top_byte,
824                    view_state.viewport.width,
825                    view_state.viewport.height,
826                );
827                // Compare against previous frame's state
828                // Skip new splits (None case) - only fire hooks for established splits
829                // This matches the original behavior where hooks only fire for splits
830                // that existed at the start of render
831                let (changed, previous) =
832                    match self.active_window().previous_viewports.get(split_id) {
833                        Some(previous) => (*previous != current, Some(*previous)),
834                        None => (false, None), // Skip new splits until they're established
835                    };
836                tracing::trace!(
837                    "viewport_changed check: split={:?} current={:?} previous={:?} changed={}",
838                    split_id,
839                    current,
840                    previous,
841                    changed
842                );
843                if changed {
844                    if let Some(buffer_id) = self
845                        .windows
846                        .get(&self.active_window)
847                        .and_then(|w| w.buffers.splits())
848                        .map(|(mgr, _)| mgr)
849                        .expect("active window must have a populated split layout")
850                        .get_buffer_id((*split_id).into())
851                    {
852                        // Compute top_line if line info is available
853                        let top_line = self
854                            .windows
855                            .get(&self.active_window)
856                            .map(|w| &w.buffers)
857                            .expect("active window present")
858                            .get(&buffer_id)
859                            .and_then(|state| {
860                                if state.buffer.line_count().is_some() {
861                                    Some(state.buffer.get_line_number(view_state.viewport.top_byte))
862                                } else {
863                                    None
864                                }
865                            });
866                        tracing::debug!(
867                            "Firing viewport_changed hook: split={:?} buffer={:?} top_byte={} top_line={:?}",
868                            split_id,
869                            buffer_id,
870                            view_state.viewport.top_byte,
871                            top_line
872                        );
873                        self.plugin_manager.read().unwrap().run_hook(
874                            "viewport_changed",
875                            crate::services::plugins::hooks::HookArgs::ViewportChanged {
876                                split_id: (*split_id).into(),
877                                buffer_id,
878                                top_byte: view_state.viewport.top_byte,
879                                top_line,
880                                width: view_state.viewport.width,
881                                height: view_state.viewport.height,
882                            },
883                        );
884                    }
885                }
886            }
887        }
888
889        // Update previous_viewports for next frame's comparison.
890        // Take both `previous_viewports` and the split view-states from
891        // the same `__win` borrow so the iterator and the inserts share
892        // a single mutable borrow on `self.windows`.
893        let __vp_win = self
894            .windows
895            .get_mut(&self.active_window)
896            .expect("active window present");
897        __vp_win.previous_viewports.clear();
898        let (_, __vp_vs_map) = __vp_win
899            .buffers
900            .splits()
901            .expect("active window must have a populated split layout");
902        let snapshot: Vec<(LeafId, (usize, u16, u16))> = __vp_vs_map
903            .iter()
904            .map(|(split_id, view_state)| {
905                (
906                    *split_id,
907                    (
908                        view_state.viewport.top_byte,
909                        view_state.viewport.width,
910                        view_state.viewport.height,
911                    ),
912                )
913            })
914            .collect();
915        for (split_id, vp) in snapshot {
916            __vp_win.previous_viewports.insert(split_id, vp);
917        }
918
919        // Render terminal content on top of split content for terminal buffers.
920        // Active-window path: cursor blinks normally when terminal_mode is on.
921        self.active_window()
922            .render_terminal_splits(frame, &split_areas, true);
923
924        self.active_layout_mut().split_areas = split_areas;
925        self.active_layout_mut().horizontal_scrollbar_areas = horizontal_scrollbar_areas;
926        self.active_layout_mut().tab_layouts = tab_layouts;
927        self.active_layout_mut().close_split_areas = close_split_areas;
928        self.active_layout_mut().maximize_split_areas = maximize_split_areas;
929        self.active_layout_mut().view_line_mappings = view_line_mappings;
930
931        // Promote any deferred virtual-buffer animations whose Rect is now
932        // known. Done here (after split_areas is recomputed, before
933        // apply_all runs at the end of render) so the first frame of the
934        // effect lands on the same paint that made the buffer visible.
935        self.drain_pending_vb_animations();
936        let mut separator_areas = self
937            .split_manager_mut()
938            .get_separators_with_ids(editor_content_area);
939        // Grouped subtrees live in a side-map outside the main split tree, so
940        // their inner separators are not visited by `get_separators_with_ids`
941        // above. The renderer collected them (using the same content rect it
942        // drew them at) — merge so clicks on those rendered columns register.
943        separator_areas.extend(grouped_separator_areas);
944        self.active_layout_mut().separator_areas = separator_areas;
945        self.active_layout_mut().editor_content_area = Some(editor_content_area);
946
947        // Render hover highlights for separators and scrollbars
948        self.render_hover_highlights(frame);
949
950        // Initialize popup/suggestion layout state (rendered after status bar below)
951        self.active_chrome_mut().suggestions_area = None;
952        self.active_chrome_mut().suggestions_outer_area = None;
953        self.active_window_mut().file_browser_layout = None;
954
955        // Clone all immutable values before the mutable borrow
956        let display_name = self
957            .active_window()
958            .buffer_metadata
959            .get(&self.active_buffer())
960            .map(|m| m.display_name.clone())
961            .unwrap_or_else(|| "[No Name]".to_string());
962
963        // Reflect the active buffer in the terminal window/tab title. Only
964        // writes when the title actually changes so we don't flood stdout
965        // with OSC sequences every frame.
966        self.update_terminal_title(&display_name);
967
968        let status_message = self.active_window().status_message.clone();
969        let plugin_status_message = self.active_window().plugin_status_message.clone();
970        let prompt = self.active_window().prompt.clone();
971        // Compute a simple buffer-aware LSP indicator.
972        // Compose the LSP status-bar segment for the active buffer. This
973        // runs every render — the editor has no precomputed LSP-status
974        // string cached anywhere else, so there is a single source of
975        // truth for what the user sees.
976        //
977        // Priority order (first non-empty wins):
978        //
979        //   1. Active `$/progress` work for this language — e.g.
980        //      "LSP (cpp): indexing (42%)". Conveys the transient
981        //      startup/indexing phase.
982        //   2. A running server — "LSP". Short because detail belongs
983        //      in LSP-specific UI, not the compact status bar pill.
984        //   3. Configured `auto_start=true` servers that haven't started
985        //      (error / crashed / pending) — "LSP off".
986        //   4. Configured `enabled && !auto_start` servers that the user
987        //      has to opt into — "LSP: off (N)".
988        //   5. Nothing.
989        //
990        // Rules 3 and 4 address heuristic eval H-1: without them, a
991        // configured-but-dormant server is indistinguishable from "no
992        // LSP at all."
993        let current_language = self
994            .buffers()
995            .get(&self.active_buffer())
996            .map(|s| s.language.clone())
997            .unwrap_or_default();
998        let buffer_lsp_disabled_reason = self
999            .active_window()
1000            .buffer_metadata
1001            .get(&self.active_buffer())
1002            .filter(|m| !m.lsp_enabled)
1003            .and_then(|m| m.lsp_disabled_reason.as_deref());
1004        let (lsp_status, lsp_indicator_state) = compose_lsp_status(
1005            &current_language,
1006            buffer_lsp_disabled_reason,
1007            &self.active_window().lsp_progress,
1008            &self.active_window().lsp_server_statuses,
1009            &self.config.lsp,
1010            &self.active_window().user_dismissed_lsp_languages,
1011        );
1012        let theme = self.theme.read().unwrap().clone();
1013        let keybindings_cloned = self.keybindings.read().unwrap().clone(); // Clone the keybindings
1014        let chord_state_cloned = self.active_window_mut().chord_state.clone(); // Clone the chord state
1015
1016        // Get update availability info
1017        let update_available = self.latest_version().map(|v| v.to_string());
1018
1019        // Render status bar (hidden when toggled off, or when suggestions/file browser popup is shown)
1020        if self.active_window_mut().status_bar_visible && !has_suggestions && !has_file_browser {
1021            // Get warning level for colored indicator (respects config setting)
1022            // LSP warning level is scoped to the current buffer's language
1023            let (warning_level, general_warning_count) =
1024                if self.config.warnings.show_status_indicator {
1025                    let lsp_level = {
1026                        use crate::services::async_bridge::LspServerStatus;
1027                        let mut level = WarningLevel::None;
1028                        for ((lang, _), status) in &self.active_window().lsp_server_statuses {
1029                            if lang == &current_language {
1030                                match status {
1031                                    LspServerStatus::Error => {
1032                                        level = WarningLevel::Error;
1033                                        break;
1034                                    }
1035                                    LspServerStatus::Starting | LspServerStatus::Initializing => {
1036                                        if level != WarningLevel::Error {
1037                                            level = WarningLevel::Warning;
1038                                        }
1039                                    }
1040                                    _ => {}
1041                                }
1042                            }
1043                        }
1044                        level
1045                    };
1046                    (
1047                        lsp_level,
1048                        self.active_window().warning_domains.general.count,
1049                    )
1050                } else {
1051                    (WarningLevel::None, 0)
1052                };
1053
1054            // Compute status bar hover state for styling
1055            use crate::view::ui::status_bar::StatusBarHover;
1056            let status_bar_hover = match &self.active_window_mut().mouse_state.hover_target {
1057                Some(HoverTarget::StatusBarLspIndicator) => StatusBarHover::LspIndicator,
1058                Some(HoverTarget::StatusBarWarningBadge) => StatusBarHover::WarningBadge,
1059                Some(HoverTarget::StatusBarLineEndingIndicator) => {
1060                    StatusBarHover::LineEndingIndicator
1061                }
1062                Some(HoverTarget::StatusBarEncodingIndicator) => StatusBarHover::EncodingIndicator,
1063                Some(HoverTarget::StatusBarLanguageIndicator) => StatusBarHover::LanguageIndicator,
1064                Some(HoverTarget::StatusBarRemoteIndicator) => StatusBarHover::RemoteIndicator,
1065                _ => StatusBarHover::None,
1066            };
1067
1068            let remote_connection = self.connection_display_string();
1069
1070            // Get session name for display (only in session mode)
1071            let session_name = self.session_name().map(|s| s.to_string());
1072
1073            let active_split = self.effective_active_split();
1074            let active_buf = self.active_buffer();
1075            let default_cursors = crate::model::cursor::Cursors::new();
1076            let is_read_only = self
1077                .active_window()
1078                .buffer_metadata
1079                .get(&active_buf)
1080                .map(|m| m.read_only)
1081                .unwrap_or(false);
1082            let is_synthetic_placeholder = self
1083                .active_window()
1084                .buffer_metadata
1085                .get(&active_buf)
1086                .map(|m| m.synthetic_placeholder)
1087                .unwrap_or(false);
1088            // Compute plugin-provided status-bar values before taking the
1089            // mutable window borrow below.
1090            let dynamic_status_bar_elements = self.get_status_bar_element_values(active_buf);
1091            // Single window borrow, split into buffers + cursors so the
1092            // status-bar context can hold both.
1093            let __active_id = self.active_window;
1094            let __win = self
1095                .windows
1096                .get_mut(&__active_id)
1097                .expect("active window must exist");
1098            let status_bar_layout = __win
1099                .buffers
1100                .with_buffer_and_view_states(active_buf, |state, vs_map| {
1101                    let cursors = vs_map
1102                        .get(&active_split)
1103                        .map(|v| &v.cursors)
1104                        .unwrap_or(&default_cursors);
1105                    let mut status_ctx = crate::view::ui::status_bar::StatusBarContext {
1106                        state,
1107                        cursors,
1108                        status_message: &status_message,
1109                        plugin_status_message: &plugin_status_message,
1110                        lsp_status: &lsp_status,
1111                        lsp_indicator_state,
1112                        theme: &theme,
1113                        display_name: &display_name,
1114                        keybindings: &keybindings_cloned,
1115                        chord_state: &chord_state_cloned,
1116                        update_available: update_available.as_deref(),
1117                        warning_level,
1118                        general_warning_count,
1119                        hover: status_bar_hover,
1120                        remote_connection: remote_connection.as_deref(),
1121                        session_name: session_name.as_deref(),
1122                        read_only: is_read_only,
1123                        remote_state_override: self.remote_indicator_override.as_ref(),
1124                        is_synthetic_placeholder,
1125                        // Filled in by `render_status` from the user's
1126                        // status_bar config; the value here is just a
1127                        // safe default for the rare path that builds the
1128                        // ctx but doesn't run `render_status`.
1129                        remote_indicator_on_bar: false,
1130                        dynamic_status_bar_elements: dynamic_status_bar_elements.clone(),
1131                    };
1132                    StatusBarRenderer::render_status_bar(
1133                        frame,
1134                        main_chunks[status_bar_idx],
1135                        &mut status_ctx,
1136                        &self.config.editor.status_bar,
1137                    )
1138                })
1139                .expect("active buffer must be present");
1140
1141            // Store status bar layout for click detection
1142            let status_bar_area = main_chunks[status_bar_idx];
1143            self.active_chrome_mut().status_bar_area =
1144                Some((status_bar_area.y, status_bar_area.x, status_bar_area.width));
1145            self.active_chrome_mut().status_bar_lsp_area = status_bar_layout.lsp_indicator;
1146            self.active_chrome_mut().status_bar_warning_area = status_bar_layout.warning_badge;
1147            self.active_chrome_mut().status_bar_line_ending_area =
1148                status_bar_layout.line_ending_indicator;
1149            self.active_chrome_mut().status_bar_encoding_area =
1150                status_bar_layout.encoding_indicator;
1151            self.active_chrome_mut().status_bar_language_area =
1152                status_bar_layout.language_indicator;
1153            self.active_chrome_mut().status_bar_message_area = status_bar_layout.message_area;
1154            self.active_chrome_mut().status_bar_remote_area = status_bar_layout.remote_indicator;
1155        }
1156
1157        // Render search options bar when in search prompt
1158        if show_search_options {
1159            // Show "Confirm" option only in replace modes
1160            let confirm_each = self.active_window().prompt.as_ref().and_then(|p| {
1161                if matches!(
1162                    p.prompt_type,
1163                    PromptType::ReplaceSearch
1164                        | PromptType::Replace { .. }
1165                        | PromptType::QueryReplaceSearch
1166                        | PromptType::QueryReplace { .. }
1167                ) {
1168                    Some(self.active_window().search_confirm_each)
1169                } else {
1170                    None
1171                }
1172            });
1173
1174            // Determine hover state for search options
1175            use crate::view::ui::status_bar::SearchOptionsHover;
1176            let search_options_hover = match &self.active_window_mut().mouse_state.hover_target {
1177                Some(HoverTarget::SearchOptionCaseSensitive) => SearchOptionsHover::CaseSensitive,
1178                Some(HoverTarget::SearchOptionWholeWord) => SearchOptionsHover::WholeWord,
1179                Some(HoverTarget::SearchOptionRegex) => SearchOptionsHover::Regex,
1180                Some(HoverTarget::SearchOptionConfirmEach) => SearchOptionsHover::ConfirmEach,
1181                _ => SearchOptionsHover::None,
1182            };
1183
1184            let search_options_layout = StatusBarRenderer::render_search_options(
1185                frame,
1186                main_chunks[search_options_idx],
1187                self.active_window().search_case_sensitive,
1188                self.active_window().search_whole_word,
1189                self.active_window().search_use_regex,
1190                confirm_each,
1191                &theme,
1192                &keybindings_cloned,
1193                search_options_hover,
1194            );
1195            self.active_chrome_mut().search_options_layout = Some(search_options_layout);
1196        } else {
1197            self.active_chrome_mut().search_options_layout = None;
1198        }
1199
1200        // Render prompt line if active. Overlay prompts (Live Grep)
1201        // skip the bottom-row render entirely — they paint their own
1202        // input row inside the centred overlay frame, so the user's
1203        // editor view stays unobstructed at the bottom.
1204        if let Some(prompt) = &prompt {
1205            if !prompt.overlay {
1206                // Use specialized renderer for file/folder open prompt to show colorized path
1207                if matches!(
1208                    prompt.prompt_type,
1209                    crate::view::prompt::PromptType::OpenFile
1210                        | crate::view::prompt::PromptType::SwitchProject
1211                ) {
1212                    if let Some(file_open_state) = &self.active_window_mut().file_open_state {
1213                        StatusBarRenderer::render_file_open_prompt(
1214                            frame,
1215                            main_chunks[prompt_line_idx],
1216                            prompt,
1217                            file_open_state,
1218                            &theme,
1219                        );
1220                    } else {
1221                        StatusBarRenderer::render_prompt(
1222                            frame,
1223                            main_chunks[prompt_line_idx],
1224                            prompt,
1225                            &theme,
1226                        );
1227                    }
1228                } else {
1229                    StatusBarRenderer::render_prompt(
1230                        frame,
1231                        main_chunks[prompt_line_idx],
1232                        prompt,
1233                        &theme,
1234                    );
1235                }
1236            }
1237        }
1238
1239        // Float-overlay preview: load the selected match's file (if
1240        // the file changed) and seed the phantom leaf's cursor before
1241        // the renderer reaches it. Done before render_prompt_popups
1242        // because that path immediately needs the leaf's view state.
1243        if self
1244            .active_window()
1245            .prompt
1246            .as_ref()
1247            .is_some_and(|p| p.overlay)
1248        {
1249            self.prepare_overlay_preview();
1250        }
1251
1252        // Render file browser popup or suggestions popup AFTER status bar + prompt,
1253        // so they overlay on top of both (fixes bottom border being overwritten by status bar)
1254        self.render_prompt_popups(frame, main_chunks[prompt_line_idx], size.width);
1255
1256        // Render popups from the active buffer state
1257        // Clone theme to avoid borrow checker issues with active_state_mut()
1258        let theme_clone = self.theme.read().unwrap().clone();
1259        let hover_target = self.active_window_mut().mouse_state.hover_target.clone();
1260
1261        // Clear popup areas and recalculate
1262        self.active_chrome_mut().popup_areas.clear();
1263
1264        // Collect popup information without holding a mutable borrow
1265        let popup_info: Vec<_> = {
1266            // Get viewport from active split's SplitViewState
1267            let active_split = self
1268                .windows
1269                .get(&self.active_window)
1270                .and_then(|w| w.buffers.splits())
1271                .map(|(mgr, _)| mgr)
1272                .expect("active window must have a populated split layout")
1273                .active_split();
1274            let viewport = self
1275                .windows
1276                .get(&self.active_window)
1277                .and_then(|w| w.buffers.splits())
1278                .map(|(_, vs)| vs)
1279                .expect("active window must have a populated split layout")
1280                .get(&active_split)
1281                .map(|vs| vs.viewport.clone());
1282
1283            // Get the content_rect for the active split from the cached layout.
1284            // This is the absolute screen rect (already accounts for file explorer,
1285            // tab bar, scrollbars, etc.). The gutter is rendered inside this rect,
1286            // so we add gutter_width to get the text content origin.
1287            let content_rect = self
1288                .active_layout()
1289                .split_areas
1290                .iter()
1291                .find(|(split_id, _, _, _, _, _)| *split_id == active_split)
1292                .map(|(_, _, rect, _, _, _)| *rect);
1293
1294            let primary_cursor = self
1295                .windows
1296                .get(&self.active_window)
1297                .and_then(|w| w.buffers.splits())
1298                .map(|(_, vs)| vs)
1299                .expect("active window must have a populated split layout")
1300                .get(&active_split)
1301                .map(|vs| *vs.cursors.primary());
1302            let state = self.active_state_mut();
1303            if state.popups.is_visible() {
1304                // Get the primary cursor position for popup positioning
1305                let primary_cursor =
1306                    primary_cursor.unwrap_or_else(|| crate::model::cursor::Cursor::new(0));
1307
1308                // Compute gutter width so we know where text content starts
1309                let gutter_width = viewport
1310                    .as_ref()
1311                    .map(|vp| vp.gutter_width(&state.buffer) as u16)
1312                    .unwrap_or(0);
1313
1314                let cursor_screen_pos = viewport
1315                    .as_ref()
1316                    .map(|vp| vp.cursor_screen_position(&mut state.buffer, &primary_cursor))
1317                    .unwrap_or((0, 0));
1318
1319                // For completion popups, compute the word-start screen position so
1320                // the popup aligns with the beginning of the word being completed,
1321                // not the current cursor position.
1322                let word_start_screen_pos = {
1323                    use crate::primitives::word_navigation::find_completion_word_start;
1324                    let word_start =
1325                        find_completion_word_start(&state.buffer, primary_cursor.position);
1326                    let word_start_cursor = crate::model::cursor::Cursor::new(word_start);
1327                    viewport
1328                        .as_ref()
1329                        .map(|vp| vp.cursor_screen_position(&mut state.buffer, &word_start_cursor))
1330                        .unwrap_or((0, 0))
1331                };
1332
1333                // Use content_rect as the single source of truth for the text
1334                // content area origin. content_rect.x is the split's left edge
1335                // (already past the file explorer), content_rect.y is below the
1336                // tab bar. Adding gutter_width gives us the text content start.
1337                let (base_x, base_y) = content_rect
1338                    .map(|r| (r.x + gutter_width, r.y))
1339                    .unwrap_or((gutter_width, 1));
1340
1341                let cursor_screen_pos =
1342                    (cursor_screen_pos.0 + base_x, cursor_screen_pos.1 + base_y);
1343                let word_start_screen_pos = (
1344                    word_start_screen_pos.0 + base_x,
1345                    word_start_screen_pos.1 + base_y,
1346                );
1347
1348                // Collect popup data
1349                state
1350                    .popups
1351                    .all()
1352                    .iter()
1353                    .enumerate()
1354                    .map(|(popup_idx, popup)| {
1355                        // Use word-start x for completion popups, cursor x for others
1356                        let popup_pos = if popup.kind == crate::view::popup::PopupKind::Completion {
1357                            (word_start_screen_pos.0, cursor_screen_pos.1)
1358                        } else {
1359                            cursor_screen_pos
1360                        };
1361                        let popup_area = popup.calculate_area(size, Some(popup_pos));
1362
1363                        // Track popup area for mouse hit testing
1364                        // Account for description height when calculating the list item area
1365                        let desc_height = popup.description_height();
1366                        let inner_area = if popup.bordered {
1367                            ratatui::layout::Rect {
1368                                x: popup_area.x + 1,
1369                                y: popup_area.y + 1 + desc_height,
1370                                width: popup_area.width.saturating_sub(2),
1371                                height: popup_area.height.saturating_sub(2 + desc_height),
1372                            }
1373                        } else {
1374                            ratatui::layout::Rect {
1375                                x: popup_area.x,
1376                                y: popup_area.y + desc_height,
1377                                width: popup_area.width,
1378                                height: popup_area.height.saturating_sub(desc_height),
1379                            }
1380                        };
1381
1382                        let num_items = match &popup.content {
1383                            crate::view::popup::PopupContent::List { items, .. } => items.len(),
1384                            _ => 0,
1385                        };
1386
1387                        // Calculate total content lines and scrollbar rect
1388                        let total_lines = popup.item_count();
1389                        let visible_lines = inner_area.height as usize;
1390                        let scrollbar_rect = if total_lines > visible_lines && inner_area.width > 2
1391                        {
1392                            Some(ratatui::layout::Rect {
1393                                x: inner_area.x + inner_area.width - 1,
1394                                y: inner_area.y,
1395                                width: 1,
1396                                height: inner_area.height,
1397                            })
1398                        } else {
1399                            None
1400                        };
1401
1402                        (
1403                            popup_idx,
1404                            popup_area,
1405                            inner_area,
1406                            popup.scroll_offset,
1407                            num_items,
1408                            scrollbar_rect,
1409                            total_lines,
1410                        )
1411                    })
1412                    .collect()
1413            } else {
1414                Vec::new()
1415            }
1416        };
1417
1418        // Store popup areas for mouse hit testing
1419        self.active_chrome_mut().popup_areas = popup_info.clone();
1420
1421        // Now render popups
1422        let state = self.active_state_mut();
1423        if state.popups.is_visible() {
1424            for (popup_idx, popup) in state.popups.all().iter().enumerate() {
1425                if let Some((_, popup_area, _, _, _, _, _)) = popup_info.get(popup_idx) {
1426                    popup.render_with_hover(
1427                        frame,
1428                        *popup_area,
1429                        &theme_clone,
1430                        hover_target.as_ref(),
1431                    );
1432                }
1433            }
1434        }
1435
1436        // Render editor-level popups (e.g. plugin action popups) on top of any
1437        // buffer content so they stay visible across buffer switches and over
1438        // virtual buffers (Dashboard, diagnostics) that own the whole split.
1439        // These don't need cursor-relative positioning — they all use absolute
1440        // positions like BottomRight or Centered.
1441        //
1442        // Queue semantics: concurrent action popups stack in `global_popups`,
1443        // but only the top one renders & receives input. Deeper popups
1444        // surface as the top is resolved — the alternative (drawing all at
1445        // the same BottomRight slot) makes them illegible.
1446        self.active_chrome_mut().global_popup_areas.clear();
1447        // The workspace-trust prompt is a blocking modal: it renders later in
1448        // the dedicated modal z-band (alongside settings / wizard) on a dimmed
1449        // backdrop, so it can't be lost amongst dashboard/explorer chrome.
1450        // Everything else on the global stack renders here, above buffer content.
1451        let top_is_trust_modal = self.global_popups.top().is_some_and(|p| {
1452            matches!(
1453                p.resolver,
1454                crate::view::popup::PopupResolver::WorkspaceTrust
1455            )
1456        });
1457        if !top_is_trust_modal {
1458            self.render_top_global_popup(frame, size, &theme_clone, hover_target.as_ref());
1459        }
1460
1461        // Render menu bar last so dropdown appears on top of all other content
1462        // Update menu context with current editor state
1463        self.update_menu_context();
1464
1465        // Render settings modal (before menu bar so menus can overlay)
1466        // Check visibility first to avoid borrow conflict with dimming
1467        let settings_visible = self
1468            .settings_state
1469            .as_ref()
1470            .map(|s| s.visible)
1471            .unwrap_or(false);
1472        if settings_visible {
1473            // Dim the editor content behind the settings modal
1474            crate::view::dimming::apply_dimming(frame, size);
1475        }
1476        if let Some(ref mut settings_state) = self.settings_state {
1477            if settings_state.visible {
1478                settings_state.update_focus_states();
1479                let settings_layout = crate::view::settings::render_settings(
1480                    frame,
1481                    size,
1482                    settings_state,
1483                    &*self.theme.read().unwrap(),
1484                );
1485                self.active_chrome_mut().settings_layout = Some(settings_layout);
1486            }
1487        }
1488
1489        // Render calibration wizard if active
1490        if let Some(ref wizard) = self.calibration_wizard {
1491            // Dim the editor content behind the wizard modal
1492            crate::view::dimming::apply_dimming(frame, size);
1493            crate::view::calibration_wizard::render_calibration_wizard(
1494                frame,
1495                size,
1496                wizard,
1497                &*self.theme.read().unwrap(),
1498            );
1499        }
1500
1501        // Render keybinding editor if active
1502        if let Some(ref mut kb_editor) = self.keybinding_editor {
1503            crate::view::dimming::apply_dimming(frame, size);
1504            crate::view::keybinding_editor::render_keybinding_editor(
1505                frame,
1506                size,
1507                kb_editor,
1508                &*self.theme.read().unwrap(),
1509            );
1510        }
1511
1512        // Render event debug dialog if active
1513        if let Some(ref debug) = self.active_window().event_debug {
1514            // Dim the editor content behind the dialog modal
1515            crate::view::dimming::apply_dimming(frame, size);
1516            crate::view::event_debug::render_event_debug(
1517                frame,
1518                size,
1519                debug,
1520                &*self.theme.read().unwrap(),
1521            );
1522        }
1523
1524        // Render the workspace-trust prompt as a blocking modal in the same
1525        // z-band as the settings / wizard modals: dim the whole frame, then
1526        // draw the dialog on top. Placed here (above the generic global-popup
1527        // slot and buffer chrome) so it has strict z-order parity with the
1528        // other modals and can never be obscured by the dashboard/explorer.
1529        let trust_layout = if top_is_trust_modal {
1530            crate::view::dimming::apply_dimming(frame, size);
1531            let selected = self
1532                .global_popups
1533                .top()
1534                .and_then(|p| match &p.content {
1535                    crate::view::popup::PopupContent::List { selected, .. } => Some(*selected),
1536                    _ => None,
1537                })
1538                .unwrap_or(1);
1539            let path = self.working_dir.display().to_string();
1540            let triggers = self.workspace_trust_markers.join(", ");
1541            let secondary_label = if self.workspace_trust_prompt_cancellable {
1542                "Cancel (Esc)".to_string()
1543            } else {
1544                let quit_hint = self.keybindings.read().ok().and_then(|kb| {
1545                    kb.get_keybinding_for_action(
1546                        &crate::input::keybindings::Action::Quit,
1547                        crate::input::keybindings::KeyContext::Normal,
1548                    )
1549                });
1550                match quit_hint {
1551                    Some(k) => format!("Quit ({k})"),
1552                    None => "Quit".to_string(),
1553                }
1554            };
1555            Some(
1556                crate::view::workspace_trust_dialog::render_workspace_trust_dialog(
1557                    frame,
1558                    size,
1559                    selected,
1560                    &path,
1561                    &triggers,
1562                    &secondary_label,
1563                    self.workspace_trust_scroll,
1564                    &theme_clone,
1565                ),
1566            )
1567        } else {
1568            None
1569        };
1570        self.active_chrome_mut().workspace_trust_dialog = trust_layout;
1571
1572        if self.active_window_mut().menu_bar_visible {
1573            // Pre-expand DynamicSubmenu items once per registry; without this
1574            // MenuRenderer::render rescans + reparses every theme JSON file
1575            // on every frame.
1576            self.expanded_menus_cache.update(
1577                &self.theme_registry,
1578                &self.menus,
1579                &self.menu_state.themes_dir,
1580            );
1581            let hover_target = self.active_window().mouse_state.hover_target.clone();
1582            let menu_bar_mnemonics = self.config.editor.menu_bar_mnemonics;
1583            let expanded = self.expanded_menus_cache.get().expect("just updated");
1584            let keybindings = self.keybindings.read().unwrap();
1585            let new_menu_layout = crate::view::ui::MenuRenderer::render(
1586                frame,
1587                menu_bar_area,
1588                expanded,
1589                &self.menu_state,
1590                &keybindings,
1591                &*self.theme.read().unwrap(),
1592                hover_target.as_ref(),
1593                menu_bar_mnemonics,
1594            );
1595            drop(keybindings);
1596            self.active_chrome_mut().menu_layout = Some(new_menu_layout);
1597        } else {
1598            self.active_chrome_mut().menu_layout = None;
1599        }
1600
1601        // Render tab context menu if open
1602        let tab_ctx_menu = self.active_window().tab_context_menu.clone();
1603        if let Some(menu) = tab_ctx_menu {
1604            self.render_tab_context_menu(frame, &menu);
1605        }
1606
1607        let fe_ctx_menu = self.active_window().file_explorer_context_menu.clone();
1608        if let Some(menu) = fe_ctx_menu {
1609            self.render_file_explorer_context_menu(frame, &menu);
1610        }
1611
1612        // Record non-editor region theme keys for the theme inspector
1613        self.record_non_editor_theme_regions();
1614
1615        // Render theme info popup (Ctrl+Right-Click)
1616        self.render_theme_info_popup(frame);
1617
1618        // Render tab drag drop zone overlay if dragging a tab
1619        let drag_state_clone = self.active_window().mouse_state.dragging_tab.clone();
1620        if let Some(ref drag_state) = drag_state_clone {
1621            if drag_state.is_dragging() {
1622                self.render_tab_drop_zone(frame, drag_state);
1623            }
1624        }
1625
1626        // Render software mouse cursor when GPM is active
1627        // GPM can't draw its cursor on the alternate screen buffer used by TUI apps,
1628        // so we draw our own cursor at the tracked mouse position.
1629        // This must happen LAST in the render flow so we can read the already-rendered
1630        // cell content and invert it.
1631        if self.active_window_mut().gpm_active {
1632            if let Some((col, row)) = self.active_window_mut().mouse_cursor_position {
1633                use ratatui::style::Modifier;
1634
1635                // Only render if within screen bounds
1636                if col < size.width && row < size.height {
1637                    // Get the cell at this position and add REVERSED modifier to invert colors
1638                    let buf = frame.buffer_mut();
1639                    if let Some(cell) = buf.cell_mut((col, row)) {
1640                        cell.set_style(cell.style().add_modifier(Modifier::REVERSED));
1641                    }
1642                }
1643            }
1644        }
1645
1646        // When keyboard capture mode is active, dim all UI elements outside the terminal
1647        // to visually indicate that focus is exclusively on the terminal
1648        if self.active_window_mut().keyboard_capture && self.active_window().terminal_mode {
1649            // Find the active split's content area
1650            let active_split = self
1651                .windows
1652                .get(&self.active_window)
1653                .and_then(|w| w.buffers.splits())
1654                .map(|(mgr, _)| mgr)
1655                .expect("active window must have a populated split layout")
1656                .active_split();
1657            let active_split_area = self
1658                .active_layout()
1659                .split_areas
1660                .iter()
1661                .find(|(split_id, _, _, _, _, _)| *split_id == active_split)
1662                .map(|(_, _, content_rect, _, _, _)| *content_rect);
1663
1664            if let Some(terminal_area) = active_split_area {
1665                self.apply_keyboard_capture_dimming(frame, terminal_area);
1666            }
1667        }
1668
1669        // Commit the active-split hardware cursor (deferred since
1670        // `render_content`) unless a popup has been drawn over that cell.
1671        // Ratatui draws the hardware caret on top of every cell, so a
1672        // popup cannot hide the cursor by painting cells — the only way
1673        // to hide it is to leave `Frame::cursor_position` as `None`, which
1674        // triggers `Terminal::hide_cursor` at the end of the draw.
1675        //
1676        // When a prompt is active the prompt renderer already placed the
1677        // caret on the prompt line via `frame.set_cursor_position`; don't
1678        // override it with the (now-irrelevant) buffer cursor.
1679        if let Some((cx, cy)) = pending_hardware_cursor {
1680            if self.active_window().prompt.is_none() && !self.cursor_obscured_by_overlay(cx, cy) {
1681                frame.set_cursor_position((cx, cy));
1682            }
1683        }
1684
1685        // Convert all colors for terminal capability (256/16 color fallback)
1686        crate::view::color_support::convert_buffer_colors(
1687            frame.buffer_mut(),
1688            self.color_capability,
1689        );
1690
1691        // Frame-buffer animations run last so they mutate the final paint.
1692        self.active_window_mut()
1693            .animations
1694            .apply_all(frame.buffer_mut());
1695
1696        // Floating widget panel is drawn last so it sits above every
1697        // other layer (prompts, popups, animations).
1698        if self.floating_widget_panel.is_some() {
1699            let frame_area = frame.area();
1700            self.render_floating_widget_panel(frame, frame_area);
1701        }
1702    }
1703
1704    /// Compare the hardware cursor's screen position to the previous frame's
1705    /// and, if it moved by more than the "jump" threshold, start a
1706    /// `CursorJump` animation from the old to the new on-screen position.
1707    /// Successive jumps cancel the prior animation so trail effects don't
1708    /// pile up.
1709    ///
1710    /// Cross-split and cross-buffer transitions (focus change, tab switch)
1711    /// are also animated — the trail crosses pane separators on its way
1712    /// from one buffer's cursor cell to another's.
1713    ///
1714    /// The threshold is intentionally generous: arrow-key/typing moves
1715    /// (small `dx`/`dy`) must NOT trigger the animation, but search jumps,
1716    /// goto-line/definition, and pane switches (which always cross several
1717    /// rows or many columns) must.
1718    fn maybe_start_cursor_jump_animation(
1719        &mut self,
1720        current_pos: Option<(u16, u16)>,
1721        active_split: crate::model::event::LeafId,
1722    ) {
1723        // Honour the global animations toggle. Tests default to
1724        // `animations = false` so single-tick `render()` calls observe the
1725        // settled buffer instead of a mid-flight trail; users can also
1726        // disable animations entirely from config. The dedicated
1727        // `cursor_jump_animation` toggle suppresses just the cursor-jump
1728        // trail while leaving ambient animations (tab slides, dashboard,
1729        // plugin effects) running.
1730        if !self.config.editor.animations || !self.config.editor.cursor_jump_animation {
1731            self.previous_cursor_screen_pos = current_pos.map(|p| (p, active_split));
1732            return;
1733        }
1734
1735        let Some(current) = current_pos else {
1736            // Cursor is hidden this frame (e.g. prompt has focus). Reset the
1737            // tracker so the re-emerging cursor doesn't animate from a stale
1738            // spot when focus returns to a buffer.
1739            self.previous_cursor_screen_pos = None;
1740            return;
1741        };
1742
1743        let prev_entry = self.previous_cursor_screen_pos;
1744        // Update tracking unconditionally for the next frame.
1745        self.previous_cursor_screen_pos = Some((current, active_split));
1746
1747        let Some((prev, prev_split)) = prev_entry else {
1748            return;
1749        };
1750        if prev == current && prev_split == active_split {
1751            return;
1752        }
1753
1754        let dx = (current.0 as i32 - prev.0 as i32).abs();
1755        let dy = (current.1 as i32 - prev.1 as i32).abs();
1756        // Animate when the cursor crossed split panes, or when it made a
1757        // non-incremental move within the same pane: more than two rows
1758        // vertically, or — for moves that stay within ±2 rows — at
1759        // least 80 columns horizontally. The horizontal threshold is
1760        // generous because typing, arrow keys, word-jump, and Home/End
1761        // on long source lines can all exceed a smaller bound without
1762        // being a genuine "jump".
1763        let crossed_panes = prev_split != active_split;
1764        let row_jump = dy > 2;
1765        let col_jump = dx >= 80;
1766        if !crossed_panes && !row_jump && !col_jump {
1767            return;
1768        }
1769
1770        // Cancel any prior cursor-jump animation so trails don't stack.
1771        if let Some(prev_anim) = self.cursor_jump_animation.take() {
1772            self.active_window_mut().animations.cancel(prev_anim);
1773        }
1774
1775        let cursor_color = self.theme.read().unwrap().cursor;
1776        let bg_color = self.theme.read().unwrap().editor_bg;
1777        let id = self.active_window_mut().animations.start(
1778            // The bounding box is for runner bookkeeping only — CursorJump
1779            // paints at absolute screen coords and ignores `area`.
1780            ratatui::layout::Rect {
1781                x: prev.0.min(current.0),
1782                y: prev.1.min(current.1),
1783                width: dx as u16 + 1,
1784                height: dy as u16 + 1,
1785            },
1786            crate::view::animation::AnimationKind::CursorJump {
1787                from: prev,
1788                to: current,
1789                duration: std::time::Duration::from_millis(140),
1790                cursor_color,
1791                bg_color,
1792            },
1793        );
1794        self.cursor_jump_animation = Some(id);
1795    }
1796
1797    /// Returns true if `(x, y)` falls inside any popup-style overlay that
1798    /// was rendered this frame. Used to decide whether the hardware cursor
1799    /// should be shown or hidden so it does not bleed through a popup.
1800    fn cursor_obscured_by_overlay(&self, x: u16, y: u16) -> bool {
1801        let inside = |rect: ratatui::layout::Rect| -> bool {
1802            x >= rect.x
1803                && x < rect.x.saturating_add(rect.width)
1804                && y >= rect.y
1805                && y < rect.y.saturating_add(rect.height)
1806        };
1807
1808        if self
1809            .active_chrome()
1810            .popup_areas
1811            .iter()
1812            .any(|entry| inside(entry.1))
1813        {
1814            return true;
1815        }
1816        if self
1817            .active_chrome()
1818            .global_popup_areas
1819            .iter()
1820            .any(|entry| inside(entry.1))
1821        {
1822            return true;
1823        }
1824        if let Some((rect, _, _, _)) = self.active_chrome().suggestions_area {
1825            if inside(rect) {
1826                return true;
1827            }
1828        }
1829        if let Some(ref fb) = self.active_window().file_browser_layout {
1830            if inside(fb.popup_area) {
1831                return true;
1832            }
1833        }
1834        false
1835    }
1836
1837    /// Render the Quick Open hints line showing available mode prefixes
1838    fn render_quick_open_hints(
1839        frame: &mut Frame,
1840        area: ratatui::layout::Rect,
1841        theme: &crate::view::theme::Theme,
1842    ) {
1843        use ratatui::style::{Modifier, Style};
1844        use ratatui::text::{Line, Span};
1845        use ratatui::widgets::Paragraph;
1846        use rust_i18n::t;
1847
1848        let hints_style = Style::default()
1849            .fg(theme.line_number_fg)
1850            .bg(theme.suggestion_selected_bg)
1851            .add_modifier(Modifier::DIM);
1852        let hints_text = t!("quick_open.mode_hints");
1853        // Left-align with small margin
1854        let left_margin = 2;
1855        let hints_width = crate::primitives::display_width::str_width(&hints_text);
1856        let mut spans = Vec::new();
1857        spans.push(Span::styled(" ".repeat(left_margin), hints_style));
1858        spans.push(Span::styled(hints_text.to_string(), hints_style));
1859        let remaining = (area.width as usize).saturating_sub(left_margin + hints_width);
1860        spans.push(Span::styled(" ".repeat(remaining), hints_style));
1861
1862        let paragraph = Paragraph::new(Line::from(spans));
1863        frame.render_widget(paragraph, area);
1864    }
1865
1866    /// Apply dimming effect to UI elements outside the focused terminal area
1867    /// This visually indicates that keyboard capture mode is active
1868    fn apply_keyboard_capture_dimming(
1869        &self,
1870        frame: &mut Frame,
1871        terminal_area: ratatui::layout::Rect,
1872    ) {
1873        let size = frame.area();
1874        crate::view::dimming::apply_dimming_excluding(frame, size, Some(terminal_area));
1875    }
1876
1877    /// Render file browser or suggestions popup as overlay above the prompt line.
1878    /// Called after status bar + prompt so the popup draws on top of both.
1879    fn render_prompt_popups(
1880        &mut self,
1881        frame: &mut Frame,
1882        prompt_area: ratatui::layout::Rect,
1883        width: u16,
1884    ) {
1885        let Some(prompt) = &self.active_window_mut().prompt else {
1886            return;
1887        };
1888
1889        // Overlay prompts (Live Grep, issue #1796) get a dedicated
1890        // centred floating frame instead of the bottom-anchored popup.
1891        if prompt.overlay {
1892            let frame_area = frame.area();
1893            self.render_overlay_prompt(frame, frame_area);
1894            return;
1895        }
1896
1897        if matches!(
1898            prompt.prompt_type,
1899            PromptType::OpenFile | PromptType::SwitchProject | PromptType::SaveFileAs
1900        ) {
1901            let hover_target = self.active_window().mouse_state.hover_target.clone();
1902            let theme = self.theme.read().unwrap().clone();
1903            let keybindings = self.keybindings.read().unwrap();
1904            let kb_clone = keybindings.clone();
1905            drop(keybindings);
1906            let max_height = prompt_area.y.saturating_sub(1).min(20);
1907            let popup_area = ratatui::layout::Rect {
1908                x: 0,
1909                y: prompt_area.y.saturating_sub(max_height),
1910                width,
1911                height: max_height,
1912            };
1913            let __win = self.active_window_mut();
1914            let Some(file_open_state) = &mut __win.file_open_state else {
1915                return;
1916            };
1917            __win.file_browser_layout = crate::view::ui::FileBrowserRenderer::render(
1918                frame,
1919                popup_area,
1920                file_open_state,
1921                &theme,
1922                &hover_target,
1923                Some(&kb_clone),
1924            );
1925            return;
1926        }
1927
1928        if prompt.suggestions.is_empty() {
1929            return;
1930        }
1931
1932        let suggestion_count = prompt.suggestions.len().min(10);
1933        let is_quick_open = prompt.prompt_type == crate::view::prompt::PromptType::QuickOpen;
1934        let hints_height: u16 = if is_quick_open { 1 } else { 0 };
1935        let height = suggestion_count as u16 + 2 + hints_height;
1936
1937        let suggestions_area = ratatui::layout::Rect {
1938            x: 0,
1939            y: prompt_area.y.saturating_sub(height),
1940            width,
1941            height: height - hints_height,
1942        };
1943
1944        frame.render_widget(ratatui::widgets::Clear, suggestions_area);
1945
1946        // Adjust the prompt's scroll position to keep the selected item
1947        // visible, scrolling the minimum amount required.
1948        if let Some(prompt) = self.active_window_mut().prompt.as_mut() {
1949            prompt.ensure_selected_visible();
1950        }
1951        let Some(prompt) = &self.active_window().prompt else {
1952            return;
1953        };
1954
1955        let new_suggestions_area = SuggestionsRenderer::render_with_hover(
1956            frame,
1957            suggestions_area,
1958            prompt,
1959            &*self.theme.read().unwrap(),
1960            self.active_window().mouse_state.hover_target.as_ref(),
1961            true,
1962        );
1963        let chrome = self.active_chrome_mut();
1964        chrome.suggestions_area = new_suggestions_area;
1965        if chrome.suggestions_area.is_some() {
1966            chrome.suggestions_outer_area = Some(suggestions_area);
1967        }
1968
1969        if is_quick_open {
1970            let hints_area = ratatui::layout::Rect {
1971                x: 0,
1972                y: prompt_area.y.saturating_sub(hints_height),
1973                width,
1974                height: hints_height,
1975            };
1976            frame.render_widget(ratatui::widgets::Clear, hints_area);
1977            Self::render_quick_open_hints(frame, hints_area, &*self.theme.read().unwrap());
1978        }
1979    }
1980
1981    /// Resolve the overlay's currently-selected match into a real
1982    /// `Buffer` parked in a phantom `LeafId`, so the preview pane can
1983    /// reuse the regular per-leaf renderer (with syntax highlighting,
1984    /// gutter, scrollbars, folding). No-op when the prompt has no
1985    /// selection or its label is not a `path:line[:col]` triple.
1986    /// Render the entire stashed split tree of `self.preview_window_id`
1987    /// into `inner` — Primitive #1 of
1988    /// `docs/internal/orchestrator-sessions-design.md`'s "Rich
1989    /// Control Room rendering". Reuses the editor's existing
1990    /// `render_content` path against the previewed session's
1991    /// stashed `(SplitManager, view_states)` so syntax
1992    /// highlighting, terminal grids, decorations, and folding
1993    /// all surface natively in the preview pane.
1994    ///
1995    /// The previewed session's splits stash is `take`n out for
1996    /// the duration of the call (so we can pass `&mut` through
1997    /// the renderer without re-entering `self.windows`) and put
1998    /// back after. `pending_hardware_cursor` and
1999    /// `cell_theme_map` use scratch locals so the active editor
2000    /// area's hit-testing isn't clobbered by the preview pass.
2001    fn render_session_preview_into_rect(
2002        &mut self,
2003        frame: &mut ratatui::Frame,
2004        inner: ratatui::layout::Rect,
2005        theme: &crate::view::theme::Theme,
2006    ) {
2007        let Some(sid) = self.preview_window_id else {
2008            return;
2009        };
2010
2011        // Terminal grid → buffer text "sync" was previously a
2012        // multi-step append/reload/truncate dance that mutated the
2013        // backing file on every preview-render frame just to make
2014        // the live screen visible inside the embed. That worked
2015        // around `render_terminal_splits` being hard-coded to the
2016        // active window's `terminal_buffers` map — during preview
2017        // the active window is the *caller's* session, so the
2018        // overlay couldn't find the previewed terminal.
2019        //
2020        // `render_terminal_splits` is now an `impl Window` method,
2021        // so the preview path can ask the previewed window
2022        // directly. The overlay paints the live PTY grid (with
2023        // colors, attributes, no cursor) on top of `SplitRenderer`'s
2024        // text rendering for every terminal buffer in the embed —
2025        // no file mutation, no reload, no truncate. The buffer's
2026        // backing file stays untouched between frames.
2027
2028        // Pull the previewed window's split stash and sub-fields
2029        // out under one `&mut Window` borrow. Multiple disjoint
2030        // sub-borrows (`buffers`, `event_logs`, `splits`) coexist
2031        // on the same `Window`, so the renderer call can take all
2032        // three by `&mut` while the rest of `&mut self` stays
2033        // available for `composite_buffers` / `config` / etc.
2034        //
2035        // Step 0h: previously this used `splits.take()` + restore
2036        // because the inline-borrow patterns elsewhere couldn't
2037        // co-exist with a held `&mut sid.splits`. Now that all
2038        // per-window state lives on `Window`, we destructure
2039        // `splits.as_mut()` directly — no transient swap, no
2040        // side-effect plumbing — matching design Primitive #1.
2041        // Bail if the session has no stash yet (never been
2042        // activated and never had a terminal / file routed in via
2043        // createTerminal({windowId})), or has been closed under us
2044        // — e.g. an Orchestrator Archive / Delete completes between
2045        // the floating panel's spec being rebuilt and the next
2046        // render, so the embed's `windowId` momentarily points to
2047        // a window the host already removed. Early-return rather
2048        // than panic; the next plugin refresh re-emits the spec
2049        // without the dead embed.
2050        let Some(__win_for_preview) = self.windows.get_mut(&sid) else {
2051            return;
2052        };
2053        let __preview_metadata = &__win_for_preview.buffer_metadata;
2054        let __preview_event_logs = &mut __win_for_preview.event_logs;
2055        let __preview_composite_buffers = &mut __win_for_preview.composite_buffers;
2056        let __preview_composite_view_states = &mut __win_for_preview.composite_view_states;
2057        // Issue #2035: pass the previewed window's actual
2058        // `grouped_subtrees` map. The previous code allocated an
2059        // empty HashMap here, which made the split renderer unable
2060        // to resolve any `active_group_tab` to its panel layout —
2061        // so a session whose active tab was a buffer group (e.g.
2062        // git_log's log/detail panels) silently fell through to
2063        // rendering the split's underlying pre-group buffer.
2064        let __preview_grouped_subtrees = &__win_for_preview.grouped_subtrees;
2065        let preview_tab_bar_visible = __win_for_preview.tab_bar_visible;
2066
2067        // Per-call scratch — keeps the preview pass from
2068        // clobbering the active editor area's hit-testing /
2069        // hardware-cursor placement.
2070        let mut scratch_cell_theme_map: Vec<crate::app::types::CellThemeInfo> = Vec::new();
2071        let mut scratch_pending_cursor: Option<(u16, u16)> = None;
2072        let lsp_waiting = false; // preview never shows LSP-waiting chrome
2073
2074        let mut preview_split_areas: Vec<(
2075            crate::model::event::LeafId,
2076            fresh_core::BufferId,
2077            ratatui::layout::Rect,
2078            ratatui::layout::Rect,
2079            usize,
2080            usize,
2081        )> = Vec::new();
2082        __win_for_preview
2083            .buffers
2084            .with_all_mut(|preview_buffers, mgr, view_states| {
2085                let result = crate::view::ui::SplitRenderer::render_content(
2086                    frame,
2087                    inner,
2088                    &*mgr,
2089                    preview_buffers,
2090                    __preview_metadata,
2091                    __preview_event_logs,
2092                    __preview_composite_buffers,
2093                    __preview_composite_view_states,
2094                    theme,
2095                    self.ansi_background.as_ref(),
2096                    self.background_fade,
2097                    lsp_waiting,
2098                    self.config.editor.large_file_threshold_bytes,
2099                    self.config.editor.line_wrap,
2100                    self.config.editor.estimated_line_length,
2101                    self.config.editor.highlight_context_bytes,
2102                    Some(view_states),
2103                    __preview_grouped_subtrees,
2104                    true, // hide_cursor — the active session owns the hardware caret
2105                    None, // no tab-hover routing in the preview
2106                    None,
2107                    None,
2108                    false, // not maximized
2109                    self.config.editor.relative_line_numbers,
2110                    preview_tab_bar_visible,
2111                    self.config.editor.use_terminal_bg,
2112                    self.session_mode || !self.software_cursor_only,
2113                    self.software_cursor_only,
2114                    // Scrollbars are noisy in a small preview rect; the
2115                    // active session's chrome is the source of truth.
2116                    false,
2117                    false,
2118                    self.config.editor.diagnostics_inline_text,
2119                    false, // hide tilde markers in the preview
2120                    self.config.editor.highlight_current_column,
2121                    &mut scratch_cell_theme_map,
2122                    inner.width,
2123                    &mut scratch_pending_cursor,
2124                );
2125                preview_split_areas = result.0;
2126            });
2127
2128        // Resize the previewed window's terminal PTYs to fit the
2129        // preview embed before painting their grids. Without this,
2130        // the PTY child (e.g. `top`, `htop`, `vim`, claude) keeps
2131        // drawing at the dimensions it had when last active — often
2132        // the full terminal height — so the preview embed only
2133        // shows the top slice of a much taller frame. Resizing
2134        // SIGWINCHes the PTY, which redraws at the new size, and
2135        // the next render frame paints the correctly-sized grid.
2136        // When the user dives into the session,
2137        // `Window::resize_visible_terminals` will resize back up to
2138        // the dive view's split rect.
2139        if let Some(win) = self.windows.get_mut(&sid) {
2140            for (_split_id, buffer_id, content_rect, _scrollbar_rect, _, _) in &preview_split_areas
2141            {
2142                if win.terminal_buffers.contains_key(buffer_id)
2143                    && content_rect.width > 0
2144                    && content_rect.height > 0
2145                {
2146                    win.resize_terminal(*buffer_id, content_rect.width, content_rect.height);
2147                }
2148            }
2149        }
2150
2151        // Overlay live PTY grids for terminal buffers in the
2152        // previewed window's splits — paints colors, attributes,
2153        // and the visible screen on top of `SplitRenderer`'s text
2154        // rendering. `cursor_visible_if_active = false` keeps the
2155        // preview read-only: no blinking cursor over a session
2156        // the user isn't currently driving.
2157        if let Some(win) = self.windows.get(&sid) {
2158            win.render_terminal_splits(frame, &preview_split_areas, false);
2159        }
2160    }
2161
2162    fn prepare_overlay_preview(&mut self) {
2163        use crate::input::quick_open::parse_path_line_col;
2164
2165        let (path_str, line, col) = {
2166            let Some(prompt) = self.active_window().prompt.as_ref() else {
2167                return;
2168            };
2169            let Some(idx) = prompt.selected_suggestion else {
2170                return;
2171            };
2172            let Some(s) = prompt.suggestions.get(idx) else {
2173                return;
2174            };
2175            // Suggestions emitted by the Finder library use `value` as
2176            // an opaque index; the parseable label lives in `text`.
2177            // Resume-replay is the inverse: `value` carries the full
2178            // path:line:col triple.
2179            let from_text = parse_path_line_col(&s.text);
2180            if !from_text.0.is_empty() && from_text.1.is_some() {
2181                from_text
2182            } else if let Some(v) = s.value.as_deref() {
2183                parse_path_line_col(v)
2184            } else {
2185                from_text
2186            }
2187        };
2188        if path_str.is_empty() {
2189            return;
2190        }
2191        let line = line.unwrap_or(1).saturating_sub(1);
2192        let col = col.unwrap_or(1).saturating_sub(1);
2193
2194        // Resolve relative to the working directory.
2195        let path_buf = std::path::PathBuf::from(&path_str);
2196        let abs_path = if path_buf.is_absolute() {
2197            path_buf
2198        } else {
2199            self.working_dir.join(&path_buf)
2200        };
2201        // Canonicalize for buffer-dedup parity with open_file_no_focus.
2202        let abs_path = self
2203            .authority
2204            .filesystem
2205            .canonicalize(&abs_path)
2206            .unwrap_or(abs_path);
2207
2208        // If the standalone state already targets this path, just
2209        // re-seed the cursor and skip the file-load roundtrip.
2210        let already_target = self
2211            .active_window()
2212            .overlay_preview_state
2213            .as_ref()
2214            .is_some_and(|st| {
2215                self.windows
2216                    .get(&self.active_window)
2217                    .map(|w| &w.buffers)
2218                    .expect("active window present")
2219                    .get(&st.buffer_id)
2220                    .and_then(|s| s.buffer.file_path())
2221                    .is_some_and(|p| p == abs_path.as_path())
2222            });
2223
2224        let buffer_id = if already_target {
2225            self.active_window_mut()
2226                .overlay_preview_state
2227                .as_ref()
2228                .unwrap()
2229                .buffer_id
2230        } else {
2231            // Snapshot whether this path was already known so we can
2232            // tell "I just loaded it for preview" from "the user had
2233            // it open" — only the former gets cleaned up on close.
2234            let was_open = self
2235                .buffers()
2236                .iter()
2237                .any(|(_, s)| s.buffer.file_path() == Some(abs_path.as_path()));
2238            // Capture the active split so we can undo the side
2239            // effects of `open_file_no_focus` (it adds the buffer to
2240            // the active split's tabs and may switch its active
2241            // buffer to the loaded file).
2242            let source_split = self
2243                .windows
2244                .get(&self.active_window)
2245                .and_then(|w| w.buffers.splits())
2246                .map(|(mgr, _)| mgr)
2247                .expect("active window must have a populated split layout")
2248                .active_split();
2249            // `open_file_for_preview` always allocates a fresh buffer
2250            // — never repurposes the "no name" empty buffer the user
2251            // is currently looking at — so the background view stays
2252            // intact while we cycle through preview results.
2253            let buffer_id = match self.open_file_for_preview(abs_path.as_path()) {
2254                Ok(id) => id,
2255                Err(_e) => return,
2256            };
2257            if !was_open {
2258                if let Some(meta) = self.active_window_mut().buffer_metadata.get_mut(&buffer_id) {
2259                    meta.hidden_from_tabs = true;
2260                }
2261                // Drop the buffer from every split's `open_buffers`
2262                // list so it doesn't surface as a tab anywhere. The
2263                // phantom buffer is rendered exclusively via the
2264                // overlay's standalone view-state — it doesn't need
2265                // to be in `open_buffers`.
2266                let leaf_ids: Vec<_> = self
2267                    .windows
2268                    .get(&self.active_window)
2269                    .and_then(|w| w.buffers.splits())
2270                    .map(|(_, vs)| vs)
2271                    .expect("active window must have a populated split layout")
2272                    .keys()
2273                    .copied()
2274                    .collect();
2275                for leaf_id in leaf_ids {
2276                    if let Some(view_state) = self
2277                        .windows
2278                        .get_mut(&self.active_window)
2279                        .and_then(|w| w.split_view_states_mut())
2280                        .expect("active window must have a populated split layout")
2281                        .get_mut(&leaf_id)
2282                    {
2283                        view_state.remove_buffer(buffer_id);
2284                    }
2285                }
2286                // open_file_no_focus may have switched the active
2287                // buffer of the source split. Restore it.
2288                let preview_loaded: std::collections::HashSet<BufferId> = self
2289                    .active_window_mut()
2290                    .overlay_preview_state
2291                    .as_ref()
2292                    .map(|st| st.loaded_buffers.clone())
2293                    .unwrap_or_default();
2294                let __active_id = self.active_window;
2295                let __win = self
2296                    .windows
2297                    .get_mut(&__active_id)
2298                    .expect("active window must exist");
2299                let __buffer_keys: Vec<BufferId> = __win.buffers.ids();
2300                let (__mgr, __vs_map) = __win
2301                    .buffers
2302                    .splits_mut()
2303                    .expect("active window must have a populated split layout");
2304                if let Some(source_state) = __vs_map.get_mut(&source_split) {
2305                    if source_state.active_buffer == buffer_id {
2306                        let fallback = source_state
2307                            .open_buffers
2308                            .iter()
2309                            .find_map(|t| t.as_buffer())
2310                            .or_else(|| {
2311                                __buffer_keys
2312                                    .iter()
2313                                    .copied()
2314                                    .find(|b| *b != buffer_id && !preview_loaded.contains(b))
2315                            });
2316                        if let Some(fb) = fallback {
2317                            source_state.switch_buffer(fb);
2318                            __mgr.set_split_buffer(source_split, fb);
2319                        }
2320                    }
2321                }
2322                self.windows
2323                    .get_mut(&self.active_window)
2324                    .and_then(|w| w.split_manager_mut())
2325                    .expect("active window must have a populated split layout")
2326                    .set_active_split(source_split);
2327            }
2328            buffer_id
2329        };
2330
2331        // Build (or update) the standalone preview state. Held off
2332        // `split_view_states` so cross-cutting iteration never touches
2333        // it.
2334        let need_init = self.active_window_mut().overlay_preview_state.is_none();
2335        if need_init {
2336            let mut view_state = crate::view::split::SplitViewState::with_buffer(
2337                self.terminal_width,
2338                self.terminal_height,
2339                buffer_id,
2340            );
2341            view_state.apply_config_defaults(
2342                self.config.editor.line_numbers,
2343                self.config.editor.highlight_current_line,
2344                self.active_window().resolve_line_wrap_for_buffer(buffer_id),
2345                self.config.editor.wrap_indent,
2346                self.active_window()
2347                    .resolve_wrap_column_for_buffer(buffer_id),
2348                self.config.editor.rulers.clone(),
2349            );
2350            let mut loaded_buffers = std::collections::HashSet::new();
2351            // Whether this *first* preview buffer was newly loaded.
2352            // The pre-existing case skips the `was_open` branch so
2353            // we re-derive it from buffer_metadata: a buffer with
2354            // hidden_from_tabs=true that we just touched is one we
2355            // owned. Simpler: track via the existing-target check:
2356            // if `already_target` was false above, the buffer was
2357            // either pre-open (we left meta alone) or freshly
2358            // loaded (we set hidden_from_tabs=true). Re-check.
2359            if let Some(meta) = self.active_window().buffer_metadata.get(&buffer_id) {
2360                if meta.hidden_from_tabs {
2361                    loaded_buffers.insert(buffer_id);
2362                }
2363            }
2364            self.active_window_mut().overlay_preview_state =
2365                Some(crate::app::types::OverlayPreviewState {
2366                    buffer_id,
2367                    view_state,
2368                    loaded_buffers,
2369                });
2370        } else {
2371            // Pre-compute hidden flag (immutable borrow on self.windows)
2372            // before taking the mutable borrow on overlay_preview_state.
2373            let hidden_from_tabs = self
2374                .windows
2375                .get(&self.active_window)
2376                .and_then(|w| w.buffer_metadata.get(&buffer_id))
2377                .is_some_and(|meta| meta.hidden_from_tabs);
2378            if let Some(state) = self.active_window_mut().overlay_preview_state.as_mut() {
2379                if state.buffer_id != buffer_id {
2380                    state.view_state.switch_buffer(buffer_id);
2381                    if hidden_from_tabs {
2382                        state.loaded_buffers.insert(buffer_id);
2383                    }
2384                }
2385            }
2386        }
2387
2388        // Set the cursor to the match position and centre the line.
2389        let byte_offset = self
2390            .buffers()
2391            .get(&buffer_id)
2392            .map(|s| {
2393                s.buffer
2394                    .position_to_offset(crate::model::piece_tree::Position { line, column: col })
2395            })
2396            .unwrap_or(0);
2397        let line_start = self
2398            .buffers()
2399            .get(&buffer_id)
2400            .and_then(|s| s.buffer.line_start_offset(line))
2401            .unwrap_or(byte_offset);
2402        // Compute top_byte BEFORE taking the mutable borrow on
2403        // overlay_preview_state to keep the borrows disjoint.
2404        let h_for_preview = self
2405            .active_window_mut()
2406            .overlay_preview_state
2407            .as_ref()
2408            .map(|s| s.view_state.viewport.height.max(1) as usize)
2409            .unwrap_or(1);
2410        let half = h_for_preview / 2;
2411        let target_top_line = line.saturating_sub(half);
2412        let top_byte = self
2413            .windows
2414            .get(&self.active_window)
2415            .map(|w| &w.buffers)
2416            .expect("active window present")
2417            .get(&buffer_id)
2418            .and_then(|s| s.buffer.line_start_offset(target_top_line))
2419            .unwrap_or(line_start);
2420        if let Some(state) = self.active_window_mut().overlay_preview_state.as_mut() {
2421            state.view_state.cursors.primary_mut().position = byte_offset;
2422            state.view_state.viewport.top_byte = top_byte;
2423        }
2424    }
2425
2426    /// Render the active prompt as a centred floating overlay
2427    /// (issue #1796). Layout, top-down inside the overlay frame:
2428    ///
2429    /// ```text
2430    /// ┌─ Live Grep ──────────────────────────────────[Esc to close]┐
2431    /// │ Search: split_active|                           12 / 142    │  ← input row
2432    /// │ ─────────────────────────────────────────────────────────── │
2433    /// │  src/view/split.rs:1117  pub fn split_active(    │ preview │  ← results
2434    /// │  src/view/split.rs:1123  self.split_active_pos…  │  pane   │     (+ optional
2435    /// │ …                                                │         │      preview)
2436    /// └────────────────────────────────────────────────────────────┘
2437    /// ```
2438    ///
2439    /// The overlay does *not* mutate the split tree; it is a pure
2440    /// `ratatui` overdraw, so dismissing leaves the user's underlying
2441    /// layout exactly as it was (the issue-#1796 acceptance test).
2442    fn render_overlay_prompt(&mut self, frame: &mut Frame, area: ratatui::layout::Rect) {
2443        use ratatui::layout::Rect;
2444        use ratatui::style::{Modifier, Style};
2445        use ratatui::text::{Line, Span};
2446        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
2447
2448        // Compute the overlay rect via the same percentage logic the
2449        // popup engine uses. 80% × 80% of the terminal, centred.
2450        let overlay_rect = Self::centered_overlay_rect(area, 80, 80);
2451
2452        // Snapshot view-relevant state before any mutable borrows.
2453        let theme = self.theme.read().unwrap().clone();
2454        // The suggestion list inside the overlay can be ~30 rows
2455        // tall on a typical terminal. Pass the *actual* visible
2456        // count to `ensure_selected_visible_within` so the scroll
2457        // offset only advances when the selection genuinely passes
2458        // the bottom of the visible window — not when it crosses
2459        // the bottom-popup default cap of `MAX_VISIBLE_SUGGESTIONS`
2460        // (= 10), which would scroll prematurely.
2461        //
2462        // Geometry: overlay frame border (2) + input row (1) +
2463        // optional toolbar row (1, when `prompt.title` is non-empty)
2464        // + separator (1). The suggestions popup is rendered
2465        // borderless inside the overlay (the outer frame already
2466        // provides a border, so adding a nested one creates a
2467        // double-frame). Inner content height = overlay.height -
2468        // chrome.
2469        let toolbar_visible = self
2470            .active_window()
2471            .prompt
2472            .as_ref()
2473            .map(|p| !p.title.is_empty())
2474            .unwrap_or(false);
2475        let chrome_rows: usize = 4 + if toolbar_visible { 1 } else { 0 };
2476        let suggestions_visible_rows = (overlay_rect.height as usize).saturating_sub(chrome_rows);
2477        if let Some(prompt) = self.active_window_mut().prompt.as_mut() {
2478            prompt.ensure_selected_visible_within(suggestions_visible_rows);
2479        }
2480        let Some(prompt) = self.active_window().prompt.as_ref() else {
2481            return;
2482        };
2483        let prompt = prompt.clone();
2484
2485        // Dim everything outside the overlay rect so the user's
2486        // focus visibly belongs to the popup. Reuses the same RGB-
2487        // darkening pass the Settings modal uses (`view::dimming`)
2488        // — Modifier::DIM alone is barely visible on most terminals.
2489        crate::view::dimming::apply_dimming_excluding(frame, frame.area(), Some(overlay_rect));
2490
2491        // Clear and frame. Plugin-owned prompts can publish their
2492        // own title via `editor.setPromptTitle(...)`; falls back to
2493        // " Live Grep " plus shortcut hints when unset (so a
2494        // Resume-replay prompt and freshly-opened plugin prompt look
2495        // similar even though they take different code paths).
2496        frame.render_widget(Clear, overlay_rect);
2497        let default_title: Vec<fresh_core::api::StyledText> = {
2498            // Mirrors `updateOverlayTitle` in live_grep.ts (kept in
2499            // sync deliberately so a Resume-replay overlay and a
2500            // freshly-opened plugin overlay look identical). The
2501            // input row's prefix already says "Live grep:", so the
2502            // frame title doesn't repeat the feature name — it
2503            // shows shortcut hints only. `resume_live_grep` is
2504            // intentionally NOT shown here; that shortcut only
2505            // matters once the overlay is closed.
2506            use crate::input::keybindings::KeyContext;
2507            use fresh_core::api::{OverlayColorSpec, OverlayOptions, StyledText};
2508            let keybindings = self.keybindings.read().unwrap();
2509            let mut hints: Vec<(String, &str)> = Vec::new();
2510            if let Some(k) = keybindings
2511                .find_keybinding_for_action("cycle_live_grep_provider", KeyContext::Prompt)
2512            {
2513                hints.push((k, "switch grep provider"));
2514            }
2515            if let Some(k) = keybindings
2516                .find_keybinding_for_action("live_grep_export_quickfix", KeyContext::Prompt)
2517            {
2518                hints.push((k, "save matches"));
2519            }
2520            if hints.is_empty() {
2521                Vec::new()
2522            } else {
2523                let hint_style = Some(OverlayOptions {
2524                    fg: Some(OverlayColorSpec::ThemeKey("ui.help_key_fg".into())),
2525                    ..OverlayOptions::default()
2526                });
2527                let sep_style = Some(OverlayOptions {
2528                    fg: Some(OverlayColorSpec::ThemeKey("ui.popup_border_fg".into())),
2529                    ..OverlayOptions::default()
2530                });
2531                let mut segs: Vec<StyledText> = Vec::new();
2532                for (i, (k, verb)) in hints.into_iter().enumerate() {
2533                    if i > 0 {
2534                        segs.push(StyledText {
2535                            text: " · ".into(),
2536                            style: sep_style.clone(),
2537                        });
2538                    }
2539                    segs.push(StyledText {
2540                        text: k,
2541                        style: hint_style.clone(),
2542                    });
2543                    segs.push(StyledText {
2544                        text: format!(" {verb}"),
2545                        style: None,
2546                    });
2547                }
2548                segs
2549            }
2550        };
2551        let title_segs: &[fresh_core::api::StyledText] = if prompt.title.is_empty() {
2552            &default_title
2553        } else {
2554            &prompt.title
2555        };
2556        let normal_title_style = Style::default()
2557            .fg(theme.prompt_fg)
2558            .add_modifier(Modifier::BOLD);
2559        let title_spans: Vec<Span> = title_segs
2560            .iter()
2561            .map(|seg| {
2562                let style = match &seg.style {
2563                    Some(opts) => Self::resolve_overlay_style(opts, &theme),
2564                    None => normal_title_style,
2565                };
2566                Span::styled(seg.text.clone(), style)
2567            })
2568            .collect();
2569        let block = Block::default()
2570            .borders(Borders::ALL)
2571            .border_style(Style::default().fg(theme.popup_border_fg))
2572            .style(Style::default().bg(theme.suggestion_bg));
2573        let inner = block.inner(overlay_rect);
2574        frame.render_widget(block, overlay_rect);
2575
2576        if inner.height == 0 || inner.width == 0 {
2577            return;
2578        }
2579
2580        // Decide whether to split the inner area into results | preview.
2581        // Below ~120 cols, stack results-only (preview hidden — see
2582        // design doc §5 "preview pane size when terminal is narrow").
2583        let preview_min_cols: u16 = 120;
2584        let show_preview = overlay_rect.width >= preview_min_cols;
2585        let (results_area, preview_area) = if show_preview {
2586            let results_w = inner.width / 2;
2587            (
2588                Rect {
2589                    x: inner.x,
2590                    y: inner.y,
2591                    width: results_w,
2592                    height: inner.height,
2593                },
2594                Some(Rect {
2595                    x: inner.x + results_w,
2596                    y: inner.y,
2597                    width: inner.width - results_w,
2598                    height: inner.height,
2599                }),
2600            )
2601        } else {
2602            (inner, None)
2603        };
2604
2605        // Top row of `results_area` is the prompt input.
2606        let input_row = Rect {
2607            x: results_area.x,
2608            y: results_area.y,
2609            width: results_area.width,
2610            height: 1,
2611        };
2612        // Two distinct styles on this row so the user can tell
2613        // the static title (`prompt.message`) apart from the
2614        // editable input field. Title gets the popup-chrome bg
2615        // (matching the toolbar/footer); input + right-side
2616        // padding + count get the editor bg so they read as one
2617        // contiguous text field. All colours from theme keys.
2618        let title_style = Style::default().fg(theme.prompt_fg).bg(theme.suggestion_bg);
2619        let input_style = Style::default().fg(theme.prompt_fg).bg(theme.editor_bg);
2620        let count_str = if prompt.suggestions.is_empty() {
2621            String::new()
2622        } else {
2623            format!(
2624                "{} / {}",
2625                prompt.selected_suggestion.map(|i| i + 1).unwrap_or(0),
2626                prompt.suggestions.len()
2627            )
2628        };
2629        use crate::primitives::display_width::str_width;
2630        let count_w = str_width(&count_str);
2631        // Reserve one trailing column so the count doesn't sit
2632        // flush against the right border.
2633        let right_gap: usize = if count_w > 0 { 1 } else { 0 };
2634        let visible_input_width = (results_area.width as usize).saturating_sub(count_w + right_gap);
2635        let truncated_input: String = prompt
2636            .input
2637            .chars()
2638            .take(visible_input_width.saturating_sub(str_width(&prompt.message)))
2639            .collect();
2640        // Pad between the typed input and the count so the count
2641        // is right-aligned (with `right_gap` empty cols at the
2642        // very edge), independent of how much the user has typed.
2643        let used = str_width(&prompt.message) + str_width(&truncated_input) + count_w;
2644        let pad = (results_area.width as usize).saturating_sub(used + right_gap);
2645        let line = Line::from(vec![
2646            Span::styled(prompt.message.clone(), title_style),
2647            Span::styled(truncated_input, input_style),
2648            Span::styled(" ".repeat(pad), input_style),
2649            Span::styled(
2650                count_str,
2651                Style::default()
2652                    .fg(theme.popup_border_fg)
2653                    .bg(theme.editor_bg),
2654            ),
2655        ]);
2656        frame.render_widget(Paragraph::new(line).style(input_style), input_row);
2657
2658        // Cursor position on the input row.
2659        let cursor_x = (str_width(&prompt.message)
2660            + str_width(&prompt.input[..prompt.cursor_pos.min(prompt.input.len())]))
2661            as u16;
2662        if cursor_x < input_row.width {
2663            frame.set_cursor_position((input_row.x + cursor_x, input_row.y));
2664        }
2665
2666        // Optional toolbar row (the styled segments the plugin set
2667        // via setPromptTitle, e.g. "Provider: rg · Alt+P switch
2668        // grep provider · …"). Sits between the input row and the
2669        // separator so the user sees feature-scoped controls right
2670        // under what they're typing — not on the frame border
2671        // where shortcut hints get visually lost.
2672        let toolbar_h: u16 = if toolbar_visible { 1 } else { 0 };
2673        if toolbar_visible && results_area.height >= 2 {
2674            let toolbar = Rect {
2675                x: results_area.x,
2676                y: results_area.y + 1,
2677                width: results_area.width,
2678                height: 1,
2679            };
2680            frame.render_widget(
2681                Paragraph::new(Line::from(title_spans))
2682                    .style(Style::default().bg(theme.suggestion_bg)),
2683                toolbar,
2684            );
2685        }
2686
2687        // Separator row.
2688        if results_area.height >= 2 + toolbar_h {
2689            let sep = Rect {
2690                x: results_area.x,
2691                y: results_area.y + 1 + toolbar_h,
2692                width: results_area.width,
2693                height: 1,
2694            };
2695            let sep_style = Style::default()
2696                .fg(theme.popup_border_fg)
2697                .bg(theme.suggestion_bg);
2698            let sep_text = "─".repeat(results_area.width as usize);
2699            frame.render_widget(Paragraph::new(sep_text).style(sep_style), sep);
2700        }
2701
2702        // Suggestions list fills the rest of `results_area`. Carve
2703        // off the rightmost 1-column lane for a scrollbar so the
2704        // user can see how far through the result set the selection
2705        // is — important when the visible area only fits ~30 of
2706        // 100+ matches. Only carve when the result set actually
2707        // exceeds the visible rows; otherwise the scrollbar is
2708        // visual noise.
2709        let chrome_above_list: u16 = 2 + toolbar_h;
2710        // Plugin-supplied footer row (Primitive #2 chrome region).
2711        // Reserves the bottom-most row of `results_area` for
2712        // styled hotkey-hint segments. Skipped when the plugin
2713        // hasn't set a footer — preserves existing behaviour for
2714        // Live Grep et al.
2715        let footer_h: u16 = if prompt.footer.is_empty() { 0 } else { 1 };
2716        if results_area.height > chrome_above_list + footer_h {
2717            // No `-2` for popup-own-border — we render the
2718            // borderless variant below since the overlay frame is
2719            // already a border.
2720            let inner_rows = (results_area.height - chrome_above_list - footer_h) as usize;
2721            let needs_scrollbar = prompt.suggestions.len() > inner_rows.max(1);
2722            let scrollbar_w: u16 = if needs_scrollbar { 1 } else { 0 };
2723            let list_area = Rect {
2724                x: results_area.x,
2725                y: results_area.y + chrome_above_list,
2726                width: results_area.width.saturating_sub(scrollbar_w),
2727                height: results_area.height - chrome_above_list - footer_h,
2728            };
2729            self.active_chrome_mut().suggestions_area = SuggestionsRenderer::render_with_hover(
2730                frame,
2731                list_area,
2732                &prompt,
2733                &theme,
2734                self.active_window_mut().mouse_state.hover_target.as_ref(),
2735                false,
2736            );
2737            if self.active_chrome_mut().suggestions_area.is_some() {
2738                self.active_chrome_mut().suggestions_outer_area = Some(list_area);
2739            }
2740            // Render the scrollbar in the carved lane. Reuses the
2741            // shared `view::ui::scrollbar` widget so thumb sizing
2742            // and theme colours match scrollbars elsewhere in the
2743            // editor (split rendering, file explorer, …).
2744            if needs_scrollbar {
2745                use crate::view::ui::scrollbar::{
2746                    render_scrollbar, ScrollbarColors, ScrollbarState,
2747                };
2748                // Scrollbar rect aligns with the borderless
2749                // suggestions list — same y/height as the list itself
2750                // since there's no popup-own border to skip.
2751                let scrollbar_rect = Rect {
2752                    x: results_area.x + results_area.width - 1,
2753                    y: list_area.y,
2754                    width: 1,
2755                    height: list_area.height,
2756                };
2757                let state = ScrollbarState::new(
2758                    prompt.suggestions.len(),
2759                    inner_rows.max(1),
2760                    prompt.scroll_offset,
2761                );
2762                render_scrollbar(
2763                    frame,
2764                    scrollbar_rect,
2765                    &state,
2766                    &ScrollbarColors::from_theme(&theme),
2767                );
2768                // Cache the rect for mouse hit testing in
2769                // `mouse_input.rs::handle_click_prompt_scrollbar`.
2770                self.active_chrome_mut().suggestions_scrollbar_rect = Some(scrollbar_rect);
2771            } else {
2772                self.active_chrome_mut().suggestions_scrollbar_rect = None;
2773            }
2774        } else {
2775            self.active_chrome_mut().suggestions_scrollbar_rect = None;
2776        }
2777
2778        // Plugin-supplied footer chrome row (Primitive #2 chrome
2779        // region). Each segment is a `StyledText` — same styling
2780        // primitive used by `setPromptTitle` and inline overlays,
2781        // so plugins can theme hotkey hints with `ui.help_key_fg`,
2782        // separators with `ui.popup_border_fg`, etc.
2783        if footer_h == 1 && results_area.height >= 1 {
2784            let footer_row = Rect {
2785                x: results_area.x,
2786                y: results_area.y + results_area.height - 1,
2787                width: results_area.width,
2788                height: 1,
2789            };
2790            let footer_default_style = Style::default().fg(theme.prompt_fg).bg(theme.suggestion_bg);
2791            let footer_spans: Vec<Span> = prompt
2792                .footer
2793                .iter()
2794                .map(|seg| {
2795                    let style = match &seg.style {
2796                        Some(opts) => Self::resolve_overlay_style(opts, &theme),
2797                        None => footer_default_style,
2798                    };
2799                    Span::styled(seg.text.clone(), style)
2800                })
2801                .collect();
2802            frame.render_widget(
2803                Paragraph::new(Line::from(footer_spans))
2804                    .style(Style::default().bg(theme.suggestion_bg)),
2805                footer_row,
2806            );
2807        }
2808
2809        // Right-half preview pane: a real Buffer rendered via the
2810        // same per-leaf pipeline regular splits use. Buffer + cursor
2811        // are already seeded by `prepare_overlay_preview` (called
2812        // earlier in the render flow). Borrows are split here so we
2813        // can hand out independent `&mut` references to the
2814        // renderer's internals without going back through `&mut self`.
2815        if let Some(preview_rect) = preview_area {
2816            // Frame the preview area first (vertical separator) so
2817            // the renderer fills the inner rect.
2818            use ratatui::widgets::{Block, Borders, Clear};
2819            frame.render_widget(Clear, preview_rect);
2820            let block = Block::default()
2821                .borders(Borders::LEFT)
2822                .border_style(Style::default().fg(theme.popup_border_fg))
2823                .style(Style::default().bg(theme.suggestion_bg));
2824            let inner = block.inner(preview_rect);
2825            frame.render_widget(block, preview_rect);
2826
2827            // Primitive #1: if the active plugin asked us to
2828            // preview a specific (inactive) session in this
2829            // rect, render that session's entire stashed split
2830            // tree natively into `inner`. Falls back to the
2831            // existing path-based phantom-leaf preview when no
2832            // session override is set.
2833            if inner.height > 0
2834                && inner.width > 0
2835                && self
2836                    .preview_window_id
2837                    .is_some_and(|sid| sid != self.active_window && self.windows.contains_key(&sid))
2838            {
2839                self.render_session_preview_into_rect(frame, inner, &theme);
2840            } else if inner.height > 0 && inner.width > 0 {
2841                // Snapshot scalar config values up front so the
2842                // mutable-borrow split below has minimal scope.
2843                // AnsiBackground isn't Clone, so it's taken as a
2844                // borrow; Rust permits disjoint-field splitting
2845                // between `&self.ansi_background` and the `&mut`
2846                // accesses below because they touch distinct fields.
2847                let bg_fade = self.background_fade;
2848                let estimated_line_length = self.config.editor.estimated_line_length;
2849                let highlight_context_bytes = self.config.editor.highlight_context_bytes;
2850                let relative_line_numbers = self.config.editor.relative_line_numbers;
2851                let use_terminal_bg = self.config.editor.use_terminal_bg;
2852                let session_mode = self.session_mode || !self.software_cursor_only;
2853                let software_cursor_only = self.software_cursor_only;
2854                let diagnostics_inline_text = self.config.editor.diagnostics_inline_text;
2855                let show_tilde = false; // preview hides tilde markers
2856                let highlight_current_column = self.config.editor.highlight_current_column;
2857                let screen_width = frame.area().width;
2858
2859                let ansi_ref = self.ansi_background.as_ref();
2860                let __win = self
2861                    .windows
2862                    .get_mut(&self.active_window)
2863                    .expect("active window present");
2864                let buffers = &mut __win.buffers;
2865                let event_logs = &mut __win.event_logs;
2866                let cell_theme_map = &mut __win.chrome_layout.cell_theme_map;
2867                let Some(preview_state) = __win.overlay_preview_state.as_mut() else {
2868                    return;
2869                };
2870                preview_state
2871                    .view_state
2872                    .viewport
2873                    .resize(inner.width, inner.height);
2874                let buffer_id = preview_state.buffer_id;
2875
2876                if let Some(state) = buffers.get_mut(&buffer_id) {
2877                    // Deref the SplitViewState once to a concrete
2878                    // `&mut BufferViewState` so disjoint field
2879                    // splits (`viewport` + `folds`) are visible
2880                    // to the borrow checker.
2881                    let buf_state = preview_state.view_state.active_state_mut();
2882                    let cursors = buf_state.cursors.clone();
2883                    let view_mode = buf_state.view_mode.clone();
2884                    let compose_width = buf_state.compose_width;
2885                    let compose_column_guides = buf_state.compose_column_guides.clone();
2886                    let view_transform = buf_state.view_transform.clone();
2887                    let rulers = buf_state.rulers.clone();
2888                    let show_line_numbers = buf_state.show_line_numbers;
2889                    let highlight_current_line = buf_state.highlight_current_line;
2890                    let viewport_ref = &mut buf_state.viewport;
2891                    let folds_ref = &mut buf_state.folds;
2892                    let event_log = event_logs.get_mut(&buffer_id);
2893                    let _ = crate::view::ui::SplitRenderer::render_phantom_leaf(
2894                        frame,
2895                        state,
2896                        &cursors,
2897                        viewport_ref,
2898                        folds_ref,
2899                        event_log,
2900                        inner,
2901                        &theme,
2902                        ansi_ref,
2903                        bg_fade,
2904                        view_mode,
2905                        compose_width,
2906                        compose_column_guides,
2907                        view_transform,
2908                        estimated_line_length,
2909                        highlight_context_bytes,
2910                        buffer_id,
2911                        relative_line_numbers,
2912                        use_terminal_bg,
2913                        session_mode,
2914                        software_cursor_only,
2915                        &rulers,
2916                        show_line_numbers,
2917                        highlight_current_line,
2918                        diagnostics_inline_text,
2919                        show_tilde,
2920                        highlight_current_column,
2921                        cell_theme_map,
2922                        screen_width,
2923                    );
2924                }
2925            }
2926        }
2927    }
2928
2929    /// Render hover highlights for interactive elements (separators, scrollbars)
2930    pub(super) fn render_hover_highlights(&self, frame: &mut Frame) {
2931        use ratatui::style::Style;
2932        use ratatui::text::Span;
2933        use ratatui::widgets::Paragraph;
2934
2935        match &self.active_window().mouse_state.hover_target {
2936            Some(HoverTarget::SplitSeparator(split_id, direction)) => {
2937                // Highlight the separator with hover color
2938                for (sid, dir, x, y, length) in &self.active_layout().separator_areas {
2939                    if sid == split_id && dir == direction {
2940                        let (hover_fg, editor_bg) = {
2941                            let theme = self.theme.read().unwrap();
2942                            (theme.split_separator_hover_fg, theme.editor_bg)
2943                        };
2944                        let hover_style = Style::default().fg(hover_fg).bg(editor_bg);
2945                        match dir {
2946                            SplitDirection::Horizontal => {
2947                                let line_text = "─".repeat(*length as usize);
2948                                let paragraph =
2949                                    Paragraph::new(Span::styled(line_text, hover_style));
2950                                frame.render_widget(
2951                                    paragraph,
2952                                    ratatui::layout::Rect::new(*x, *y, *length, 1),
2953                                );
2954                            }
2955                            SplitDirection::Vertical => {
2956                                for offset in 0..*length {
2957                                    let paragraph = Paragraph::new(Span::styled("│", hover_style));
2958                                    frame.render_widget(
2959                                        paragraph,
2960                                        ratatui::layout::Rect::new(*x, y + offset, 1, 1),
2961                                    );
2962                                }
2963                            }
2964                        }
2965                    }
2966                }
2967            }
2968            Some(HoverTarget::ScrollbarThumb(split_id)) => {
2969                // Highlight scrollbar thumb
2970                for (sid, _buffer_id, _content_rect, scrollbar_rect, thumb_start, thumb_end) in
2971                    &self.active_layout().split_areas
2972                {
2973                    if sid == split_id {
2974                        let hover_style = Style::default().bg(self
2975                            .theme
2976                            .read()
2977                            .unwrap()
2978                            .scrollbar_thumb_hover_fg);
2979                        for row_offset in *thumb_start..*thumb_end {
2980                            let paragraph = Paragraph::new(Span::styled(" ", hover_style));
2981                            frame.render_widget(
2982                                paragraph,
2983                                ratatui::layout::Rect::new(
2984                                    scrollbar_rect.x,
2985                                    scrollbar_rect.y + row_offset as u16,
2986                                    1,
2987                                    1,
2988                                ),
2989                            );
2990                        }
2991                    }
2992                }
2993            }
2994            Some(HoverTarget::ScrollbarTrack(split_id, hovered_row)) => {
2995                // Highlight only the hovered cell on the scrollbar track
2996                for (sid, _buffer_id, _content_rect, scrollbar_rect, _thumb_start, _thumb_end) in
2997                    &self.active_layout().split_areas
2998                {
2999                    if sid == split_id {
3000                        let track_hover_style = Style::default().bg(self
3001                            .theme
3002                            .read()
3003                            .unwrap()
3004                            .scrollbar_track_hover_fg);
3005                        let paragraph = Paragraph::new(Span::styled(" ", track_hover_style));
3006                        frame.render_widget(
3007                            paragraph,
3008                            ratatui::layout::Rect::new(
3009                                scrollbar_rect.x,
3010                                scrollbar_rect.y + hovered_row,
3011                                1,
3012                                1,
3013                            ),
3014                        );
3015                    }
3016                }
3017            }
3018            Some(HoverTarget::FileExplorerBorder) => {
3019                // Highlight the file explorer border for resize
3020                if let Some(explorer_area) = self.active_layout().file_explorer_area {
3021                    let (hover_fg, editor_bg) = {
3022                        let theme = self.theme.read().unwrap();
3023                        (theme.split_separator_hover_fg, theme.editor_bg)
3024                    };
3025                    let hover_style = Style::default().fg(hover_fg).bg(editor_bg);
3026                    let border_x = explorer_area.x + explorer_area.width.saturating_sub(1);
3027                    for row_offset in 0..explorer_area.height {
3028                        let paragraph = Paragraph::new(Span::styled("│", hover_style));
3029                        frame.render_widget(
3030                            paragraph,
3031                            ratatui::layout::Rect::new(
3032                                border_x,
3033                                explorer_area.y + row_offset,
3034                                1,
3035                                1,
3036                            ),
3037                        );
3038                    }
3039                }
3040            }
3041            // Menu hover is handled by MenuRenderer
3042            _ => {}
3043        }
3044    }
3045
3046    /// Render the tab context menu
3047    fn render_tab_context_menu(&self, frame: &mut Frame, menu: &TabContextMenu) {
3048        use ratatui::style::Style;
3049        use ratatui::text::{Line, Span};
3050        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
3051
3052        let items = super::types::TabContextMenuItem::all();
3053        let menu_width = 22u16; // "Close to the Right" + padding
3054        let menu_height = items.len() as u16 + 2; // items + borders
3055
3056        // Adjust position to stay within screen bounds
3057        let screen_width = frame.area().width;
3058        let screen_height = frame.area().height;
3059
3060        let menu_x = if menu.position.0 + menu_width > screen_width {
3061            screen_width.saturating_sub(menu_width)
3062        } else {
3063            menu.position.0
3064        };
3065
3066        let menu_y = if menu.position.1 + menu_height > screen_height {
3067            screen_height.saturating_sub(menu_height)
3068        } else {
3069            menu.position.1
3070        };
3071
3072        let area = ratatui::layout::Rect::new(menu_x, menu_y, menu_width, menu_height);
3073
3074        // Clear the area first
3075        frame.render_widget(Clear, area);
3076
3077        // Build the menu lines
3078        let mut lines = Vec::new();
3079        for (idx, item) in items.iter().enumerate() {
3080            let is_highlighted = idx == menu.highlighted;
3081
3082            let style = if is_highlighted {
3083                Style::default()
3084                    .fg(self.theme.read().unwrap().menu_highlight_fg)
3085                    .bg(self.theme.read().unwrap().menu_highlight_bg)
3086            } else {
3087                Style::default()
3088                    .fg(self.theme.read().unwrap().menu_dropdown_fg)
3089                    .bg(self.theme.read().unwrap().menu_dropdown_bg)
3090            };
3091
3092            // Pad the label to fill the menu width
3093            let label = item.label();
3094            let content_width = (menu_width as usize).saturating_sub(2); // -2 for borders
3095            let padded_label = format!(" {:<width$}", label, width = content_width - 1);
3096
3097            lines.push(Line::from(vec![Span::styled(padded_label, style)]));
3098        }
3099
3100        let block = Block::default()
3101            .borders(Borders::ALL)
3102            .border_style(Style::default().fg(self.theme.read().unwrap().menu_border_fg))
3103            .style(Style::default().bg(self.theme.read().unwrap().menu_dropdown_bg));
3104
3105        let paragraph = Paragraph::new(lines).block(block);
3106        frame.render_widget(paragraph, area);
3107    }
3108
3109    /// Render the file explorer context menu
3110    fn render_file_explorer_context_menu(
3111        &self,
3112        frame: &mut Frame,
3113        menu: &super::types::FileExplorerContextMenu,
3114    ) {
3115        use ratatui::style::Style;
3116        use ratatui::text::{Line, Span};
3117        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
3118
3119        let items = menu.items();
3120        let menu_width = super::types::FILE_EXPLORER_CONTEXT_MENU_WIDTH;
3121        let menu_height = menu.height();
3122        let (menu_x, menu_y) = menu.clamped_position(frame.area().width, frame.area().height);
3123
3124        let area = ratatui::layout::Rect::new(menu_x, menu_y, menu_width, menu_height);
3125
3126        frame.render_widget(Clear, area);
3127
3128        let mut lines = Vec::new();
3129        for (idx, item) in items.iter().enumerate() {
3130            let is_highlighted = idx == menu.highlighted;
3131
3132            let style = if is_highlighted {
3133                Style::default()
3134                    .fg(self.theme.read().unwrap().menu_highlight_fg)
3135                    .bg(self.theme.read().unwrap().menu_highlight_bg)
3136            } else {
3137                Style::default()
3138                    .fg(self.theme.read().unwrap().menu_dropdown_fg)
3139                    .bg(self.theme.read().unwrap().menu_dropdown_bg)
3140            };
3141
3142            let label = item.label();
3143            let content_width = (menu_width as usize).saturating_sub(2);
3144            let padded_label = format!(" {:<width$}", label, width = content_width - 1);
3145
3146            lines.push(Line::from(vec![Span::styled(padded_label, style)]));
3147        }
3148
3149        let block = Block::default()
3150            .borders(Borders::ALL)
3151            .border_style(Style::default().fg(self.theme.read().unwrap().menu_border_fg))
3152            .style(Style::default().bg(self.theme.read().unwrap().menu_dropdown_bg));
3153
3154        let paragraph = Paragraph::new(lines).block(block);
3155        frame.render_widget(paragraph, area);
3156    }
3157
3158    /// Render the tab drag drop zone overlay
3159    fn render_tab_drop_zone(&self, frame: &mut Frame, drag_state: &super::types::TabDragState) {
3160        use ratatui::style::Modifier;
3161
3162        let Some(ref drop_zone) = drag_state.drop_zone else {
3163            return;
3164        };
3165
3166        let split_id = drop_zone.split_id();
3167
3168        // Find the content area for the target split
3169        let split_area = self
3170            .active_layout()
3171            .split_areas
3172            .iter()
3173            .find(|(sid, _, _, _, _, _)| *sid == split_id)
3174            .map(|(_, _, content_rect, _, _, _)| *content_rect);
3175
3176        let Some(content_rect) = split_area else {
3177            return;
3178        };
3179
3180        // Determine the highlight area based on drop zone type
3181        use super::types::TabDropZone;
3182
3183        let highlight_area = match drop_zone {
3184            TabDropZone::TabBar(_, _) | TabDropZone::SplitCenter(_) => {
3185                // For tab bar and center drops, highlight the entire split area
3186                // This indicates the tab will be added to this split's tab bar
3187                content_rect
3188            }
3189            TabDropZone::SplitLeft(_) => {
3190                // Left 50% of the split (matches the actual split size created)
3191                let width = (content_rect.width / 2).max(3);
3192                ratatui::layout::Rect::new(
3193                    content_rect.x,
3194                    content_rect.y,
3195                    width,
3196                    content_rect.height,
3197                )
3198            }
3199            TabDropZone::SplitRight(_) => {
3200                // Right 50% of the split (matches the actual split size created)
3201                let width = (content_rect.width / 2).max(3);
3202                let x = content_rect.x + content_rect.width - width;
3203                ratatui::layout::Rect::new(x, content_rect.y, width, content_rect.height)
3204            }
3205            TabDropZone::SplitTop(_) => {
3206                // Top 50% of the split (matches the actual split size created)
3207                let height = (content_rect.height / 2).max(2);
3208                ratatui::layout::Rect::new(
3209                    content_rect.x,
3210                    content_rect.y,
3211                    content_rect.width,
3212                    height,
3213                )
3214            }
3215            TabDropZone::SplitBottom(_) => {
3216                // Bottom 50% of the split (matches the actual split size created)
3217                let height = (content_rect.height / 2).max(2);
3218                let y = content_rect.y + content_rect.height - height;
3219                ratatui::layout::Rect::new(content_rect.x, y, content_rect.width, height)
3220            }
3221        };
3222
3223        // Draw the overlay with the drop zone color
3224        // We apply a semi-transparent effect by modifying existing cells
3225        let buf = frame.buffer_mut();
3226        let drop_zone_bg = self.theme.read().unwrap().tab_drop_zone_bg;
3227        let drop_zone_border = self.theme.read().unwrap().tab_drop_zone_border;
3228
3229        // Fill the highlight area with a semi-transparent overlay
3230        for y in highlight_area.y..highlight_area.y + highlight_area.height {
3231            for x in highlight_area.x..highlight_area.x + highlight_area.width {
3232                if let Some(cell) = buf.cell_mut((x, y)) {
3233                    // Blend the drop zone color with the existing background
3234                    // For a simple effect, we just set the background
3235                    cell.set_bg(drop_zone_bg);
3236
3237                    // Draw border on edges
3238                    let is_border = x == highlight_area.x
3239                        || x == highlight_area.x + highlight_area.width - 1
3240                        || y == highlight_area.y
3241                        || y == highlight_area.y + highlight_area.height - 1;
3242
3243                    if is_border {
3244                        cell.set_fg(drop_zone_border);
3245                        cell.set_style(cell.style().add_modifier(Modifier::BOLD));
3246                    }
3247                }
3248            }
3249        }
3250
3251        // Draw a border indicator based on the zone type
3252        match drop_zone {
3253            TabDropZone::SplitLeft(_) => {
3254                // Draw vertical indicator on left edge
3255                for y in highlight_area.y..highlight_area.y + highlight_area.height {
3256                    if let Some(cell) = buf.cell_mut((highlight_area.x, y)) {
3257                        cell.set_symbol("▌");
3258                        cell.set_fg(drop_zone_border);
3259                    }
3260                }
3261            }
3262            TabDropZone::SplitRight(_) => {
3263                // Draw vertical indicator on right edge
3264                let x = highlight_area.x + highlight_area.width - 1;
3265                for y in highlight_area.y..highlight_area.y + highlight_area.height {
3266                    if let Some(cell) = buf.cell_mut((x, y)) {
3267                        cell.set_symbol("▐");
3268                        cell.set_fg(drop_zone_border);
3269                    }
3270                }
3271            }
3272            TabDropZone::SplitTop(_) => {
3273                // Draw horizontal indicator on top edge
3274                for x in highlight_area.x..highlight_area.x + highlight_area.width {
3275                    if let Some(cell) = buf.cell_mut((x, highlight_area.y)) {
3276                        cell.set_symbol("▀");
3277                        cell.set_fg(drop_zone_border);
3278                    }
3279                }
3280            }
3281            TabDropZone::SplitBottom(_) => {
3282                // Draw horizontal indicator on bottom edge
3283                let y = highlight_area.y + highlight_area.height - 1;
3284                for x in highlight_area.x..highlight_area.x + highlight_area.width {
3285                    if let Some(cell) = buf.cell_mut((x, y)) {
3286                        cell.set_symbol("▄");
3287                        cell.set_fg(drop_zone_border);
3288                    }
3289                }
3290            }
3291            TabDropZone::SplitCenter(_) | TabDropZone::TabBar(_, _) => {
3292                // For center and tab bar, the filled background is sufficient
3293            }
3294        }
3295    }
3296
3297    /// Recompute the view_line_mappings layout without drawing.
3298    /// Used during macro replay so that visual-line movements (MoveLineEnd,
3299    /// MoveUp, MoveDown on wrapped lines) see correct, up-to-date layout
3300    /// information between each replayed action.
3301    pub fn recompute_layout(&mut self, width: u16, height: u16) {
3302        let size = ratatui::layout::Rect::new(0, 0, width, height);
3303
3304        // Replicate the pre-render sync steps from render()
3305        let active_split = self
3306            .windows
3307            .get(&self.active_window)
3308            .and_then(|w| w.buffers.splits())
3309            .map(|(mgr, _)| mgr)
3310            .expect("active window must have a populated split layout")
3311            .active_split();
3312        self.active_window_mut()
3313            .pre_sync_ensure_visible(active_split);
3314        self.active_window_mut().sync_scroll_groups();
3315
3316        // Replicate the layout computation that produces editor_content_area.
3317        // Same constraints as render(): [menu_bar, main_content, status_bar, search_options, prompt_line]
3318        let constraints = vec![
3319            Constraint::Length(if self.active_window_mut().menu_bar_visible {
3320                1
3321            } else {
3322                0
3323            }),
3324            Constraint::Min(0),
3325            Constraint::Length(if self.active_window_mut().status_bar_visible {
3326                1
3327            } else {
3328                0
3329            }), // status bar
3330            Constraint::Length(0), // search options (doesn't matter for layout)
3331            Constraint::Length(if self.active_window_mut().prompt_line_visible {
3332                1
3333            } else {
3334                0
3335            }), // prompt line
3336        ];
3337        let main_chunks = Layout::default()
3338            .direction(Direction::Vertical)
3339            .constraints(constraints)
3340            .split(size);
3341        let main_content_area = main_chunks[1];
3342
3343        // Compute editor_content_area (with file explorer split if visible)
3344        let file_explorer_should_show = self.file_explorer_visible()
3345            && (self.file_explorer().is_some()
3346                || self.active_window().file_explorer_sync_in_progress);
3347        let editor_content_area = if file_explorer_should_show {
3348            let explorer_cols = self
3349                .active_window()
3350                .file_explorer_width
3351                .to_cols(main_content_area.width);
3352            let horizontal_chunks = Layout::default()
3353                .direction(Direction::Horizontal)
3354                .constraints([Constraint::Length(explorer_cols), Constraint::Min(0)])
3355                .split(main_content_area);
3356            horizontal_chunks[1]
3357        } else {
3358            main_content_area
3359        };
3360
3361        // Compute layout for all visible splits and update cached view_line_mappings.
3362        // Take one &mut borrow on the active window's splits; destructure into
3363        // (&SplitManager, &mut HashMap<...>) so both arguments come from the
3364        // same `&mut self.windows` borrow.
3365        let active_window_id = self.active_window;
3366        let __win_l = self
3367            .windows
3368            .get_mut(&active_window_id)
3369            .expect("active window must exist");
3370        let tab_bar_visible = __win_l.tab_bar_visible;
3371        let theme = self.theme.read().unwrap().clone();
3372        let view_line_mappings = __win_l
3373            .buffers
3374            .with_all_mut(|buffers, mgr, vs_map| {
3375                SplitRenderer::compute_content_layout(
3376                    editor_content_area,
3377                    &*mgr,
3378                    buffers,
3379                    vs_map,
3380                    &theme,
3381                    false, // lsp_waiting — not relevant for layout
3382                    self.config.editor.estimated_line_length,
3383                    self.config.editor.highlight_context_bytes,
3384                    self.config.editor.relative_line_numbers,
3385                    self.config.editor.use_terminal_bg,
3386                    self.session_mode || !self.software_cursor_only,
3387                    self.software_cursor_only,
3388                    tab_bar_visible,
3389                    self.config.editor.show_vertical_scrollbar,
3390                    self.config.editor.show_horizontal_scrollbar,
3391                    self.config.editor.diagnostics_inline_text,
3392                    self.config.editor.show_tilde,
3393                )
3394            })
3395            .expect("active window must have a populated split layout");
3396
3397        self.active_layout_mut().view_line_mappings = view_line_mappings;
3398    }
3399
3400    /// Clear the search history
3401    /// Used primarily for testing to ensure test isolation
3402    pub fn clear_search_history(&mut self) {
3403        if let Some(history) = self.active_window_mut().prompt_histories.get_mut("search") {
3404            history.clear();
3405        }
3406    }
3407
3408    /// Emit an OSC 2 escape sequence to set the host terminal's window/tab
3409    /// title based on the active buffer's display name and the project name
3410    /// (the working directory's last path component). Deduplicated against
3411    /// the last title we wrote so we don't spam stdout every frame.
3412    ///
3413    /// Gated by `editor.set_window_title` (default on). Terminals that
3414    /// don't implement OSC 2 silently drop the sequence.
3415    fn update_terminal_title(&mut self, display_name: &str) {
3416        if !self.config.editor.set_window_title {
3417            return;
3418        }
3419        let project_name = self.working_dir.file_name().and_then(|s| s.to_str());
3420        let new_title =
3421            crate::services::terminal_title::build_window_title(display_name, project_name);
3422        if self.last_window_title.as_deref() == Some(new_title.as_str()) {
3423            return;
3424        }
3425        crate::services::terminal_title::write_terminal_title(&new_title);
3426        self.last_window_title = Some(new_title);
3427    }
3428
3429    /// Save all prompt histories to disk
3430    /// Called on shutdown to persist history across sessions
3431    pub fn save_histories(&self) {
3432        // Ensure data directory exists
3433        if let Err(e) = self
3434            .authority
3435            .filesystem
3436            .create_dir_all(&self.dir_context.data_dir)
3437        {
3438            tracing::warn!("Failed to create data directory: {}", e);
3439            return;
3440        }
3441
3442        // Save all prompt histories
3443        for (key, history) in &self.active_window().prompt_histories {
3444            let path = self.dir_context.prompt_history_path(key);
3445            if let Err(e) = history.save_to_file(&path) {
3446                tracing::warn!("Failed to save {} history: {}", key, e);
3447            } else {
3448                tracing::debug!("Saved {} history to {:?}", key, path);
3449            }
3450        }
3451    }
3452
3453    /// Resolve a plugin-supplied [`OverlayOptions`] to a ratatui
3454    /// [`Style`] against the active theme. RGB colours pass through;
3455    /// theme keys (e.g. `"ui.help_key_fg"`) are looked up via
3456    /// `theme.resolve_theme_key`. Mirrors the resolution
3457    /// `OverlayFace::from_options` + char_style.rs do for buffer
3458    /// overlays — pulled here so the prompt-frame renderer can build
3459    /// styled spans inline.
3460    /// Compute a centered overlay rect of `width_pct` × `height_pct`
3461    /// of the given area. Mirrors `PopupPosition::CenteredOverlay`
3462    /// math used by `render_overlay_prompt`; minimum 20×8 cells so
3463    /// content stays legible on tiny terminals.
3464    pub(super) fn centered_overlay_rect(
3465        area: ratatui::layout::Rect,
3466        width_pct: u8,
3467        height_pct: u8,
3468    ) -> ratatui::layout::Rect {
3469        let w_pct = width_pct.clamp(1, 100) as u32;
3470        let h_pct = height_pct.clamp(1, 100) as u32;
3471        let w = ((area.width as u32 * w_pct) / 100) as u16;
3472        let h = ((area.height as u32 * h_pct) / 100) as u16;
3473        let w = w.max(20).min(area.width);
3474        let h = h.max(8).min(area.height);
3475        ratatui::layout::Rect {
3476            x: area.x + (area.width.saturating_sub(w)) / 2,
3477            y: area.y + (area.height.saturating_sub(h)) / 2,
3478            width: w,
3479            height: h,
3480        }
3481    }
3482
3483    /// Render the currently-mounted floating widget panel: dim the
3484    /// background outside the centered rect, draw the frame, paint
3485    /// the panel's rendered entries inside, and place the hardware
3486    /// caret at the focused TextInput. Stores the inner rect on the
3487    /// `FloatingWidgetState` so the click hit-test can recover the
3488    /// geometry on the next mouse event.
3489    pub(super) fn render_floating_widget_panel(
3490        &mut self,
3491        frame: &mut Frame,
3492        area: ratatui::layout::Rect,
3493    ) {
3494        use ratatui::widgets::{Block, Borders, Clear};
3495
3496        let (width_pct, height_pct, entries, focus_cursor, embeds, overlays) =
3497            match self.floating_widget_panel.as_ref() {
3498                Some(fwp) => (
3499                    fwp.width_pct,
3500                    fwp.height_pct,
3501                    fwp.entries.clone(),
3502                    fwp.focus_cursor,
3503                    fwp.embeds.clone(),
3504                    fwp.overlays.clone(),
3505                ),
3506                None => return,
3507            };
3508        let theme = self.theme.read().unwrap().clone();
3509        // Compute the requested rect from width%/height%, then
3510        // shrink the height to fit the rendered content (Bug 7).
3511        // Plugins call `mount({widthPct, heightPct})` mostly because
3512        // they don't know how tall their content is up front; the
3513        // requested height should act as a *max*, not a fixed
3514        // canvas. Without this shrink, the new-session form's 10
3515        // content rows leave ~20 blank rows under "Tab next  S-Tab
3516        // prev  Enter submit  Esc cancel" inside a 90%-of-screen
3517        // panel.
3518        //
3519        // Entries include every row the spec produces — including
3520        // WindowEmbed reservations (each `windowEmbed({rows: N})`
3521        // contributes N blank entries plus an EmbedRect that paints
3522        // over them at draw time). So `entries.len() + 2` (top
3523        // border + content + bottom border) is the natural fit.
3524        let overlay_rect = {
3525            let requested = Self::centered_overlay_rect(area, width_pct, height_pct);
3526            let needed_h = (entries.len() as u16).saturating_add(2);
3527            let effective_h = needed_h.min(requested.height).max(3);
3528            ratatui::layout::Rect {
3529                x: requested.x,
3530                y: area.y + (area.height.saturating_sub(effective_h)) / 2,
3531                width: requested.width,
3532                height: effective_h,
3533            }
3534        };
3535
3536        crate::view::dimming::apply_dimming_excluding(frame, area, Some(overlay_rect));
3537        frame.render_widget(Clear, overlay_rect);
3538        let block = Block::default()
3539            .borders(Borders::ALL)
3540            .border_style(ratatui::style::Style::default().fg(theme.popup_border_fg))
3541            .style(ratatui::style::Style::default().bg(theme.suggestion_bg));
3542        let inner = block.inner(overlay_rect);
3543        frame.render_widget(block, overlay_rect);
3544
3545        if inner.width == 0 || inner.height == 0 {
3546            if let Some(fwp) = self.floating_widget_panel.as_mut() {
3547                fwp.last_inner_rect = Some(inner);
3548            }
3549            return;
3550        }
3551
3552        let max_rows = inner.height as usize;
3553        for (i, entry) in entries.iter().take(max_rows).enumerate() {
3554            paint_text_property_entry(
3555                frame,
3556                entry,
3557                inner.x,
3558                inner.y + i as u16,
3559                inner.width,
3560                &theme,
3561            );
3562        }
3563
3564        // Walk WindowEmbed widgets and paint their referenced
3565        // editor window into the cells they reserved. Each embed
3566        // rect is panel-relative; translate to screen cells via
3567        // `inner`. We temporarily borrow `preview_window_id` to
3568        // reuse the existing per-window paint path — it reads
3569        // that field to decide which session to draw.
3570        let saved_preview = self.preview_window_id;
3571        for emb in &embeds {
3572            if emb.window_id == 0 {
3573                continue;
3574            }
3575            let ex = inner.x.saturating_add(emb.col_in_row as u16);
3576            let ey = inner.y.saturating_add(emb.buffer_row as u16);
3577            // Clip the embed rect to the panel's inner area so a
3578            // partially-offscreen embed (tiny terminal) doesn't
3579            // paint into the frame border.
3580            let max_w = inner.x.saturating_add(inner.width).saturating_sub(ex);
3581            let max_h = inner.y.saturating_add(inner.height).saturating_sub(ey);
3582            let w = (emb.width_cols as u16).min(max_w);
3583            let h = (emb.height_rows as u16).min(max_h);
3584            if w == 0 || h == 0 {
3585                continue;
3586            }
3587            let rect = ratatui::layout::Rect {
3588                x: ex,
3589                y: ey,
3590                width: w,
3591                height: h,
3592            };
3593            self.preview_window_id = Some(fresh_core::WindowId(emb.window_id as u64));
3594            self.render_session_preview_into_rect(frame, rect, &theme);
3595        }
3596        self.preview_window_id = saved_preview;
3597
3598        // Paint overlay rows AFTER the main entries + embeds. Each
3599        // overlay row sits on top of whatever's at its
3600        // `buffer_row` (the row it would have occupied if it
3601        // weren't floating). Used for dropdown completions
3602        // anchored to a text input — the completion list rows
3603        // overpaint the form's static rows beneath without
3604        // shifting them on every show / hide.
3605        //
3606        // Clear the row first so the underlying entry's text
3607        // doesn't bleed past the overlay's content width.
3608        // `Paragraph` only paints cells it has content for; a
3609        // bare `Clear` resets the row to the panel background
3610        // (the `Block` here just supplies the bg style — no
3611        // borders).
3612        let panel_bg = theme.popup_bg;
3613        let panel_bg_style = ratatui::style::Style::default().bg(panel_bg);
3614        for o in &overlays {
3615            let row_y = inner.y.saturating_add(o.buffer_row as u16);
3616            if row_y >= inner.y.saturating_add(inner.height) {
3617                continue;
3618            }
3619            let row_rect = ratatui::layout::Rect {
3620                x: inner.x,
3621                y: row_y,
3622                width: inner.width,
3623                height: 1,
3624            };
3625            frame.render_widget(Clear, row_rect);
3626            frame.render_widget(Block::default().style(panel_bg_style), row_rect);
3627            paint_text_property_entry(frame, &o.entry, inner.x, row_y, inner.width, &theme);
3628        }
3629
3630        if let Some(fc) = focus_cursor {
3631            let cx = inner.x.saturating_add(byte_to_screen_col(
3632                entries
3633                    .get(fc.buffer_row as usize)
3634                    .map(|e| e.text.as_str())
3635                    .unwrap_or(""),
3636                fc.byte_in_row as usize,
3637            ) as u16);
3638            let cy = inner.y.saturating_add(fc.buffer_row as u16);
3639            if cx < inner.x + inner.width && cy < inner.y + inner.height {
3640                frame.set_cursor_position((cx, cy));
3641            }
3642        } else {
3643            // No focused text input — the underlying editor's
3644            // `set_cursor_position` (called earlier in this frame)
3645            // would otherwise leave a hardware caret blinking
3646            // inside the dimmed buffer behind the panel. Park the
3647            // cursor on the floating panel's bottom-right corner
3648            // so it's hidden under the panel chrome instead of
3649            // bleeding through.
3650            let cx = inner.x + inner.width.saturating_sub(1);
3651            let cy = inner.y + inner.height.saturating_sub(1);
3652            frame.set_cursor_position((cx, cy));
3653        }
3654
3655        if let Some(fwp) = self.floating_widget_panel.as_mut() {
3656            fwp.last_inner_rect = Some(inner);
3657        }
3658    }
3659
3660    fn resolve_overlay_style(
3661        opts: &fresh_core::api::OverlayOptions,
3662        theme: &crate::view::theme::Theme,
3663    ) -> ratatui::style::Style {
3664        use crate::view::theme::named_color_from_str;
3665        use fresh_core::api::OverlayColorSpec;
3666        use ratatui::style::{Color, Modifier, Style};
3667
3668        let resolve = |spec: &OverlayColorSpec| -> Option<Color> {
3669            match spec {
3670                OverlayColorSpec::Rgb(r, g, b) => Some(Color::Rgb(*r, *g, *b)),
3671                OverlayColorSpec::ThemeKey(k) => {
3672                    named_color_from_str(k).or_else(|| theme.resolve_theme_key(k))
3673                }
3674            }
3675        };
3676
3677        let mut style = Style::default();
3678        if let Some(ref fg) = opts.fg {
3679            if let Some(c) = resolve(fg) {
3680                style = style.fg(c);
3681            }
3682        }
3683        if let Some(ref bg) = opts.bg {
3684            if let Some(c) = resolve(bg) {
3685                style = style.bg(c);
3686            }
3687        }
3688        let mut m = Modifier::empty();
3689        if opts.bold {
3690            m |= Modifier::BOLD;
3691        }
3692        if opts.italic {
3693            m |= Modifier::ITALIC;
3694        }
3695        if opts.underline {
3696            m |= Modifier::UNDERLINED;
3697        }
3698        if opts.strikethrough {
3699            m |= Modifier::CROSSED_OUT;
3700        }
3701        if !m.is_empty() {
3702            style = style.add_modifier(m);
3703        }
3704        style
3705    }
3706}
3707
3708/// Paint a single rendered widget entry into the frame buffer at
3709/// `(x, y)` over `width` cells. Resolves the entry's segments / inline
3710/// overlays to styled spans using the panel's theme; trailing columns
3711/// are filled with spaces in the panel's bg so the row reads as one
3712/// solid line.
3713fn paint_text_property_entry(
3714    frame: &mut ratatui::Frame,
3715    entry: &fresh_core::text_property::TextPropertyEntry,
3716    x: u16,
3717    y: u16,
3718    width: u16,
3719    theme: &crate::view::theme::Theme,
3720) {
3721    use ratatui::style::Style;
3722    use ratatui::text::{Line, Span};
3723    use ratatui::widgets::Paragraph;
3724
3725    let mut normalized = entry.clone();
3726    normalized.normalize_widths();
3727    let mut text = normalized.text.clone();
3728    while text.ends_with('\n') {
3729        text.pop();
3730    }
3731
3732    let base_bg = theme.suggestion_bg;
3733    let base_style = if let Some(opts) = normalized.style.as_ref() {
3734        // Resolve the entry's row-level style, then fill in the
3735        // suggestion_bg only when the style didn't supply one
3736        // of its own. Without this guard, calling `.bg(base_bg)`
3737        // unconditionally would wipe out a row-level
3738        // `popup_selection_bg` (the highlight on the completion
3739        // popup's selected candidate) — `Style::bg` is a
3740        // replacement, not a merge.
3741        let resolved = Editor::resolve_overlay_style(opts, theme);
3742        if resolved.bg.is_none() {
3743            resolved.bg(base_bg)
3744        } else {
3745            resolved
3746        }
3747    } else {
3748        Style::default().bg(base_bg)
3749    };
3750
3751    // Split the line at inline-overlay byte boundaries so each
3752    // resulting span carries one consistent style. The overlays are
3753    // produced in declaration order by the widget renderer; later
3754    // overlays override earlier ones for any cells they cover.
3755    let boundaries: std::collections::BTreeSet<usize> = std::iter::once(0)
3756        .chain(std::iter::once(text.len()))
3757        .chain(
3758            normalized
3759                .inline_overlays
3760                .iter()
3761                .flat_map(|o| [o.start.min(text.len()), o.end.min(text.len())]),
3762        )
3763        .collect();
3764    let bounds: Vec<usize> = boundaries.into_iter().collect();
3765
3766    let mut spans: Vec<Span<'_>> = Vec::new();
3767    for win in bounds.windows(2) {
3768        let (a, b) = (win[0], win[1]);
3769        if a >= b {
3770            continue;
3771        }
3772        let slice = text[a..b].to_string();
3773        // Merge (don't replace) overlapping overlays so a later
3774        // overlay can override individual properties (bg, fg,
3775        // italic, …) without wiping the earlier overlay's other
3776        // properties. The text-input renderer relies on this:
3777        // the placeholder overlay sets fg + italic, then the
3778        // focused overlay sets bg only — without per-property
3779        // merge the focused-bg overlay would also clear the
3780        // placeholder's italic-dim styling, making placeholder
3781        // text indistinguishable from a typed value under focus.
3782        let mut style = base_style;
3783        for o in &normalized.inline_overlays {
3784            let os = o.start.min(text.len());
3785            let oe = o.end.min(text.len());
3786            if a >= os && b <= oe && oe > os {
3787                let resolved = Editor::resolve_overlay_style(&o.style, theme);
3788                if let Some(fg) = resolved.fg {
3789                    style = style.fg(fg);
3790                }
3791                if let Some(bg) = resolved.bg {
3792                    style = style.bg(bg);
3793                }
3794                // Ratatui `Style` carries add/sub modifier sets;
3795                // OR the additions in so subsequent overlays can
3796                // add italic / bold / etc. on top of the prior
3797                // overlay's modifiers.
3798                style = style.add_modifier(resolved.add_modifier);
3799                style = style.remove_modifier(resolved.sub_modifier);
3800            }
3801        }
3802        // Ensure a bg is set: ratatui will paint the slot with
3803        // the terminal's default bg otherwise, which doesn't
3804        // match the surrounding panel chrome.
3805        if style.bg.is_none() {
3806            style = style.bg(base_bg);
3807        }
3808        spans.push(Span::styled(slice, style));
3809    }
3810
3811    let line = Line::from(spans);
3812    let rect = ratatui::layout::Rect {
3813        x,
3814        y,
3815        width,
3816        height: 1,
3817    };
3818    frame.render_widget(Paragraph::new(line).style(base_style), rect);
3819}
3820
3821/// Translate a UTF-8 byte offset within a rendered line into a
3822/// display-column offset, walking codepoints with their Unicode
3823/// width. Used to place the hardware caret on the focused
3824/// TextInput's byte position.
3825fn byte_to_screen_col(text: &str, target_byte: usize) -> usize {
3826    use unicode_width::UnicodeWidthChar;
3827    let mut byte = 0;
3828    let mut col = 0usize;
3829    for ch in text.chars() {
3830        if byte >= target_byte {
3831            break;
3832        }
3833        col += UnicodeWidthChar::width(ch).unwrap_or(0);
3834        byte += ch.len_utf8();
3835    }
3836    col
3837}