use crate::FocusMode;
pub fn try_focus(tty_device: &str, mode: FocusMode) -> bool {
match mode {
FocusMode::SingleWindow => try_focus_single_window(tty_device),
FocusMode::ActivateApp => try_focus_activate_app(tty_device),
}
}
#[cfg(target_os = "macos")]
fn try_focus_single_window(tty_device: &str) -> bool {
let script = format!(
r#"
(function() {{
try {{
var Terminal = Application("Terminal");
if (!Terminal.running()) return false;
var windows = Terminal.windows();
for (var i = 0; i < windows.length; i++) {{
var tabs = windows[i].tabs();
for (var j = 0; j < tabs.length; j++) {{
var tty = tabs[j].tty();
if (tty && tty.includes("{tty_device}")) {{
// Select the tab within Terminal
tabs[j].selected = true;
// Make this window frontmost among Terminal windows
// Setting index=1 reorders Terminal's window list so our target is first
windows[i].index = 1;
// Use System Events to raise ONLY this specific window
// After setting index=1, the first window in System Events
// should be our target window
var se = Application("System Events");
var termProcess = se.processes["Terminal"];
// Bring Terminal to front (required for AXRaise to work across apps)
termProcess.frontmost = true;
var seWindows = termProcess.windows();
if (seWindows.length > 0) {{
// AXRaise brings just this window to front
seWindows[0].actions["AXRaise"].perform();
}}
return true;
}}
}}
}}
return false;
}} catch(e) {{
return false;
}}
}})()
"#
);
run_jxa(&script)
}
#[cfg(not(target_os = "macos"))]
fn try_focus_single_window(_tty_device: &str) -> bool {
false
}
#[cfg(target_os = "macos")]
fn try_focus_activate_app(tty_device: &str) -> bool {
let script = format!(
r#"
(function() {{
try {{
var Terminal = Application("Terminal");
if (!Terminal.running()) return false;
var windows = Terminal.windows();
for (var i = 0; i < windows.length; i++) {{
var tabs = windows[i].tabs();
for (var j = 0; j < tabs.length; j++) {{
var tty = tabs[j].tty();
if (tty && tty.includes("{tty_device}")) {{
// Select the tab within Terminal
tabs[j].selected = true;
// Make this window frontmost among Terminal windows
// Setting index=1 reorders Terminal's window list so our target is first
windows[i].index = 1;
// Activate the entire app (brings ALL windows to front)
Terminal.activate();
return true;
}}
}}
}}
return false;
}} catch(e) {{
return false;
}}
}})()
"#
);
run_jxa(&script)
}
#[cfg(not(target_os = "macos"))]
fn try_focus_activate_app(_tty_device: &str) -> bool {
false
}
#[cfg(target_os = "macos")]
fn run_jxa(script: &str) -> bool {
super::jxa::run_with_timeout(script)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_try_focus_nonexistent_tty_single_window() {
let result = try_focus("ttys999999", FocusMode::SingleWindow);
assert!(!result);
}
#[test]
fn test_try_focus_nonexistent_tty_activate_app() {
let result = try_focus("ttys999999", FocusMode::ActivateApp);
assert!(!result);
}
}