focal 0.2.8

Terminal focus library - focus terminal windows and multiplexer panes
Documentation
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
//! Terminal detection from TTY device.
//!
//! Provides cross-platform terminal detection by examining which process
//! owns a TTY device.
//!
//! # Detection Strategy
//!
//! GUI terminal emulators (iTerm2, Ghostty, etc.) don't have a controlling
//! terminal - they CREATE PTYs for their child processes. So we can't find
//! them directly by their TTY.
//!
//! Instead, we:
//! 1. Find a process on the TTY (e.g., the shell)
//! 2. Walk UP its parent chain to find the terminal emulator ancestor

/// Maximum depth to walk up process ancestry when searching for a terminal.
/// 50 levels is more than sufficient for any real process tree.
const MAX_ANCESTRY_DEPTH: usize = 50;

/// A detected terminal emulator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Terminal {
    /// The kind of terminal (for dispatch to specific handlers).
    pub kind: TerminalKind,
    /// The process name (for generic activation).
    pub process_name: String,
}

/// Known terminal emulator types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TerminalKind {
    // macOS
    /// iTerm2 terminal emulator
    ITerm2,
    /// macOS Terminal.app
    TerminalApp,

    // Cross-platform
    /// WezTerm terminal emulator
    WezTerm,
    /// Kitty terminal emulator
    Kitty,
    /// Ghostty terminal emulator
    Ghostty,
    /// Alacritty terminal emulator
    Alacritty,
    /// Warp terminal emulator (modern Rust-based terminal with AI)
    Warp,
    /// Tabby terminal emulator (formerly Terminus, cross-platform)
    Tabby,
    /// Wave terminal emulator (open-source, AI-native)
    Wave,

    // Linux
    /// GNOME Terminal
    GnomeTerminal,
    /// KDE Konsole
    Konsole,
    /// Foot terminal (Wayland)
    Foot,
    /// Terminator terminal
    Terminator,
    /// Hyper terminal
    Hyper,
    /// Rio terminal
    Rio,

    // IDEs with integrated terminals
    /// Visual Studio Code (Electron-based IDE)
    VSCode,
    /// Cursor IDE (VS Code fork)
    Cursor,

    /// Unknown terminal (detected but no specific handler)
    Unknown,
}

impl TerminalKind {
    /// Get the app name to use for window activation.
    #[must_use]
    pub fn app_name(&self) -> &'static str {
        match self {
            Self::ITerm2 => "iTerm2",
            Self::TerminalApp => "Terminal",
            Self::WezTerm => "WezTerm",
            Self::Kitty => "kitty",
            Self::Ghostty => "Ghostty",
            Self::Alacritty => "Alacritty",
            Self::Warp => "Warp",
            Self::Tabby => "Tabby",
            Self::Wave => "Wave",
            Self::GnomeTerminal => "gnome-terminal",
            Self::Konsole => "konsole",
            Self::Foot => "foot",
            Self::Terminator => "terminator",
            Self::Hyper => "Hyper",
            Self::Rio => "Rio",
            Self::VSCode => "Code",
            Self::Cursor => "Cursor",
            Self::Unknown => "unknown",
        }
    }
}

/// Detect the terminal emulator that owns a TTY device.
///
/// This function finds a process on the TTY and walks UP its parent chain
/// to find the terminal emulator. This is necessary because GUI terminal
/// emulators don't have a controlling terminal themselves - they create
/// PTYs for their children.
///
/// For unknown terminals (not in the built-in list), returns a `Terminal`
/// with `kind: TerminalKind::Unknown` and the actual process name. This
/// enables generic window activation for any terminal emulator.
///
/// # Arguments
/// * `tty_device` - TTY device name (e.g., "ttys003" or "/dev/ttys003")
///
/// # Returns
/// The detected terminal, or `None` if no terminal could be found in the
/// process ancestry (e.g., invalid TTY or no GUI process in tree).
#[must_use]
pub fn terminal(tty_device: &str) -> Option<Terminal> {
    let tty_path = if tty_device.starts_with("/dev/") {
        tty_device.to_string()
    } else {
        format!("/dev/{tty_device}")
    };

    // Get a process on the TTY to use as starting point for ancestry search
    let start_pid = get_process_on_tty(&tty_path)?;

    // Walk up the parent chain looking for a terminal emulator
    terminal_from_ancestry(start_pid)
}

/// Detect terminal from a specific process's ancestry.
///
/// Walks up the parent chain looking for a terminal emulator.
/// This is useful when you have a PID (e.g., from `tmux list-clients`)
/// and want to find which terminal it's running in.
///
/// For unknown terminals (not in the built-in list), returns a `Terminal`
/// with `kind: TerminalKind::Unknown` and the actual process name. This
/// enables generic window activation for any terminal emulator.
///
/// # Arguments
/// * `pid` - Process ID to start from
///
/// # Returns
/// The detected terminal, or `None` if no terminal could be found in the
/// process ancestry (e.g., invalid PID or no GUI process in tree).
#[must_use]
pub fn terminal_from_pid(pid: i32) -> Option<Terminal> {
    terminal_from_ancestry(pid)
}

/// Get a process PID that's on the given TTY.
///
/// Scans all processes using fast syscalls (~1-5µs per process) rather than
/// spawning `ps`. Returns the first process found on the TTY.
fn get_process_on_tty(tty_path: &str) -> Option<i32> {
    // Normalize TTY name (remove /dev/ prefix if present)
    let tty_name = tty_path.strip_prefix("/dev/").unwrap_or(tty_path);

    // Scan all processes looking for one on this TTY
    prock::list_all_pids()
        .into_iter()
        .find(|&pid| prock::get_tty(pid).is_some_and(|tty| tty == tty_name))
}

/// Walk up the process tree from the given PID to find a terminal emulator.
///
/// Uses prock's parent map and get_process_path for pure syscall-based
/// detection with no shell spawning.
///
/// If no known terminal is found, returns the topmost GUI process (the one
/// whose parent is launchd/init) as `TerminalKind::Unknown`. This enables
/// generic window activation for any terminal emulator.
fn terminal_from_ancestry(start_pid: i32) -> Option<Terminal> {
    // Build parent map using prock (fast syscalls, no shell spawning)
    let parent_map = prock::build_parent_map();

    // Walk up the parent chain checking each process
    let mut current_pid = start_pid;

    // Track the last viable candidate for unknown terminal fallback.
    // This will be the topmost process before launchd/init.
    let mut last_candidate: Option<String> = None;

    for _ in 0..MAX_ANCESTRY_DEPTH {
        // Get the executable path for this process (direct syscall, no shell)
        if let Some(path) = prock::get_process_path(current_pid) {
            // Extract just the executable name from the path
            let exec_name = path
                .rsplit('/')
                .next()
                .unwrap_or(&path)
                .trim_end_matches(".app");

            // Check if this is a known terminal
            if let Some((kind, canonical_name)) = map_process_to_terminal(exec_name) {
                return Some(Terminal {
                    kind,
                    process_name: canonical_name.to_string(),
                });
            }

            // Also check the full path for patterns like iTerm2's helper
            if path.contains("iTerm") {
                return Some(Terminal {
                    kind: TerminalKind::ITerm2,
                    process_name: "iTerm2".to_string(),
                });
            }

            // Track this as a potential unknown terminal candidate,
            // but skip common non-terminal processes
            if !is_non_terminal_process(exec_name) {
                last_candidate = Some(exec_name.to_string());
            }
        }

        // Move to parent
        match parent_map.get(&current_pid) {
            Some(&ppid) if ppid > 1 => current_pid = ppid,
            _ => break, // Reached init/launchd or process not found
        }
    }

    // If we didn't find a known terminal but have a candidate,
    // return it as Unknown for generic activation
    last_candidate.map(|name| Terminal {
        kind: TerminalKind::Unknown,
        process_name: name,
    })
}

/// Check if a process name is a known non-terminal process that should be
/// skipped when looking for unknown terminal candidates.
fn is_non_terminal_process(name: &str) -> bool {
    matches!(
        name,
        // Shells
        "bash"
            | "zsh"
            | "fish"
            | "sh"
            | "dash"
            | "ksh"
            | "tcsh"
            | "csh"
            | "nu"
            | "nushell"
            | "pwsh"
            | "powershell"
            | "elvish"
            | "ion"
            | "xonsh"
            // Common utilities that might be in the process tree
            | "login"
            | "sshd"
            | "ssh"
            | "sudo"
            | "su"
            | "env"
            | "direnv"
            // Terminal multiplexers (handled separately, but exclude for defense-in-depth)
            | "tmux"
            | "screen"
            | "zellij"
            // Process managers / launchers
            | "launchd"
            | "init"
            | "systemd"
            | "xinit"
            | "startx"
    )
}

/// Map a process name to a terminal kind and canonical app name.
fn map_process_to_terminal(proc_name: &str) -> Option<(TerminalKind, &'static str)> {
    // Match against known terminal process names
    match proc_name {
        // macOS terminals
        "iTerm2" | "iTerm.app" | "iterm2" => Some((TerminalKind::ITerm2, "iTerm2")),
        "Terminal" | "Terminal.app" | "Apple_Terminal" => {
            Some((TerminalKind::TerminalApp, "Terminal"))
        }

        // Cross-platform terminals
        "wezterm" | "wezterm-gui" | "WezTerm" => Some((TerminalKind::WezTerm, "WezTerm")),
        "kitty" => Some((TerminalKind::Kitty, "kitty")),
        "ghostty" | "Ghostty" => Some((TerminalKind::Ghostty, "Ghostty")),
        "alacritty" | "Alacritty" => Some((TerminalKind::Alacritty, "Alacritty")),
        "Warp" | "warp" => Some((TerminalKind::Warp, "Warp")),
        "Tabby" | "tabby" => Some((TerminalKind::Tabby, "Tabby")),
        "Wave" | "waveterm" | "wave" => Some((TerminalKind::Wave, "Wave")),

        // Linux terminals
        "gnome-terminal" | "gnome-terminal-" | "gnome-terminal-server" => {
            Some((TerminalKind::GnomeTerminal, "gnome-terminal"))
        }
        "konsole" => Some((TerminalKind::Konsole, "konsole")),
        "foot" => Some((TerminalKind::Foot, "foot")),
        "terminator" => Some((TerminalKind::Terminator, "terminator")),
        "Hyper" | "hyper" => Some((TerminalKind::Hyper, "Hyper")),
        "rio" | "Rio" => Some((TerminalKind::Rio, "Rio")),

        // IDEs with integrated terminals
        "Code" | "code" | "Code - Insiders" | "code-insiders" => {
            Some((TerminalKind::VSCode, "Code"))
        }
        "Cursor" | "cursor" => Some((TerminalKind::Cursor, "Cursor")),

        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_map_process_to_terminal_iterm2() {
        assert_eq!(
            map_process_to_terminal("iTerm2"),
            Some((TerminalKind::ITerm2, "iTerm2"))
        );
        assert_eq!(
            map_process_to_terminal("iterm2"),
            Some((TerminalKind::ITerm2, "iTerm2"))
        );
    }

    #[test]
    fn test_map_process_to_terminal_wezterm() {
        assert_eq!(
            map_process_to_terminal("wezterm-gui"),
            Some((TerminalKind::WezTerm, "WezTerm"))
        );
    }

    #[test]
    fn test_map_process_to_terminal_unknown() {
        assert_eq!(map_process_to_terminal("unknown-terminal"), None);
    }

    #[test]
    fn test_terminal_kind_app_name() {
        assert_eq!(TerminalKind::ITerm2.app_name(), "iTerm2");
        assert_eq!(TerminalKind::Kitty.app_name(), "kitty");
        assert_eq!(TerminalKind::Warp.app_name(), "Warp");
        assert_eq!(TerminalKind::Tabby.app_name(), "Tabby");
        assert_eq!(TerminalKind::Wave.app_name(), "Wave");
    }

    #[test]
    fn test_map_process_to_terminal_warp() {
        assert_eq!(
            map_process_to_terminal("Warp"),
            Some((TerminalKind::Warp, "Warp"))
        );
        assert_eq!(
            map_process_to_terminal("warp"),
            Some((TerminalKind::Warp, "Warp"))
        );
    }

    #[test]
    fn test_map_process_to_terminal_tabby() {
        assert_eq!(
            map_process_to_terminal("Tabby"),
            Some((TerminalKind::Tabby, "Tabby"))
        );
        assert_eq!(
            map_process_to_terminal("tabby"),
            Some((TerminalKind::Tabby, "Tabby"))
        );
    }

    #[test]
    fn test_map_process_to_terminal_wave() {
        assert_eq!(
            map_process_to_terminal("Wave"),
            Some((TerminalKind::Wave, "Wave"))
        );
        assert_eq!(
            map_process_to_terminal("waveterm"),
            Some((TerminalKind::Wave, "Wave"))
        );
        assert_eq!(
            map_process_to_terminal("wave"),
            Some((TerminalKind::Wave, "Wave"))
        );
    }

    #[test]
    fn test_detect_terminal_invalid_tty() {
        // Should return None for non-existent TTY
        assert!(terminal("ttys999999").is_none());
    }

    #[test]
    fn test_terminal_from_pid_invalid() {
        // Should return None for non-existent PID
        assert!(terminal_from_pid(999_999_999).is_none());
    }

    #[test]
    fn test_terminal_from_pid_current_process() {
        // Walking up from current process should either find a terminal or reach init
        // This test verifies the function doesn't panic and handles real process trees
        let pid = std::process::id() as i32;
        let result = terminal_from_pid(pid);
        // Result may be Some (if run in a terminal) or None (if run in CI/daemon)
        // Either is valid - we just verify it doesn't crash
        let _ = result;
    }

    #[test]
    fn test_map_process_to_terminal_vscode() {
        assert_eq!(
            map_process_to_terminal("Code"),
            Some((TerminalKind::VSCode, "Code"))
        );
        assert_eq!(
            map_process_to_terminal("code"),
            Some((TerminalKind::VSCode, "Code"))
        );
        assert_eq!(
            map_process_to_terminal("Code - Insiders"),
            Some((TerminalKind::VSCode, "Code"))
        );
    }

    #[test]
    fn test_map_process_to_terminal_cursor() {
        assert_eq!(
            map_process_to_terminal("Cursor"),
            Some((TerminalKind::Cursor, "Cursor"))
        );
        assert_eq!(
            map_process_to_terminal("cursor"),
            Some((TerminalKind::Cursor, "Cursor"))
        );
    }

    #[test]
    fn test_terminal_kind_app_name_ides() {
        assert_eq!(TerminalKind::VSCode.app_name(), "Code");
        assert_eq!(TerminalKind::Cursor.app_name(), "Cursor");
    }

    #[test]
    fn test_is_non_terminal_process_shells() {
        assert!(is_non_terminal_process("bash"));
        assert!(is_non_terminal_process("zsh"));
        assert!(is_non_terminal_process("fish"));
        assert!(is_non_terminal_process("sh"));
        assert!(is_non_terminal_process("nu"));
        assert!(is_non_terminal_process("pwsh"));
        assert!(is_non_terminal_process("elvish"));
        assert!(is_non_terminal_process("ion"));
        assert!(is_non_terminal_process("xonsh"));
    }

    #[test]
    fn test_is_non_terminal_process_utilities() {
        assert!(is_non_terminal_process("login"));
        assert!(is_non_terminal_process("sshd"));
        assert!(is_non_terminal_process("sudo"));
        assert!(is_non_terminal_process("env"));
        assert!(is_non_terminal_process("direnv"));
    }

    #[test]
    fn test_is_non_terminal_process_multiplexers() {
        assert!(is_non_terminal_process("tmux"));
        assert!(is_non_terminal_process("screen"));
        assert!(is_non_terminal_process("zellij"));
    }

    #[test]
    fn test_is_non_terminal_process_launchers() {
        assert!(is_non_terminal_process("launchd"));
        assert!(is_non_terminal_process("init"));
        assert!(is_non_terminal_process("systemd"));
    }

    #[test]
    fn test_is_non_terminal_process_terminals_are_not_excluded() {
        // Terminal emulators should NOT be excluded
        assert!(!is_non_terminal_process("alacritty"));
        assert!(!is_non_terminal_process("kitty"));
        assert!(!is_non_terminal_process("wezterm"));
        assert!(!is_non_terminal_process("iTerm2"));
        assert!(!is_non_terminal_process("Ghostty"));
        // Unknown terminals should also not be excluded
        assert!(!is_non_terminal_process("my-cool-terminal"));
        assert!(!is_non_terminal_process("xterm"));
        assert!(!is_non_terminal_process("urxvt"));
    }
}