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 parsed = {
2166            self.active_window()
2167                .prompt
2168                .as_ref()
2169                .and_then(|prompt| {
2170                    let idx = prompt.selected_suggestion?;
2171                    prompt.suggestions.get(idx)
2172                })
2173                .map(|s| {
2174                    // `value` is the authoritative `path:line:col` for the
2175                    // result. We must not rely on parsing the user-facing
2176                    // label (`text`), which may carry source badges (e.g.
2177                    // "[term]") that make it unparseable as a path. Only fall
2178                    // back to the label when `value` is absent/unparseable.
2179                    if let Some(v) = s.value.as_deref() {
2180                        let from_value = parse_path_line_col(v);
2181                        if !from_value.0.is_empty() && from_value.1.is_some() {
2182                            return from_value;
2183                        }
2184                    }
2185                    parse_path_line_col(&s.text)
2186                })
2187        };
2188        // No selectable result (empty list, no selection, or an
2189        // unparseable entry): blank the preview so the previous match's
2190        // content doesn't linger after the result list clears.
2191        let (path_str, line, col) = match parsed {
2192            Some((path, line, col)) if !path.is_empty() => (path, line, col),
2193            _ => {
2194                self.blank_overlay_preview();
2195                return;
2196            }
2197        };
2198        let line = line.unwrap_or(1).saturating_sub(1);
2199        let col = col.unwrap_or(1).saturating_sub(1);
2200
2201        // Resolve relative to the working directory.
2202        let path_buf = std::path::PathBuf::from(&path_str);
2203        let abs_path = if path_buf.is_absolute() {
2204            path_buf
2205        } else {
2206            self.working_dir().join(&path_buf)
2207        };
2208        // Canonicalize for buffer-dedup parity with open_file_no_focus.
2209        let abs_path = self
2210            .authority
2211            .filesystem
2212            .canonicalize(&abs_path)
2213            .unwrap_or(abs_path);
2214
2215        // If the standalone state already targets this path, just
2216        // re-seed the cursor and skip the file-load roundtrip.
2217        let already_target = self
2218            .active_window()
2219            .overlay_preview_state
2220            .as_ref()
2221            .is_some_and(|st| {
2222                self.windows
2223                    .get(&self.active_window)
2224                    .map(|w| &w.buffers)
2225                    .expect("active window present")
2226                    .get(&st.buffer_id)
2227                    .and_then(|s| s.buffer.file_path())
2228                    .is_some_and(|p| p == abs_path.as_path())
2229            });
2230
2231        let buffer_id = if already_target {
2232            self.active_window_mut()
2233                .overlay_preview_state
2234                .as_ref()
2235                .unwrap()
2236                .buffer_id
2237        } else {
2238            // Snapshot whether this path was already known so we can
2239            // tell "I just loaded it for preview" from "the user had
2240            // it open" — only the former gets cleaned up on close.
2241            let was_open = self
2242                .buffers()
2243                .iter()
2244                .any(|(_, s)| s.buffer.file_path() == Some(abs_path.as_path()));
2245            // Capture the active split so we can undo the side
2246            // effects of `open_file_no_focus` (it adds the buffer to
2247            // the active split's tabs and may switch its active
2248            // buffer to the loaded file).
2249            let source_split = self
2250                .windows
2251                .get(&self.active_window)
2252                .and_then(|w| w.buffers.splits())
2253                .map(|(mgr, _)| mgr)
2254                .expect("active window must have a populated split layout")
2255                .active_split();
2256            // `open_file_for_preview` always allocates a fresh buffer
2257            // — never repurposes the "no name" empty buffer the user
2258            // is currently looking at — so the background view stays
2259            // intact while we cycle through preview results.
2260            let buffer_id = match self.open_file_for_preview(abs_path.as_path()) {
2261                Ok(id) => id,
2262                Err(_e) => return,
2263            };
2264            if !was_open {
2265                if let Some(meta) = self.active_window_mut().buffer_metadata.get_mut(&buffer_id) {
2266                    meta.hidden_from_tabs = true;
2267                }
2268                // Drop the buffer from every split's `open_buffers`
2269                // list so it doesn't surface as a tab anywhere. The
2270                // phantom buffer is rendered exclusively via the
2271                // overlay's standalone view-state — it doesn't need
2272                // to be in `open_buffers`.
2273                let leaf_ids: Vec<_> = self
2274                    .windows
2275                    .get(&self.active_window)
2276                    .and_then(|w| w.buffers.splits())
2277                    .map(|(_, vs)| vs)
2278                    .expect("active window must have a populated split layout")
2279                    .keys()
2280                    .copied()
2281                    .collect();
2282                for leaf_id in leaf_ids {
2283                    if let Some(view_state) = self
2284                        .windows
2285                        .get_mut(&self.active_window)
2286                        .and_then(|w| w.split_view_states_mut())
2287                        .expect("active window must have a populated split layout")
2288                        .get_mut(&leaf_id)
2289                    {
2290                        view_state.remove_buffer(buffer_id);
2291                    }
2292                }
2293                // open_file_no_focus may have switched the active
2294                // buffer of the source split. Restore it.
2295                let preview_loaded: std::collections::HashSet<BufferId> = self
2296                    .active_window_mut()
2297                    .overlay_preview_state
2298                    .as_ref()
2299                    .map(|st| st.loaded_buffers.clone())
2300                    .unwrap_or_default();
2301                let __active_id = self.active_window;
2302                let __win = self
2303                    .windows
2304                    .get_mut(&__active_id)
2305                    .expect("active window must exist");
2306                let __buffer_keys: Vec<BufferId> = __win.buffers.ids();
2307                let (__mgr, __vs_map) = __win
2308                    .buffers
2309                    .splits_mut()
2310                    .expect("active window must have a populated split layout");
2311                if let Some(source_state) = __vs_map.get_mut(&source_split) {
2312                    if source_state.active_buffer == buffer_id {
2313                        let fallback = source_state
2314                            .open_buffers
2315                            .iter()
2316                            .find_map(|t| t.as_buffer())
2317                            .or_else(|| {
2318                                __buffer_keys
2319                                    .iter()
2320                                    .copied()
2321                                    .find(|b| *b != buffer_id && !preview_loaded.contains(b))
2322                            });
2323                        if let Some(fb) = fallback {
2324                            source_state.switch_buffer(fb);
2325                            __mgr.set_split_buffer(source_split, fb);
2326                        }
2327                    }
2328                }
2329                self.windows
2330                    .get_mut(&self.active_window)
2331                    .and_then(|w| w.split_manager_mut())
2332                    .expect("active window must have a populated split layout")
2333                    .set_active_split(source_split);
2334            }
2335            buffer_id
2336        };
2337
2338        // Build (or update) the standalone preview state. Held off
2339        // `split_view_states` so cross-cutting iteration never touches
2340        // it.
2341        let need_init = self.active_window_mut().overlay_preview_state.is_none();
2342        if need_init {
2343            let mut view_state = crate::view::split::SplitViewState::with_buffer(
2344                self.terminal_width,
2345                self.terminal_height,
2346                buffer_id,
2347            );
2348            view_state.apply_config_defaults(
2349                self.config.editor.line_numbers,
2350                self.config.editor.highlight_current_line,
2351                self.active_window().resolve_line_wrap_for_buffer(buffer_id),
2352                self.config.editor.wrap_indent,
2353                self.active_window()
2354                    .resolve_wrap_column_for_buffer(buffer_id),
2355                self.config.editor.rulers.clone(),
2356            );
2357            let mut loaded_buffers = std::collections::HashSet::new();
2358            // Whether this *first* preview buffer was newly loaded.
2359            // The pre-existing case skips the `was_open` branch so
2360            // we re-derive it from buffer_metadata: a buffer with
2361            // hidden_from_tabs=true that we just touched is one we
2362            // owned. Simpler: track via the existing-target check:
2363            // if `already_target` was false above, the buffer was
2364            // either pre-open (we left meta alone) or freshly
2365            // loaded (we set hidden_from_tabs=true). Re-check.
2366            if let Some(meta) = self.active_window().buffer_metadata.get(&buffer_id) {
2367                if meta.hidden_from_tabs {
2368                    loaded_buffers.insert(buffer_id);
2369                }
2370            }
2371            self.active_window_mut().overlay_preview_state =
2372                Some(crate::app::types::OverlayPreviewState {
2373                    buffer_id,
2374                    view_state,
2375                    loaded_buffers,
2376                    blanked: false,
2377                });
2378        } else {
2379            // Pre-compute hidden flag (immutable borrow on self.windows)
2380            // before taking the mutable borrow on overlay_preview_state.
2381            let hidden_from_tabs = self
2382                .windows
2383                .get(&self.active_window)
2384                .and_then(|w| w.buffer_metadata.get(&buffer_id))
2385                .is_some_and(|meta| meta.hidden_from_tabs);
2386            if let Some(state) = self.active_window_mut().overlay_preview_state.as_mut() {
2387                if state.buffer_id != buffer_id {
2388                    state.view_state.switch_buffer(buffer_id);
2389                    // Keep the struct's `buffer_id` in lockstep with the
2390                    // view-state's active buffer: the renderer looks up the
2391                    // buffer to draw via this field, so a stale value here
2392                    // renders the *previous* file's text at the new file's
2393                    // scroll offset (wrong content, or blank past EOF).
2394                    state.buffer_id = buffer_id;
2395                    if hidden_from_tabs {
2396                        state.loaded_buffers.insert(buffer_id);
2397                    }
2398                }
2399            }
2400        }
2401
2402        // Set the cursor to the match position and centre the line.
2403        let byte_offset = self
2404            .buffers()
2405            .get(&buffer_id)
2406            .map(|s| {
2407                s.buffer
2408                    .position_to_offset(crate::model::piece_tree::Position { line, column: col })
2409            })
2410            .unwrap_or(0);
2411        let line_start = self
2412            .buffers()
2413            .get(&buffer_id)
2414            .and_then(|s| s.buffer.line_start_offset(line))
2415            .unwrap_or(byte_offset);
2416        // Compute top_byte BEFORE taking the mutable borrow on
2417        // overlay_preview_state to keep the borrows disjoint.
2418        let h_for_preview = self
2419            .active_window_mut()
2420            .overlay_preview_state
2421            .as_ref()
2422            .map(|s| s.view_state.viewport.height.max(1) as usize)
2423            .unwrap_or(1);
2424        let half = h_for_preview / 2;
2425        let target_top_line = line.saturating_sub(half);
2426        let top_byte = self
2427            .windows
2428            .get(&self.active_window)
2429            .map(|w| &w.buffers)
2430            .expect("active window present")
2431            .get(&buffer_id)
2432            .and_then(|s| s.buffer.line_start_offset(target_top_line))
2433            .unwrap_or(line_start);
2434        if let Some(state) = self.active_window_mut().overlay_preview_state.as_mut() {
2435            state.view_state.cursors.primary_mut().position = byte_offset;
2436            // Force line wrapping on for the preview regardless of the
2437            // global `editor.line_wrap` setting (and of a switched-in
2438            // buffer's fresh default): the preview pane has no horizontal
2439            // scroll affordance, so without wrapping a match deep in a long
2440            // line scrolls the start of the line off-screen and the context
2441            // is unreadable. Wrapping also moots horizontal scroll, so reset
2442            // it to the left edge. `view_state` derefs to the active
2443            // buffer's `BufferViewState`, so this targets the buffer that's
2444            // actually rendered.
2445            state.view_state.viewport.line_wrap_enabled = true;
2446            state.view_state.viewport.left_column = 0;
2447            state.view_state.viewport.horizontal_scroll_offset = 0;
2448            state.view_state.viewport.top_byte = top_byte;
2449            // We have a live target: ensure the pane is shown.
2450            state.blanked = false;
2451        }
2452    }
2453
2454    /// Blank the Live Grep preview pane: it renders just its frame until
2455    /// the next selectable result. Keeps `overlay_preview_state` (and its
2456    /// `loaded_buffers` cleanup tracking) intact.
2457    fn blank_overlay_preview(&mut self) {
2458        if let Some(state) = self.active_window_mut().overlay_preview_state.as_mut() {
2459            state.blanked = true;
2460        }
2461    }
2462
2463    /// Render the active prompt as a centred floating overlay
2464    /// (issue #1796). Layout, top-down inside the overlay frame:
2465    ///
2466    /// ```text
2467    /// ┌─ Live Grep ──────────────────────────────────[Esc to close]┐
2468    /// │ Search: split_active|                           12 / 142    │  ← input row
2469    /// │ ─────────────────────────────────────────────────────────── │
2470    /// │  src/view/split.rs:1117  pub fn split_active(    │ preview │  ← results
2471    /// │  src/view/split.rs:1123  self.split_active_pos…  │  pane   │     (+ optional
2472    /// │ …                                                │         │      preview)
2473    /// └────────────────────────────────────────────────────────────┘
2474    /// ```
2475    ///
2476    /// The overlay does *not* mutate the split tree; it is a pure
2477    /// `ratatui` overdraw, so dismissing leaves the user's underlying
2478    /// layout exactly as it was (the issue-#1796 acceptance test).
2479    fn render_overlay_prompt(&mut self, frame: &mut Frame, area: ratatui::layout::Rect) {
2480        use ratatui::layout::Rect;
2481        use ratatui::style::{Modifier, Style};
2482        use ratatui::text::{Line, Span};
2483        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
2484
2485        // Compute the overlay rect via the same percentage logic the
2486        // popup engine uses. 90% × 90% of the terminal, centred.
2487        let overlay_rect = Self::centered_overlay_rect(area, 90, 90);
2488
2489        // Snapshot view-relevant state before any mutable borrows.
2490        let theme = self.theme.read().unwrap().clone();
2491        // The suggestion list inside the overlay can be ~30 rows
2492        // tall on a typical terminal. Pass the *actual* visible
2493        // count to `ensure_selected_visible_within` so the scroll
2494        // offset only advances when the selection genuinely passes
2495        // the bottom of the visible window — not when it crosses
2496        // the bottom-popup default cap of `MAX_VISIBLE_SUGGESTIONS`
2497        // (= 10), which would scroll prematurely.
2498        //
2499        // Geometry: overlay frame border (2) + input row (1) +
2500        // optional toolbar row (1, when `prompt.title` is non-empty)
2501        // + separator (1). The suggestions popup is rendered
2502        // borderless inside the overlay (the outer frame already
2503        // provides a border, so adding a nested one creates a
2504        // double-frame). Inner content height = overlay.height -
2505        // chrome.
2506        // Toolbar height must be the *actual* rendered row count — a widget
2507        // toolbar is ≥2 rows (e.g. "Search in:" + "Match:") and wraps to more
2508        // on a narrow terminal. Measuring it (vs assuming 1) keeps
2509        // `suggestions_visible_rows` honest, so `ensure_selected_visible`
2510        // doesn't let the selection scroll just past the real list bottom.
2511        let inner_w = overlay_rect.width.saturating_sub(2);
2512        let toolbar_rows: usize = self
2513            .active_window()
2514            .prompt
2515            .as_ref()
2516            .map(|p| {
2517                if let Some(spec) = p.toolbar_widget.as_ref() {
2518                    crate::widgets::render_spec_no_autofocus(
2519                        spec,
2520                        &std::collections::HashMap::new(),
2521                        p.toolbar_focus.as_deref().unwrap_or(""),
2522                        inner_w as u32,
2523                    )
2524                    .entries
2525                    .len()
2526                } else if p.title.is_empty() {
2527                    0
2528                } else {
2529                    1
2530                }
2531            })
2532            .unwrap_or(0);
2533        let footer_visible = self
2534            .active_window()
2535            .prompt
2536            .as_ref()
2537            .map(|p| !p.footer.is_empty())
2538            .unwrap_or(false);
2539        // Chrome around the result list: frame border (2) + input (1) +
2540        // separator (1) + toolbar (`toolbar_rows`) + optional full-width footer (1).
2541        let chrome_rows: usize = 4 + toolbar_rows + usize::from(footer_visible);
2542        let suggestions_visible_rows = (overlay_rect.height as usize).saturating_sub(chrome_rows);
2543        if let Some(prompt) = self.active_window_mut().prompt.as_mut() {
2544            prompt.ensure_selected_visible_within(suggestions_visible_rows);
2545        }
2546        let Some(prompt) = self.active_window().prompt.as_ref() else {
2547            return;
2548        };
2549        let prompt = prompt.clone();
2550
2551        // Dim everything outside the overlay rect so the user's
2552        // focus visibly belongs to the popup. Reuses the same RGB-
2553        // darkening pass the Settings modal uses (`view::dimming`)
2554        // — Modifier::DIM alone is barely visible on most terminals.
2555        crate::view::dimming::apply_dimming_excluding(frame, frame.area(), Some(overlay_rect));
2556
2557        // Clear and frame. Plugin-owned prompts can publish their
2558        // own title via `editor.setPromptTitle(...)`; falls back to
2559        // " Live Grep " plus shortcut hints when unset (so a
2560        // Resume-replay prompt and freshly-opened plugin prompt look
2561        // similar even though they take different code paths).
2562        frame.render_widget(Clear, overlay_rect);
2563        let default_title: Vec<fresh_core::api::StyledText> = {
2564            // Mirrors `updateOverlayTitle` in live_grep.ts (kept in
2565            // sync deliberately so a Resume-replay overlay and a
2566            // freshly-opened plugin overlay look identical). The
2567            // input row's prefix already says "Live grep:", so the
2568            // frame title doesn't repeat the feature name — it
2569            // shows shortcut hints only. `resume_live_grep` is
2570            // intentionally NOT shown here; that shortcut only
2571            // matters once the overlay is closed.
2572            use crate::input::keybindings::KeyContext;
2573            use fresh_core::api::{OverlayColorSpec, OverlayOptions, StyledText};
2574            let keybindings = self.keybindings.read().unwrap();
2575            let mut hints: Vec<(String, &str)> = Vec::new();
2576            if let Some(k) = keybindings
2577                .find_keybinding_for_action("cycle_live_grep_provider", KeyContext::Prompt)
2578            {
2579                hints.push((k, "switch grep provider"));
2580            }
2581            if let Some(k) = keybindings
2582                .find_keybinding_for_action("live_grep_export_quickfix", KeyContext::Prompt)
2583            {
2584                hints.push((k, "save matches"));
2585            }
2586            if hints.is_empty() {
2587                Vec::new()
2588            } else {
2589                let hint_style = Some(OverlayOptions {
2590                    fg: Some(OverlayColorSpec::ThemeKey("ui.help_key_fg".into())),
2591                    ..OverlayOptions::default()
2592                });
2593                let sep_style = Some(OverlayOptions {
2594                    fg: Some(OverlayColorSpec::ThemeKey("ui.popup_border_fg".into())),
2595                    ..OverlayOptions::default()
2596                });
2597                let mut segs: Vec<StyledText> = Vec::new();
2598                for (i, (k, verb)) in hints.into_iter().enumerate() {
2599                    if i > 0 {
2600                        segs.push(StyledText {
2601                            text: " · ".into(),
2602                            style: sep_style.clone(),
2603                        });
2604                    }
2605                    segs.push(StyledText {
2606                        text: k,
2607                        style: hint_style.clone(),
2608                    });
2609                    segs.push(StyledText {
2610                        text: format!(" {verb}"),
2611                        style: None,
2612                    });
2613                }
2614                segs
2615            }
2616        };
2617        let title_segs: &[fresh_core::api::StyledText] = if prompt.title.is_empty() {
2618            &default_title
2619        } else {
2620            &prompt.title
2621        };
2622        let normal_title_style = Style::default()
2623            .fg(theme.prompt_fg)
2624            .add_modifier(Modifier::BOLD);
2625        let title_spans: Vec<Span> = title_segs
2626            .iter()
2627            .map(|seg| {
2628                let style = match &seg.style {
2629                    Some(opts) => Self::resolve_overlay_style(opts, &theme),
2630                    None => normal_title_style,
2631                };
2632                Span::styled(seg.text.clone(), style)
2633            })
2634            .collect();
2635        let block = Block::default()
2636            .borders(Borders::ALL)
2637            .border_style(Style::default().fg(theme.popup_border_fg))
2638            .style(Style::default().bg(theme.suggestion_bg));
2639        let inner = block.inner(overlay_rect);
2640        frame.render_widget(block, overlay_rect);
2641
2642        if inner.height == 0 || inner.width == 0 {
2643            return;
2644        }
2645
2646        // If the plugin supplied a widget toolbar, render it now (full inner
2647        // width) so we know its height before laying out the header band. The
2648        // toggles are real `Toggle` widgets — themed and clickable — rather
2649        // than styled text. `render_spec` is stateless here (empty prior
2650        // state / no focus key): a `Toggle`'s checked-ness lives in the spec,
2651        // and click-to-toggle is routed by key (no registry needed).
2652        let toolbar_focus_key = prompt.toolbar_focus.as_deref().unwrap_or("");
2653        let toolbar_widget_out: Option<crate::widgets::RenderOutput> =
2654            prompt.toolbar_widget.as_ref().map(|spec| {
2655                crate::widgets::render_spec_no_autofocus(
2656                    spec,
2657                    &std::collections::HashMap::new(),
2658                    toolbar_focus_key,
2659                    inner.width as u32,
2660                )
2661            });
2662
2663        // Layout: a full-width HEADER band (input + toolbar + separator)
2664        // spans the whole inner width at the top; the BODY below it splits
2665        // into results | preview; a full-width FOOTER (when the plugin set
2666        // one) sits at the very bottom. This gives the toolbar the entire
2667        // pane width — the scope checkboxes don't fit when squeezed into the
2668        // left half beside the preview — and places the preview *under* the
2669        // toolbar, side-by-side with the result list. See
2670        // docs/internal/global-search-ux.md §12.
2671        let toolbar_h: u16 = match &toolbar_widget_out {
2672            Some(out) => out.entries.len() as u16,
2673            None if !prompt.title.is_empty() => 1,
2674            None => 0,
2675        };
2676        let footer_h: u16 = if prompt.footer.is_empty() { 0 } else { 1 };
2677        // Header rows = input(1) + toolbar(toolbar_h) + separator(1).
2678        let header_h: u16 = 2 + toolbar_h;
2679        let body = Rect {
2680            x: inner.x,
2681            y: inner.y.saturating_add(header_h),
2682            width: inner.width,
2683            height: inner.height.saturating_sub(header_h + footer_h),
2684        };
2685
2686        // Split the body into results | preview. Below ~120 cols, stack
2687        // results-only (preview hidden — see design doc §5 "preview pane size
2688        // when terminal is narrow").
2689        let preview_min_cols: u16 = 120;
2690        let show_preview = overlay_rect.width >= preview_min_cols && body.height > 0;
2691        let (results_area, preview_area) = if show_preview {
2692            let results_w = body.width / 2;
2693            (
2694                Rect {
2695                    x: body.x,
2696                    y: body.y,
2697                    width: results_w,
2698                    height: body.height,
2699                },
2700                Some(Rect {
2701                    x: body.x + results_w,
2702                    y: body.y,
2703                    width: body.width - results_w,
2704                    height: body.height,
2705                }),
2706            )
2707        } else {
2708            (body, None)
2709        };
2710
2711        // The prompt input is the full-width top row of the header band.
2712        let input_row = Rect {
2713            x: inner.x,
2714            y: inner.y,
2715            width: inner.width,
2716            height: 1,
2717        };
2718        // Two distinct styles on this row so the user can tell
2719        // the static title (`prompt.message`) apart from the
2720        // editable input field. Title gets the popup-chrome bg
2721        // (matching the toolbar/footer); input + right-side
2722        // padding + count get the editor bg so they read as one
2723        // contiguous text field. All colours from theme keys.
2724        let title_style = Style::default().fg(theme.prompt_fg).bg(theme.suggestion_bg);
2725        let input_style = Style::default().fg(theme.prompt_fg).bg(theme.editor_bg);
2726        let count_str = if prompt.suggestions.is_empty() {
2727            String::new()
2728        } else {
2729            format!(
2730                "{} / {}",
2731                prompt.selected_suggestion.map(|i| i + 1).unwrap_or(0),
2732                prompt.suggestions.len()
2733            )
2734        };
2735        use crate::primitives::display_width::str_width;
2736        let count_w = str_width(&count_str);
2737        // Reserve one trailing column so the count doesn't sit
2738        // flush against the right border.
2739        let right_gap: usize = if count_w > 0 { 1 } else { 0 };
2740        // Right cluster: "<status>  <count>" — the plugin's search status
2741        // (e.g. "Searching…", "No matches") sits just left of the count, so
2742        // it's on the same row the user is typing on rather than a wasted
2743        // chrome row. Two-space gap between status and count when both show.
2744        let status_str = prompt.status.clone();
2745        let status_w = str_width(&status_str);
2746        let status_gap: usize = if status_w > 0 && count_w > 0 { 2 } else { 0 };
2747        let right_cluster_w = status_w + status_gap + count_w + right_gap;
2748        let visible_input_width = (input_row.width as usize).saturating_sub(right_cluster_w);
2749        let truncated_input: String = prompt
2750            .input
2751            .chars()
2752            .take(visible_input_width.saturating_sub(str_width(&prompt.message)))
2753            .collect();
2754        // Pad between the typed input and the right cluster so the count is
2755        // right-aligned (with `right_gap` empty cols at the very edge),
2756        // independent of how much the user has typed.
2757        let used = str_width(&prompt.message) + str_width(&truncated_input) + right_cluster_w;
2758        let pad = (input_row.width as usize).saturating_sub(used);
2759        let dim = Style::default()
2760            .fg(theme.popup_border_fg)
2761            .bg(theme.editor_bg);
2762        let line = Line::from(vec![
2763            Span::styled(prompt.message.clone(), title_style),
2764            Span::styled(truncated_input, input_style),
2765            Span::styled(" ".repeat(pad), input_style),
2766            Span::styled(status_str, dim),
2767            Span::styled(" ".repeat(status_gap), input_style),
2768            Span::styled(count_str, dim),
2769        ]);
2770        frame.render_widget(Paragraph::new(line).style(input_style), input_row);
2771
2772        // Cursor position on the input row — only when the input is focused.
2773        // When a toolbar control owns focus, the highlighted toggle is the
2774        // focus indicator and the input caret would be misleading.
2775        let input_focused = prompt.toolbar_focus.is_none();
2776        let cursor_x = (str_width(&prompt.message)
2777            + str_width(&prompt.input[..prompt.cursor_pos.min(prompt.input.len())]))
2778            as u16;
2779        if input_focused && cursor_x < input_row.width {
2780            frame.set_cursor_position((input_row.x + cursor_x, input_row.y));
2781        }
2782
2783        // Optional toolbar row (the styled segments the plugin set
2784        // via setPromptTitle, e.g. "Provider: rg · Alt+P switch
2785        // grep provider · …"). Sits between the input row and the
2786        // separator so the user sees feature-scoped controls right
2787        // under what they're typing — not on the frame border
2788        // where shortcut hints get visually lost.
2789        self.active_chrome_mut().prompt_toolbar_hits.clear();
2790        if let Some(out) = &toolbar_widget_out {
2791            // Widget toolbar: paint each rendered row across the full width
2792            // and record screen-space hit rects (key → rect) for click
2793            // routing. `HitArea` carries byte offsets within the row's text;
2794            // convert to display columns so the rect lines up with the glyphs.
2795            use crate::primitives::display_width::str_width;
2796            let band_y = inner.y + 1;
2797            for (i, entry) in out.entries.iter().enumerate() {
2798                let y = band_y + i as u16;
2799                if y >= inner.y + inner.height {
2800                    break;
2801                }
2802                paint_text_property_entry(frame, entry, inner.x, y, inner.width, &theme);
2803            }
2804            for hit in &out.hits {
2805                if hit.widget_key.is_empty() {
2806                    continue;
2807                }
2808                let Some(entry) = out.entries.get(hit.buffer_row as usize) else {
2809                    continue;
2810                };
2811                let text = &entry.text;
2812                let start_col = str_width(text.get(..hit.byte_start).unwrap_or(""));
2813                let end_col = str_width(text.get(..hit.byte_end).unwrap_or(text));
2814                let y = band_y + hit.buffer_row as u16;
2815                let rect = Rect {
2816                    x: inner.x + start_col as u16,
2817                    y,
2818                    width: (end_col.saturating_sub(start_col)) as u16,
2819                    height: 1,
2820                };
2821                self.active_chrome_mut()
2822                    .prompt_toolbar_hits
2823                    .push((hit.widget_key.clone(), rect));
2824            }
2825        } else if !prompt.title.is_empty() && inner.height >= 2 {
2826            let toolbar = Rect {
2827                x: inner.x,
2828                y: inner.y + 1,
2829                width: inner.width,
2830                height: 1,
2831            };
2832            frame.render_widget(
2833                Paragraph::new(Line::from(title_spans))
2834                    .style(Style::default().bg(theme.suggestion_bg)),
2835                toolbar,
2836            );
2837        }
2838
2839        // Separator row (full width), closing the header band.
2840        if inner.height >= 2 + toolbar_h {
2841            let sep = Rect {
2842                x: inner.x,
2843                y: inner.y + 1 + toolbar_h,
2844                width: inner.width,
2845                height: 1,
2846            };
2847            let sep_style = Style::default()
2848                .fg(theme.popup_border_fg)
2849                .bg(theme.suggestion_bg);
2850            let sep_text = "─".repeat(inner.width as usize);
2851            frame.render_widget(Paragraph::new(sep_text).style(sep_style), sep);
2852        }
2853
2854        // Suggestions list fills `results_area` (the left half of the body)
2855        // entirely — the input, toolbar and separator now live in the header
2856        // band above, and the footer is a separate full-width row below, so
2857        // there's no in-column chrome to subtract here. Carve off the
2858        // rightmost 1-column lane for a scrollbar so the user can see how far
2859        // through the result set the selection is — only when the result set
2860        // actually exceeds the visible rows; otherwise the scrollbar is
2861        // visual noise.
2862        if results_area.height >= 1 {
2863            // No `-2` for popup-own-border — we render the
2864            // borderless variant below since the overlay frame is
2865            // already a border.
2866            let inner_rows = results_area.height as usize;
2867            let needs_scrollbar = prompt.suggestions.len() > inner_rows.max(1);
2868            let scrollbar_w: u16 = if needs_scrollbar { 1 } else { 0 };
2869            let list_area = Rect {
2870                x: results_area.x,
2871                y: results_area.y,
2872                width: results_area.width.saturating_sub(scrollbar_w),
2873                height: results_area.height,
2874            };
2875            self.active_chrome_mut().suggestions_area = SuggestionsRenderer::render_with_hover(
2876                frame,
2877                list_area,
2878                &prompt,
2879                &theme,
2880                self.active_window_mut().mouse_state.hover_target.as_ref(),
2881                false,
2882            );
2883            if self.active_chrome_mut().suggestions_area.is_some() {
2884                self.active_chrome_mut().suggestions_outer_area = Some(list_area);
2885            }
2886            // Render the scrollbar in the carved lane. Reuses the
2887            // shared `view::ui::scrollbar` widget so thumb sizing
2888            // and theme colours match scrollbars elsewhere in the
2889            // editor (split rendering, file explorer, …).
2890            if needs_scrollbar {
2891                use crate::view::ui::scrollbar::{
2892                    render_scrollbar, ScrollbarColors, ScrollbarState,
2893                };
2894                // Scrollbar rect aligns with the borderless
2895                // suggestions list — same y/height as the list itself
2896                // since there's no popup-own border to skip.
2897                let scrollbar_rect = Rect {
2898                    x: results_area.x + results_area.width - 1,
2899                    y: list_area.y,
2900                    width: 1,
2901                    height: list_area.height,
2902                };
2903                let state = ScrollbarState::new(
2904                    prompt.suggestions.len(),
2905                    inner_rows.max(1),
2906                    prompt.scroll_offset,
2907                );
2908                render_scrollbar(
2909                    frame,
2910                    scrollbar_rect,
2911                    &state,
2912                    &ScrollbarColors::from_theme(&theme),
2913                );
2914                // Cache the rect for mouse hit testing in
2915                // `mouse_input.rs::handle_click_prompt_scrollbar`.
2916                self.active_chrome_mut().suggestions_scrollbar_rect = Some(scrollbar_rect);
2917            } else {
2918                self.active_chrome_mut().suggestions_scrollbar_rect = None;
2919            }
2920        } else {
2921            self.active_chrome_mut().suggestions_scrollbar_rect = None;
2922        }
2923
2924        // Plugin-supplied footer chrome row (Primitive #2 chrome
2925        // region). Each segment is a `StyledText` — same styling
2926        // primitive used by `setPromptTitle` and inline overlays,
2927        // so plugins can theme hotkey hints with `ui.help_key_fg`,
2928        // separators with `ui.popup_border_fg`, etc.
2929        if footer_h == 1 && inner.height >= 1 {
2930            let footer_row = Rect {
2931                x: inner.x,
2932                y: inner.y + inner.height - 1,
2933                width: inner.width,
2934                height: 1,
2935            };
2936            let footer_default_style = Style::default().fg(theme.prompt_fg).bg(theme.suggestion_bg);
2937            let footer_spans: Vec<Span> = prompt
2938                .footer
2939                .iter()
2940                .map(|seg| {
2941                    let style = match &seg.style {
2942                        Some(opts) => Self::resolve_overlay_style(opts, &theme),
2943                        None => footer_default_style,
2944                    };
2945                    Span::styled(seg.text.clone(), style)
2946                })
2947                .collect();
2948            frame.render_widget(
2949                Paragraph::new(Line::from(footer_spans))
2950                    .style(Style::default().bg(theme.suggestion_bg)),
2951                footer_row,
2952            );
2953        }
2954
2955        // Right-half preview pane: a real Buffer rendered via the
2956        // same per-leaf pipeline regular splits use. Buffer + cursor
2957        // are already seeded by `prepare_overlay_preview` (called
2958        // earlier in the render flow). Borrows are split here so we
2959        // can hand out independent `&mut` references to the
2960        // renderer's internals without going back through `&mut self`.
2961        if let Some(preview_rect) = preview_area {
2962            // Frame the preview area first (vertical separator) so
2963            // the renderer fills the inner rect.
2964            use ratatui::widgets::{Block, Borders, Clear};
2965            frame.render_widget(Clear, preview_rect);
2966            let block = Block::default()
2967                .borders(Borders::LEFT)
2968                .border_style(Style::default().fg(theme.popup_border_fg))
2969                .style(Style::default().bg(theme.suggestion_bg));
2970            let inner = block.inner(preview_rect);
2971            frame.render_widget(block, preview_rect);
2972
2973            // Primitive #1: if the active plugin asked us to
2974            // preview a specific (inactive) session in this
2975            // rect, render that session's entire stashed split
2976            // tree natively into `inner`. Falls back to the
2977            // existing path-based phantom-leaf preview when no
2978            // session override is set.
2979            if inner.height > 0
2980                && inner.width > 0
2981                && self
2982                    .preview_window_id
2983                    .is_some_and(|sid| sid != self.active_window && self.windows.contains_key(&sid))
2984            {
2985                self.render_session_preview_into_rect(frame, inner, &theme);
2986            } else if inner.height > 0 && inner.width > 0 {
2987                // Snapshot scalar config values up front so the
2988                // mutable-borrow split below has minimal scope.
2989                // AnsiBackground isn't Clone, so it's taken as a
2990                // borrow; Rust permits disjoint-field splitting
2991                // between `&self.ansi_background` and the `&mut`
2992                // accesses below because they touch distinct fields.
2993                let bg_fade = self.background_fade;
2994                let estimated_line_length = self.config.editor.estimated_line_length;
2995                let highlight_context_bytes = self.config.editor.highlight_context_bytes;
2996                let relative_line_numbers = self.config.editor.relative_line_numbers;
2997                let use_terminal_bg = self.config.editor.use_terminal_bg;
2998                let session_mode = self.session_mode || !self.software_cursor_only;
2999                let software_cursor_only = self.software_cursor_only;
3000                let diagnostics_inline_text = self.config.editor.diagnostics_inline_text;
3001                let show_tilde = false; // preview hides tilde markers
3002                let highlight_current_column = self.config.editor.highlight_current_column;
3003                let screen_width = frame.area().width;
3004
3005                let ansi_ref = self.ansi_background.as_ref();
3006                let __win = self
3007                    .windows
3008                    .get_mut(&self.active_window)
3009                    .expect("active window present");
3010                let buffers = &mut __win.buffers;
3011                let event_logs = &mut __win.event_logs;
3012                let cell_theme_map = &mut __win.chrome_layout.cell_theme_map;
3013                let Some(preview_state) = __win.overlay_preview_state.as_mut() else {
3014                    return;
3015                };
3016                // Blanked: the current query has no selectable result, so
3017                // leave the framed pane empty rather than rendering a stale
3018                // match.
3019                if preview_state.blanked {
3020                    return;
3021                }
3022                preview_state
3023                    .view_state
3024                    .viewport
3025                    .resize(inner.width, inner.height);
3026                let buffer_id = preview_state.buffer_id;
3027
3028                if let Some(state) = buffers.get_mut(&buffer_id) {
3029                    // Deref the SplitViewState once to a concrete
3030                    // `&mut BufferViewState` so disjoint field
3031                    // splits (`viewport` + `folds`) are visible
3032                    // to the borrow checker.
3033                    let buf_state = preview_state.view_state.active_state_mut();
3034                    let cursors = buf_state.cursors.clone();
3035                    let view_mode = buf_state.view_mode.clone();
3036                    let compose_width = buf_state.compose_width;
3037                    let compose_column_guides = buf_state.compose_column_guides.clone();
3038                    let view_transform = buf_state.view_transform.clone();
3039                    let rulers = buf_state.rulers.clone();
3040                    let show_line_numbers = buf_state.show_line_numbers;
3041                    let highlight_current_line = buf_state.highlight_current_line;
3042                    let viewport_ref = &mut buf_state.viewport;
3043                    let folds_ref = &mut buf_state.folds;
3044                    let event_log = event_logs.get_mut(&buffer_id);
3045                    let _ = crate::view::ui::SplitRenderer::render_phantom_leaf(
3046                        frame,
3047                        state,
3048                        &cursors,
3049                        viewport_ref,
3050                        folds_ref,
3051                        event_log,
3052                        inner,
3053                        &theme,
3054                        ansi_ref,
3055                        bg_fade,
3056                        view_mode,
3057                        compose_width,
3058                        compose_column_guides,
3059                        view_transform,
3060                        estimated_line_length,
3061                        highlight_context_bytes,
3062                        buffer_id,
3063                        relative_line_numbers,
3064                        use_terminal_bg,
3065                        session_mode,
3066                        software_cursor_only,
3067                        &rulers,
3068                        show_line_numbers,
3069                        highlight_current_line,
3070                        diagnostics_inline_text,
3071                        show_tilde,
3072                        highlight_current_column,
3073                        cell_theme_map,
3074                        screen_width,
3075                    );
3076                }
3077            }
3078        }
3079    }
3080
3081    /// Render hover highlights for interactive elements (separators, scrollbars)
3082    pub(super) fn render_hover_highlights(&self, frame: &mut Frame) {
3083        use ratatui::style::Style;
3084        use ratatui::text::Span;
3085        use ratatui::widgets::Paragraph;
3086
3087        match &self.active_window().mouse_state.hover_target {
3088            Some(HoverTarget::SplitSeparator(split_id, direction)) => {
3089                // Highlight the separator with hover color
3090                for (sid, dir, x, y, length) in &self.active_layout().separator_areas {
3091                    if sid == split_id && dir == direction {
3092                        let (hover_fg, editor_bg) = {
3093                            let theme = self.theme.read().unwrap();
3094                            (theme.split_separator_hover_fg, theme.editor_bg)
3095                        };
3096                        let hover_style = Style::default().fg(hover_fg).bg(editor_bg);
3097                        match dir {
3098                            SplitDirection::Horizontal => {
3099                                let line_text = "─".repeat(*length as usize);
3100                                let paragraph =
3101                                    Paragraph::new(Span::styled(line_text, hover_style));
3102                                frame.render_widget(
3103                                    paragraph,
3104                                    ratatui::layout::Rect::new(*x, *y, *length, 1),
3105                                );
3106                            }
3107                            SplitDirection::Vertical => {
3108                                for offset in 0..*length {
3109                                    let paragraph = Paragraph::new(Span::styled("│", hover_style));
3110                                    frame.render_widget(
3111                                        paragraph,
3112                                        ratatui::layout::Rect::new(*x, y + offset, 1, 1),
3113                                    );
3114                                }
3115                            }
3116                        }
3117                    }
3118                }
3119            }
3120            Some(HoverTarget::ScrollbarThumb(split_id)) => {
3121                // Highlight scrollbar thumb
3122                for (sid, _buffer_id, _content_rect, scrollbar_rect, thumb_start, thumb_end) in
3123                    &self.active_layout().split_areas
3124                {
3125                    if sid == split_id {
3126                        let hover_style = Style::default().bg(self
3127                            .theme
3128                            .read()
3129                            .unwrap()
3130                            .scrollbar_thumb_hover_fg);
3131                        for row_offset in *thumb_start..*thumb_end {
3132                            let paragraph = Paragraph::new(Span::styled(" ", hover_style));
3133                            frame.render_widget(
3134                                paragraph,
3135                                ratatui::layout::Rect::new(
3136                                    scrollbar_rect.x,
3137                                    scrollbar_rect.y + row_offset as u16,
3138                                    1,
3139                                    1,
3140                                ),
3141                            );
3142                        }
3143                    }
3144                }
3145            }
3146            Some(HoverTarget::ScrollbarTrack(split_id, hovered_row)) => {
3147                // Highlight only the hovered cell on the scrollbar track
3148                for (sid, _buffer_id, _content_rect, scrollbar_rect, _thumb_start, _thumb_end) in
3149                    &self.active_layout().split_areas
3150                {
3151                    if sid == split_id {
3152                        let track_hover_style = Style::default().bg(self
3153                            .theme
3154                            .read()
3155                            .unwrap()
3156                            .scrollbar_track_hover_fg);
3157                        let paragraph = Paragraph::new(Span::styled(" ", track_hover_style));
3158                        frame.render_widget(
3159                            paragraph,
3160                            ratatui::layout::Rect::new(
3161                                scrollbar_rect.x,
3162                                scrollbar_rect.y + hovered_row,
3163                                1,
3164                                1,
3165                            ),
3166                        );
3167                    }
3168                }
3169            }
3170            Some(HoverTarget::FileExplorerBorder) => {
3171                // Highlight the file explorer border for resize
3172                if let Some(explorer_area) = self.active_layout().file_explorer_area {
3173                    let (hover_fg, editor_bg) = {
3174                        let theme = self.theme.read().unwrap();
3175                        (theme.split_separator_hover_fg, theme.editor_bg)
3176                    };
3177                    let hover_style = Style::default().fg(hover_fg).bg(editor_bg);
3178                    let border_x = explorer_area.x + explorer_area.width.saturating_sub(1);
3179                    for row_offset in 0..explorer_area.height {
3180                        let paragraph = Paragraph::new(Span::styled("│", hover_style));
3181                        frame.render_widget(
3182                            paragraph,
3183                            ratatui::layout::Rect::new(
3184                                border_x,
3185                                explorer_area.y + row_offset,
3186                                1,
3187                                1,
3188                            ),
3189                        );
3190                    }
3191                }
3192            }
3193            // Menu hover is handled by MenuRenderer
3194            _ => {}
3195        }
3196    }
3197
3198    /// Render the tab context menu
3199    fn render_tab_context_menu(&self, frame: &mut Frame, menu: &TabContextMenu) {
3200        use ratatui::style::Style;
3201        use ratatui::text::{Line, Span};
3202        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
3203
3204        let items = super::types::TabContextMenuItem::all();
3205        let menu_width = 22u16; // "Close to the Right" + padding
3206        let menu_height = items.len() as u16 + 2; // items + borders
3207
3208        // Adjust position to stay within screen bounds
3209        let screen_width = frame.area().width;
3210        let screen_height = frame.area().height;
3211
3212        let menu_x = if menu.position.0 + menu_width > screen_width {
3213            screen_width.saturating_sub(menu_width)
3214        } else {
3215            menu.position.0
3216        };
3217
3218        let menu_y = if menu.position.1 + menu_height > screen_height {
3219            screen_height.saturating_sub(menu_height)
3220        } else {
3221            menu.position.1
3222        };
3223
3224        let area = ratatui::layout::Rect::new(menu_x, menu_y, menu_width, menu_height);
3225
3226        // Clear the area first
3227        frame.render_widget(Clear, area);
3228
3229        // Build the menu lines
3230        let mut lines = Vec::new();
3231        for (idx, item) in items.iter().enumerate() {
3232            let is_highlighted = idx == menu.highlighted;
3233
3234            let style = if is_highlighted {
3235                Style::default()
3236                    .fg(self.theme.read().unwrap().menu_highlight_fg)
3237                    .bg(self.theme.read().unwrap().menu_highlight_bg)
3238            } else {
3239                Style::default()
3240                    .fg(self.theme.read().unwrap().menu_dropdown_fg)
3241                    .bg(self.theme.read().unwrap().menu_dropdown_bg)
3242            };
3243
3244            // Pad the label to fill the menu width
3245            let label = item.label();
3246            let content_width = (menu_width as usize).saturating_sub(2); // -2 for borders
3247            let padded_label = format!(" {:<width$}", label, width = content_width - 1);
3248
3249            lines.push(Line::from(vec![Span::styled(padded_label, style)]));
3250        }
3251
3252        let block = Block::default()
3253            .borders(Borders::ALL)
3254            .border_style(Style::default().fg(self.theme.read().unwrap().menu_border_fg))
3255            .style(Style::default().bg(self.theme.read().unwrap().menu_dropdown_bg));
3256
3257        let paragraph = Paragraph::new(lines).block(block);
3258        frame.render_widget(paragraph, area);
3259    }
3260
3261    /// Render the file explorer context menu
3262    fn render_file_explorer_context_menu(
3263        &self,
3264        frame: &mut Frame,
3265        menu: &super::types::FileExplorerContextMenu,
3266    ) {
3267        use ratatui::style::Style;
3268        use ratatui::text::{Line, Span};
3269        use ratatui::widgets::{Block, Borders, Clear, Paragraph};
3270
3271        let items = menu.items();
3272        let menu_width = super::types::FILE_EXPLORER_CONTEXT_MENU_WIDTH;
3273        let menu_height = menu.height();
3274        let (menu_x, menu_y) = menu.clamped_position(frame.area().width, frame.area().height);
3275
3276        let area = ratatui::layout::Rect::new(menu_x, menu_y, menu_width, menu_height);
3277
3278        frame.render_widget(Clear, area);
3279
3280        let mut lines = Vec::new();
3281        for (idx, item) in items.iter().enumerate() {
3282            let is_highlighted = idx == menu.highlighted;
3283
3284            let style = if is_highlighted {
3285                Style::default()
3286                    .fg(self.theme.read().unwrap().menu_highlight_fg)
3287                    .bg(self.theme.read().unwrap().menu_highlight_bg)
3288            } else {
3289                Style::default()
3290                    .fg(self.theme.read().unwrap().menu_dropdown_fg)
3291                    .bg(self.theme.read().unwrap().menu_dropdown_bg)
3292            };
3293
3294            let label = item.label();
3295            let content_width = (menu_width as usize).saturating_sub(2);
3296            let padded_label = format!(" {:<width$}", label, width = content_width - 1);
3297
3298            lines.push(Line::from(vec![Span::styled(padded_label, style)]));
3299        }
3300
3301        let block = Block::default()
3302            .borders(Borders::ALL)
3303            .border_style(Style::default().fg(self.theme.read().unwrap().menu_border_fg))
3304            .style(Style::default().bg(self.theme.read().unwrap().menu_dropdown_bg));
3305
3306        let paragraph = Paragraph::new(lines).block(block);
3307        frame.render_widget(paragraph, area);
3308    }
3309
3310    /// Render the tab drag drop zone overlay
3311    fn render_tab_drop_zone(&self, frame: &mut Frame, drag_state: &super::types::TabDragState) {
3312        use ratatui::style::Modifier;
3313
3314        let Some(ref drop_zone) = drag_state.drop_zone else {
3315            return;
3316        };
3317
3318        let split_id = drop_zone.split_id();
3319
3320        // Find the content area for the target split
3321        let split_area = self
3322            .active_layout()
3323            .split_areas
3324            .iter()
3325            .find(|(sid, _, _, _, _, _)| *sid == split_id)
3326            .map(|(_, _, content_rect, _, _, _)| *content_rect);
3327
3328        let Some(content_rect) = split_area else {
3329            return;
3330        };
3331
3332        // Determine the highlight area based on drop zone type
3333        use super::types::TabDropZone;
3334
3335        let highlight_area = match drop_zone {
3336            TabDropZone::TabBar(_, _) | TabDropZone::SplitCenter(_) => {
3337                // For tab bar and center drops, highlight the entire split area
3338                // This indicates the tab will be added to this split's tab bar
3339                content_rect
3340            }
3341            TabDropZone::SplitLeft(_) => {
3342                // Left 50% of the split (matches the actual split size created)
3343                let width = (content_rect.width / 2).max(3);
3344                ratatui::layout::Rect::new(
3345                    content_rect.x,
3346                    content_rect.y,
3347                    width,
3348                    content_rect.height,
3349                )
3350            }
3351            TabDropZone::SplitRight(_) => {
3352                // Right 50% of the split (matches the actual split size created)
3353                let width = (content_rect.width / 2).max(3);
3354                let x = content_rect.x + content_rect.width - width;
3355                ratatui::layout::Rect::new(x, content_rect.y, width, content_rect.height)
3356            }
3357            TabDropZone::SplitTop(_) => {
3358                // Top 50% of the split (matches the actual split size created)
3359                let height = (content_rect.height / 2).max(2);
3360                ratatui::layout::Rect::new(
3361                    content_rect.x,
3362                    content_rect.y,
3363                    content_rect.width,
3364                    height,
3365                )
3366            }
3367            TabDropZone::SplitBottom(_) => {
3368                // Bottom 50% of the split (matches the actual split size created)
3369                let height = (content_rect.height / 2).max(2);
3370                let y = content_rect.y + content_rect.height - height;
3371                ratatui::layout::Rect::new(content_rect.x, y, content_rect.width, height)
3372            }
3373        };
3374
3375        // Draw the overlay with the drop zone color
3376        // We apply a semi-transparent effect by modifying existing cells
3377        let buf = frame.buffer_mut();
3378        let drop_zone_bg = self.theme.read().unwrap().tab_drop_zone_bg;
3379        let drop_zone_border = self.theme.read().unwrap().tab_drop_zone_border;
3380
3381        // Fill the highlight area with a semi-transparent overlay
3382        for y in highlight_area.y..highlight_area.y + highlight_area.height {
3383            for x in highlight_area.x..highlight_area.x + highlight_area.width {
3384                if let Some(cell) = buf.cell_mut((x, y)) {
3385                    // Blend the drop zone color with the existing background
3386                    // For a simple effect, we just set the background
3387                    cell.set_bg(drop_zone_bg);
3388
3389                    // Draw border on edges
3390                    let is_border = x == highlight_area.x
3391                        || x == highlight_area.x + highlight_area.width - 1
3392                        || y == highlight_area.y
3393                        || y == highlight_area.y + highlight_area.height - 1;
3394
3395                    if is_border {
3396                        cell.set_fg(drop_zone_border);
3397                        cell.set_style(cell.style().add_modifier(Modifier::BOLD));
3398                    }
3399                }
3400            }
3401        }
3402
3403        // Draw a border indicator based on the zone type
3404        match drop_zone {
3405            TabDropZone::SplitLeft(_) => {
3406                // Draw vertical indicator on left edge
3407                for y in highlight_area.y..highlight_area.y + highlight_area.height {
3408                    if let Some(cell) = buf.cell_mut((highlight_area.x, y)) {
3409                        cell.set_symbol("▌");
3410                        cell.set_fg(drop_zone_border);
3411                    }
3412                }
3413            }
3414            TabDropZone::SplitRight(_) => {
3415                // Draw vertical indicator on right edge
3416                let x = highlight_area.x + highlight_area.width - 1;
3417                for y in highlight_area.y..highlight_area.y + highlight_area.height {
3418                    if let Some(cell) = buf.cell_mut((x, y)) {
3419                        cell.set_symbol("▐");
3420                        cell.set_fg(drop_zone_border);
3421                    }
3422                }
3423            }
3424            TabDropZone::SplitTop(_) => {
3425                // Draw horizontal indicator on top edge
3426                for x in highlight_area.x..highlight_area.x + highlight_area.width {
3427                    if let Some(cell) = buf.cell_mut((x, highlight_area.y)) {
3428                        cell.set_symbol("▀");
3429                        cell.set_fg(drop_zone_border);
3430                    }
3431                }
3432            }
3433            TabDropZone::SplitBottom(_) => {
3434                // Draw horizontal indicator on bottom edge
3435                let y = highlight_area.y + highlight_area.height - 1;
3436                for x in highlight_area.x..highlight_area.x + highlight_area.width {
3437                    if let Some(cell) = buf.cell_mut((x, y)) {
3438                        cell.set_symbol("▄");
3439                        cell.set_fg(drop_zone_border);
3440                    }
3441                }
3442            }
3443            TabDropZone::SplitCenter(_) | TabDropZone::TabBar(_, _) => {
3444                // For center and tab bar, the filled background is sufficient
3445            }
3446        }
3447    }
3448
3449    /// Recompute the view_line_mappings layout without drawing.
3450    /// Used during macro replay so that visual-line movements (MoveLineEnd,
3451    /// MoveUp, MoveDown on wrapped lines) see correct, up-to-date layout
3452    /// information between each replayed action.
3453    pub fn recompute_layout(&mut self, width: u16, height: u16) {
3454        let size = ratatui::layout::Rect::new(0, 0, width, height);
3455
3456        // Replicate the pre-render sync steps from render()
3457        let active_split = self
3458            .windows
3459            .get(&self.active_window)
3460            .and_then(|w| w.buffers.splits())
3461            .map(|(mgr, _)| mgr)
3462            .expect("active window must have a populated split layout")
3463            .active_split();
3464        self.active_window_mut()
3465            .pre_sync_ensure_visible(active_split);
3466        self.active_window_mut().sync_scroll_groups();
3467
3468        // Replicate the layout computation that produces editor_content_area.
3469        // Same constraints as render(): [menu_bar, main_content, status_bar, search_options, prompt_line]
3470        let constraints = vec![
3471            Constraint::Length(if self.active_window_mut().menu_bar_visible {
3472                1
3473            } else {
3474                0
3475            }),
3476            Constraint::Min(0),
3477            Constraint::Length(if self.active_window_mut().status_bar_visible {
3478                1
3479            } else {
3480                0
3481            }), // status bar
3482            Constraint::Length(0), // search options (doesn't matter for layout)
3483            Constraint::Length(if self.active_window_mut().prompt_line_visible {
3484                1
3485            } else {
3486                0
3487            }), // prompt line
3488        ];
3489        let main_chunks = Layout::default()
3490            .direction(Direction::Vertical)
3491            .constraints(constraints)
3492            .split(size);
3493        let main_content_area = main_chunks[1];
3494
3495        // Compute editor_content_area (with file explorer split if visible)
3496        let file_explorer_should_show = self.file_explorer_visible()
3497            && (self.file_explorer().is_some()
3498                || self.active_window().file_explorer_sync_in_progress);
3499        let editor_content_area = if file_explorer_should_show {
3500            let explorer_cols = self
3501                .active_window()
3502                .file_explorer_width
3503                .to_cols(main_content_area.width);
3504            let horizontal_chunks = Layout::default()
3505                .direction(Direction::Horizontal)
3506                .constraints([Constraint::Length(explorer_cols), Constraint::Min(0)])
3507                .split(main_content_area);
3508            horizontal_chunks[1]
3509        } else {
3510            main_content_area
3511        };
3512
3513        // Compute layout for all visible splits and update cached view_line_mappings.
3514        // Take one &mut borrow on the active window's splits; destructure into
3515        // (&SplitManager, &mut HashMap<...>) so both arguments come from the
3516        // same `&mut self.windows` borrow.
3517        let active_window_id = self.active_window;
3518        let __win_l = self
3519            .windows
3520            .get_mut(&active_window_id)
3521            .expect("active window must exist");
3522        let tab_bar_visible = __win_l.tab_bar_visible;
3523        let theme = self.theme.read().unwrap().clone();
3524        let view_line_mappings = __win_l
3525            .buffers
3526            .with_all_mut(|buffers, mgr, vs_map| {
3527                SplitRenderer::compute_content_layout(
3528                    editor_content_area,
3529                    &*mgr,
3530                    buffers,
3531                    vs_map,
3532                    &theme,
3533                    false, // lsp_waiting — not relevant for layout
3534                    self.config.editor.estimated_line_length,
3535                    self.config.editor.highlight_context_bytes,
3536                    self.config.editor.relative_line_numbers,
3537                    self.config.editor.use_terminal_bg,
3538                    self.session_mode || !self.software_cursor_only,
3539                    self.software_cursor_only,
3540                    tab_bar_visible,
3541                    self.config.editor.show_vertical_scrollbar,
3542                    self.config.editor.show_horizontal_scrollbar,
3543                    self.config.editor.diagnostics_inline_text,
3544                    self.config.editor.show_tilde,
3545                )
3546            })
3547            .expect("active window must have a populated split layout");
3548
3549        self.active_layout_mut().view_line_mappings = view_line_mappings;
3550    }
3551
3552    /// Clear the search history
3553    /// Used primarily for testing to ensure test isolation
3554    pub fn clear_search_history(&mut self) {
3555        if let Some(history) = self.active_window_mut().prompt_histories.get_mut("search") {
3556            history.clear();
3557        }
3558    }
3559
3560    /// Emit an OSC 2 escape sequence to set the host terminal's window/tab
3561    /// title based on the active buffer's display name and the project name
3562    /// (the working directory's last path component). Deduplicated against
3563    /// the last title we wrote so we don't spam stdout every frame.
3564    ///
3565    /// Gated by `editor.set_window_title` (default on). Terminals that
3566    /// don't implement OSC 2 silently drop the sequence.
3567    fn update_terminal_title(&mut self, display_name: &str) {
3568        if !self.config.editor.set_window_title {
3569            return;
3570        }
3571        let project_name = self.working_dir().file_name().and_then(|s| s.to_str());
3572        let new_title =
3573            crate::services::terminal_title::build_window_title(display_name, project_name);
3574        if self.last_window_title.as_deref() == Some(new_title.as_str()) {
3575            return;
3576        }
3577        crate::services::terminal_title::write_terminal_title(&new_title);
3578        self.last_window_title = Some(new_title);
3579    }
3580
3581    /// Save all prompt histories to disk
3582    /// Called on shutdown to persist history across sessions
3583    pub fn save_histories(&self) {
3584        // Ensure data directory exists
3585        if let Err(e) = self
3586            .authority
3587            .filesystem
3588            .create_dir_all(&self.dir_context.data_dir)
3589        {
3590            tracing::warn!("Failed to create data directory: {}", e);
3591            return;
3592        }
3593
3594        // Save all prompt histories
3595        for (key, history) in &self.active_window().prompt_histories {
3596            let path = self.dir_context.prompt_history_path(key);
3597            if let Err(e) = history.save_to_file(&path) {
3598                tracing::warn!("Failed to save {} history: {}", key, e);
3599            } else {
3600                tracing::debug!("Saved {} history to {:?}", key, path);
3601            }
3602        }
3603    }
3604
3605    /// Resolve a plugin-supplied [`OverlayOptions`] to a ratatui
3606    /// [`Style`] against the active theme. RGB colours pass through;
3607    /// theme keys (e.g. `"ui.help_key_fg"`) are looked up via
3608    /// `theme.resolve_theme_key`. Mirrors the resolution
3609    /// `OverlayFace::from_options` + char_style.rs do for buffer
3610    /// overlays — pulled here so the prompt-frame renderer can build
3611    /// styled spans inline.
3612    /// Compute a centered overlay rect of `width_pct` × `height_pct`
3613    /// of the given area. Mirrors `PopupPosition::CenteredOverlay`
3614    /// math used by `render_overlay_prompt`; minimum 20×8 cells so
3615    /// content stays legible on tiny terminals.
3616    pub(super) fn centered_overlay_rect(
3617        area: ratatui::layout::Rect,
3618        width_pct: u8,
3619        height_pct: u8,
3620    ) -> ratatui::layout::Rect {
3621        let w_pct = width_pct.clamp(1, 100) as u32;
3622        let h_pct = height_pct.clamp(1, 100) as u32;
3623        let w = ((area.width as u32 * w_pct) / 100) as u16;
3624        let h = ((area.height as u32 * h_pct) / 100) as u16;
3625        let w = w.max(20).min(area.width);
3626        let h = h.max(8).min(area.height);
3627        ratatui::layout::Rect {
3628            x: area.x + (area.width.saturating_sub(w)) / 2,
3629            y: area.y + (area.height.saturating_sub(h)) / 2,
3630            width: w,
3631            height: h,
3632        }
3633    }
3634
3635    /// Render the currently-mounted floating widget panel: dim the
3636    /// background outside the centered rect, draw the frame, paint
3637    /// the panel's rendered entries inside, and place the hardware
3638    /// caret at the focused TextInput. Stores the inner rect on the
3639    /// `FloatingWidgetState` so the click hit-test can recover the
3640    /// geometry on the next mouse event.
3641    pub(super) fn render_floating_widget_panel(
3642        &mut self,
3643        frame: &mut Frame,
3644        area: ratatui::layout::Rect,
3645    ) {
3646        use ratatui::widgets::{Block, Borders, Clear};
3647
3648        let (width_pct, height_pct, entries, focus_cursor, embeds, overlays, scroll_regions) =
3649            match self.floating_widget_panel.as_ref() {
3650                Some(fwp) => (
3651                    fwp.width_pct,
3652                    fwp.height_pct,
3653                    fwp.entries.clone(),
3654                    fwp.focus_cursor,
3655                    fwp.embeds.clone(),
3656                    fwp.overlays.clone(),
3657                    fwp.scroll_regions.clone(),
3658                ),
3659                None => return,
3660            };
3661        let theme = self.theme.read().unwrap().clone();
3662        // Compute the requested rect from width%/height%, then
3663        // shrink the height to fit the rendered content (Bug 7).
3664        // Plugins call `mount({widthPct, heightPct})` mostly because
3665        // they don't know how tall their content is up front; the
3666        // requested height should act as a *max*, not a fixed
3667        // canvas. Without this shrink, the new-session form's 10
3668        // content rows leave ~20 blank rows under "Tab next  S-Tab
3669        // prev  Enter submit  Esc cancel" inside a 90%-of-screen
3670        // panel.
3671        //
3672        // Entries include every row the spec produces — including
3673        // WindowEmbed reservations (each `windowEmbed({rows: N})`
3674        // contributes N blank entries plus an EmbedRect that paints
3675        // over them at draw time). So `entries.len() + 2` (top
3676        // border + content + bottom border) is the natural fit.
3677        let overlay_rect = {
3678            let requested = Self::centered_overlay_rect(area, width_pct, height_pct);
3679            let needed_h = (entries.len() as u16).saturating_add(2);
3680            let effective_h = needed_h.min(requested.height).max(3);
3681            ratatui::layout::Rect {
3682                x: requested.x,
3683                y: area.y + (area.height.saturating_sub(effective_h)) / 2,
3684                width: requested.width,
3685                height: effective_h,
3686            }
3687        };
3688
3689        crate::view::dimming::apply_dimming_excluding(frame, area, Some(overlay_rect));
3690        frame.render_widget(Clear, overlay_rect);
3691        let block = Block::default()
3692            .borders(Borders::ALL)
3693            .border_style(ratatui::style::Style::default().fg(theme.popup_border_fg))
3694            .style(ratatui::style::Style::default().bg(theme.suggestion_bg));
3695        let inner = block.inner(overlay_rect);
3696        frame.render_widget(block, overlay_rect);
3697
3698        if inner.width == 0 || inner.height == 0 {
3699            if let Some(fwp) = self.floating_widget_panel.as_mut() {
3700                fwp.last_inner_rect = Some(inner);
3701            }
3702            return;
3703        }
3704
3705        let max_rows = inner.height as usize;
3706        for (i, entry) in entries.iter().take(max_rows).enumerate() {
3707            paint_text_property_entry(
3708                frame,
3709                entry,
3710                inner.x,
3711                inner.y + i as u16,
3712                inner.width,
3713                &theme,
3714            );
3715        }
3716
3717        // Walk WindowEmbed widgets and paint their referenced
3718        // editor window into the cells they reserved. Each embed
3719        // rect is panel-relative; translate to screen cells via
3720        // `inner`. We temporarily borrow `preview_window_id` to
3721        // reuse the existing per-window paint path — it reads
3722        // that field to decide which session to draw.
3723        let saved_preview = self.preview_window_id;
3724        for emb in &embeds {
3725            if emb.window_id == 0 {
3726                continue;
3727            }
3728            let ex = inner.x.saturating_add(emb.col_in_row as u16);
3729            let ey = inner.y.saturating_add(emb.buffer_row as u16);
3730            // Clip the embed rect to the panel's inner area so a
3731            // partially-offscreen embed (tiny terminal) doesn't
3732            // paint into the frame border.
3733            let max_w = inner.x.saturating_add(inner.width).saturating_sub(ex);
3734            let max_h = inner.y.saturating_add(inner.height).saturating_sub(ey);
3735            let w = (emb.width_cols as u16).min(max_w);
3736            let h = (emb.height_rows as u16).min(max_h);
3737            if w == 0 || h == 0 {
3738                continue;
3739            }
3740            let rect = ratatui::layout::Rect {
3741                x: ex,
3742                y: ey,
3743                width: w,
3744                height: h,
3745            };
3746            self.preview_window_id = Some(fresh_core::WindowId(emb.window_id as u64));
3747            self.render_session_preview_into_rect(frame, rect, &theme);
3748        }
3749        self.preview_window_id = saved_preview;
3750
3751        // Paint a draggable scrollbar over the rightmost column of each
3752        // overflowing list, reusing the canonical `render_scrollbar` /
3753        // `ScrollbarState` (same path as the keybinding editor &
3754        // settings dialog). Record each track's screen rect + state so
3755        // the mouse handlers can hit-test press/drag against it.
3756        let mut scrollbar_tracks: Vec<super::WidgetScrollbarTrack> = Vec::new();
3757        {
3758            use crate::view::ui::scrollbar::{render_scrollbar, ScrollbarColors, ScrollbarState};
3759            let colors = ScrollbarColors::from_theme(&theme);
3760            for region in &scroll_regions {
3761                // Scrollbar column = right edge of the list's column,
3762                // clamped inside the panel. Height = visible rows,
3763                // clamped to the panel bottom.
3764                let sb_x = inner
3765                    .x
3766                    .saturating_add(region.col_in_row as u16)
3767                    .saturating_add((region.width_cols.saturating_sub(1)) as u16)
3768                    .min(inner.x + inner.width.saturating_sub(1));
3769                let sb_y = inner.y.saturating_add(region.buffer_row as u16);
3770                if sb_y >= inner.y + inner.height {
3771                    continue;
3772                }
3773                let max_h = inner.y + inner.height - sb_y;
3774                let sb_h = (region.height_rows as u16).min(max_h);
3775                if sb_h == 0 {
3776                    continue;
3777                }
3778                let sb_rect = ratatui::layout::Rect {
3779                    x: sb_x,
3780                    y: sb_y,
3781                    width: 1,
3782                    height: sb_h,
3783                };
3784                let state = ScrollbarState::new(region.total, region.visible, region.scroll);
3785                render_scrollbar(frame, sb_rect, &state, &colors);
3786                scrollbar_tracks.push(super::WidgetScrollbarTrack {
3787                    list_key: region.list_key.clone(),
3788                    rect: sb_rect,
3789                    total: region.total,
3790                    visible: region.visible,
3791                    scroll: region.scroll,
3792                });
3793            }
3794        }
3795
3796        // Paint overlay rows AFTER the main entries + embeds. Each
3797        // overlay row sits on top of whatever's at its
3798        // `buffer_row` (the row it would have occupied if it
3799        // weren't floating). Used for dropdown completions
3800        // anchored to a text input — the completion list rows
3801        // overpaint the form's static rows beneath without
3802        // shifting them on every show / hide.
3803        //
3804        // Clear the row first so the underlying entry's text
3805        // doesn't bleed past the overlay's content width.
3806        // `Paragraph` only paints cells it has content for; a
3807        // bare `Clear` resets the row to the panel background
3808        // (the `Block` here just supplies the bg style — no
3809        // borders).
3810        let panel_bg = theme.popup_bg;
3811        let panel_bg_style = ratatui::style::Style::default().bg(panel_bg);
3812        for o in &overlays {
3813            let row_y = inner.y.saturating_add(o.buffer_row as u16);
3814            if row_y >= inner.y.saturating_add(inner.height) {
3815                continue;
3816            }
3817            let row_rect = ratatui::layout::Rect {
3818                x: inner.x,
3819                y: row_y,
3820                width: inner.width,
3821                height: 1,
3822            };
3823            frame.render_widget(Clear, row_rect);
3824            frame.render_widget(Block::default().style(panel_bg_style), row_rect);
3825            paint_text_property_entry(frame, &o.entry, inner.x, row_y, inner.width, &theme);
3826        }
3827
3828        if let Some(fc) = focus_cursor {
3829            let cx = inner.x.saturating_add(byte_to_screen_col(
3830                entries
3831                    .get(fc.buffer_row as usize)
3832                    .map(|e| e.text.as_str())
3833                    .unwrap_or(""),
3834                fc.byte_in_row as usize,
3835            ) as u16);
3836            let cy = inner.y.saturating_add(fc.buffer_row as u16);
3837            if cx < inner.x + inner.width && cy < inner.y + inner.height {
3838                frame.set_cursor_position((cx, cy));
3839            }
3840        } else {
3841            // No focused text input — the underlying editor's
3842            // `set_cursor_position` (called earlier in this frame)
3843            // would otherwise leave a hardware caret blinking
3844            // inside the dimmed buffer behind the panel. Park the
3845            // cursor on the floating panel's bottom-right corner
3846            // so it's hidden under the panel chrome instead of
3847            // bleeding through.
3848            let cx = inner.x + inner.width.saturating_sub(1);
3849            let cy = inner.y + inner.height.saturating_sub(1);
3850            frame.set_cursor_position((cx, cy));
3851        }
3852
3853        if let Some(fwp) = self.floating_widget_panel.as_mut() {
3854            fwp.last_inner_rect = Some(inner);
3855            fwp.scrollbar_tracks = scrollbar_tracks;
3856        }
3857    }
3858
3859    fn resolve_overlay_style(
3860        opts: &fresh_core::api::OverlayOptions,
3861        theme: &crate::view::theme::Theme,
3862    ) -> ratatui::style::Style {
3863        use crate::view::theme::named_color_from_str;
3864        use fresh_core::api::OverlayColorSpec;
3865        use ratatui::style::{Color, Modifier, Style};
3866
3867        let resolve = |spec: &OverlayColorSpec| -> Option<Color> {
3868            match spec {
3869                OverlayColorSpec::Rgb(r, g, b) => Some(Color::Rgb(*r, *g, *b)),
3870                OverlayColorSpec::ThemeKey(k) => {
3871                    named_color_from_str(k).or_else(|| theme.resolve_theme_key(k))
3872                }
3873            }
3874        };
3875
3876        let mut style = Style::default();
3877        if let Some(ref fg) = opts.fg {
3878            if let Some(c) = resolve(fg) {
3879                style = style.fg(c);
3880            }
3881        }
3882        if let Some(ref bg) = opts.bg {
3883            if let Some(c) = resolve(bg) {
3884                style = style.bg(c);
3885            }
3886        }
3887        let mut m = Modifier::empty();
3888        if opts.bold {
3889            m |= Modifier::BOLD;
3890        }
3891        if opts.italic {
3892            m |= Modifier::ITALIC;
3893        }
3894        if opts.underline {
3895            m |= Modifier::UNDERLINED;
3896        }
3897        if opts.strikethrough {
3898            m |= Modifier::CROSSED_OUT;
3899        }
3900        if !m.is_empty() {
3901            style = style.add_modifier(m);
3902        }
3903        style
3904    }
3905}
3906
3907/// Paint a single rendered widget entry into the frame buffer at
3908/// `(x, y)` over `width` cells. Resolves the entry's segments / inline
3909/// overlays to styled spans using the panel's theme; trailing columns
3910/// are filled with spaces in the panel's bg so the row reads as one
3911/// solid line.
3912fn paint_text_property_entry(
3913    frame: &mut ratatui::Frame,
3914    entry: &fresh_core::text_property::TextPropertyEntry,
3915    x: u16,
3916    y: u16,
3917    width: u16,
3918    theme: &crate::view::theme::Theme,
3919) {
3920    use ratatui::style::Style;
3921    use ratatui::text::{Line, Span};
3922    use ratatui::widgets::Paragraph;
3923
3924    let mut normalized = entry.clone();
3925    normalized.normalize_widths();
3926    let mut text = normalized.text.clone();
3927    while text.ends_with('\n') {
3928        text.pop();
3929    }
3930
3931    let base_bg = theme.suggestion_bg;
3932    let base_style = if let Some(opts) = normalized.style.as_ref() {
3933        // Resolve the entry's row-level style, then fill in the
3934        // suggestion_bg only when the style didn't supply one
3935        // of its own. Without this guard, calling `.bg(base_bg)`
3936        // unconditionally would wipe out a row-level
3937        // `popup_selection_bg` (the highlight on the completion
3938        // popup's selected candidate) — `Style::bg` is a
3939        // replacement, not a merge.
3940        let resolved = Editor::resolve_overlay_style(opts, theme);
3941        if resolved.bg.is_none() {
3942            resolved.bg(base_bg)
3943        } else {
3944            resolved
3945        }
3946    } else {
3947        Style::default().bg(base_bg)
3948    };
3949
3950    // Split the line at inline-overlay byte boundaries so each
3951    // resulting span carries one consistent style. The overlays are
3952    // produced in declaration order by the widget renderer; later
3953    // overlays override earlier ones for any cells they cover.
3954    let boundaries: std::collections::BTreeSet<usize> = std::iter::once(0)
3955        .chain(std::iter::once(text.len()))
3956        .chain(
3957            normalized
3958                .inline_overlays
3959                .iter()
3960                .flat_map(|o| [o.start.min(text.len()), o.end.min(text.len())]),
3961        )
3962        .collect();
3963    let bounds: Vec<usize> = boundaries.into_iter().collect();
3964
3965    let mut spans: Vec<Span<'_>> = Vec::new();
3966    for win in bounds.windows(2) {
3967        let (a, b) = (win[0], win[1]);
3968        if a >= b {
3969            continue;
3970        }
3971        let slice = text[a..b].to_string();
3972        // Merge (don't replace) overlapping overlays so a later
3973        // overlay can override individual properties (bg, fg,
3974        // italic, …) without wiping the earlier overlay's other
3975        // properties. The text-input renderer relies on this:
3976        // the placeholder overlay sets fg + italic, then the
3977        // focused overlay sets bg only — without per-property
3978        // merge the focused-bg overlay would also clear the
3979        // placeholder's italic-dim styling, making placeholder
3980        // text indistinguishable from a typed value under focus.
3981        let mut style = base_style;
3982        for o in &normalized.inline_overlays {
3983            let os = o.start.min(text.len());
3984            let oe = o.end.min(text.len());
3985            if a >= os && b <= oe && oe > os {
3986                let resolved = Editor::resolve_overlay_style(&o.style, theme);
3987                if let Some(fg) = resolved.fg {
3988                    style = style.fg(fg);
3989                }
3990                if let Some(bg) = resolved.bg {
3991                    style = style.bg(bg);
3992                }
3993                // Ratatui `Style` carries add/sub modifier sets;
3994                // OR the additions in so subsequent overlays can
3995                // add italic / bold / etc. on top of the prior
3996                // overlay's modifiers.
3997                style = style.add_modifier(resolved.add_modifier);
3998                style = style.remove_modifier(resolved.sub_modifier);
3999            }
4000        }
4001        // Ensure a bg is set: ratatui will paint the slot with
4002        // the terminal's default bg otherwise, which doesn't
4003        // match the surrounding panel chrome.
4004        if style.bg.is_none() {
4005            style = style.bg(base_bg);
4006        }
4007        spans.push(Span::styled(slice, style));
4008    }
4009
4010    let line = Line::from(spans);
4011    let rect = ratatui::layout::Rect {
4012        x,
4013        y,
4014        width,
4015        height: 1,
4016    };
4017    frame.render_widget(Paragraph::new(line).style(base_style), rect);
4018}
4019
4020/// Translate a UTF-8 byte offset within a rendered line into a
4021/// display-column offset, walking codepoints with their Unicode
4022/// width. Used to place the hardware caret on the focused
4023/// TextInput's byte position.
4024fn byte_to_screen_col(text: &str, target_byte: usize) -> usize {
4025    use unicode_width::UnicodeWidthChar;
4026    let mut byte = 0;
4027    let mut col = 0usize;
4028    for ch in text.chars() {
4029        if byte >= target_byte {
4030            break;
4031        }
4032        col += UnicodeWidthChar::width(ch).unwrap_or(0);
4033        byte += ch.len_utf8();
4034    }
4035    col
4036}