psmux 3.3.5

Terminal multiplexer for Windows - tmux alternative for PowerShell and Windows Terminal
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
use std::io;

use crate::format::expand_format_for_window;
use crate::types::{AppState, Node, Window};
use crate::util::WinInfo;

/// Collect all leaf pane paths in tree order (for next/prev pane cycling).
pub(crate) fn collect_pane_paths_server(
    node: &Node,
    path: &mut Vec<usize>,
    panes: &mut Vec<Vec<usize>>,
) {
    match node {
        Node::Leaf(_) => {
            panes.push(path.clone());
        }
        Node::Split { children, .. } => {
            for (i, c) in children.iter().enumerate() {
                path.push(i);
                collect_pane_paths_server(c, path, panes);
                path.pop();
            }
        }
    }
}

/// Serialize key_tables into a compact JSON array for syncing to the client.
/// Format: [{"t":"prefix","k":"x","c":"split-window -v","r":false}, ...]
pub(crate) fn serialize_bindings_json(app: &AppState) -> String {
    use crate::commands::format_action;
    use crate::config::format_key_binding;
    let mut out = String::from("[");
    let mut first = true;
    for (table_name, binds) in &app.key_tables {
        for bind in binds {
            if !first {
                out.push(',');
            }
            first = false;
            let key_str = json_escape_string(&format_key_binding(&bind.key));
            let cmd_str = json_escape_string(&format_action(&bind.action));
            let tbl_str = json_escape_string(table_name);
            out.push_str(&format!(
                "{{\"t\":\"{}\",\"k\":\"{}\",\"c\":\"{}\",\"r\":{}}}",
                tbl_str, key_str, cmd_str, bind.repeat
            ));
        }
    }
    out.push(']');
    out
}

/// Escape a string for embedding inside a JSON double-quoted value.
/// Handles backslashes, double-quotes, and control characters.
pub(crate) fn json_escape_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 8);
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out
}

/// Build windows JSON with pre-expanded tab_text for each window.
/// The tab_text is the fully expanded window-status-format / window-status-current-format.
pub(crate) fn list_windows_json_with_tabs(app: &AppState) -> io::Result<String> {
    let mut v: Vec<WinInfo> = Vec::new();
    for (i, w) in app.windows.iter().enumerate() {
        let is_active = i == app.active_idx;
        let fmt = if is_active {
            &app.window_status_current_format
        } else {
            &app.window_status_format
        };
        let tab = expand_format_for_window(fmt, app, i);
        v.push(WinInfo {
            id: w.id,
            name: w.name.clone(),
            active: is_active,
            activity: w.activity_flag,
            tab_text: tab,
        });
    }
    serde_json::to_string(&v)
        .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("json error: {e}")))
}

/// Sum data_version counters across all panes in the active window.
pub(crate) fn combined_data_version(app: &AppState) -> u64 {
    let mut v = 0u64;
    fn walk(node: &Node, v: &mut u64) {
        match node {
            Node::Leaf(p) => {
                *v = v.wrapping_add(p.data_version.load(std::sync::atomic::Ordering::Acquire));
            }
            Node::Split { children, .. } => {
                for c in children {
                    walk(c, v);
                }
            }
        }
    }
    if let Some(win) = app.windows.get(app.active_idx) {
        walk(&win.root, &mut v);
    }
    // Include mode discriminant so overlay state changes (PopupMode, MenuMode,
    // ConfirmMode, PaneChooser, ClockMode) always invalidate the cached version.
    // Without this, the NC optimization could return stale frames that lack
    // overlay fields, causing overlays to not render on the client.
    let mode_tag: u64 = match &app.mode {
        crate::types::Mode::Passthrough => 0,
        crate::types::Mode::Prefix { .. } => 1,
        crate::types::Mode::CopyMode => 2,
        crate::types::Mode::CopySearch { .. } => 3,
        crate::types::Mode::ClockMode => 4,
        crate::types::Mode::PopupMode { .. } => 5,
        crate::types::Mode::ConfirmMode { .. } => 6,
        crate::types::Mode::MenuMode { .. } => 7,
        crate::types::Mode::PaneChooser { .. } => 8,
        crate::types::Mode::BufferChooser { .. } => 9,
        _ => 10,
    };
    v = v.wrapping_add(mode_tag.wrapping_mul(0x1_0000_0000));
    // Include zoom state so toggling zoom always invalidates the cached
    // frame, even when no PTY data has changed (issue #125).
    // Check per-window zoom state — each window tracks zoom independently.
    for (wi, w) in app.windows.iter().enumerate() {
        if w.zoom_saved.is_some() {
            v = v.wrapping_add(0x8000_0000_0000_u64.wrapping_add(wi as u64));
        }
    }
    // Include client prefix state so the status bar re-renders
    // immediately when the prefix key is pressed/released (issue #126).
    if app.client_prefix_active {
        v = v.wrapping_add(0x4000_0000_0000);
    }
    // Include copy mode cursor position and scroll offset so cursor
    // movement and scrolling in copy mode always invalidate the cached
    // frame.  Without this, keyboard navigation in copy mode produces
    // no visible change because the server returns NC (no change).
    if let Some((r, c)) = app.copy_pos {
        v = v.wrapping_add((r as u64).wrapping_mul(0x10001).wrapping_add(c as u64));
    }
    v = v.wrapping_add((app.copy_scroll_offset as u64).wrapping_mul(0x20003));
    if let Some((ar, ac)) = app.copy_anchor {
        v = v.wrapping_add((ar as u64).wrapping_mul(0x30007).wrapping_add(ac as u64));
    }
    v
}

/// Per-window data version for activity detection
pub(crate) fn window_data_version(win: &Window) -> u64 {
    let mut v = 0u64;
    fn walk(node: &Node, v: &mut u64) {
        match node {
            Node::Leaf(p) => {
                *v = v.wrapping_add(p.data_version.load(std::sync::atomic::Ordering::Acquire));
            }
            Node::Split { children, .. } => {
                for c in children {
                    walk(c, v);
                }
            }
        }
    }
    walk(&win.root, &mut v);
    v
}

/// Check non-active windows for output activity and set their activity_flag.
/// Also checks bell_pending on all panes and sets window bell_flag,
/// and checks monitor-silence timeout to set silence_flag.
pub(crate) fn check_window_activity(app: &mut AppState) -> Vec<&'static str> {
    let active = app.active_idx;
    let monitor_silence_secs = app.monitor_silence;
    let bell_action = app.bell_action.clone();
    let mut triggered_hooks: Vec<&'static str> = Vec::new();
    let mut forward_bell = false;

    for (i, win) in app.windows.iter_mut().enumerate() {
        // ── Bell detection: check all panes for pending bells ──
        let has_bell = check_pane_bells(&win.root);
        if has_bell && i != active {
            // Apply bell-action: "any" = always, "current" = only active (skip),
            // "other" = only non-active (this path), "none" = never
            match bell_action.as_str() {
                "any" | "other" => {
                    if !win.bell_flag {
                        win.bell_flag = true;
                        triggered_hooks.push("alert-bell");
                    }
                    forward_bell = true;
                }
                _ => {} // "none" or "current" — don't flag non-active windows
            }
        } else if has_bell && i == active {
            match bell_action.as_str() {
                "any" | "current" => {
                    if !win.bell_flag {
                        win.bell_flag = true;
                        triggered_hooks.push("alert-bell");
                    }
                    forward_bell = true;
                }
                _ => {}
            }
        }

        // ── Activity detection ──
        if i == active {
            // Active window: clear activity/bell/silence flags, update version
            win.activity_flag = false;
            win.bell_flag = false;
            win.silence_flag = false;
            win.last_seen_version = window_data_version(win);
            // Update last_output_time for active window too
            let cur = window_data_version(win);
            if cur != win.last_seen_version {
                win.last_output_time = std::time::Instant::now();
            }
            continue;
        }
        let cur = window_data_version(win);
        if cur != win.last_seen_version {
            if app.monitor_activity && !win.activity_flag {
                win.activity_flag = true;
                triggered_hooks.push("alert-activity");
            }
            win.last_output_time = std::time::Instant::now();
            win.silence_flag = false; // Reset silence on new output
            win.last_seen_version = cur;
        }

        // ── Silence detection ──
        if monitor_silence_secs > 0 {
            let elapsed = win.last_output_time.elapsed().as_secs();
            if elapsed >= monitor_silence_secs && !win.silence_flag {
                win.silence_flag = true;
                triggered_hooks.push("alert-silence");
            }
        }
    }
    if forward_bell {
        app.bell_forward = true;
    }
    triggered_hooks
}

/// Propagate OSC 0/2 titles from the vt100 parser to pane.title for all windows.
/// tmux updates pane_title immediately when the child sends an OSC 0 or OSC 2
/// escape sequence, gated by the allow-set-title option. In psmux, the vt100
/// parser stores the title but we must explicitly copy it to pane.title.
/// Returns true if any pane title changed (i.e. state is dirty).
pub(crate) fn propagate_osc_titles(app: &mut AppState) -> bool {
    let allow_set_title = app.allow_set_title;
    if !allow_set_title {
        return false;
    }
    let mut dirty = false;
    for win in app.windows.iter_mut() {
        propagate_osc_titles_in_tree(&mut win.root, &mut dirty);
    }
    dirty
}

/// Read the active pane's most recent OSC 9;4 progress indicator state.
/// Returns `Some((state, value))` when a progress sequence has been received,
/// where state ∈ 0..=4 (0=hide, 1=default, 2=error, 3=indeterminate, 4=warning)
/// and value ∈ 0..=100. Used by the dump-state builder so the client can
/// re-emit OSC 9;4 to the host terminal (issue #269).
pub(crate) fn active_pane_progress(app: &AppState) -> Option<(u8, u8)> {
    let win = app.windows.get(app.active_idx)?;
    let pane = crate::tree::active_pane(&win.root, &win.active_path)?;
    if pane.dead {
        return None;
    }
    let parser = pane.term.lock().ok()?;
    parser.screen().progress()
}

/// Drain a pending OSC 52 clipboard payload from any pane in the tree.
/// Returns the first `(selector, base64_data)` found and clears it on the
/// source pane.  Lets a child process inside any pane (e.g. Claude Code's
/// `/copy`) ask the host terminal to copy text — the dump-state builder
/// stages the result onto `App.clipboard_osc52`, the client re-emits OSC
/// 52 on its own stdout, and the host terminal performs the copy.
pub(crate) fn take_pane_clipboard(app: &AppState) -> Option<(Vec<u8>, Vec<u8>)> {
    for win in &app.windows {
        if let Some(payload) = drain_clipboard_in_node(&win.root) {
            return Some(payload);
        }
    }
    None
}

fn drain_clipboard_in_node(node: &Node) -> Option<(Vec<u8>, Vec<u8>)> {
    match node {
        Node::Leaf(p) => {
            if p.dead {
                return None;
            }
            let mut parser = p.term.lock().ok()?;
            parser.screen_mut().take_clipboard()
        }
        Node::Split { children, .. } => {
            for c in children {
                if let Some(r) = drain_clipboard_in_node(c) {
                    return Some(r);
                }
            }
            None
        }
    }
}

fn propagate_osc_titles_in_tree(node: &mut Node, dirty: &mut bool) {
    match node {
        Node::Leaf(p) => {
            if p.dead || p.title_locked {
                return;
            }
            if let Ok(parser) = p.term.lock() {
                let osc = parser.screen().title();
                if !osc.is_empty() {
                    let osc_owned = osc.to_string();
                    drop(parser);
                    if p.title != osc_owned {
                        p.title = osc_owned;
                        *dirty = true;
                    }
                }
            }
        }
        Node::Split { children, .. } => {
            for c in children {
                propagate_osc_titles_in_tree(c, dirty);
            }
        }
    }
}

/// Walk a pane tree and check/consume bell_pending flags.
/// Returns true if any pane had a pending bell.
fn check_pane_bells(node: &Node) -> bool {
    match node {
        Node::Leaf(p) => p
            .bell_pending
            .swap(false, std::sync::atomic::Ordering::AcqRel),
        Node::Split { children, .. } => {
            let mut any = false;
            for c in children {
                if check_pane_bells(c) {
                    any = true;
                }
            }
            any
        }
    }
}

/// Injects ESC[row;colR into any pane whose reader thread detected ESC[6n.
/// pwsh re-issues the CPR query after lock/unlock; without this response it
/// blocks indefinitely since the preemptive write at spawn time is long gone.
pub(crate) fn drain_cpr_pending(node: &mut crate::types::Node) {
    use std::io::Write as _;
    match node {
        crate::types::Node::Leaf(p) => {
            if p.cpr_pending
                .swap(false, std::sync::atomic::Ordering::AcqRel)
            {
                let (r, c) = p
                    .term
                    .lock()
                    .map(|g| g.screen().cursor_position())
                    .unwrap_or((0, 0));
                let response = format!("\x1b[{};{}R", r + 1, c + 1);
                let _ = p.writer.write_all(response.as_bytes());
                let _ = p.writer.flush();
            }
        }
        crate::types::Node::Split { children, .. } => {
            for c in children {
                drain_cpr_pending(c);
            }
        }
    }
}

/// Complete list of supported tmux-compatible commands (for list-commands).
pub(crate) const TMUX_COMMANDS: &[&str] = &[
    "attach-session (attach)",
    "bind-key (bind)",
    "break-pane (breakp)",
    "capture-pane (capturep)",
    "choose-buffer (chooseb)",
    "choose-client",
    "choose-session",
    "choose-tree",
    "choose-window",
    "clear-history (clearhist)",
    "clear-prompt-history (clearphist)",
    "clock-mode",
    "command-prompt",
    "confirm-before (confirm)",
    "copy-mode",
    "customize-mode",
    "delete-buffer (deleteb)",
    "detach-client (detach)",
    "display-menu (menu)",
    "display-message (display)",
    "display-panes (displayp)",
    "display-popup (popup)",
    "find-window (findw)",
    "has-session (has)",
    "if-shell (if)",
    "join-pane (joinp)",
    "kill-pane (killp)",
    "kill-server",
    "kill-session",
    "kill-window (killw)",
    "last-pane (lastp)",
    "last-window (last)",
    "link-window (linkw)",
    "list-buffers (lsb)",
    "list-clients (lsc)",
    "list-commands (lscm)",
    "list-keys (lsk)",
    "list-panes (lsp)",
    "list-sessions (ls)",
    "list-windows (lsw)",
    "load-buffer (loadb)",
    "lock-client (lockc)",
    "lock-server (lock)",
    "lock-session (locks)",
    "move-pane (movep)",
    "move-window (movew)",
    "new-session (new)",
    "new-window (neww)",
    "next-layout (nextl)",
    "next-window (next)",
    "paste-buffer (pasteb)",
    "pipe-pane (pipep)",
    "previous-layout (prevl)",
    "previous-window (prev)",
    "refresh-client (refresh)",
    "rename-session (rename)",
    "rename-window (renamew)",
    "resize-pane (resizep)",
    "resize-window (resizew)",
    "respawn-pane (respawnp)",
    "respawn-window (respawnw)",
    "rotate-window (rotatew)",
    "run-shell (run)",
    "save-buffer (saveb)",
    "select-layout (selectl)",
    "select-pane (selectp)",
    "select-window (selectw)",
    "send-keys (send)",
    "send-prefix",
    "server-info (info)",
    "set-buffer (setb)",
    "set-environment (setenv)",
    "set-hook",
    "set-option (set)",
    "set-window-option (setw)",
    "show-buffer (showb)",
    "show-environment (showenv)",
    "show-hooks",
    "show-messages (showmsgs)",
    "show-options (show)",
    "show-prompt-history (showphist)",
    "show-window-options (showw)",
    "source-file (source)",
    "split-window (splitw)",
    "start-server (start)",
    "suspend-client (suspendc)",
    "swap-pane (swapp)",
    "swap-window (swapw)",
    "switch-client (switchc)",
    "unbind-key (unbind)",
    "unlink-window (unlinkw)",
    "wait-for (wait)",
];