Skip to main content

fresh/app/
popup_dialogs.rs

1//! Popup-dialog orchestrators on `Editor`.
2//!
3//! These build and show various popups as buffer-level events:
4//! warnings popup, LSP status popup (with refresh hook), file-message
5//! popup, and a small text-properties query helper. The biggest of
6//! these — build_and_show_lsp_status_popup — is ~315 lines of popup
7//! construction that has nothing to do with buffer management proper;
8//! it just needed access to the buffer to dispatch the ShowPopup event.
9
10use rust_i18n::t;
11
12use crate::app::warning_domains::WarningDomain;
13
14use super::Editor;
15
16/// True when `popup` is the LSP status popup (as built by
17/// `build_and_show_lsp_status_popup`). Used by the auto-prompt
18/// drain to find and clean up orphan prompts on non-active
19/// buffers without affecting unrelated popups (completion, hover,
20/// etc.) that might be on top.
21fn is_lsp_status_popup(popup: &crate::view::popup::Popup) -> bool {
22    matches!(popup.resolver, crate::view::popup::PopupResolver::LspStatus)
23}
24
25impl Editor {
26    /// Show warnings by opening the warning log file directly
27    ///
28    /// If there are no warnings, shows a brief status message.
29    /// Otherwise, opens the warning log file for the user to view.
30    pub fn show_warnings_popup(&mut self) {
31        if !self.active_window_mut().warning_domains.has_any_warnings() {
32            self.active_window_mut().status_message = Some(t!("warnings.none").to_string());
33            return;
34        }
35
36        // Open the warning log file directly
37        self.open_warning_log();
38    }
39
40    /// Show LSP status popup with details about servers active for the current buffer.
41    /// Lists each server with its status and provides actions: restart, stop, view log.
42    ///
43    /// User-initiated (status-bar click, `lsp_status` action). The popup
44    /// grabs focus on show because the user explicitly asked for it,
45    /// matching the historical click-to-pick-action affordance.
46    pub fn show_lsp_status_popup(&mut self) {
47        // Toggle behavior: if the LSP popup is already showing, close it
48        // instead of rebuilding and re-showing it.  This lets clicking the
49        // status-bar LSP indicator a second time dismiss the popup, matching
50        // the common affordance for status-bar menus.
51        if self
52            .active_state()
53            .popups
54            .top()
55            .is_some_and(is_lsp_status_popup)
56        {
57            self.hide_popup();
58            return;
59        }
60
61        let has_error =
62            self.active_window_mut().warning_domains.lsp.level() == crate::app::WarningLevel::Error;
63        let language = self
64            .buffers()
65            .get(&self.active_buffer())
66            .map(|s| s.language.clone())
67            .unwrap_or_else(|| "unknown".to_string());
68
69        // Compute the set of configured servers whose binaries are not
70        // resolvable — plugins and the popup itself both need this to
71        // decide between "offer to start" and "offer install help".
72        // Probe missing binaries through the active authority. When the
73        // LspManager isn't wired (tests or very early boot), fall
74        // back to the synchronous host-side `which` probe — same path
75        // `command_exists_via_authority` would take after the
76        // long-running spawner bootstrap completes.
77        let missing_servers: Vec<String> = self
78            .config
79            .lsp
80            .get(&language)
81            .map(|cfg| {
82                cfg.as_slice()
83                    .iter()
84                    .filter(|c| c.enabled && !c.command.is_empty())
85                    .filter(|c| match self.lsp() {
86                        Some(mgr) => !mgr.command_exists_via_authority(&c.command),
87                        None => !crate::services::lsp::command_exists(&c.command),
88                    })
89                    .map(|c| c.command.clone())
90                    .collect()
91            })
92            .unwrap_or_default();
93        let user_dismissed = self
94            .active_window()
95            .is_lsp_language_user_dismissed(&language);
96
97        // Fire the LspStatusClicked hook for plugins. A plugin's
98        // handler may itself push a popup (e.g. the embedded
99        // rust-lsp.ts plugin shows install instructions when its
100        // `rustLspError` is set).
101        self.plugin_manager.read().unwrap().run_hook(
102            "lsp_status_clicked",
103            crate::services::plugins::hooks::HookArgs::LspStatusClicked {
104                language: language.clone(),
105                has_error,
106                missing_servers,
107                user_dismissed,
108            },
109        );
110
111        // If something is already on the popup stack at this point
112        // — either pushed by the hook above (the common case: a
113        // plugin's `editor.showActionPopup` in response to
114        // `lsp_status_clicked`) or already showing when the user
115        // clicked the indicator — don't stack the built-in LSP
116        // Servers popup on top. The hook's popup is the more
117        // contextual answer to the click; layering two popups for
118        // one gesture is the user-reported "I had several kinds of
119        // popups" bug.
120        if self.active_state().popups.top().is_some() {
121            return;
122        }
123
124        self.build_and_show_lsp_status_popup(&language, true);
125    }
126
127    /// Rebuild the LSP-status popup in place if it's currently open.
128    ///
129    /// Used when an async event (progress update, server state change) might
130    /// change the popup's contents — notably while rust-analyzer is indexing
131    /// and emits `$/progress` every few hundred ms.  Without this, the popup
132    /// would freeze on the snapshot taken at open time while the status-bar
133    /// spinner keeps moving, making them look disconnected.
134    pub fn refresh_lsp_status_popup_if_open(&mut self) {
135        // Only rebuild if the active buffer's top popup IS an LSP
136        // status popup — otherwise we'd spuriously build one on top of
137        // unrelated state.
138        if !self
139            .active_state()
140            .popups
141            .top()
142            .is_some_and(is_lsp_status_popup)
143        {
144            return;
145        }
146        let language = self
147            .buffers()
148            .get(&self.active_buffer())
149            .map(|s| s.language.clone())
150            .unwrap_or_else(|| "unknown".to_string());
151        // Replace contents: hide then rebuild. Refresh is triggered by
152        // async progress updates while the popup is already on screen,
153        // so we keep its existing focused state — flipping it back to
154        // unfocused on every progress tick would yank focus away from
155        // a user mid-interaction.
156        let was_focused = self
157            .active_state()
158            .popups
159            .top()
160            .map(|p| p.focused)
161            .unwrap_or(true);
162        self.hide_popup();
163        self.build_and_show_lsp_status_popup(&language, was_focused);
164    }
165
166    fn build_and_show_lsp_status_popup(&mut self, language: &str, focused: bool) {
167        use crate::services::async_bridge::LspServerStatus;
168
169        // Build a unified list of all configured servers for this language,
170        // merged with their runtime status (if running).
171        let running_statuses: std::collections::HashMap<String, LspServerStatus> = self
172            .active_window()
173            .lsp_server_statuses
174            .iter()
175            .filter(|((lang, _), _)| lang == language)
176            .map(|((_, name), status)| (name.clone(), *status))
177            .collect();
178
179        let configured_servers: Vec<String> = self
180            .config
181            .lsp
182            .get(language)
183            .map(|cfg| {
184                cfg.as_slice()
185                    .iter()
186                    .filter(|c| !c.command.is_empty())
187                    .map(|c| c.display_name())
188                    .collect()
189            })
190            .unwrap_or_default();
191
192        // Per-server binary availability map (display_name → bool).
193        // `command_exists` is cached, so repeated popup opens or a
194        // refresh-while-open are cheap.  We look up by display name
195        // because `all_servers` below is built from display names;
196        // LspServerConfig::display_name() falls back to the command
197        // basename when no explicit `name` is set.
198        let missing_by_server: std::collections::HashMap<String, bool> = self
199            .config
200            .lsp
201            .get(language)
202            .map(|cfg| {
203                cfg.as_slice()
204                    .iter()
205                    .filter(|c| !c.command.is_empty())
206                    .map(|c| {
207                        let missing = match self.lsp() {
208                            Some(mgr) => !mgr.command_exists_via_authority(&c.command),
209                            None => !crate::services::lsp::command_exists(&c.command),
210                        };
211                        (c.display_name(), missing)
212                    })
213                    .collect()
214            })
215            .unwrap_or_default();
216        // Per-server auto_start flag map (display_name → auto_start).
217        // Used to decide whether to offer an "Enable auto-start for X"
218        // row alongside the "Start X" action — relevant only when the
219        // server is enabled but dormant and the user hasn't opted into
220        // auto-start yet.
221        let auto_start_by_server: std::collections::HashMap<String, bool> = self
222            .config
223            .lsp
224            .get(language)
225            .map(|cfg| {
226                cfg.as_slice()
227                    .iter()
228                    .filter(|c| !c.command.is_empty())
229                    .map(|c| (c.display_name(), c.auto_start))
230                    .collect()
231            })
232            .unwrap_or_default();
233        let user_dismissed = self
234            .active_window()
235            .is_lsp_language_user_dismissed(language);
236
237        if configured_servers.is_empty() && running_statuses.is_empty() {
238            self.active_window_mut().status_message = Some(t!("lsp.no_server_active").to_string());
239            return;
240        }
241
242        // Merge: start with configured servers, then add any running servers
243        // not in the config (shouldn't happen, but be safe).
244        let mut all_servers: Vec<String> = configured_servers;
245        for name in running_statuses.keys() {
246            if !all_servers.contains(name) {
247                all_servers.push(name.clone());
248            }
249        }
250        all_servers.sort();
251
252        // Build the popup's items as view-level `PopupListItem`s directly.
253        // We bypass the `PopupListItemData` event type here because we need
254        // the `disabled` field (for "View Log" when no log exists), which
255        // is a view-only concern and plumbing it through the event boundary
256        // would require touching ~40 existing literals across the test
257        // suite.
258        let mut items: Vec<crate::view::popup::PopupListItem> = Vec::new();
259        let mut action_keys: Vec<(String, String)> = Vec::new();
260
261        /// Truncate `s` to at most `max_cells` display cells, appending an
262        /// ellipsis if truncation happened (the ellipsis is included in the
263        /// budget, so the result is ≤ `max_cells` wide regardless of input).
264        fn truncate(s: &str, max_cells: usize) -> String {
265            use unicode_width::UnicodeWidthChar;
266            let w = unicode_width::UnicodeWidthStr::width(s);
267            if w <= max_cells {
268                return s.to_string();
269            }
270            let budget = max_cells.saturating_sub(1);
271            let mut used = 0;
272            let mut out = String::new();
273            for ch in s.chars() {
274                let cw = ch.width().unwrap_or(0);
275                if used + cw > budget {
276                    break;
277                }
278                used += cw;
279                out.push(ch);
280            }
281            out.push('…');
282            out
283        }
284        const PROGRESS_FIELD_MAX: usize = 14;
285        const POPUP_WIDTH_MAX: u16 = 50;
286
287        for name in &all_servers {
288            let status = running_statuses.get(name).copied();
289            let is_active = status
290                .map(|s| !matches!(s, LspServerStatus::Shutdown))
291                .unwrap_or(false);
292            // A server is "missing" only when it's NOT currently running
293            // (an absolute-path binary could have been removed mid-session,
294            // but the live server is still talking to us).
295            let binary_missing =
296                !is_active && missing_by_server.get(name).copied().unwrap_or(false);
297
298            // Header: server name + status (data = None → not clickable,
299            // not underlined).  Swap the "not running" label for a more
300            // actionable "binary not found" when we can see up-front that
301            // a start attempt would fail — this is the user-visible half
302            // of the pre-click probe. The `binary_missing` signal comes
303            // from the authority-routed `command_exists` (L-3c), so the
304            // "not installed" copy says where it actually isn't: in the
305            // container for container authorities, on the host
306            // otherwise.
307            let authority_is_container = self.authority().display_label.starts_with("Container:");
308            let missing_label = if authority_is_container {
309                "not installed in container"
310            } else {
311                "binary not in PATH"
312            };
313            let (icon, label) = match status {
314                Some(LspServerStatus::Running) => ("●", "ready"),
315                Some(LspServerStatus::Error) => ("✗", "error"),
316                Some(LspServerStatus::Starting) => ("◌", "starting"),
317                Some(LspServerStatus::Initializing) => ("◌", "initializing"),
318                Some(LspServerStatus::Shutdown) | None => {
319                    if binary_missing {
320                        ("○", missing_label)
321                    } else {
322                        ("○", "not running")
323                    }
324                }
325            };
326            items.push(crate::view::popup::PopupListItem::new(format!(
327                "{} {} ({})",
328                icon, name, label
329            )));
330
331            // Progress row immediately UNDER the server's name row, if
332            // there's an active `$/progress` notification for this
333            // language.  Indented to match the action rows below, and the
334            // title + message fields are individually truncated so a
335            // runaway progress path can't stretch the popup.  The popup
336            // width is pinned in advance (see below) so the row's content
337            // changing never reshapes the popup.
338            if let Some(info) = self
339                .active_window()
340                .lsp_progress
341                .values()
342                .find(|info| info.language == language)
343            {
344                let mut line = format!("    ⏳ {}", truncate(&info.title, PROGRESS_FIELD_MAX));
345                if let Some(ref msg) = info.message {
346                    line.push_str(&format!(" · {}", truncate(msg, PROGRESS_FIELD_MAX)));
347                }
348                if let Some(pct) = info.percentage {
349                    line.push_str(&format!(" ({}%)", pct));
350                }
351                items.push(crate::view::popup::PopupListItem::new(line));
352            }
353
354            if is_active {
355                // Restart
356                let restart_key = format!("restart:{}/{}", language, name);
357                items.push(
358                    crate::view::popup::PopupListItem::new(format!("    Restart {}", name))
359                        .with_data(restart_key.clone()),
360                );
361                action_keys.push((restart_key, format!("Restart {}", name)));
362
363                // Stop
364                let stop_key = format!("stop:{}/{}", language, name);
365                items.push(
366                    crate::view::popup::PopupListItem::new(format!("    Stop {}", name))
367                        .with_data(stop_key.clone()),
368                );
369                action_keys.push((stop_key, format!("Stop {}", name)));
370            } else if binary_missing {
371                // Show a disabled advisory row instead of an actionable
372                // "Start" — clicking Start here would spawn, fail, and
373                // noise up the status area. Copy shifts with the
374                // authority so the user is pointed at the right
375                // install surface: `devcontainer.json`'s
376                // `postCreateCommand` for containers, the host's
377                // package manager otherwise.
378                let advisory = if authority_is_container {
379                    format!("    Install {name} in container (postCreateCommand)")
380                } else {
381                    format!("    Install {name} to enable")
382                };
383                items.push(crate::view::popup::PopupListItem::new(advisory).disabled());
384            } else {
385                // Two sibling rows for a dormant server, in the
386                // order the user most likely wants:
387                //
388                //   "Start <name> (always)" — persist auto_start=true
389                //                              AND start the server now.
390                //                              Listed first because
391                //                              persistent-start is the
392                //                              common case, so pre-
393                //                              selecting it lets the
394                //                              user press Enter and
395                //                              move on.
396                //   "Start <name> once"     — start for this session,
397                //                              config stays auto_start=false.
398                //
399                // The "once" suffix is only needed (vs. just "Start")
400                // when the "(always)" sibling is also present — i.e.
401                // when auto_start is currently false. Otherwise there
402                // is nothing to disambiguate it from.
403                let is_manual = !auto_start_by_server.get(name).copied().unwrap_or(true);
404
405                // "(always)" row — first, so it's the default.
406                if is_manual {
407                    let autostart_key = format!("autostart:{}/{}", language, name);
408                    items.push(
409                        crate::view::popup::PopupListItem::new(format!(
410                            "    Start {} (always)",
411                            name
412                        ))
413                        .with_data(autostart_key.clone()),
414                    );
415                    action_keys.push((autostart_key, format!("Start {} (always)", name)));
416                }
417
418                // "once" / plain Start row.
419                let start_label = if is_manual {
420                    format!("    Start {} once", name)
421                } else {
422                    format!("    Start {}", name)
423                };
424                let start_action_label = if is_manual {
425                    format!("Start {} once", name)
426                } else {
427                    format!("Start {}", name)
428                };
429                let start_key = format!("start:{}", language);
430                if !action_keys.iter().any(|(k, _)| k == &start_key) {
431                    items.push(
432                        crate::view::popup::PopupListItem::new(start_label)
433                            .with_data(start_key.clone()),
434                    );
435                    action_keys.push((start_key, start_action_label));
436                }
437            }
438        }
439
440        // Disable / Enable row — shown whenever the language has at
441        // least one configured server. The label flips on either the
442        // session-level dismiss flag OR the persisted `enabled = false`
443        // half: both mean "the language is currently muted from the
444        // user's POV", and showing "Disable" while the config already
445        // has every server disabled would leave the user with no
446        // surface to undo it. Picking the row writes through to the
447        // matching half of the state in `handle_lsp_status_action`
448        // (`dismiss:` flips both, `enable:` flips both) so the two
449        // signals stay in sync after every round-trip.
450        let any_enabled = self
451            .config
452            .lsp
453            .get(language)
454            .is_some_and(|cfg| cfg.as_slice().iter().any(|c| c.enabled));
455        let muted = user_dismissed || !any_enabled;
456        if muted {
457            let enable_key = format!("enable:{}", language);
458            items.push(
459                crate::view::popup::PopupListItem::new(format!("    Enable LSP for {}", language))
460                    .with_data(enable_key.clone()),
461            );
462            action_keys.push((enable_key, format!("Enable LSP for {}", language)));
463        } else {
464            let dismiss_key = format!("dismiss:{}", language);
465            items.push(
466                crate::view::popup::PopupListItem::new(format!("    Disable LSP for {}", language))
467                    .with_data(dismiss_key.clone()),
468            );
469            action_keys.push((dismiss_key, format!("Disable LSP for {}", language)));
470        }
471
472        // View log action — grayed out and non-actionable when no
473        // log file exists yet for this language (e.g. the server was
474        // never started, or has been rotated away).
475        let log_path = crate::services::log_dirs::lsp_log_path(language);
476        let log_exists = log_path.exists();
477        let log_key = format!("log:{}", language);
478        let mut log_item = crate::view::popup::PopupListItem::new("    View Log".to_string());
479        if log_exists {
480            log_item = log_item.with_data(log_key.clone());
481            action_keys.push((log_key, "View Log".to_string()));
482        } else {
483            log_item = log_item.disabled();
484        }
485        items.push(log_item);
486
487        // Plugin-contributed rows — injected between View Log and
488        // Dismiss as an extra "Plugin actions" section. This is the
489        // merge half of "Option B" (#1941 follow-up): instead of
490        // plugins pushing their own separate popup via
491        // `editor.showActionPopup` (which stacked on top of this one
492        // and confused the user), they install rows here via
493        // `PluginCommand::SetLspMenuContributions` and the editor
494        // routes the eventual selection back via
495        // `action_popup_result` with `popup_id = "lsp_status"` and
496        // `action_id = "{plugin_id}|{item_id}"`.
497        //
498        // Sorted by (plugin_id, item index) for stable ordering so
499        // the popup doesn't shuffle rows between renders. A single
500        // header row labels the section when there's at least one
501        // contributed item, so the user can tell the rows below come
502        // from a plugin (vs. built-in actions like Stop/Restart).
503        let mut contributed: Vec<(&String, &Vec<crate::app::LspMenuItem>)> = self
504            .active_window()
505            .lsp_menu_contributions
506            .iter()
507            .filter_map(|((lang, plugin_id), items)| {
508                if lang == language && !items.is_empty() {
509                    Some((plugin_id, items))
510                } else {
511                    None
512                }
513            })
514            .collect();
515        contributed.sort_by(|a, b| a.0.cmp(b.0));
516        if !contributed.is_empty() {
517            // Section header — non-actionable, mimics the language
518            // header at the top (no data → not clickable).
519            items.push(crate::view::popup::PopupListItem::new(
520                "  ─ Plugin actions ─".to_string(),
521            ));
522            for (plugin_id, plugin_items) in contributed {
523                for it in plugin_items {
524                    let key = format!("plugin:{}|{}", plugin_id, it.id);
525                    items.push(
526                        crate::view::popup::PopupListItem::new(format!("    {}", it.label))
527                            .with_data(key.clone()),
528                    );
529                    action_keys.push((key, it.label.clone()));
530                }
531            }
532        }
533
534        // Trailing Dismiss row — gives users an on-screen way out of
535        // the popup without having to know that Esc works. The key
536        // label is looked up from the keybinding resolver so a
537        // rebound PopupCancel stays visible in the row label
538        // ("Dismiss (Q)", etc.). Falls back to "Esc" as the usual
539        // default if the resolver has no binding at all (unusual,
540        // but we don't want an empty parenthetical).
541        let cancel_binding = self
542            .keybindings
543            .read()
544            .ok()
545            .and_then(|kb| {
546                kb.get_keybinding_for_action(
547                    &crate::input::keybindings::Action::PopupCancel,
548                    crate::input::keybindings::KeyContext::Popup,
549                )
550            })
551            .unwrap_or_else(|| "Esc".to_string());
552        let cancel_key = "cancel_popup".to_string();
553        items.push(
554            crate::view::popup::PopupListItem::new(format!("    Dismiss ({})", cancel_binding))
555                .with_data(cancel_key.clone()),
556        );
557        action_keys.push((cancel_key, format!("Dismiss ({})", cancel_binding)));
558        // `action_keys` is no longer kept on the editor — each list
559        // item already carries its action key in its `data` field, and
560        // the `LspStatus` resolver on the popup tells confirm how to
561        // interpret that data. The local binding is retained only to
562        // keep the existing construction logic unchanged; it falls out
563        // of scope with the rest.
564        let _ = action_keys;
565
566        // Pin the popup width up-front, using the *worst-case* widths for
567        // any row that varies at runtime (the progress line).  This keeps
568        // the popup from jittering when progress messages come and go or
569        // change length — the whole point of the spinner + live-refresh
570        // pair is that the UI should look stable while the LSP churns.
571        //
572        //   worst-case progress line =
573        //     "    ⏳ " (4-space indent + ⏳ (2 cells) + space = 7 cells)
574        //     + PROGRESS_FIELD_MAX   (title)
575        //     + " · "                (3 cells)
576        //     + PROGRESS_FIELD_MAX   (message)
577        //     + " (100%)"            (7 cells)
578        //   = 7 + 14 + 3 + 14 + 7 = 45 cells
579        const PROGRESS_LINE_MAX: usize = 7 + PROGRESS_FIELD_MAX + 3 + PROGRESS_FIELD_MAX + 7;
580        let max_static_item_width = items
581            .iter()
582            .map(|i| unicode_width::UnicodeWidthStr::width(i.text.as_str()))
583            .max()
584            .unwrap_or(20);
585        let popup_width =
586            (max_static_item_width.max(PROGRESS_LINE_MAX) as u16 + 4).clamp(30, POPUP_WIDTH_MAX);
587
588        // Pre-select the first actionable item (skip header items with no
589        // data and disabled items like a non-existent View Log).
590        let first_actionable = items
591            .iter()
592            .position(|i| i.data.is_some() && !i.disabled)
593            .unwrap_or(0);
594
595        // Left-align the popup's column with the LSP indicator on the
596        // status bar, if we know where it was drawn in the last frame.
597        // Falls back to the previous BottomRight anchor when the LSP
598        // segment isn't visible (e.g. first render). `status_row` comes
599        // from the same cached layout so the popup hugs the status bar
600        // even in prompt-auto-hide mode.
601        let position = self
602            .active_chrome()
603            .status_bar_lsp_area
604            .map(
605                |(status_row, col_start, _)| crate::view::popup::PopupPosition::AboveStatusBarAt {
606                    x: col_start,
607                    status_row,
608                },
609            )
610            .unwrap_or(crate::view::popup::PopupPosition::BottomRight);
611
612        use crate::view::popup::{Popup, PopupContent, PopupKind, PopupResolver};
613        use ratatui::style::Style;
614
615        let focus_hint = if !focused {
616            self.popup_focus_key_hint()
617        } else {
618            None
619        };
620        let popup = Popup {
621            kind: PopupKind::List,
622            title: Some(format!("LSP Servers ({})", language)),
623            description: None,
624            transient: false,
625            content: PopupContent::List {
626                items,
627                selected: first_actionable,
628            },
629            position,
630            width: popup_width,
631            max_height: 15,
632            bordered: true,
633            border_style: Style::default().fg(self.theme.read().unwrap().popup_border_fg),
634            background_style: Style::default().bg(self.theme.read().unwrap().popup_bg),
635            scroll_offset: 0,
636            text_selection: None,
637            accept_key_hint: None,
638            // This is the LSP status popup — mark it so confirm/cancel
639            // routes through handle_lsp_status_action regardless of what
640            // other popups are on screen.
641            resolver: PopupResolver::LspStatus,
642            focused,
643            focus_key_hint: focus_hint,
644        };
645
646        let buffer_id = self.active_buffer();
647        if let Some(state) = self
648            .windows
649            .get_mut(&self.active_window)
650            .map(|w| &mut w.buffers)
651            .expect("active window present")
652            .get_mut(&buffer_id)
653        {
654            state.popups.show(popup);
655        }
656    }
657
658    /// Show the Remote Indicator context menu popup.
659    ///
660    /// The menu is context-aware based on the current authority state:
661    /// - **Local:** offers "Attach to Dev Container" (when a devcontainer
662    ///   config is detectable) and "Open Dev Container Config".
663    /// - **Connected (container):** offers "Reopen Locally" (detach),
664    ///   "Rebuild Container", and "Show Container Info".
665    /// - **Connected (SSH):** offers "Disconnect Remote" and "Show Info".
666    /// - **Disconnected:** offers "Reconnect" (best-effort) and "Go Local".
667    ///
668    /// Clicking the `{remote}` status-bar element a second time toggles
669    /// the popup closed, matching the LSP-indicator affordance.
670    ///
671    /// # Design note
672    ///
673    /// Plugin-owned actions (attach, rebuild) are dispatched via
674    /// `Action::PluginAction` so core code never names the devcontainer
675    /// plugin directly. If the plugin isn't loaded the action becomes a
676    /// no-op with a status message, which is the same fallback every
677    /// other plugin-command invocation site uses.
678    pub fn show_remote_indicator_popup(&mut self) {
679        use crate::view::popup::{Popup, PopupContent, PopupKind, PopupListItem, PopupResolver};
680        use ratatui::style::Style;
681
682        if self
683            .active_state()
684            .popups
685            .top()
686            .is_some_and(|p| matches!(p.resolver, PopupResolver::RemoteIndicator))
687        {
688            self.hide_popup();
689            return;
690        }
691
692        let connection = self.connection_display_string();
693        let is_disconnected = connection
694            .as_deref()
695            .is_some_and(|c| c.contains("(Disconnected)"));
696        let is_container = connection
697            .as_deref()
698            .is_some_and(|c| c.starts_with("Container:"));
699        let is_ssh = connection.is_some() && !is_container;
700
701        let devcontainer_config_path = self.find_devcontainer_config();
702
703        let mut items: Vec<PopupListItem> = Vec::new();
704        let mut title: String = String::new();
705
706        // Plugin-supplied override (Connecting / FailedAttach) takes
707        // precedence over the authority-derived branches. A Connecting
708        // indicator shouldn't render the "Reopen in Container" menu
709        // of the underlying derived state — an attach is in flight;
710        // the user needs Show Logs / Cancel / (after B-3b) Retry.
711        //
712        // Local / Connected / Disconnected overrides are treated as
713        // labelling shortcuts, not menu-shape changes — they fall
714        // through to the derived branches below.
715        use crate::view::ui::status_bar::RemoteIndicatorOverride;
716        let override_handled = matches!(
717            self.remote_indicator_override,
718            Some(RemoteIndicatorOverride::Connecting { .. })
719                | Some(RemoteIndicatorOverride::FailedAttach { .. })
720        );
721        if let Some(over) = self.remote_indicator_override.clone() {
722            match over {
723                RemoteIndicatorOverride::Connecting { label } => {
724                    let suffix = label
725                        .filter(|s| !s.is_empty())
726                        .map(|s| format!(" — {}", s))
727                        .unwrap_or_default();
728                    title = format!("Remote: Connecting{}", suffix);
729                    items.push(
730                        PopupListItem::new("    Cancel Startup".to_string())
731                            .with_data("plugin:devcontainer_cancel_attach".to_string()),
732                    );
733                    items.push(
734                        PopupListItem::new("    Show Logs".to_string())
735                            .with_data("plugin:devcontainer_show_build_logs".to_string()),
736                    );
737                }
738                RemoteIndicatorOverride::FailedAttach { error } => {
739                    let suffix = error
740                        .filter(|s| !s.is_empty())
741                        .map(|s| format!(" — {}", s))
742                        .unwrap_or_default();
743                    title = format!("Remote: Attach failed{}", suffix);
744                    items.push(
745                        PopupListItem::new("    Retry".to_string())
746                            .with_data("plugin:devcontainer_retry_attach".to_string()),
747                    );
748                    items.push(
749                        PopupListItem::new("    Reopen Locally".to_string())
750                            .with_data("clear_override".to_string()),
751                    );
752                    items.push(
753                        PopupListItem::new("    Show Build Logs".to_string())
754                            .with_data("plugin:devcontainer_show_build_logs".to_string()),
755                    );
756                }
757                _ => {
758                    // Fall through to the derived branches.
759                }
760            }
761        }
762
763        if !override_handled {
764            match (connection.as_deref(), is_disconnected) {
765                // Connected authority (container or SSH), not disconnected.
766                (Some(label), false) => {
767                    title = format!("Remote: {}", label);
768                    if is_container {
769                        items.push(
770                            PopupListItem::new("    Reopen Locally".to_string())
771                                .with_data("detach".to_string()),
772                        );
773                        items.push(
774                            PopupListItem::new("    Rebuild Container".to_string())
775                                .with_data("plugin:devcontainer_rebuild".to_string()),
776                        );
777                        items.push(
778                            PopupListItem::new("    Show Container Logs".to_string())
779                                .with_data("plugin:devcontainer_show_logs".to_string()),
780                        );
781                        items.push(
782                            PopupListItem::new("    Show Container Info".to_string())
783                                .with_data("plugin:devcontainer_show_info".to_string()),
784                        );
785                        // The build log file from the most recent
786                        // `devcontainer up` survives the post-attach
787                        // restart (path stashed in plugin global state,
788                        // file lives under the workspace's
789                        // `.fresh-cache/`). Surfacing it here means
790                        // users can revisit "what did the build
791                        // actually do" any time after attach without
792                        // hunting through the file tree.
793                        items.push(
794                            PopupListItem::new("    Show Build Logs".to_string())
795                                .with_data("plugin:devcontainer_show_build_logs".to_string()),
796                        );
797                    } else if is_ssh {
798                        items.push(
799                            PopupListItem::new("    Disconnect Remote".to_string())
800                                .with_data("detach".to_string()),
801                        );
802                    }
803                }
804                // Disconnected — warn and offer fallbacks.
805                (Some(_), true) => {
806                    title = "Remote: Disconnected".to_string();
807                    items.push(
808                        PopupListItem::new("    Go Local".to_string())
809                            .with_data("detach".to_string()),
810                    );
811                }
812                // Local authority.
813                (None, _) => {
814                    title = "Remote: Local".to_string();
815                    if devcontainer_config_path.is_some() {
816                        items.push(
817                            PopupListItem::new("    Reopen in Container".to_string())
818                                .with_data("plugin:devcontainer_attach".to_string()),
819                        );
820                        items.push(
821                            PopupListItem::new("    Open Dev Container Config".to_string())
822                                .with_data("plugin:devcontainer_open_config".to_string()),
823                        );
824                    } else {
825                        // No .devcontainer present — offer the scaffold
826                        // so users can bootstrap a config in one click
827                        // without dropping to a shell. The scaffold
828                        // command is plugin-owned and registered
829                        // unconditionally at plugin load, so this row is
830                        // always actionable.
831                        items.push(
832                            PopupListItem::new("    Create Dev Container Config".to_string())
833                                .with_data("plugin:devcontainer_scaffold_config".to_string()),
834                        );
835                    }
836                }
837            }
838        } // end: if !override_handled
839
840        // Dismiss row — mirrors the LSP popup's terminal Dismiss row so
841        // users have an on-screen way out of the popup.
842        let cancel_binding = self
843            .keybindings
844            .read()
845            .ok()
846            .and_then(|kb| {
847                kb.get_keybinding_for_action(
848                    &crate::input::keybindings::Action::PopupCancel,
849                    crate::input::keybindings::KeyContext::Popup,
850                )
851            })
852            .unwrap_or_else(|| "Esc".to_string());
853        items.push(
854            PopupListItem::new(format!("    Dismiss ({})", cancel_binding))
855                .with_data("cancel_popup".to_string()),
856        );
857
858        let first_actionable = items
859            .iter()
860            .position(|i| i.data.is_some() && !i.disabled)
861            .unwrap_or(0);
862
863        // Anchor the popup to the remote-indicator's left edge if it's
864        // visible in the last frame; otherwise fall back to the bottom-
865        // right corner so the popup still appears. `status_row` comes
866        // from the same cached layout so the popup hugs the status bar
867        // even in prompt-auto-hide mode.
868        let position = self
869            .active_chrome()
870            .status_bar_remote_area
871            .map(
872                |(status_row, col_start, _)| crate::view::popup::PopupPosition::AboveStatusBarAt {
873                    x: col_start,
874                    status_row,
875                },
876            )
877            .unwrap_or(crate::view::popup::PopupPosition::BottomRight);
878
879        let popup_width = (items
880            .iter()
881            .map(|i| unicode_width::UnicodeWidthStr::width(i.text.as_str()))
882            .max()
883            .unwrap_or(24)
884            + 4) as u16;
885
886        let popup = Popup {
887            kind: PopupKind::List,
888            title: Some(title),
889            description: None,
890            transient: false,
891            content: PopupContent::List {
892                items,
893                selected: first_actionable,
894            },
895            position,
896            width: popup_width.clamp(28, 50),
897            max_height: 10,
898            bordered: true,
899            border_style: Style::default().fg(self.theme.read().unwrap().popup_border_fg),
900            background_style: Style::default().bg(self.theme.read().unwrap().popup_bg),
901            scroll_offset: 0,
902            text_selection: None,
903            accept_key_hint: None,
904            resolver: PopupResolver::RemoteIndicator,
905            // Explicitly invoked from the status-bar `{remote}` element,
906            // so this popup wants the keyboard immediately.
907            focused: true,
908            focus_key_hint: None,
909        };
910
911        let buffer_id = self.active_buffer();
912        if let Some(state) = self
913            .windows
914            .get_mut(&self.active_window)
915            .map(|w| &mut w.buffers)
916            .expect("active window present")
917            .get_mut(&buffer_id)
918        {
919            state.popups.show(popup);
920        }
921    }
922
923    /// Dispatch the action selected from the Remote Indicator popup.
924    ///
925    /// - `"detach"` — `clear_authority()` (falls back to local).
926    /// - `"clear_override"` — drop the Remote Indicator override
927    ///   without changing the authority. Used by the FailedAttach
928    ///   "Reopen Locally" row: nothing to detach (no authority was
929    ///   ever installed), but the FailedAttach indicator should
930    ///   clear.
931    /// - `"plugin:<name>"` — forwards to `Action::PluginAction(name)`.
932    /// - `"cancel_popup"` — no-op; the popup framework already
933    ///   closed the popup when the row was confirmed.
934    /// - anything else — logged and ignored.
935    pub fn handle_remote_indicator_action(&mut self, action_key: &str) {
936        if action_key == "detach" {
937            self.remote_indicator_override = None;
938            self.clear_authority();
939            return;
940        }
941        if action_key == "clear_override" {
942            self.remote_indicator_override = None;
943            return;
944        }
945        if action_key == "cancel_popup" {
946            return;
947        }
948        if let Some(plugin_action) = action_key.strip_prefix("plugin:") {
949            // `handle_action` wires this through the plugin manager; if
950            // the plugin isn't loaded it surfaces a status message, which
951            // is the correct no-op behavior for every plugin-command
952            // invocation site in the codebase. We still want to log an
953            // unexpected dispatch error — plugin misbehavior shouldn't
954            // leave the user staring at a silently-failed Retry click.
955            if let Err(e) = self.handle_action(crate::input::keybindings::Action::PluginAction(
956                plugin_action.to_string(),
957            )) {
958                tracing::warn!(
959                    "remote indicator popup: dispatching '{}' failed: {}",
960                    plugin_action,
961                    e
962                );
963            }
964            return;
965        }
966        tracing::warn!(
967            "handle_remote_indicator_action: unknown action key '{}'",
968            action_key
969        );
970    }
971
972    /// Probe for a `devcontainer.json` under the current working
973    /// directory. Mirrors the first two priorities of the devcontainer
974    /// plugin's `findConfig()` so the Remote Indicator menu can decide
975    /// whether to offer "Reopen in Container" without actually having to
976    /// call into the plugin.
977    ///
978    /// Routes through `authority.filesystem` per `CONTRIBUTING.md`
979    /// guideline 4, so an SSH-rooted workspace probes the remote host
980    /// rather than the local one.
981    fn find_devcontainer_config(&self) -> Option<std::path::PathBuf> {
982        let cwd = self.working_dir();
983        let fs = self.authority.filesystem.as_ref();
984        let primary = cwd.join(".devcontainer").join("devcontainer.json");
985        if fs.exists(&primary) {
986            return Some(primary);
987        }
988        let secondary = cwd.join(".devcontainer.json");
989        if fs.exists(&secondary) {
990            return Some(secondary);
991        }
992        None
993    }
994
995    /// Show a transient hover popup with the given message text, positioned below the cursor.
996    /// Used for file-open messages (e.g. `file.txt:10@"Look at this"`).
997    pub fn show_file_message_popup(&mut self, message: &str) {
998        use crate::view::popup::{Popup, PopupPosition};
999        use ratatui::style::Style;
1000
1001        // Build markdown: message text + blank line + italic hint
1002        let md = format!("{}\n\n*esc to dismiss*", message);
1003        // Size popup width to content: longest line + border padding, clamped to reasonable bounds
1004        let content_width = message.lines().map(|l| l.len()).max().unwrap_or(0) as u16;
1005        let hint_width = 16u16; // "*esc to dismiss*"
1006        let popup_width = (content_width.max(hint_width) + 4).clamp(20, 60);
1007
1008        let mut popup = Popup::markdown(
1009            &md,
1010            &*self.theme.read().unwrap(),
1011            Some(&self.grammar_registry),
1012        );
1013        popup.transient = false;
1014        popup.position = PopupPosition::BelowCursor;
1015        popup.width = popup_width;
1016        popup.max_height = 15;
1017        popup.border_style = Style::default().fg(self.theme.read().unwrap().popup_border_fg);
1018        popup.background_style = Style::default().bg(self.theme.read().unwrap().popup_bg);
1019
1020        let buffer_id = self.active_buffer();
1021        if let Some(state) = self
1022            .windows
1023            .get_mut(&self.active_window)
1024            .map(|w| &mut w.buffers)
1025            .expect("active window present")
1026            .get_mut(&buffer_id)
1027        {
1028            state.popups.show(popup);
1029        }
1030    }
1031
1032    /// Get text properties at the cursor position in the active buffer
1033    pub fn get_text_properties_at_cursor(
1034        &self,
1035    ) -> Option<Vec<&crate::primitives::text_property::TextProperty>> {
1036        let state = self
1037            .windows
1038            .get(&self.active_window)
1039            .map(|w| &w.buffers)
1040            .expect("active window present")
1041            .get(&self.active_buffer())?;
1042        let cursor_pos = self.active_cursors().primary().position;
1043        Some(state.text_properties.get_at(cursor_pos))
1044    }
1045}