par_term/app/tmux_handler/gateway.rs
1//! tmux gateway session management and I/O routing.
2//!
3//! Covers:
4//! - Session lifecycle: initiate, attach, disconnect, status queries
5//! - Input routing: send_input_via_tmux, paste_via_tmux, prefix key handling
6//! - Pane operations: split_pane_via_tmux, close_pane_via_tmux
7//! - Clipboard + resize synchronization
8//!
9//! Profile auto-application on session connect lives in `gateway_profile`.
10
11use crate::app::window_state::WindowState;
12use crate::tmux::{SessionState, TmuxSession};
13
14impl WindowState {
15 // =========================================================================
16 // Gateway Mode Session Management
17 // =========================================================================
18
19 /// Initiate a new tmux session via gateway mode.
20 ///
21 /// This writes `tmux -CC new-session` to the active tab's PTY and enables
22 /// tmux control mode parsing. The session will be fully connected once we
23 /// receive the `%session-changed` notification.
24 ///
25 /// # Arguments
26 /// * `session_name` - Optional session name. If None, tmux will auto-generate one.
27 pub fn initiate_tmux_gateway(&mut self, session_name: Option<&str>) -> anyhow::Result<()> {
28 if !self.config.load().tmux.tmux_enabled {
29 anyhow::bail!("tmux integration is disabled");
30 }
31
32 if self.tmux_state.tmux_session.is_some() && self.is_tmux_connected() {
33 anyhow::bail!("Already connected to a tmux session");
34 }
35
36 crate::debug_info!(
37 "TMUX",
38 "Initiating gateway mode session: {:?}",
39 session_name.unwrap_or("(auto)")
40 );
41
42 // Generate the command
43 let cmd = match session_name {
44 Some(name) => TmuxSession::create_or_attach_command(name),
45 None => TmuxSession::create_new_command(None),
46 };
47
48 // Get the active tab ID and write the command to its PTY
49 let gateway_tab_id = self
50 .tab_manager
51 .active_tab_id()
52 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
53
54 let tab = self
55 .tab_manager
56 .active_tab_mut()
57 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
58
59 // Write the command to the PTY
60 // try_lock: intentional — initiate_tmux_gateway is user-initiated but called from
61 // the sync event loop context. If the terminal is locked by the async PTY reader
62 // the command cannot be sent. On miss: bails with an error so the caller can retry.
63 if let Ok(term) = tab.terminal.try_read() {
64 crate::debug_info!(
65 "TMUX",
66 "Writing gateway command to tab {}: {}",
67 gateway_tab_id,
68 cmd.trim()
69 );
70 term.write(cmd.as_bytes())?;
71 // Enable tmux control mode parsing AFTER writing the command
72 term.set_tmux_control_mode(true);
73 crate::debug_info!(
74 "TMUX",
75 "Enabled tmux control mode parsing on tab {}",
76 gateway_tab_id
77 );
78 } else {
79 anyhow::bail!("Could not acquire terminal lock");
80 }
81
82 // Mark this tab as the gateway
83 tab.tmux.tmux_gateway_active = true;
84
85 // Store the gateway tab ID so we know where to send commands
86 self.tmux_state.tmux_gateway_tab_id = Some(gateway_tab_id);
87 crate::debug_info!(
88 "TMUX",
89 "Gateway tab set to {}, state: Initiating",
90 gateway_tab_id
91 );
92
93 // Create session and set gateway state
94 let mut session = TmuxSession::new();
95 session.set_gateway_initiating();
96 self.tmux_state.tmux_session = Some(session);
97
98 // Show toast
99 self.show_toast("tmux: Connecting...");
100
101 Ok(())
102 }
103
104 /// Attach to an existing tmux session via gateway mode.
105 ///
106 /// This writes `tmux -CC attach -t session` to the active tab's PTY.
107 pub fn attach_tmux_gateway(&mut self, session_name: &str) -> anyhow::Result<()> {
108 if !self.config.load().tmux.tmux_enabled {
109 anyhow::bail!("tmux integration is disabled");
110 }
111
112 if self.tmux_state.tmux_session.is_some() && self.is_tmux_connected() {
113 anyhow::bail!("Already connected to a tmux session");
114 }
115
116 crate::debug_info!("TMUX", "Attaching to session via gateway: {}", session_name);
117
118 // Generate the attach command
119 let cmd = TmuxSession::create_attach_command(session_name);
120
121 // Get the active tab ID and write the command to its PTY
122 let gateway_tab_id = self
123 .tab_manager
124 .active_tab_id()
125 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
126
127 let tab = self
128 .tab_manager
129 .active_tab_mut()
130 .ok_or_else(|| anyhow::anyhow!("No active tab available for tmux gateway"))?;
131
132 // Write the command to the PTY
133 // try_lock: intentional — same rationale as initiate_tmux_gateway. On miss: bails
134 // so the user can retry the attach operation explicitly.
135 if let Ok(term) = tab.terminal.try_read() {
136 crate::debug_info!(
137 "TMUX",
138 "Writing attach command to tab {}: {}",
139 gateway_tab_id,
140 cmd.trim()
141 );
142 term.write(cmd.as_bytes())?;
143 term.set_tmux_control_mode(true);
144 crate::debug_info!(
145 "TMUX",
146 "Enabled tmux control mode parsing on tab {}",
147 gateway_tab_id
148 );
149 } else {
150 anyhow::bail!("Could not acquire terminal lock");
151 }
152
153 // Mark this tab as the gateway
154 tab.tmux.tmux_gateway_active = true;
155
156 // Store the gateway tab ID so we know where to send commands
157 self.tmux_state.tmux_gateway_tab_id = Some(gateway_tab_id);
158 crate::debug_info!(
159 "TMUX",
160 "Gateway tab set to {}, state: Initiating",
161 gateway_tab_id
162 );
163
164 // Create session and set gateway state
165 let mut session = TmuxSession::new();
166 session.set_gateway_initiating();
167 self.tmux_state.tmux_session = Some(session);
168
169 // Show toast
170 self.show_toast(format!("tmux: Attaching to '{}'...", session_name));
171
172 Ok(())
173 }
174
175 /// Disconnect from the current tmux session
176 pub fn disconnect_tmux_session(&mut self) {
177 // Restore gateway tab visibility before clearing state
178 self.show_gateway_tab();
179
180 // Clear the gateway tab ID
181 self.tmux_state.tmux_gateway_tab_id = None;
182
183 // First, disable tmux control mode on any gateway tabs
184 for tab in self.tab_manager.tabs_mut() {
185 if tab.tmux.tmux_gateway_active {
186 tab.tmux.tmux_gateway_active = false;
187 // try_lock: intentional — disconnect is called from the sync event loop.
188 // On miss: control mode stays on the terminal until the next frame; benign
189 // since the session is already being torn down and no further output arrives.
190 if let Ok(term) = tab.terminal.try_read() {
191 term.set_tmux_control_mode(false);
192 }
193 }
194 }
195
196 if let Some(mut session) = self.tmux_state.tmux_session.take() {
197 crate::debug_info!("TMUX", "Disconnecting from tmux session");
198 session.disconnect();
199 }
200
201 // Clear session name
202 self.tmux_state.tmux_session_name = None;
203
204 // Reset sync state
205 self.tmux_state.tmux_sync = crate::tmux::TmuxSync::new();
206
207 // Reset window title (now without tmux info)
208 self.update_window_title_with_tmux();
209 }
210
211 /// Check if tmux session is active
212 pub fn is_tmux_connected(&self) -> bool {
213 self.tmux_state
214 .tmux_session
215 .as_ref()
216 .is_some_and(|s| s.state() == SessionState::Connected)
217 }
218
219 /// Return true when a `tmux*` process is running under the active tab's
220 /// shell. Used by the input path to decide whether to encode Shift+Enter
221 /// as raw LF (iTerm2 convention) or as a CSI-u extended-keys sequence
222 /// that tmux's `extended-keys on` parser can relay to the inner app in
223 /// whatever keyboard protocol that app has negotiated (kitty/modifyOtherKeys).
224 pub fn shell_has_tmux_child(&self) -> bool {
225 use std::sync::atomic::Ordering;
226 let tab = match self.tab_manager.active_tab() {
227 Some(t) => t,
228 None => return false,
229 };
230 // Cache fallback: on `try_read` contention (frequent in release/LTO
231 // builds because the renderer holds the write lock briefly on every
232 // frame), fall back to the last-known result rather than reporting
233 // "no tmux". Returning `false` here was causing the Shift+Enter
234 // handler to send raw LF in shell context, which tmux mangles into
235 // Ctrl+J. See cached_has_tmux_child docs in src/tab/mod.rs.
236 match tab.terminal.try_read() {
237 Ok(term) => {
238 let has = term
239 .get_running_child_processes(&[])
240 .iter()
241 .any(|name| name.eq_ignore_ascii_case("tmux") || name.starts_with("tmux"));
242 tab.cached_has_tmux_child.store(has, Ordering::Relaxed);
243 has
244 }
245 Err(_) => tab.cached_has_tmux_child.load(Ordering::Relaxed),
246 }
247 }
248
249 /// Check if gateway mode is active (connected or connecting)
250 pub fn is_gateway_active(&self) -> bool {
251 self.tmux_state
252 .tmux_session
253 .as_ref()
254 .is_some_and(|s| s.is_gateway_active())
255 }
256
257 /// Update the tmux focused pane when a native pane is focused
258 ///
259 /// This should be called when the user clicks on a pane to ensure
260 /// input is routed to the correct tmux pane.
261 pub fn set_tmux_focused_pane_from_native(&mut self, native_pane_id: crate::pane::PaneId) {
262 if let Some(tmux_pane_id) = self
263 .tmux_state
264 .native_pane_to_tmux_pane
265 .get(&native_pane_id)
266 && let Some(session) = &mut self.tmux_state.tmux_session
267 {
268 crate::debug_info!(
269 "TMUX",
270 "Setting focused pane: native {} -> tmux %{}",
271 native_pane_id,
272 tmux_pane_id
273 );
274 session.set_focused_pane(Some(*tmux_pane_id));
275 }
276 }
277
278 // =========================================================================
279 // Gateway Mode Input Routing
280 // =========================================================================
281
282 /// Write a command to the gateway tab's terminal.
283 ///
284 /// The gateway tab is where the tmux control mode connection lives.
285 /// All tmux commands must be written to this tab, not the active tab.
286 pub(crate) fn write_to_gateway(&self, cmd: &str) -> bool {
287 let gateway_tab_id = match self.tmux_state.tmux_gateway_tab_id {
288 Some(id) => id,
289 None => {
290 crate::debug_trace!("TMUX", "No gateway tab ID set");
291 return false;
292 }
293 };
294
295 // try_lock: intentional — write_to_gateway is called from the sync event loop and
296 // from input handlers. Blocking would stall the GUI or create deadlock risk.
297 // On miss: the tmux command is silently dropped. For input this means a keypress
298 // is lost; for control commands (resize, split) the caller should retry as needed.
299 if let Some(tab) = self.tab_manager.get_tab(gateway_tab_id)
300 && tab.tmux.tmux_gateway_active
301 && let Ok(term) = tab.terminal.try_read()
302 {
303 match term.write(cmd.as_bytes()) {
304 Ok(()) => return true,
305 Err(e) => {
306 crate::debug_error!("TMUX", "PTY write failed (gateway command): {e}");
307 return false;
308 }
309 }
310 }
311
312 crate::debug_trace!("TMUX", "Failed to write to gateway tab");
313 false
314 }
315
316 /// Split the current pane via tmux control mode.
317 ///
318 /// Writes split-window command to the gateway PTY.
319 ///
320 /// # Arguments
321 /// * `vertical` - true for vertical split (side by side), false for horizontal (stacked)
322 ///
323 /// Returns true if the command was sent successfully.
324 pub fn split_pane_via_tmux(&self, vertical: bool) -> bool {
325 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
326 return false;
327 }
328
329 let session = match &self.tmux_state.tmux_session {
330 Some(s) => s,
331 None => return false,
332 };
333
334 // Get the focused pane ID
335 let pane_id = session.focused_pane();
336
337 // Format the split command
338 let cmd = if vertical {
339 match pane_id {
340 Some(id) => format!("split-window -h -t %{}\n", id),
341 None => "split-window -h\n".to_string(),
342 }
343 } else {
344 match pane_id {
345 Some(id) => format!("split-window -v -t %{}\n", id),
346 None => "split-window -v\n".to_string(),
347 }
348 };
349
350 // Write to gateway tab
351 if self.write_to_gateway(&cmd) {
352 crate::debug_info!(
353 "TMUX",
354 "Sent {} split command via gateway",
355 if vertical { "vertical" } else { "horizontal" }
356 );
357 return true;
358 }
359
360 false
361 }
362
363 /// Close the focused pane via tmux control mode.
364 ///
365 /// Writes kill-pane command to the gateway PTY.
366 ///
367 /// Returns true if the command was sent successfully.
368 pub fn close_pane_via_tmux(&self) -> bool {
369 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
370 return false;
371 }
372
373 let session = match &self.tmux_state.tmux_session {
374 Some(s) => s,
375 None => return false,
376 };
377
378 // Get the focused pane ID
379 let pane_id = match session.focused_pane() {
380 Some(id) => id,
381 None => {
382 crate::debug_info!("TMUX", "No focused pane to close");
383 return false;
384 }
385 };
386
387 let cmd = format!("kill-pane -t %{}\n", pane_id);
388
389 // Write to gateway tab
390 if self.write_to_gateway(&cmd) {
391 crate::debug_info!("TMUX", "Sent kill-pane command for pane %{}", pane_id);
392 return true;
393 }
394
395 false
396 }
397
398 /// Sync clipboard content to tmux paste buffer.
399 ///
400 /// Writes set-buffer command to the gateway PTY.
401 ///
402 /// Returns true if the command was sent successfully.
403 pub fn sync_clipboard_to_tmux(&self, content: &str) -> bool {
404 // Check if clipboard sync is enabled
405 if !self.config.load().tmux.tmux_clipboard_sync {
406 return false;
407 }
408
409 if !self.config.load().tmux.tmux_enabled || !self.is_tmux_connected() {
410 return false;
411 }
412
413 // Don't sync empty content
414 if content.is_empty() {
415 return false;
416 }
417
418 // Format the set-buffer command
419 let escaped = content.replace('\'', "'\\''");
420 let cmd = format!("set-buffer '{}'\n", escaped);
421
422 // Write to gateway tab
423 if self.write_to_gateway(&cmd) {
424 crate::debug_trace!(
425 "TMUX",
426 "Synced {} chars to tmux paste buffer",
427 content.len()
428 );
429 return true;
430 }
431
432 false
433 }
434
435 // =========================================================================
436 // Pane Resize Sync
437 // =========================================================================
438
439 /// Sync pane resize to tmux after a divider drag.
440 ///
441 /// When the user resizes panes by dragging a divider in par-term, this
442 /// sends the new pane sizes to tmux so external clients see the same layout.
443 ///
444 /// # Arguments
445 /// * `is_horizontal_divider` - true if dragging a horizontal divider (changes heights),
446 /// false if dragging a vertical divider (changes widths)
447 pub fn sync_pane_resize_to_tmux(&self, is_horizontal_divider: bool) {
448 // Only sync if tmux gateway is active
449 if !self.is_gateway_active() {
450 return;
451 }
452
453 // Get cell dimensions from renderer
454 let (cell_width, cell_height) = match &self.renderer {
455 Some(r) => (r.cell_width(), r.cell_height()),
456 None => return,
457 };
458
459 // Get pane sizes from active tab's pane manager
460 let pane_sizes: Vec<(crate::tmux::TmuxPaneId, usize, usize)> = if let Some(tab) =
461 self.tab_manager.active_tab()
462 && let Some(pm) = tab.pane_manager()
463 {
464 pm.all_panes()
465 .iter()
466 .filter_map(|pane| {
467 // Get the tmux pane ID for this native pane
468 let tmux_pane_id = self.tmux_state.native_pane_to_tmux_pane.get(&pane.id)?;
469 // Calculate size in columns/rows
470 let cols = (pane.bounds.width / cell_width).floor() as usize;
471 let rows = (pane.bounds.height / cell_height).floor() as usize;
472 Some((*tmux_pane_id, cols.max(1), rows.max(1)))
473 })
474 .collect()
475 } else {
476 return;
477 };
478
479 // Send resize commands for each pane, but only for the dimension that changed
480 // Horizontal divider: changes height (rows) - use -y
481 // Vertical divider: changes width (cols) - use -x
482 for (tmux_pane_id, cols, rows) in pane_sizes {
483 let cmd = if is_horizontal_divider {
484 format!("resize-pane -t %{} -y {}\n", tmux_pane_id, rows)
485 } else {
486 format!("resize-pane -t %{} -x {}\n", tmux_pane_id, cols)
487 };
488 if self.write_to_gateway(&cmd) {
489 crate::debug_info!(
490 "TMUX",
491 "Synced pane %{} {} resize to {}",
492 tmux_pane_id,
493 if is_horizontal_divider {
494 "height"
495 } else {
496 "width"
497 },
498 if is_horizontal_divider { rows } else { cols }
499 );
500 }
501 }
502 }
503
504 // =========================================================================
505 // Gateway Tab Visibility
506 // =========================================================================
507
508 /// Hide the gateway tab from the tab bar once tmux windows are active.
509 ///
510 /// Called after the first tmux window tab is created so the control-mode
511 /// connection tab no longer clutters the tab bar. The tab still exists and
512 /// all PTY I/O continues to flow through it; it is simply excluded from the
513 /// visible tab list. The tab is restored when the session ends.
514 ///
515 /// No-op when `config.tmux_hide_gateway_tab` is false.
516 pub(crate) fn hide_gateway_tab(&mut self) {
517 if !self.config.load().tmux.tmux_hide_gateway_tab {
518 return;
519 }
520 if let Some(gateway_tab_id) = self.tmux_state.tmux_gateway_tab_id
521 && let Some(tab) = self.tab_manager.get_tab_mut(gateway_tab_id)
522 && !tab.is_hidden
523 {
524 tab.is_hidden = true;
525 crate::debug_info!(
526 "TMUX",
527 "Gateway tab {} hidden (tmux windows active)",
528 gateway_tab_id
529 );
530 }
531 }
532
533 /// Restore the gateway tab to the tab bar when no tmux windows are active.
534 pub(crate) fn show_gateway_tab(&mut self) {
535 if let Some(gateway_tab_id) = self.tmux_state.tmux_gateway_tab_id
536 && let Some(tab) = self.tab_manager.get_tab_mut(gateway_tab_id)
537 && tab.is_hidden
538 {
539 tab.is_hidden = false;
540 crate::debug_info!("TMUX", "Gateway tab {} restored to tab bar", gateway_tab_id);
541 }
542 }
543
544 // =========================================================================
545 // Prefix Key Handling
546 // =========================================================================
547}