Skip to main content

fresh/app/
lifecycle.rs

1//! Editor-lifecycle methods: quit, restart, session/detach control,
2//! focus/resize hooks, theme/settings queries, escape-sequence + clipboard
3//! piping, and the should_quit confirmation flow that walks modified buffers.
4
5use super::*;
6
7impl Editor {
8    /// Check if the editor should quit
9    pub fn should_quit(&self) -> bool {
10        self.should_quit
11    }
12
13    /// Check if the client should detach (keep server running)
14    pub fn should_detach(&self) -> bool {
15        self.should_detach
16    }
17
18    /// Clear the detach flag (after processing)
19    pub fn clear_detach(&mut self) {
20        self.should_detach = false;
21    }
22
23    /// Set session mode (use hardware cursor only, no REVERSED style for software cursor)
24    pub fn set_session_mode(&mut self, session_mode: bool) {
25        self.session_mode = session_mode;
26        self.clipboard.set_session_mode(session_mode);
27        // Also set custom context for command palette filtering
28        if session_mode {
29            self.active_window_mut()
30                .active_custom_contexts
31                .insert(crate::types::context_keys::SESSION_MODE.to_string());
32        } else {
33            self.active_window_mut()
34                .active_custom_contexts
35                .remove(crate::types::context_keys::SESSION_MODE);
36        }
37    }
38
39    /// Check if running in session mode
40    pub fn is_session_mode(&self) -> bool {
41        self.session_mode
42    }
43
44    /// Mark that the backend does not render a hardware cursor.
45    /// When set, the renderer always draws a software cursor indicator.
46    pub fn set_software_cursor_only(&mut self, enabled: bool) {
47        self.software_cursor_only = enabled;
48    }
49
50    /// Set the session name for display in status bar.
51    ///
52    /// When a session name is set, the recovery service is reinitialized
53    /// to use a session-scoped recovery directory so each named session's
54    /// recovery data is isolated.
55    pub fn set_session_name(&mut self, name: Option<String>) {
56        if let Some(ref session_name) = name {
57            let base_recovery_dir = self.dir_context.recovery_dir();
58            let scope = crate::services::recovery::RecoveryScope::Session {
59                name: session_name.clone(),
60            };
61            let recovery_config = RecoveryConfig {
62                enabled: self.recovery_service.lock().unwrap().is_enabled(),
63                ..RecoveryConfig::default()
64            };
65            // Replace the shared service's contents in place — the
66            // `Arc<Mutex>` is cloned into every window, so we must not
67            // swap the `Arc` itself (that would desync the windows).
68            *self.recovery_service.lock().unwrap() =
69                RecoveryService::with_scope(recovery_config, &base_recovery_dir, &scope);
70        }
71        self.session_name = name;
72    }
73
74    /// Get the session name (for status bar display)
75    pub fn session_name(&self) -> Option<&str> {
76        self.session_name.as_deref()
77    }
78
79    /// Queue escape sequences to be sent to the client (session mode only)
80    pub fn queue_escape_sequences(&mut self, sequences: &[u8]) {
81        self.pending_escape_sequences.extend_from_slice(sequences);
82    }
83
84    /// Take pending escape sequences, clearing the queue
85    pub fn take_pending_escape_sequences(&mut self) -> Vec<u8> {
86        std::mem::take(&mut self.pending_escape_sequences)
87    }
88
89    /// Take pending clipboard data queued in session mode, clearing the request
90    pub fn take_pending_clipboard(
91        &mut self,
92    ) -> Option<crate::services::clipboard::PendingClipboard> {
93        self.clipboard.take_pending_clipboard()
94    }
95
96    /// Check if the editor should restart with a new working directory
97    pub fn should_restart(&self) -> bool {
98        self.restart_with_dir.is_some()
99    }
100
101    /// Take the restart directory, clearing the restart request
102    /// Returns the new working directory if a restart was requested
103    pub fn take_restart_dir(&mut self) -> Option<PathBuf> {
104        self.restart_with_dir.take()
105    }
106
107    /// Request the editor to restart with a new working directory
108    /// This triggers a clean shutdown and restart with the new project root
109    /// Request a full hardware terminal clear and redraw on the next frame.
110    /// Used after external commands have messed up the terminal state.
111    pub fn request_full_redraw(&mut self) {
112        self.full_redraw_requested = true;
113    }
114
115    /// Check if a full redraw was requested, and clear the flag.
116    pub fn take_full_redraw_request(&mut self) -> bool {
117        let requested = self.full_redraw_requested;
118        self.full_redraw_requested = false;
119        requested
120    }
121
122    /// Request the event loop to suspend the editor process (SIGTSTP on Unix).
123    /// The loop tears down terminal modes, raises the signal, then re-enables
124    /// modes once the shell sends SIGCONT (e.g. via `fg`).
125    pub fn request_suspend(&mut self) {
126        self.suspend_requested = true;
127    }
128
129    /// Check if a suspend was requested, and clear the flag.
130    pub fn take_suspend_request(&mut self) -> bool {
131        let requested = self.suspend_requested;
132        self.suspend_requested = false;
133        requested
134    }
135
136    pub fn request_restart(&mut self, new_working_dir: PathBuf) {
137        tracing::info!(
138            "Restart requested with new working directory: {}",
139            new_working_dir.display()
140        );
141        self.restart_with_dir = Some(new_working_dir);
142        // Also signal quit so the event loop exits
143        self.should_quit = true;
144    }
145
146    /// Get the active theme (read lock).
147    pub fn theme(&self) -> std::sync::RwLockReadGuard<'_, crate::view::theme::Theme> {
148        self.theme.read().unwrap()
149    }
150
151    /// Check if the settings dialog is open and visible
152    pub fn is_settings_open(&self) -> bool {
153        self.settings_state.as_ref().is_some_and(|s| s.visible)
154    }
155
156    /// Request the editor to quit
157    pub fn quit(&mut self) {
158        // Check for unsaved buffers (all are auto-persisted when hot_exit is enabled)
159        let modified_count = self.count_modified_buffers_needing_prompt();
160        if modified_count == 0 && self.config.editor.confirm_quit {
161            // No dirty buffers, but the user has opted into a
162            // safety-net confirmation for a stray Ctrl+Q (issue #2030).
163            let msg = t!("prompt.quit_confirm").to_string();
164            self.start_prompt(msg, PromptType::ConfirmQuit);
165            return;
166        }
167        if modified_count > 0 {
168            let save_key = t!("prompt.key.save").to_string();
169            let cancel_key = t!("prompt.key.cancel").to_string();
170            let hot_exit = self.config.editor.hot_exit;
171
172            let discard_key = t!("prompt.key.discard").to_string();
173            let msg = if hot_exit {
174                // With hot exit: offer save, discard, quit-without-saving (recoverable), or cancel
175                let quit_key = t!("prompt.key.quit").to_string();
176                if modified_count == 1 {
177                    t!(
178                        "prompt.quit_modified_hot_one",
179                        save_key = save_key,
180                        discard_key = discard_key,
181                        quit_key = quit_key,
182                        cancel_key = cancel_key
183                    )
184                    .to_string()
185                } else {
186                    t!(
187                        "prompt.quit_modified_hot_many",
188                        count = modified_count,
189                        save_key = save_key,
190                        discard_key = discard_key,
191                        quit_key = quit_key,
192                        cancel_key = cancel_key
193                    )
194                    .to_string()
195                }
196            } else {
197                // Without hot exit: offer save, discard, or cancel
198                if modified_count == 1 {
199                    t!(
200                        "prompt.quit_modified_one",
201                        save_key = save_key,
202                        discard_key = discard_key,
203                        cancel_key = cancel_key
204                    )
205                    .to_string()
206                } else {
207                    t!(
208                        "prompt.quit_modified_many",
209                        count = modified_count,
210                        save_key = save_key,
211                        discard_key = discard_key,
212                        cancel_key = cancel_key
213                    )
214                    .to_string()
215                }
216            };
217            self.start_prompt(msg, PromptType::ConfirmQuitWithModified);
218        } else {
219            self.should_quit = true;
220        }
221    }
222
223    /// Count modified buffers that would require a save prompt on quit.
224    ///
225    /// When `hot_exit` is enabled, unnamed buffers are excluded (they are
226    /// automatically recovered across sessions), but file-backed modified
227    /// buffers still trigger a prompt with a "recoverable" option.
228    /// When `auto_save_enabled` is true, file-backed buffers are excluded
229    /// (they will be saved to disk on exit).
230    fn count_modified_buffers_needing_prompt(&self) -> usize {
231        let hot_exit = self.config.editor.hot_exit;
232        let auto_save = self.config.editor.auto_save_enabled;
233
234        self.windows
235            .get(&self.active_window)
236            .map(|w| &w.buffers)
237            .expect("active window present")
238            .iter()
239            .filter(|(buffer_id, state)| {
240                if !state.buffer.is_modified() {
241                    return false;
242                }
243                if let Some(meta) = self.active_window().buffer_metadata.get(buffer_id) {
244                    if let Some(path) = meta.file_path() {
245                        let is_unnamed = path.as_os_str().is_empty();
246                        if is_unnamed && hot_exit {
247                            return false; // unnamed buffer, auto-recovered via hot exit
248                        }
249                        if !is_unnamed && auto_save {
250                            return false; // file-backed, will be auto-saved on exit
251                        }
252                    }
253                }
254                true
255            })
256            .count()
257    }
258
259    /// Handle terminal focus gained event
260    pub fn focus_gained(&mut self) {
261        self.plugin_manager.read().unwrap().run_hook(
262            "focus_gained",
263            crate::services::plugins::hooks::HookArgs::FocusGained {},
264        );
265    }
266
267    /// Resize all buffers to match new terminal size. Loops over every
268    /// `Window` so each one updates its own split viewports and visible
269    /// terminal PTYs; the plugin `resize` hook fires once for the editor
270    /// as a whole.
271    pub fn resize(&mut self, width: u16, height: u16) {
272        // Editor's canonical screen dimensions (used to seed new windows).
273        self.terminal_width = width;
274        self.terminal_height = height;
275
276        for window in self.windows.values_mut() {
277            window.resize(width, height);
278        }
279
280        // Refresh the plugin-facing snapshot BEFORE firing the
281        // resize hook. Without this, the orchestrator's resize
282        // handler reads `editor.getViewport()` from a snapshot
283        // whose `viewport.height` still reflects the pre-resize
284        // size — the one-way ratchet in `buildOpenSpec` then sees
285        // `old > old` and skips the update, leaving the picker
286        // stuck small even after a terminal-grow event. (The
287        // ratchet itself is correct; the input it consumes was
288        // stale.) Updating the snapshot here lets plugins observe
289        // the new dimensions when they react to the hook.
290        #[cfg(feature = "plugins")]
291        self.update_plugin_state_snapshot();
292
293        // Notify plugins of the resize so they can adjust layouts.
294        self.plugin_manager.read().unwrap().run_hook(
295            "resize",
296            fresh_core::hooks::HookArgs::Resize { width, height },
297        );
298
299        // If a floating widget panel is currently mounted (the
300        // Orchestrator picker, New-Session form, plugin overlays),
301        // its cached `entries` were laid out against the old screen
302        // width — re-render against the new one so column widths,
303        // side borders and embed rects all reflect the new
304        // dimensions (Bug 13). The hook above lets plugins update
305        // their spec; this rerender picks up either the updated
306        // spec or the existing spec at the new width.
307        if let Some(panel_id) = self.floating_widget_panel.as_ref().map(|f| f.panel_id) {
308            self.rerender_widget_panel(panel_id);
309        }
310    }
311}
312
313impl crate::app::window::Window {
314    /// Adopt the new terminal dimensions for this window: update the
315    /// cached `terminal_width` / `terminal_height`, resize every split
316    /// viewport, and resize any visible terminal PTYs.
317    pub fn resize(&mut self, width: u16, height: u16) {
318        self.terminal_width = width;
319        self.terminal_height = height;
320
321        if let Some(view_states) = self.split_view_states_mut() {
322            for view_state in view_states.values_mut() {
323                view_state.viewport.resize(width, height);
324            }
325        }
326
327        self.resize_visible_terminals();
328    }
329}