fresh/app/editor_accessors.rs
1//! Plain accessor methods on `Editor`.
2//!
3//! Configuration getters, key-translator/time-source/event-broadcaster
4//! handles, LSP / completion / update query helpers, mode registry
5//! access, status/warning log setup, and the per-frame timer-check
6//! methods (mouse hover / semantic highlight / diagnostic pull /
7//! completion trigger).
8//!
9//! These are mostly small `&self` queries that read a single field;
10//! grouping them together keeps mod.rs focused on the central
11//! orchestration.
12
13use super::*;
14
15impl Editor {
16 /// Get a reference to the async bridge (if available)
17 pub fn async_bridge(&self) -> Option<&AsyncBridge> {
18 self.async_bridge.as_ref()
19 }
20
21 /// Get a reference to the config
22 pub fn config(&self) -> &Config {
23 &self.config
24 }
25
26 /// Get a mutable reference to the config.
27 ///
28 /// Routes through `Arc::make_mut`: if the plugin state snapshot (or any
29 /// other reader) still holds an `Arc` to the current value, this
30 /// CoW-clones so existing readers observe a stable value and the next
31 /// snapshot refresh sees a new pointer. `Arc<T>` has no `DerefMut`, so
32 /// the only way to mutate through `self.config` is via this accessor —
33 /// there is no code path that can silently leave a reader with stale
34 /// data.
35 ///
36 /// Window-side reads (`Window::config()`) read a *separate* Arc clone
37 /// stashed in `WindowResources`. Mutations through `config_mut`
38 /// therefore leave window clones stale until [`Editor::sync_windows_config`]
39 /// runs. Callers that mutate a config field which Window code reads
40 /// (e.g. `editor.line_wrap`, `editor.enable_inlay_hints`,
41 /// `languages`, etc.) must call `sync_windows_config()` afterwards.
42 /// `set_config` does this automatically.
43 pub fn config_mut(&mut self) -> &mut Config {
44 Arc::make_mut(&mut self.config)
45 }
46
47 /// Replace the config wholesale. Used by the "reload config" path and
48 /// by tests that want to swap in a freshly-parsed file. Constructs a
49 /// fresh `Arc`, so any snapshot that still holds the old value sees
50 /// the pointer move and will reserialize on the next refresh.
51 ///
52 /// Also propagates the new `Arc` to every window's
53 /// `resources.config`, so window-scoped reads see the swap.
54 pub fn set_config(&mut self, new_config: Config) {
55 self.config = Arc::new(new_config);
56 self.sync_windows_config();
57 }
58
59 /// Propagate `self.config` to every window's `resources.config` so
60 /// window-side reads (`Window::config()`) see the latest value.
61 /// `Arc::clone` is cheap, so this is a constant-time fanout per
62 /// window. Called from `set_config` and at the end of any
63 /// `config_mut()`-driven mutation that affects window-read fields.
64 pub(crate) fn sync_windows_config(&mut self) {
65 let cfg = self.config.clone();
66 for w in self.windows.values_mut() {
67 w.resources.config = cfg.clone();
68 }
69 }
70
71 /// Replace the cached raw user config. Like `set_config`, constructs
72 /// a fresh `Arc` so the plugin snapshot notices the change.
73 pub(crate) fn set_user_config_raw(&mut self, value: serde_json::Value) {
74 self.user_config_raw = Arc::new(value);
75 }
76
77 /// Mutable access to the active window's merged diagnostics map.
78 /// Routes through `Arc::make_mut`, which CoW-clones while the
79 /// plugin snapshot still holds the old map — readers never
80 /// observe an in-place mutation.
81 pub(crate) fn stored_diagnostics_mut(
82 &mut self,
83 ) -> &mut HashMap<String, Vec<lsp_types::Diagnostic>> {
84 Arc::make_mut(&mut self.active_window_mut().stored_diagnostics)
85 }
86
87 /// Mutable access to the active window's folding-ranges map.
88 /// Same `Arc::make_mut` CoW pattern as `stored_diagnostics_mut`.
89 pub(crate) fn stored_folding_ranges_mut(
90 &mut self,
91 ) -> &mut HashMap<String, Vec<lsp_types::FoldingRange>> {
92 Arc::make_mut(&mut self.active_window_mut().stored_folding_ranges)
93 }
94
95 /// Get a reference to the key translator (for input calibration)
96 pub fn key_translator(&self) -> &crate::input::key_translator::KeyTranslator {
97 &self.key_translator
98 }
99
100 /// Get a reference to the time source
101 pub fn time_source(&self) -> &SharedTimeSource {
102 &self.time_source
103 }
104
105 /// Emit a control event
106 pub fn emit_event(&self, name: impl Into<String>, data: serde_json::Value) {
107 self.event_broadcaster.emit_named(name, data);
108 }
109
110 /// Send a response to a plugin for an async operation
111 pub(super) fn send_plugin_response(&self, response: fresh_core::api::PluginResponse) {
112 self.plugin_manager
113 .read()
114 .unwrap()
115 .deliver_response(response);
116 }
117
118 // `take_pending_semantic_token_request` and
119 // `take_pending_semantic_token_range_request` live on `impl Window`
120 // — call them via `self.active_window_mut()`.
121
122 /// Get all keybindings as (key, action) pairs
123 pub fn get_all_keybindings(&self) -> Vec<(String, String)> {
124 self.keybindings.read().unwrap().get_all_bindings()
125 }
126
127 /// Get the formatted keybinding for a specific action (for display in messages)
128 /// Returns None if no keybinding is found for the action
129 pub fn get_keybinding_for_action(&self, action_name: &str) -> Option<String> {
130 self.keybindings
131 .read()
132 .unwrap()
133 .find_keybinding_for_action(action_name, self.active_window().key_context.clone())
134 }
135
136 /// Raw-event counterpart: return the `(KeyCode, KeyModifiers)` currently
137 /// bound to `action` in `context`. Intended for callers that need to
138 /// simulate the user pressing the bound key (e2e tests, some hotkey-
139 /// chaining code) without hardcoding a default that a user's rebind
140 /// would invalidate.
141 pub fn keybinding_event_for_action(
142 &self,
143 action: &crate::input::keybindings::Action,
144 context: crate::input::keybindings::KeyContext,
145 ) -> Option<(crossterm::event::KeyCode, crossterm::event::KeyModifiers)> {
146 self.keybindings
147 .read()
148 .unwrap()
149 .get_keybinding_event_for_action(action, context)
150 }
151
152 /// Get mutable access to the mode registry
153 pub fn mode_registry_mut(&mut self) -> &mut ModeRegistry {
154 &mut self.mode_registry
155 }
156
157 /// Get immutable access to the mode registry
158 pub fn mode_registry(&self) -> &ModeRegistry {
159 &self.mode_registry
160 }
161
162 /// Get the currently active buffer ID.
163 ///
164 /// This is derived from the split manager (single source of truth).
165 /// The editor always has at least one buffer, so this never fails.
166 ///
167 /// When the active split has a buffer-group tab as its active target
168 /// (i.e., `active_group_tab.is_some()`), this returns the buffer of the
169 /// currently-focused inner panel — so that input routing, command palette
170 /// context, buffer mode, and other "what is the user looking at" queries
171 /// resolve to the panel the user is actually interacting with rather than
172 /// the split's background leaf buffer.
173 ///
174 /// The override only takes effect if the inner panel's buffer is still
175 /// live in `self.buffers`; otherwise it falls back to the main split's
176 /// leaf buffer so callers never see a stale/freed buffer id.
177 #[inline]
178 pub fn active_buffer(&self) -> BufferId {
179 let (_, buf) = self.effective_active_pair();
180 buf
181 }
182
183 /// The split id whose `SplitViewState` owns the currently-focused
184 /// cursors/viewport/buffer state. For a regular split this is just
185 /// `split_manager.active_split()`. For a split that has a group tab
186 /// active, this returns the focused inner panel's leaf id (which
187 /// lives in `split_view_states` even though it's not in the main
188 /// split tree).
189 #[inline]
190 pub fn effective_active_split(&self) -> crate::model::event::LeafId {
191 let (split, _) = self.effective_active_pair();
192 split
193 }
194
195 /// Resolve the effective (split, buffer) pair for the currently-focused
196 /// target. This is the single source of truth — both `active_buffer` and
197 /// `effective_active_split` derive from it so they can never disagree.
198 ///
199 /// Returned invariant: `split_view_states[split]` exists, its
200 /// `active_buffer` equals the returned buffer id, `self.buffers`
201 /// contains the returned buffer id, and `split.keyed_states` contains
202 /// an entry for the returned buffer id. Consequently the mutation path
203 /// in `apply_event_to_active_buffer` (which indexes into
204 /// `keyed_states[buffer]`) is always well-defined for the returned pair.
205 ///
206 /// If a buffer-group panel is focused but any of the invariants above
207 /// is not satisfied for the inner leaf (for example because the panel
208 /// buffer was freed without clearing `focused_group_leaf`), the helper
209 /// falls back to the outer split's own leaf. The fallback is also
210 /// validated before being returned.
211 #[inline]
212 fn effective_active_pair(&self) -> (crate::model::event::LeafId, BufferId) {
213 self.active_window().effective_active_pair()
214 }
215
216 /// Get the mode name for the active buffer.
217 ///
218 /// Resolution order:
219 /// 1. The buffer's own virtual-buffer mode, if it has one.
220 /// 2. The mode declared by the buffer-group containing this
221 /// buffer (e.g. a `git-log` group's keybindings apply to its
222 /// panels regardless of whether each panel is a virtual
223 /// buffer or a file-backed one — `openFileStreaming` produces
224 /// the latter for streaming detail panels).
225 pub fn active_buffer_mode(&self) -> Option<&str> {
226 let buffer_id = self.active_buffer();
227 let win = self.active_window();
228 if let Some(mode) = win
229 .buffer_metadata
230 .get(&buffer_id)
231 .and_then(|meta| meta.virtual_mode())
232 {
233 return Some(mode);
234 }
235 let group_id = win.buffer_to_group.get(&buffer_id).copied()?;
236 win.buffer_groups.get(&group_id).map(|g| g.mode.as_str())
237 }
238
239 /// Check if the active buffer is read-only
240 pub fn is_active_buffer_read_only(&self) -> bool {
241 if let Some(metadata) = self
242 .active_window()
243 .buffer_metadata
244 .get(&self.active_buffer())
245 {
246 if metadata.read_only {
247 return true;
248 }
249 // Also check if the mode is read-only
250 if let Some(mode_name) = metadata.virtual_mode() {
251 return self.mode_registry.is_read_only(mode_name);
252 }
253 }
254 false
255 }
256
257 // `mark_buffer_read_only` lives on `impl Window` — call it via
258 // `self.active_window_mut().mark_buffer_read_only(buffer_id, ro)`.
259
260 /// Get the effective mode for the active buffer.
261 ///
262 /// Buffer-local mode (virtual buffers) takes precedence over the global
263 /// editor mode, so that e.g. a search-replace panel isn't hijacked by
264 /// a markdown-source or vi-mode global mode.
265 pub fn effective_mode(&self) -> Option<&str> {
266 // When a floating widget panel is mounted, its plugin-defined
267 // mode (`editor.setEditorMode(...)`) takes precedence over the
268 // underlying buffer's virtual mode. Without this, opening the
269 // Orchestrator picker from a python3 terminal session would
270 // resolve mode-keybindings against `"terminal"` instead of
271 // `"orchestrator-open"`, so picker-specific shortcuts like
272 // `Alt+N` never reached their handlers.
273 if self.floating_widget_panel.is_some() {
274 if let Some(mode) = self.active_window().editor_mode.as_deref() {
275 return Some(mode);
276 }
277 }
278 self.active_buffer_mode()
279 .or(self.active_window().editor_mode.as_deref())
280 }
281
282 // `has_active_lsp_progress`, `get_lsp_progress`, and
283 // `is_lsp_server_ready` live on `impl Window` — call them via
284 // `self.active_window().has_active_lsp_progress()` etc.
285
286 /// Read-only view of the editor-wide popup stack.
287 ///
288 /// `global_popups` itself is `pub(crate)` so its internals stay
289 /// private to the app module; tests need to inspect its depth /
290 /// contents to verify "no two popups stacked across the buffer-
291 /// local and global stacks" invariants (e.g. issue 1 of the LSP
292 /// indicator-click bugs), so we expose an immutable accessor here.
293 pub fn global_popups(&self) -> &crate::view::popup::PopupManager {
294 &self.global_popups
295 }
296
297 /// The earliest wall-clock deadline at which the main event loop
298 /// needs to wake up and re-render, *purely because of internal
299 /// time-driven UI elements* (animations, the LSP status-bar
300 /// spinner). Returns `None` when no time-driven UI is in flight —
301 /// the loop can sleep until the next user / async event without
302 /// missing a frame.
303 ///
304 /// The `Some` case includes the LSP-progress spinner: its glyph
305 /// is computed from `SystemTime::now() / 100ms`, so the loop has
306 /// to wake at ~100ms cadence to actually advance it. Without
307 /// this signal, the indicator would only tick when an unrelated
308 /// event caused a frame, and the user would see a "frozen"
309 /// spinner whenever the server stopped emitting `$/progress`
310 /// (e.g. died externally — see #1941 issue 3).
311 pub fn next_periodic_redraw_deadline(&self) -> Option<std::time::Instant> {
312 let lsp_progress_deadline = if self.active_window().has_active_lsp_progress() {
313 // 100ms matches the spinner-glyph period in
314 // `lsp_status::compose_lsp_status`.
315 Some(std::time::Instant::now() + std::time::Duration::from_millis(100))
316 } else {
317 None
318 };
319 let anim_deadline = self.active_window().animations.next_deadline();
320 [lsp_progress_deadline, anim_deadline]
321 .into_iter()
322 .flatten()
323 .min()
324 }
325
326 /// Get stored LSP diagnostics (for testing and external access)
327 /// Returns a reference to the diagnostics map keyed by file URI
328 pub fn get_stored_diagnostics(&self) -> &HashMap<String, Vec<lsp_types::Diagnostic>> {
329 &self.active_window().stored_diagnostics
330 }
331
332 /// Check if an update is available
333 pub fn is_update_available(&self) -> bool {
334 self.update_checker
335 .as_ref()
336 .map(|c| c.is_update_available())
337 .unwrap_or(false)
338 }
339
340 /// Get the latest version string if an update is available
341 pub fn latest_version(&self) -> Option<&str> {
342 self.update_checker
343 .as_ref()
344 .and_then(|c| c.latest_version())
345 }
346
347 /// Get the cached release check result (for shutdown notification)
348 pub fn get_update_result(
349 &self,
350 ) -> Option<&crate::services::release_checker::ReleaseCheckResult> {
351 self.update_checker
352 .as_ref()
353 .and_then(|c| c.get_cached_result())
354 }
355
356 /// Set a custom update checker (for testing)
357 ///
358 /// This allows injecting a custom PeriodicUpdateChecker that points to a mock server,
359 /// enabling E2E tests for the update notification UI.
360 #[doc(hidden)]
361 pub fn set_update_checker(
362 &mut self,
363 checker: crate::services::release_checker::PeriodicUpdateChecker,
364 ) {
365 self.update_checker = Some(checker);
366 }
367
368 /// Configure LSP server for a specific language
369 pub fn set_lsp_config(&mut self, language: String, config: Vec<LspServerConfig>) {
370 let __active_id = self.active_window;
371 if let Some(lsp) = self
372 .windows
373 .get_mut(&__active_id)
374 .and_then(|w| w.lsp.as_mut())
375 {
376 lsp.set_language_configs(language, config);
377 }
378 }
379
380 // `running_lsp_servers`, `pending_completion_requests_count`,
381 // `completion_items_count`, `initialized_lsp_server_count`, and
382 // `shutdown_lsp_server` live on `impl Window` — call them via
383 // `self.active_window()` / `self.active_window_mut()`.
384
385 /// Set up warning log monitoring
386 ///
387 /// When warnings/errors are logged, they will be written to the specified path
388 /// and the editor will be notified via the receiver.
389 pub fn set_warning_log(&mut self, receiver: std::sync::mpsc::Receiver<()>, path: PathBuf) {
390 self.warning_log = Some((receiver, path));
391 }
392
393 /// Take the warning-log receiver+path out of this editor.
394 ///
395 /// The receiver is single-consumer and lives for the process's
396 /// lifetime; on a destructive editor restart (e.g. authority swap)
397 /// `main.rs` lifts it from the old editor and re-installs it on the
398 /// new one so warnings keep flowing post-restart instead of vanishing
399 /// with the dropped editor.
400 pub fn take_warning_log(&mut self) -> Option<(std::sync::mpsc::Receiver<()>, PathBuf)> {
401 self.warning_log.take()
402 }
403
404 /// Set the status message log path
405 pub fn set_status_log_path(&mut self, path: PathBuf) {
406 self.status_log_path = Some(path);
407 }
408
409 /// Queue a new authority and restart the editor.
410 ///
411 /// Per the design decision in `docs/internal/AUTHORITY_DESIGN.md`,
412 /// authority transitions piggy-back on the existing
413 /// `change_working_dir` restart path. The caller never sees an
414 /// editor that is half-transitioned: the current `Editor` is
415 /// dropped, `main.rs` rebuilds a fresh one with the queued
416 /// authority, and session restore reopens buffers against the new
417 /// backend. This is slower than an in-place pointer swap but is
418 /// far more robust — every cached `Arc<dyn FileSystem>`, LSP
419 /// handle, terminal PTY, plugin state, and in-flight task is
420 /// dropped cleanly by the existing restart machinery.
421 pub fn install_authority(&mut self, authority: crate::services::authority::Authority) {
422 self.pending_authority = Some(authority);
423 // Re-open the same working directory; `main.rs` picks up the
424 // pending authority from the old editor just before dropping it.
425 self.request_restart(self.working_dir.clone());
426 }
427
428 /// Restore the default local authority. Same destructive-restart
429 /// semantics as `install_authority` — the caller never observes a
430 /// half-transitioned editor.
431 pub fn clear_authority(&mut self) {
432 self.install_authority(crate::services::authority::Authority::local());
433 }
434
435 /// Take the queued authority (if any). Called by `main.rs` on
436 /// restart to move the queued authority into the fresh editor.
437 pub fn take_pending_authority(&mut self) -> Option<crate::services::authority::Authority> {
438 self.pending_authority.take()
439 }
440
441 /// Directly replace the active authority without triggering a
442 /// restart. Intended for the post-construction wiring in `main.rs`
443 /// only, where the editor is still being set up and there is no
444 /// user-visible state to preserve. Do not call this from the event
445 /// loop — use `install_authority` for that.
446 ///
447 /// Also refreshes the plugin state snapshot so hooks that fire after
448 /// this call (notably `plugins_loaded`, fired by `main.rs` right
449 /// after `set_boot_authority`) see the real `authority_label` instead
450 /// of the empty string the temporary `Authority::local()` carried
451 /// during construction.
452 pub fn set_boot_authority(&mut self, authority: crate::services::authority::Authority) {
453 self.authority = authority;
454 // Propagate the new authority to every window's resources so
455 // window-side filesystem/path-translation reads (`Window::authority()`)
456 // see the swap. `Authority` carries internal `Arc`s, so this just
457 // clones cheap handles.
458 let auth = self.authority.clone();
459 for w in self.windows.values_mut() {
460 w.resources.authority = auth.clone();
461 }
462 // Propagate the authority's long-running spawner into the LSP
463 // manager so `force_spawn` can route server processes through
464 // the right backend. The editor rebuilds on every authority
465 // transition (AUTHORITY_DESIGN.md principle 7), so this is the
466 // single wiring point — no need for a hot-swap API. Path
467 // translation rides along for the same reason — LSP URIs need
468 // to be host↔container-translated under the new authority.
469 let __active_id = self.active_window;
470 if let Some(lsp) = self
471 .windows
472 .get_mut(&__active_id)
473 .and_then(|w| w.lsp.as_mut())
474 {
475 lsp.set_long_running_spawner(self.authority.long_running_spawner.clone());
476 lsp.set_path_translation(self.authority.path_translation.clone());
477 }
478 #[cfg(feature = "plugins")]
479 {
480 self.update_plugin_state_snapshot();
481 // Notify plugins so they can re-register state-gated
482 // commands (e.g. devcontainer `Attach` only when not
483 // attached). Production transitions also trigger a full
484 // editor restart that re-runs plugin init, but firing
485 // here keeps in-process transitions and the test harness
486 // (which simulates the restart inline) consistent.
487 let label = self.authority.display_label.clone();
488 self.plugin_manager.read().unwrap().run_hook(
489 "authority_changed",
490 crate::services::plugins::hooks::HookArgs::AuthorityChanged { label },
491 );
492 }
493 }
494
495 /// Read-only access to the active authority.
496 pub fn authority(&self) -> &crate::services::authority::Authority {
497 &self.authority
498 }
499
500 /// The editor's current working directory. This is the project
501 /// root; individual buffers may live elsewhere.
502 pub fn working_dir(&self) -> &std::path::Path {
503 &self.working_dir
504 }
505
506 /// The currently active `Session`. Always `WindowId(1)` until
507 /// the multi-session migration step lands; until then this is
508 /// effectively a typed wrapper around `working_dir`. New code
509 /// should prefer this accessor so the eventual migration is a
510 /// no-op for the call site.
511 ///
512 /// Panics if the active session id is not present in the
513 /// `sessions` map. That invariant is upheld by the constructor
514 /// and `setActiveWindow` (when added) — if the panic ever fires
515 /// it indicates a bug in session lifecycle code.
516 pub fn active_window(&self) -> &crate::app::window::Window {
517 self.windows
518 .get(&self.active_window)
519 .expect("active_window id must be a member of sessions")
520 }
521
522 /// The active session's id.
523 pub fn active_session_id(&self) -> fresh_core::WindowId {
524 self.active_window
525 }
526
527 /// Allocate the next globally-unique `BufferId`. Use this in
528 /// `impl Editor` handler bodies that mint new buffer ids. Handlers
529 /// that have already moved to `impl Window` use
530 /// `Window::alloc_buffer_id` (which delegates to the same
531 /// `Arc<BufferIdAllocator>` shared via `WindowResources`).
532 ///
533 /// Keeps `next_buffer_id` in sync with the allocator's high-water
534 /// mark so workspace snapshots that read the `next_buffer_id`
535 /// counter directly continue to see a correct value. The
536 /// allocator's atomic is the source of truth; this counter mirrors
537 /// it for serialization compatibility.
538 pub(crate) fn alloc_buffer_id(&mut self) -> fresh_core::BufferId {
539 let id = self.buffer_id_alloc.next();
540 // Bump the legacy counter past the freshly-issued id so
541 // workspace serialization snapshots see a value at least one
542 // greater than every issued id.
543 if id.0 + 1 > self.next_buffer_id {
544 self.next_buffer_id = id.0 + 1;
545 }
546 id
547 }
548
549 /// Number of sessions currently in the editor. Always 1 until
550 /// the multi-session step lands.
551 pub fn session_count(&self) -> usize {
552 self.windows.len()
553 }
554
555 /// Look up a session by id. Returns `None` if `id` is not in
556 /// the sessions map. Useful for tests; production code that
557 /// needs the active session should use `active_window()`.
558 pub fn session(&self, id: fresh_core::WindowId) -> Option<&crate::app::window::Window> {
559 self.windows.get(&id)
560 }
561
562 /// Active session's utility-dock panel-id → buffer-id map.
563 /// Used by tests to assert that the active window's dock
564 /// occupancy is what was set on it. (Pre-0b this asserted
565 /// "warm-swap restored the stash"; post-0b every window owns
566 /// its own dock, so the assertion is just "this window's
567 /// `panel_ids` map matches expectations.")
568 #[doc(hidden)]
569 pub fn panel_ids_for_test(&self) -> &std::collections::HashMap<String, fresh_core::BufferId> {
570 self.panel_ids()
571 }
572
573 /// Inject a panel_ids entry. Used by tests to populate the
574 /// active session's dock occupancy without going through the
575 /// async plugin command path.
576 #[doc(hidden)]
577 pub fn insert_panel_id_for_test(&mut self, key: String, buffer_id: fresh_core::BufferId) {
578 self.panel_ids_mut().insert(key, buffer_id);
579 }
580
581 /// True iff the active session has an LSP manager attached.
582 /// Used by tests to assert that the active window's `lsp`
583 /// slot is populated. (Pre-0b this exercised the warm-swap
584 /// code; post-0b the LSP manager lives directly on `Window`,
585 /// so the assertion is just "this window's `lsp` is `Some`.")
586 #[doc(hidden)]
587 pub fn has_lsp_for_test(&self) -> bool {
588 self.lsp().is_some()
589 }
590
591 /// Inject an LspManager so tests can prove the swap routes
592 /// it through the session stash without depending on real
593 /// LSP server spawn.
594 #[doc(hidden)]
595 pub fn install_dummy_lsp_for_test(&mut self) {
596 let active = self.active_window;
597 self.active_window_mut().lsp =
598 Some(crate::services::lsp::manager::LspManager::new(active, None));
599 }
600
601 /// Most-recent `path_changed` event the editor received.
602 /// Test-only — used by `watch_path` e2e tests to assert
603 /// kernel events surfaced to the editor.
604 #[doc(hidden)]
605 pub fn last_path_change_for_test(&self) -> Option<&(u64, std::path::PathBuf, &'static str)> {
606 self.last_path_change_for_test.as_ref()
607 }
608
609 /// Most-recent `WatchPathRegistered` plugin response, paired
610 /// with its request_id. Test-only.
611 #[doc(hidden)]
612 pub fn last_watch_response_for_test(&self) -> Option<&(u64, Result<u64, String>)> {
613 self.last_watch_response_for_test.as_ref()
614 }
615
616 /// Inject an mtime entry into the active session's mod-time
617 /// cache. Used by tests to populate `Window.file_mod_times`
618 /// without going through real file I/O. (Pre-0b this was
619 /// reaching the warm-swap stash; post-0b it's a direct
620 /// insert into the active window's cache.)
621 #[doc(hidden)]
622 pub fn insert_mtime_for_test(&mut self, path: std::path::PathBuf, t: std::time::SystemTime) {
623 self.file_mod_times_mut().insert(path, t);
624 }
625
626 /// Whether the active session's mtime cache contains `path`.
627 #[doc(hidden)]
628 pub fn has_mtime_for_test(&self, path: &std::path::Path) -> bool {
629 self.file_mod_times().contains_key(path)
630 }
631
632 /// Mutable access to the active session. Used by lifecycle code
633 /// that re-targets per-session state (renaming, etc.). Same
634 /// panic invariant as `active_window()`.
635 pub fn active_window_mut(&mut self) -> &mut crate::app::window::Window {
636 let id = self.active_window;
637 self.windows
638 .get_mut(&id)
639 .expect("active_window id must be a member of sessions")
640 }
641
642 /// The active window's layout-cache (split-leaf rects, tab rects,
643 /// file-explorer rect, view-line mappings). Mouse hit-testing and
644 /// visual-line motion read from here.
645 pub(crate) fn active_layout(&self) -> &crate::app::types::WindowLayoutCache {
646 &self.active_window().layout_cache
647 }
648
649 /// Mutable handle to the active window's layout cache. Renderer
650 /// writes split / tab / file-explorer hit-test rects here at the
651 /// end of each frame.
652 pub(crate) fn active_layout_mut(&mut self) -> &mut crate::app::types::WindowLayoutCache {
653 &mut self.active_window_mut().layout_cache
654 }
655
656 /// The active window's editor-chrome layout cache (status bar,
657 /// menu, popups, prompt overlay, full-frame cell-theme map).
658 /// Mouse hit-testing reads from here.
659 pub(crate) fn active_chrome(&self) -> &crate::app::types::ChromeLayout {
660 &self.active_window().chrome_layout
661 }
662
663 /// Mutable handle to the active window's chrome-layout cache.
664 /// Renderer writes status-bar / menu / popup / prompt-overlay
665 /// hit-test rects here at the end of each frame.
666 pub(crate) fn active_chrome_mut(&mut self) -> &mut crate::app::types::ChromeLayout {
667 &mut self.active_window_mut().chrome_layout
668 }
669
670 /// Active window's utility-dock panel-id → buffer-id map.
671 /// Each window owns its own dock; switching windows shows a
672 /// different (possibly empty) dock.
673 pub(crate) fn panel_ids(&self) -> &std::collections::HashMap<String, BufferId> {
674 &self.active_window().panel_ids
675 }
676
677 /// Mutable handle to the active window's panel-id map.
678 pub(crate) fn panel_ids_mut(&mut self) -> &mut std::collections::HashMap<String, BufferId> {
679 &mut self.active_window_mut().panel_ids
680 }
681
682 /// Active window's open-file mtime cache. Auto-revert only
683 /// fires for files in the active window — dormant windows
684 /// keep their mtime snapshot until the next dive.
685 pub(crate) fn file_mod_times(
686 &self,
687 ) -> &std::collections::HashMap<std::path::PathBuf, std::time::SystemTime> {
688 &self.active_window().file_mod_times
689 }
690
691 /// Mutable handle to the active window's mtime cache.
692 pub(crate) fn file_mod_times_mut(
693 &mut self,
694 ) -> &mut std::collections::HashMap<std::path::PathBuf, std::time::SystemTime> {
695 &mut self.active_window_mut().file_mod_times
696 }
697
698 /// Active window's file-explorer view (`None` if it's never been
699 /// opened in this window). Each window has its own tree;
700 /// switching windows shows that window's view (or none).
701 pub fn file_explorer(&self) -> Option<&FileTreeView> {
702 self.active_window().file_explorer.as_ref()
703 }
704
705 /// Mutable handle to the active window's file-explorer view.
706 /// Holds `&mut self` for the call's lifetime — for sites that
707 /// also need to read other Editor fields, use direct
708 /// `self.windows.get_mut(&self.active_window).and_then(|w| w.file_explorer.as_mut())`
709 /// instead so the borrow on `self.windows` stays disjoint.
710 pub fn file_explorer_mut(&mut self) -> Option<&mut FileTreeView> {
711 self.active_window_mut().file_explorer.as_mut()
712 }
713
714 /// Active window's buffer storage. Each window owns its
715 /// `EditorState` map outright; closing the window drops them.
716 /// Cross-window iteration goes through `self.windows.values()`
717 /// directly.
718 pub(crate) fn buffers(&self) -> &crate::app::window::WindowBuffers {
719 &self.active_window().buffers
720 }
721
722 /// Mutable handle to the active window's buffer storage.
723 /// Holds `&mut self` for the call's lifetime — at sites that
724 /// need a concurrent mutable borrow on another Window field
725 /// (`splits`, `event_logs`, etc.) take a single
726 /// `let window = self.windows.get_mut(&self.active_window).unwrap()`
727 /// and split-access the disjoint sub-fields directly.
728 pub(crate) fn buffers_mut(&mut self) -> &mut crate::app::window::WindowBuffers {
729 &mut self.active_window_mut().buffers
730 }
731
732 /// Active window's LSP manager (`None` if no LSP has been spawned
733 /// for this window yet). Each window has its own LSP set rooted
734 /// at its project root.
735 pub(crate) fn lsp(&self) -> Option<&crate::services::lsp::manager::LspManager> {
736 self.active_window().lsp.as_ref()
737 }
738
739 /// Mutable handle to the active window's LSP manager. Same
740 /// borrow caveat as `file_explorer_mut()`: at sites that also
741 /// need to read other Editor fields, prefer direct
742 /// `self.windows.get_mut(&self.active_window).and_then(|w| w.lsp.as_mut())`.
743 pub(crate) fn lsp_mut(&mut self) -> Option<&mut crate::services::lsp::manager::LspManager> {
744 self.active_window_mut().lsp.as_mut()
745 }
746
747 /// Active window's split tree. Panics if the window has no
748 /// layout yet — the invariant is "the active window always has
749 /// `splits` populated", upheld by `set_active_window` (which
750 /// seeds the layout on first dive) and by editor init (which
751 /// hands the initial layout to the base window).
752 pub(crate) fn split_manager(&self) -> &crate::view::split::SplitManager {
753 &self
754 .active_window()
755 .buffers
756 .splits()
757 .expect("active window must have a populated split layout")
758 .0
759 }
760
761 /// Mutable handle to the active window's split tree.
762 pub(crate) fn split_manager_mut(&mut self) -> &mut crate::view::split::SplitManager {
763 &mut self
764 .active_window_mut()
765 .buffers
766 .splits_mut()
767 .expect("active window must have a populated split layout")
768 .0
769 }
770
771 /// Active window's per-leaf view state map.
772 #[cfg(test)]
773 pub(crate) fn split_view_states(
774 &self,
775 ) -> &std::collections::HashMap<crate::model::event::LeafId, crate::view::split::SplitViewState>
776 {
777 &self
778 .active_window()
779 .buffers
780 .splits()
781 .expect("active window must have a populated split layout")
782 .1
783 }
784
785 /// Mutable handle to the active window's per-leaf view state map.
786 pub(crate) fn split_view_states_mut(
787 &mut self,
788 ) -> &mut std::collections::HashMap<
789 crate::model::event::LeafId,
790 crate::view::split::SplitViewState,
791 > {
792 &mut self
793 .active_window_mut()
794 .buffers
795 .splits_mut()
796 .expect("active window must have a populated split layout")
797 .1
798 }
799
800 /// Return buffer ids whose on-disk path sits at or under `root`.
801 /// Used by file-explorer operations that need to react when a file
802 /// or directory on disk goes away or moves.
803 pub fn buffer_ids_under_path(&self, root: &std::path::Path) -> Vec<BufferId> {
804 self.windows
805 .get(&self.active_window)
806 .map(|w| &w.buffers)
807 .expect("active window present")
808 .iter()
809 .filter_map(|(id, state)| {
810 let p = state.buffer.file_path()?;
811 if p == root || p.starts_with(root) {
812 Some(*id)
813 } else {
814 None
815 }
816 })
817 .collect()
818 }
819
820 /// Get remote connection info if editing remote files
821 ///
822 /// Returns `Some("user@host")` for remote editing, `None` for local.
823 pub fn remote_connection_info(&self) -> Option<&str> {
824 self.authority.filesystem.remote_connection_info()
825 }
826
827 /// Get connection string for display in status bar and file explorer.
828 ///
829 /// Per principle 9, identity lives in the authority. The label set
830 /// by whoever constructed the authority wins; if it is empty (the
831 /// SSH constructor leaves it that way) we fall back to the
832 /// filesystem's `remote_connection_info()`, which knows how to
833 /// annotate disconnected SSH sessions.
834 pub fn connection_display_string(&self) -> Option<String> {
835 if !self.authority.display_label.is_empty() {
836 return Some(self.authority.display_label.clone());
837 }
838 self.remote_connection_info().map(|conn| {
839 if self.authority.filesystem.is_remote_connected() {
840 conn.to_string()
841 } else {
842 format!("{} (Disconnected)", conn)
843 }
844 })
845 }
846
847 /// Get the status log path
848 pub fn get_status_log_path(&self) -> Option<&PathBuf> {
849 self.status_log_path.as_ref()
850 }
851
852 /// Open the status log file (user clicked on status message)
853 pub fn open_status_log(&mut self) {
854 if let Some(path) = self.status_log_path.clone() {
855 // Use open_local_file since log files are always local
856 match self.active_window_mut().open_local_file(&path) {
857 Ok(buffer_id) => {
858 self.active_window_mut()
859 .mark_buffer_read_only(buffer_id, true);
860 }
861 Err(e) => {
862 tracing::error!("Failed to open status log: {}", e);
863 }
864 }
865 } else {
866 self.set_status_message("Status log not available".to_string());
867 }
868 }
869
870 /// Check for and handle any new warnings in the warning log
871 ///
872 /// Updates the general warning domain for the status bar.
873 /// Returns true if new warnings were found.
874 pub fn check_warning_log(&mut self) -> bool {
875 let path = match &self.warning_log {
876 Some((receiver, path)) => {
877 let mut new_warning_count = 0usize;
878 while receiver.try_recv().is_ok() {
879 new_warning_count += 1;
880 }
881 if new_warning_count == 0 {
882 return false;
883 }
884 (path.clone(), new_warning_count)
885 }
886 None => return false,
887 };
888 let (path, new_warning_count) = path;
889 self.active_window_mut()
890 .warning_domains
891 .general
892 .add_warnings(new_warning_count);
893 self.active_window_mut()
894 .warning_domains
895 .general
896 .set_log_path(path);
897
898 true
899 }
900
901 /// Get the warning domain registry
902 // Warning-domain accessors live on `impl Window`:
903 // - `clear_warnings` — call as `self.active_window_mut().clear_warnings()`.
904 // - Read access via `active_window().warning_domains` directly
905 // (and its `.general` / `.lsp` sub-registries).
906 // `has_lsp_error`, `get_effective_warning_level`,
907 // `get_general_warning_level`, `get_general_warning_count`,
908 // `get_warning_domains`, `get_warning_log_path`,
909 // `clear_warning_indicator` were thin getters with no remaining
910 // callers and have been removed.
911
912 /// Open the warning log file (user-initiated action). Stays on
913 /// `impl Editor` because it calls editor-orchestration helpers
914 /// (`open_local_file`, `mark_buffer_read_only`).
915 pub fn open_warning_log(&mut self) {
916 if let Some(path) = self
917 .active_window_mut()
918 .warning_domains
919 .general
920 .log_path
921 .clone()
922 {
923 // Use open_local_file since log files are always local
924 match self.active_window_mut().open_local_file(&path) {
925 Ok(buffer_id) => {
926 self.active_window_mut()
927 .mark_buffer_read_only(buffer_id, true);
928 }
929 Err(e) => {
930 tracing::error!("Failed to open warning log: {}", e);
931 }
932 }
933 }
934 }
935
936 // `update_lsp_warning_domain` lives on `impl Window` — call it via
937 // `self.active_window_mut().update_lsp_warning_domain()`.
938
939 /// Check if mouse hover timer has expired and trigger LSP hover request
940 ///
941 /// This implements debounced hover - we wait for the configured delay before
942 /// sending the request to avoid spamming the LSP server on every mouse move.
943 /// Returns true if a hover request was triggered.
944 pub fn check_mouse_hover_timer(&mut self) -> bool {
945 // Check if mouse hover is enabled
946 if !self.config.editor.mouse_hover_enabled {
947 return false;
948 }
949
950 let hover_delay = std::time::Duration::from_millis(self.config.editor.mouse_hover_delay_ms);
951
952 // Get hover state without borrowing self
953 let hover_info = match self.active_window_mut().mouse_state.lsp_hover_state {
954 Some((byte_pos, start_time, screen_x, screen_y)) => {
955 if self.active_window_mut().mouse_state.lsp_hover_request_sent {
956 return false; // Already sent request for this position
957 }
958 if start_time.elapsed() < hover_delay {
959 return false; // Timer hasn't expired yet
960 }
961 Some((byte_pos, screen_x, screen_y))
962 }
963 None => return false,
964 };
965
966 let Some((byte_pos, screen_x, screen_y)) = hover_info else {
967 return false;
968 };
969
970 // Store mouse position for popup positioning
971 self.active_window_mut()
972 .hover
973 .set_screen_position((screen_x, screen_y));
974
975 // Request hover at the byte position — only mark as sent if dispatched
976 match self.request_hover_at_position(byte_pos) {
977 Ok(true) => {
978 self.active_window_mut().mouse_state.lsp_hover_request_sent = true;
979 true
980 }
981 Ok(false) => false, // no server ready, timer will retry
982 Err(e) => {
983 tracing::debug!("Failed to request hover: {}", e);
984 false
985 }
986 }
987 }
988
989 // `check_semantic_highlight_timer` lives on `impl Window` — call it
990 // via `self.active_window().check_semantic_highlight_timer()`.
991
992 // `check_diagnostic_pull_timer` lives on `impl Window` — call it via
993 // `self.active_window_mut().check_diagnostic_pull_timer()`. Pulls
994 // run against the active window's LSP manager and its per-window
995 // `scheduled_diagnostic_pull` debounce slot.
996
997 /// Check if completion trigger timer has expired and trigger completion if so
998 ///
999 /// This implements debounced completion - we wait for quick_suggestions_delay_ms
1000 /// before sending the completion request to avoid spamming the LSP server.
1001 /// Returns true if a completion request was triggered.
1002 pub fn check_completion_trigger_timer(&mut self) -> bool {
1003 // Check if we have a scheduled completion trigger
1004 let Some(trigger_time) = self.active_window_mut().scheduled_completion_trigger else {
1005 return false;
1006 };
1007
1008 // Check if the timer has expired
1009 if Instant::now() < trigger_time {
1010 return false;
1011 }
1012
1013 // Clear the scheduled trigger
1014 self.active_window_mut().scheduled_completion_trigger = None;
1015
1016 // Don't trigger if a popup is already visible
1017 if self.active_state().popups.is_visible() {
1018 return false;
1019 }
1020
1021 // Trigger the completion request
1022 self.request_completion();
1023
1024 true
1025 }
1026}