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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Kitty-specific focus handler.
//!
//! Uses the `kitty @` remote control to find and focus the specific window
//! matching a target process. Supports both TTY-based and PID-based matching.
//!
//! # Socket Discovery
//!
//! The handler uses the `KITTY_LISTEN_ON` environment variable to find the
//! Kitty remote control socket. This is automatically set for processes
//! running inside Kitty when `listen_on` is configured.
//!
//! # Configuration Requirements
//!
//! Users must add to their `kitty.conf`:
//! ```text
//! allow_remote_control socket-only
//! listen_on unix:/tmp/kitty-{kitty_pid}.sock
//! ```

use crate::FocusMode;
use crate::activate;
use crate::util::DEFAULT_TIMEOUT;
use std::collections::HashMap;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::thread;

/// Information about a matched Kitty window.
#[derive(Debug, Clone)]
struct WindowMatch {
    tab_id: i64,
    window_id: i64,
}

/// Try to focus the Kitty window containing the given process.
///
/// Uses PID ancestry matching for reliability: checks if the target PID
/// is a descendant of any foreground process in Kitty windows.
///
/// # Focus Modes
///
/// - **SingleWindow**: Uses System Events AXRaise to bring only the
///   specific window to the front. Requires accessibility permissions.
///
/// - **ActivateApp**: Uses traditional app activation which brings ALL
///   Kitty windows to the front. No special permissions required.
///
/// # Arguments
/// * `target_pid` - Process ID to find and focus
/// * `_tty_device` - TTY device name (unused, kept for interface compatibility)
/// * `mode` - The focus mode to use
///
/// # Returns
/// - `true` if focusing succeeded (including fallback to generic activation
///   when remote control is unavailable)
/// - `false` if the target window was not found
pub fn try_focus_by_pid(target_pid: i32, _tty_device: &str, mode: FocusMode) -> bool {
    // Get socket address from environment
    let socket = get_socket();

    // Query kitty for window list
    let Some(os_windows) = query_kitty_ls(socket.as_deref()) else {
        // Remote control not available - fall back to generic activation with warning
        log_remote_control_warning();
        activate::window("kitty");
        return true;
    };

    // Build parent map for ancestry checks
    let parent_map = prock::build_parent_map();

    // Find window containing target process
    let Some(window_match) = find_window_by_pid(&os_windows, target_pid, &parent_map) else {
        return false;
    };

    // Focus the tab and window
    if !focus_tab_and_window(socket.as_deref(), &window_match) {
        return false;
    }

    // Bring Kitty to front using the appropriate mode
    bring_to_front(mode)
}

/// Try to focus the Kitty window with matching TTY.
///
/// This is the legacy interface that uses TTY-based matching.
/// Prefer `try_focus_by_pid` when the target PID is available.
///
/// # Arguments
/// * `tty_device` - TTY device name (e.g., "ttys003")
/// * `mode` - The focus mode to use
///
/// # Returns
/// - `true` if focusing succeeded (including fallback to generic activation
///   when remote control is unavailable)
/// - `false` if the target window was not found
pub fn try_focus(tty_device: &str, mode: FocusMode) -> bool {
    // Get socket address from environment
    let socket = get_socket();

    // Query kitty for window list
    let Some(os_windows) = query_kitty_ls(socket.as_deref()) else {
        // Remote control not available - fall back to generic activation with warning
        log_remote_control_warning();
        activate::window("kitty");
        return true;
    };

    // Find window by TTY (legacy matching)
    let Some(window_match) = find_window_by_tty(&os_windows, tty_device) else {
        return false;
    };

    // Focus the tab and window
    if !focus_tab_and_window(socket.as_deref(), &window_match) {
        return false;
    }

    // Bring Kitty to front using the appropriate mode
    bring_to_front(mode)
}

/// Get the Kitty socket address from environment.
///
/// Returns the socket path from `KITTY_LISTEN_ON` if set.
fn get_socket() -> Option<String> {
    std::env::var("KITTY_LISTEN_ON").ok()
}

/// Flag to ensure we only warn once per process about remote control.
static WARNED_REMOTE_CONTROL: AtomicBool = AtomicBool::new(false);

/// Log a warning when remote control is not available.
/// Only warns once per process to avoid spamming stderr.
#[expect(clippy::print_stderr, reason = "intentional warning message to stderr")]
fn log_remote_control_warning() {
    // Only warn once per process
    if WARNED_REMOTE_CONTROL.swap(true, Ordering::Relaxed) {
        return;
    }

    eprintln!(
        "focal: Kitty remote control is not available. Falling back to app activation.\n\
         For precise tab/pane focus, add to kitty.conf:\n  \
         allow_remote_control socket-only\n  \
         listen_on unix:/tmp/kitty-{{kitty_pid}}.sock"
    );
}

/// Query `kitty @ ls` with timeout protection.
///
/// Returns the parsed JSON array of OS windows, or None if the command fails.
fn query_kitty_ls(socket: Option<&str>) -> Option<Vec<serde_json::Value>> {
    let output = run_kitty_command_with_timeout(socket, &["ls"])?;

    if !output.status.success() {
        return None;
    }

    serde_json::from_slice(&output.stdout).ok()
}

/// Run a kitty @ command with timeout protection.
///
/// Spawns a thread to run the command and waits with a timeout to prevent
/// indefinite blocking if Kitty is unresponsive.
fn run_kitty_command_with_timeout(socket: Option<&str>, args: &[&str]) -> Option<Output> {
    let socket_owned = socket.map(String::from);
    let args_owned: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();

    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let mut cmd = Command::new("kitty");
        cmd.arg("@");

        // Add --to socket if we have one
        if let Some(ref socket) = socket_owned {
            cmd.args(["--to", socket]);
        }

        cmd.args(&args_owned);

        let result = cmd.output();
        let _ = tx.send(result);
    });

    match rx.recv_timeout(DEFAULT_TIMEOUT) {
        Ok(Ok(output)) => Some(output),
        _ => None,
    }
}

/// Run a kitty @ command (without timeout, for fire-and-forget).
fn run_kitty_command(socket: Option<&str>, args: &[&str]) -> bool {
    let mut cmd = Command::new("kitty");
    cmd.arg("@");

    if let Some(socket) = socket {
        cmd.args(["--to", socket]);
    }

    cmd.args(args);

    cmd.status().map(|s| s.success()).unwrap_or(false)
}

/// Find the Kitty window containing a process by PID ancestry.
///
/// Traverses os_windows -> tabs -> windows -> foreground_processes and checks
/// if the target PID is a descendant of any foreground process.
fn find_window_by_pid<S: std::hash::BuildHasher>(
    os_windows: &[serde_json::Value],
    target_pid: i32,
    parent_map: &HashMap<i32, i32, S>,
) -> Option<WindowMatch> {
    for os_window in os_windows {
        let Some(tabs) = os_window.get("tabs").and_then(|v| v.as_array()) else {
            continue;
        };

        for tab in tabs {
            let Some(tab_id) = tab.get("id").and_then(|v| v.as_i64()) else {
                continue;
            };
            let Some(windows) = tab.get("windows").and_then(|v| v.as_array()) else {
                continue;
            };

            for window in windows {
                let Some(window_id) = window.get("id").and_then(|v| v.as_i64()) else {
                    continue;
                };

                if let Some(procs) = window
                    .get("foreground_processes")
                    .and_then(|v| v.as_array())
                {
                    for proc in procs {
                        if let Some(fg_pid) = proc.get("pid").and_then(|v| v.as_i64()) {
                            let fg_pid = fg_pid as i32;

                            // Check if target is this process or a descendant
                            if prock::is_descendant_of(target_pid, fg_pid, parent_map) {
                                return Some(WindowMatch { tab_id, window_id });
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Find the Kitty window by TTY device (legacy matching).
///
/// This is a fallback for when PID is not available. It searches for the
/// TTY device string in foreground process cmdline and cwd fields.
fn find_window_by_tty(os_windows: &[serde_json::Value], tty_device: &str) -> Option<WindowMatch> {
    let tty_full = format!("/dev/{tty_device}");

    for os_window in os_windows {
        let Some(tabs) = os_window.get("tabs").and_then(|v| v.as_array()) else {
            continue;
        };

        for tab in tabs {
            let Some(tab_id) = tab.get("id").and_then(|v| v.as_i64()) else {
                continue;
            };
            let Some(windows) = tab.get("windows").and_then(|v| v.as_array()) else {
                continue;
            };

            for window in windows {
                let Some(window_id) = window.get("id").and_then(|v| v.as_i64()) else {
                    continue;
                };

                if let Some(procs) = window
                    .get("foreground_processes")
                    .and_then(|v| v.as_array())
                {
                    for proc in procs {
                        // Check cmdline array for TTY path
                        if let Some(cmdline) = proc.get("cmdline").and_then(|v| v.as_array()) {
                            for arg in cmdline {
                                if let Some(s) = arg.as_str()
                                    && (s == tty_full || s.ends_with(tty_device))
                                {
                                    return Some(WindowMatch { tab_id, window_id });
                                }
                            }
                        }

                        // Check cwd for TTY device
                        if let Some(cwd) = proc.get("cwd").and_then(|v| v.as_str())
                            && (cwd == tty_full || cwd.ends_with(tty_device))
                        {
                            return Some(WindowMatch { tab_id, window_id });
                        }
                    }
                }
            }
        }
    }
    None
}

/// Focus a Kitty tab and window.
///
/// Explicitly focuses the tab first, then the window within it.
fn focus_tab_and_window(socket: Option<&str>, window_match: &WindowMatch) -> bool {
    // Step 1: Focus the tab
    if !run_kitty_command(
        socket,
        &["focus-tab", "-m", &format!("id:{}", window_match.tab_id)],
    ) {
        return false;
    }

    // Step 2: Focus the window (pane) within the tab
    run_kitty_command(
        socket,
        &[
            "focus-window",
            "-m",
            &format!("id:{}", window_match.window_id),
        ],
    )
}

/// Bring Kitty window to front using the specified mode.
fn bring_to_front(mode: FocusMode) -> bool {
    match mode {
        FocusMode::SingleWindow => bring_to_front_single_window(),
        FocusMode::ActivateApp => {
            activate::window("kitty");
            true
        }
    }
}

/// Bring only the frontmost Kitty window to front using AXRaise.
#[cfg(target_os = "macos")]
fn bring_to_front_single_window() -> bool {
    super::jxa::raise_front_window("kitty")
}

#[cfg(not(target_os = "macos"))]
fn bring_to_front_single_window() -> bool {
    // On non-macOS, fall back to generic activation
    activate::window("kitty");
    true
}

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

    // NOTE: This test is ignored because it can steal window focus when Kitty
    // is running and remote control is unavailable (falls back to app activation).
    // Run manually with: cargo test --package focal -- --ignored
    #[test]
    #[ignore = "steals window focus when Kitty is running without remote control"]
    fn test_try_focus_nonexistent_tty() {
        // Test that try_focus handles nonexistent TTY gracefully (no panic).
        //
        // The return value depends on the test environment:
        // - If Kitty remote control is unavailable: returns `true` (fallback to generic activation)
        // - If Kitty remote control is available but TTY not found: returns `false`
        //
        // We can't assert a specific value without controlling the environment.
        let result = try_focus("ttys999999", FocusMode::SingleWindow);
        let _ = result;
    }

    #[test]
    fn test_find_window_by_pid_direct_match() {
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {"pid": 1234, "cmdline": ["/bin/zsh"], "cwd": "/Users/test"}
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();

        // Build a minimal parent map where 1234 is its own parent (top of chain)
        let mut parent_map = HashMap::new();
        parent_map.insert(1234, 1);

        // Direct match
        let result = find_window_by_pid(&os_windows, 1234, &parent_map);
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.tab_id, 10);
        assert_eq!(m.window_id, 100);
    }

    #[test]
    fn test_find_window_by_pid_descendant() {
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {"pid": 1000, "cmdline": ["/bin/zsh"], "cwd": "/Users/test"}
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();

        // Build parent map: 1234 -> 1100 -> 1000 (so 1234 is descendant of 1000)
        let mut parent_map = HashMap::new();
        parent_map.insert(1234, 1100);
        parent_map.insert(1100, 1000);
        parent_map.insert(1000, 1);

        // Descendant match
        let result = find_window_by_pid(&os_windows, 1234, &parent_map);
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.tab_id, 10);
        assert_eq!(m.window_id, 100);
    }

    #[test]
    fn test_find_window_by_pid_no_match() {
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {"pid": 1000, "cmdline": ["/bin/zsh"], "cwd": "/Users/test"}
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();

        // Build parent map where 9999 is unrelated to 1000
        let mut parent_map = HashMap::new();
        parent_map.insert(9999, 5000);
        parent_map.insert(5000, 1);

        let result = find_window_by_pid(&os_windows, 9999, &parent_map);
        assert!(result.is_none());
    }

    #[test]
    fn test_find_window_by_tty() {
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {
                                        "pid": 1234,
                                        "cmdline": ["/bin/zsh", "-l"],
                                        "cwd": "/dev/ttys003"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();

        let result = find_window_by_tty(&os_windows, "ttys003");
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.tab_id, 10);
        assert_eq!(m.window_id, 100);
    }

    #[test]
    fn test_find_window_by_tty_no_match() {
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {
                                        "pid": 1234,
                                        "cmdline": ["/bin/zsh"],
                                        "cwd": "/Users/test"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();

        let result = find_window_by_tty(&os_windows, "ttys999");
        assert!(result.is_none());
    }

    #[test]
    fn test_json_parsing_complex() {
        // Test parsing with multiple OS windows, tabs, and windows
        let json = r#"[
            {
                "id": 1,
                "tabs": [
                    {
                        "id": 10,
                        "windows": [
                            {
                                "id": 100,
                                "foreground_processes": [
                                    {"pid": 1234, "cmdline": ["/bin/zsh"], "cwd": "/Users/test"}
                                ]
                            },
                            {
                                "id": 101,
                                "foreground_processes": [
                                    {"pid": 5678, "cmdline": ["/bin/bash"], "cwd": "/tmp"}
                                ]
                            }
                        ]
                    },
                    {
                        "id": 11,
                        "windows": [
                            {
                                "id": 110,
                                "foreground_processes": [
                                    {"pid": 9999, "cmdline": ["vim"], "cwd": "/home"}
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                "id": 2,
                "tabs": [
                    {
                        "id": 20,
                        "windows": [
                            {
                                "id": 200,
                                "foreground_processes": [
                                    {"pid": 4321, "cmdline": ["htop"], "cwd": "/"}
                                ]
                            }
                        ]
                    }
                ]
            }
        ]"#;

        let os_windows: Vec<serde_json::Value> = serde_json::from_str(json).unwrap();
        assert_eq!(os_windows.len(), 2);

        // Verify structure
        let tabs = os_windows[0]["tabs"].as_array().unwrap();
        assert_eq!(tabs.len(), 2);

        let windows = tabs[0]["windows"].as_array().unwrap();
        assert_eq!(windows.len(), 2);
    }
}