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