@@ -0,0 +1,691 @@ |
| 1 | +//! Persistent Lua runtime for garterm scripting |
| 2 | +//! |
| 3 | +//! Provides a long-lived Lua environment that supports: |
| 4 | +//! - Function keybinds (callbacks executed on keypress) |
| 5 | +//! - Terminal API (gar.terminal.* functions) |
| 6 | +//! - Session definitions |
| 7 | +//! |
| 8 | +//! Unlike the static config loader, this runtime is kept alive |
| 9 | +//! for the entire application lifetime to support callbacks. |
| 10 | + |
| 11 | +use super::keybinds::{Action, Keybind, KeybindSet, Modifiers}; |
| 12 | +use super::{Config, ConfigLoader}; |
| 13 | +use mlua::{Function, Lua, RegistryKey, Result as LuaResult, Table, Value}; |
| 14 | +use std::collections::HashMap; |
| 15 | +use std::path::{Path, PathBuf}; |
| 16 | +use std::sync::{Arc, Mutex}; |
| 17 | +use tracing::{debug, error, info, warn}; |
| 18 | + |
| 19 | +/// Terminal commands queued by Lua callbacks |
| 20 | +#[derive(Debug, Clone)] |
| 21 | +pub enum TerminalCommand { |
| 22 | + NewTab { |
| 23 | + cwd: Option<String>, |
| 24 | + cmd: Option<String>, |
| 25 | + title: Option<String>, |
| 26 | + }, |
| 27 | + Split { |
| 28 | + direction: String, |
| 29 | + cwd: Option<String>, |
| 30 | + cmd: Option<String>, |
| 31 | + }, |
| 32 | + SendText { |
| 33 | + pane_id: Option<u32>, |
| 34 | + text: String, |
| 35 | + }, |
| 36 | + CloseTab { |
| 37 | + tab_id: Option<u32>, |
| 38 | + }, |
| 39 | + ClosePane { |
| 40 | + pane_id: Option<u32>, |
| 41 | + }, |
| 42 | + FocusTab { |
| 43 | + index: usize, |
| 44 | + }, |
| 45 | + FocusPane { |
| 46 | + pane_id: u32, |
| 47 | + }, |
| 48 | + FocusDirection { |
| 49 | + direction: String, |
| 50 | + }, |
| 51 | + NextTab, |
| 52 | + PrevTab, |
| 53 | + LoadSession { |
| 54 | + name: String, |
| 55 | + }, |
| 56 | +} |
| 57 | + |
| 58 | +/// Session definition parsed from Lua |
| 59 | +#[derive(Debug, Clone)] |
| 60 | +pub struct Session { |
| 61 | + pub name: String, |
| 62 | + pub tabs: Vec<SessionTab>, |
| 63 | +} |
| 64 | + |
| 65 | +/// Tab within a session |
| 66 | +#[derive(Debug, Clone)] |
| 67 | +pub struct SessionTab { |
| 68 | + pub title: Option<String>, |
| 69 | + pub cwd: Option<PathBuf>, |
| 70 | + pub cmd: Option<String>, |
| 71 | + pub splits: Vec<SessionSplit>, |
| 72 | +} |
| 73 | + |
| 74 | +/// Split within a session tab |
| 75 | +#[derive(Debug, Clone)] |
| 76 | +pub struct SessionSplit { |
| 77 | + pub direction: String, |
| 78 | + pub cwd: Option<PathBuf>, |
| 79 | + pub cmd: Option<String>, |
| 80 | +} |
| 81 | + |
| 82 | +/// Shared state between Rust and Lua |
| 83 | +pub struct LuaState { |
| 84 | + /// Registered Lua function callbacks |
| 85 | + pub callbacks: Vec<RegistryKey>, |
| 86 | + /// Parsed session definitions |
| 87 | + pub sessions: HashMap<String, Session>, |
| 88 | + /// Pending terminal commands from Lua callbacks |
| 89 | + pub pending_commands: Vec<TerminalCommand>, |
| 90 | + /// Keybinds parsed from Lua (separate from TOML keybinds) |
| 91 | + pub lua_keybinds: Vec<(String, LuaKeybind)>, |
| 92 | + /// Last assigned IDs for return values |
| 93 | + pub last_tab_id: u32, |
| 94 | + pub last_pane_id: u32, |
| 95 | +} |
| 96 | + |
| 97 | +impl Default for LuaState { |
| 98 | + fn default() -> Self { |
| 99 | + Self { |
| 100 | + callbacks: Vec::new(), |
| 101 | + sessions: HashMap::new(), |
| 102 | + pending_commands: Vec::new(), |
| 103 | + lua_keybinds: Vec::new(), |
| 104 | + last_tab_id: 0, |
| 105 | + last_pane_id: 0, |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/// Type of keybind action from Lua |
| 111 | +#[derive(Debug, Clone)] |
| 112 | +pub enum LuaKeybind { |
| 113 | + /// String action name: "new_tab", "copy", etc. |
| 114 | + Action(String), |
| 115 | + /// Index into callbacks vector |
| 116 | + Callback(usize), |
| 117 | + /// Load a named session |
| 118 | + SessionLoad(String), |
| 119 | +} |
| 120 | + |
| 121 | +/// Persistent Lua runtime |
| 122 | +pub struct LuaRuntime { |
| 123 | + lua: Lua, |
| 124 | + state: Arc<Mutex<LuaState>>, |
| 125 | + lua_path: PathBuf, |
| 126 | +} |
| 127 | + |
| 128 | +impl LuaRuntime { |
| 129 | + /// Create a new Lua runtime |
| 130 | + pub fn new() -> LuaResult<Self> { |
| 131 | + let lua = Lua::new(); |
| 132 | + let state = Arc::new(Mutex::new(LuaState::default())); |
| 133 | + |
| 134 | + let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from("~/.config")); |
| 135 | + let lua_path = config_dir.join("gar/init.lua"); |
| 136 | + |
| 137 | + Ok(Self { |
| 138 | + lua, |
| 139 | + state, |
| 140 | + lua_path, |
| 141 | + }) |
| 142 | + } |
| 143 | + |
| 144 | + /// Load and execute the Lua config file |
| 145 | + pub fn load(&self) -> LuaResult<Option<Config>> { |
| 146 | + // Set up gar.* stubs for WM compatibility |
| 147 | + self.setup_gar_stubs()?; |
| 148 | + |
| 149 | + // Register gar.terminal.* API |
| 150 | + self.register_terminal_api()?; |
| 151 | + |
| 152 | + // Load the config file if it exists |
| 153 | + if !self.lua_path.exists() { |
| 154 | + debug!("No Lua config at {}", self.lua_path.display()); |
| 155 | + return Ok(None); |
| 156 | + } |
| 157 | + |
| 158 | + let content = match std::fs::read_to_string(&self.lua_path) { |
| 159 | + Ok(c) => c, |
| 160 | + Err(e) => { |
| 161 | + warn!("Failed to read {}: {}", self.lua_path.display(), e); |
| 162 | + return Ok(None); |
| 163 | + } |
| 164 | + }; |
| 165 | + |
| 166 | + // Execute the Lua file |
| 167 | + if let Err(e) = self.lua.load(&content).exec() { |
| 168 | + error!("Lua config error: {}", e); |
| 169 | + return Ok(None); |
| 170 | + } |
| 171 | + |
| 172 | + info!("Loaded Lua config from {}", self.lua_path.display()); |
| 173 | + |
| 174 | + // Parse gar.terminal table into Config |
| 175 | + let config = self.parse_terminal_config()?; |
| 176 | + |
| 177 | + // Parse sessions |
| 178 | + self.parse_sessions()?; |
| 179 | + |
| 180 | + // Parse keybinds (including function callbacks) |
| 181 | + self.parse_keybinds()?; |
| 182 | + |
| 183 | + Ok(config) |
| 184 | + } |
| 185 | + |
| 186 | + /// Set up gar.* stub functions for WM compatibility |
| 187 | + fn setup_gar_stubs(&self) -> LuaResult<()> { |
| 188 | + let globals = self.lua.globals(); |
| 189 | + let gar = self.lua.create_table()?; |
| 190 | + |
| 191 | + // No-op functions that accept any arguments |
| 192 | + let noop = self.lua.create_function(|_, _: mlua::MultiValue| Ok(()))?; |
| 193 | + |
| 194 | + gar.set("set", noop.clone())?; |
| 195 | + gar.set("bind", noop.clone())?; |
| 196 | + gar.set("exec", noop.clone())?; |
| 197 | + gar.set("exec_once", noop.clone())?; |
| 198 | + gar.set("rule", noop.clone())?; |
| 199 | + gar.set("picom_rule", noop.clone())?; |
| 200 | + |
| 201 | + // Action functions that return nil |
| 202 | + let nil_fn = self.lua.create_function(|_, _: mlua::MultiValue| Ok(Value::Nil))?; |
| 203 | + |
| 204 | + gar.set("focus", nil_fn.clone())?; |
| 205 | + gar.set("swap", nil_fn.clone())?; |
| 206 | + gar.set("resize", nil_fn.clone())?; |
| 207 | + gar.set("workspace", nil_fn.clone())?; |
| 208 | + gar.set("workspace_next", nil_fn.clone())?; |
| 209 | + gar.set("workspace_prev", nil_fn.clone())?; |
| 210 | + gar.set("move_to_workspace", nil_fn.clone())?; |
| 211 | + gar.set("focus_monitor", nil_fn.clone())?; |
| 212 | + gar.set("move_to_monitor", nil_fn.clone())?; |
| 213 | + gar.set("close_window", nil_fn.clone())?; |
| 214 | + gar.set("force_close_window", nil_fn.clone())?; |
| 215 | + gar.set("exit", nil_fn.clone())?; |
| 216 | + gar.set("reload", nil_fn.clone())?; |
| 217 | + gar.set("equalize", nil_fn.clone())?; |
| 218 | + gar.set("toggle_floating", nil_fn.clone())?; |
| 219 | + gar.set("toggle_fullscreen", nil_fn.clone())?; |
| 220 | + |
| 221 | + globals.set("gar", gar)?; |
| 222 | + Ok(()) |
| 223 | + } |
| 224 | + |
| 225 | + /// Register gar.terminal.* API functions |
| 226 | + fn register_terminal_api(&self) -> LuaResult<()> { |
| 227 | + let globals = self.lua.globals(); |
| 228 | + let gar: Table = globals.get("gar")?; |
| 229 | + let terminal = self.lua.create_table()?; |
| 230 | + |
| 231 | + // gar.terminal.new_tab({ cwd = "...", cmd = "...", title = "..." }) |
| 232 | + let state = Arc::clone(&self.state); |
| 233 | + let new_tab = self.lua.create_function(move |_, opts: Option<Table>| { |
| 234 | + let (cwd, cmd, title) = if let Some(t) = opts { |
| 235 | + ( |
| 236 | + t.get::<Option<String>>("cwd").ok().flatten(), |
| 237 | + t.get::<Option<String>>("cmd").ok().flatten(), |
| 238 | + t.get::<Option<String>>("title").ok().flatten(), |
| 239 | + ) |
| 240 | + } else { |
| 241 | + (None, None, None) |
| 242 | + }; |
| 243 | + |
| 244 | + let mut state = state.lock().unwrap(); |
| 245 | + state.last_tab_id += 1; |
| 246 | + let tab_id = state.last_tab_id; |
| 247 | + state.pending_commands.push(TerminalCommand::NewTab { cwd, cmd, title }); |
| 248 | + Ok(tab_id) |
| 249 | + })?; |
| 250 | + terminal.set("new_tab", new_tab)?; |
| 251 | + |
| 252 | + // gar.terminal.split({ direction = "horizontal", cwd = "...", cmd = "..." }) |
| 253 | + let state = Arc::clone(&self.state); |
| 254 | + let split = self.lua.create_function(move |_, opts: Option<Table>| { |
| 255 | + let (direction, cwd, cmd) = if let Some(t) = opts { |
| 256 | + ( |
| 257 | + t.get::<String>("direction").unwrap_or_else(|_| "vertical".into()), |
| 258 | + t.get::<Option<String>>("cwd").ok().flatten(), |
| 259 | + t.get::<Option<String>>("cmd").ok().flatten(), |
| 260 | + ) |
| 261 | + } else { |
| 262 | + ("vertical".into(), None, None) |
| 263 | + }; |
| 264 | + |
| 265 | + let mut state = state.lock().unwrap(); |
| 266 | + state.last_pane_id += 1; |
| 267 | + let pane_id = state.last_pane_id; |
| 268 | + state.pending_commands.push(TerminalCommand::Split { direction, cwd, cmd }); |
| 269 | + Ok(pane_id) |
| 270 | + })?; |
| 271 | + terminal.set("split", split)?; |
| 272 | + |
| 273 | + // gar.terminal.send_text(pane_id, text) or gar.terminal.send_text(text) |
| 274 | + let state = Arc::clone(&self.state); |
| 275 | + let send_text = self.lua.create_function(move |_, args: mlua::MultiValue| { |
| 276 | + let args: Vec<Value> = args.into_iter().collect(); |
| 277 | + let (pane_id, text) = match args.len() { |
| 278 | + 1 => { |
| 279 | + // send_text("text") - send to focused pane |
| 280 | + let text = match &args[0] { |
| 281 | + Value::String(s) => s.to_str()?.to_string(), |
| 282 | + _ => return Err(mlua::Error::runtime("expected string")), |
| 283 | + }; |
| 284 | + (None, text) |
| 285 | + } |
| 286 | + 2 => { |
| 287 | + // send_text(pane_id, "text") |
| 288 | + let pane_id = match &args[0] { |
| 289 | + Value::Integer(n) => Some(*n as u32), |
| 290 | + Value::Nil => None, |
| 291 | + _ => return Err(mlua::Error::runtime("expected pane_id or nil")), |
| 292 | + }; |
| 293 | + let text = match &args[1] { |
| 294 | + Value::String(s) => s.to_str()?.to_string(), |
| 295 | + _ => return Err(mlua::Error::runtime("expected string")), |
| 296 | + }; |
| 297 | + (pane_id, text) |
| 298 | + } |
| 299 | + _ => return Err(mlua::Error::runtime("expected 1 or 2 arguments")), |
| 300 | + }; |
| 301 | + |
| 302 | + let mut state = state.lock().unwrap(); |
| 303 | + state.pending_commands.push(TerminalCommand::SendText { pane_id, text }); |
| 304 | + Ok(()) |
| 305 | + })?; |
| 306 | + terminal.set("send_text", send_text)?; |
| 307 | + |
| 308 | + // gar.terminal.close_tab(tab_id?) |
| 309 | + let state = Arc::clone(&self.state); |
| 310 | + let close_tab = self.lua.create_function(move |_, tab_id: Option<u32>| { |
| 311 | + let mut state = state.lock().unwrap(); |
| 312 | + state.pending_commands.push(TerminalCommand::CloseTab { tab_id }); |
| 313 | + Ok(()) |
| 314 | + })?; |
| 315 | + terminal.set("close_tab", close_tab)?; |
| 316 | + |
| 317 | + // gar.terminal.close_pane(pane_id?) |
| 318 | + let state = Arc::clone(&self.state); |
| 319 | + let close_pane = self.lua.create_function(move |_, pane_id: Option<u32>| { |
| 320 | + let mut state = state.lock().unwrap(); |
| 321 | + state.pending_commands.push(TerminalCommand::ClosePane { pane_id }); |
| 322 | + Ok(()) |
| 323 | + })?; |
| 324 | + terminal.set("close_pane", close_pane)?; |
| 325 | + |
| 326 | + // gar.terminal.focus_tab(n) |
| 327 | + let state = Arc::clone(&self.state); |
| 328 | + let focus_tab = self.lua.create_function(move |_, index: usize| { |
| 329 | + let mut state = state.lock().unwrap(); |
| 330 | + state.pending_commands.push(TerminalCommand::FocusTab { index }); |
| 331 | + Ok(()) |
| 332 | + })?; |
| 333 | + terminal.set("focus_tab", focus_tab)?; |
| 334 | + |
| 335 | + // gar.terminal.focus_pane(pane_id) |
| 336 | + let state = Arc::clone(&self.state); |
| 337 | + let focus_pane = self.lua.create_function(move |_, pane_id: u32| { |
| 338 | + let mut state = state.lock().unwrap(); |
| 339 | + state.pending_commands.push(TerminalCommand::FocusPane { pane_id }); |
| 340 | + Ok(()) |
| 341 | + })?; |
| 342 | + terminal.set("focus_pane", focus_pane)?; |
| 343 | + |
| 344 | + // gar.terminal.focus_direction(dir) |
| 345 | + let state = Arc::clone(&self.state); |
| 346 | + let focus_direction = self.lua.create_function(move |_, direction: String| { |
| 347 | + let mut state = state.lock().unwrap(); |
| 348 | + state.pending_commands.push(TerminalCommand::FocusDirection { direction }); |
| 349 | + Ok(()) |
| 350 | + })?; |
| 351 | + terminal.set("focus_direction", focus_direction)?; |
| 352 | + |
| 353 | + // gar.terminal.next_tab() |
| 354 | + let state = Arc::clone(&self.state); |
| 355 | + let next_tab = self.lua.create_function(move |_, ()| { |
| 356 | + let mut state = state.lock().unwrap(); |
| 357 | + state.pending_commands.push(TerminalCommand::NextTab); |
| 358 | + Ok(()) |
| 359 | + })?; |
| 360 | + terminal.set("next_tab", next_tab)?; |
| 361 | + |
| 362 | + // gar.terminal.prev_tab() |
| 363 | + let state = Arc::clone(&self.state); |
| 364 | + let prev_tab = self.lua.create_function(move |_, ()| { |
| 365 | + let mut state = state.lock().unwrap(); |
| 366 | + state.pending_commands.push(TerminalCommand::PrevTab); |
| 367 | + Ok(()) |
| 368 | + })?; |
| 369 | + terminal.set("prev_tab", prev_tab)?; |
| 370 | + |
| 371 | + // gar.terminal.load_session(name) |
| 372 | + let state = Arc::clone(&self.state); |
| 373 | + let load_session = self.lua.create_function(move |_, name: String| { |
| 374 | + let mut state = state.lock().unwrap(); |
| 375 | + state.pending_commands.push(TerminalCommand::LoadSession { name }); |
| 376 | + Ok(()) |
| 377 | + })?; |
| 378 | + terminal.set("load_session", load_session)?; |
| 379 | + |
| 380 | + gar.set("terminal", terminal)?; |
| 381 | + Ok(()) |
| 382 | + } |
| 383 | + |
| 384 | + /// Parse gar.terminal table into Config (static settings only) |
| 385 | + fn parse_terminal_config(&self) -> LuaResult<Option<Config>> { |
| 386 | + let globals = self.lua.globals(); |
| 387 | + let gar: Table = match globals.get("gar") { |
| 388 | + Ok(t) => t, |
| 389 | + Err(_) => return Ok(None), |
| 390 | + }; |
| 391 | + |
| 392 | + let terminal: Table = match gar.get("terminal") { |
| 393 | + Ok(t) => t, |
| 394 | + Err(_) => return Ok(None), |
| 395 | + }; |
| 396 | + |
| 397 | + // Delegate to existing lua.rs parsing logic |
| 398 | + // This reuses the static config parsing |
| 399 | + let config = super::lua::parse_terminal_table_internal(&terminal); |
| 400 | + Ok(Some(config)) |
| 401 | + } |
| 402 | + |
| 403 | + /// Parse session definitions from gar.terminal.sessions |
| 404 | + fn parse_sessions(&self) -> LuaResult<()> { |
| 405 | + let globals = self.lua.globals(); |
| 406 | + let gar: Table = globals.get("gar")?; |
| 407 | + let terminal: Table = match gar.get("terminal") { |
| 408 | + Ok(t) => t, |
| 409 | + Err(_) => return Ok(()), |
| 410 | + }; |
| 411 | + |
| 412 | + let sessions: Table = match terminal.get("sessions") { |
| 413 | + Ok(t) => t, |
| 414 | + Err(_) => return Ok(()), |
| 415 | + }; |
| 416 | + |
| 417 | + let mut state = self.state.lock().unwrap(); |
| 418 | + |
| 419 | + for pair in sessions.pairs::<String, Table>() { |
| 420 | + let (name, session_table) = pair?; |
| 421 | + if let Ok(session) = self.parse_session(&name, &session_table) { |
| 422 | + debug!("Parsed session: {}", name); |
| 423 | + state.sessions.insert(name, session); |
| 424 | + } |
| 425 | + } |
| 426 | + |
| 427 | + info!("Loaded {} sessions", state.sessions.len()); |
| 428 | + Ok(()) |
| 429 | + } |
| 430 | + |
| 431 | + /// Parse a single session definition |
| 432 | + fn parse_session(&self, name: &str, table: &Table) -> LuaResult<Session> { |
| 433 | + let mut tabs = Vec::new(); |
| 434 | + |
| 435 | + if let Ok(tabs_table) = table.get::<Table>("tabs") { |
| 436 | + for i in 1..=tabs_table.len()? { |
| 437 | + if let Ok(tab_table) = tabs_table.get::<Table>(i) { |
| 438 | + tabs.push(self.parse_session_tab(&tab_table)?); |
| 439 | + } |
| 440 | + } |
| 441 | + } |
| 442 | + |
| 443 | + Ok(Session { |
| 444 | + name: name.to_string(), |
| 445 | + tabs, |
| 446 | + }) |
| 447 | + } |
| 448 | + |
| 449 | + /// Parse a session tab definition |
| 450 | + fn parse_session_tab(&self, table: &Table) -> LuaResult<SessionTab> { |
| 451 | + let title = table.get::<Option<String>>("title").ok().flatten(); |
| 452 | + let cwd = table.get::<Option<String>>("cwd").ok().flatten().map(PathBuf::from); |
| 453 | + let cmd = table.get::<Option<String>>("cmd").ok().flatten(); |
| 454 | + |
| 455 | + let mut splits = Vec::new(); |
| 456 | + if let Ok(splits_table) = table.get::<Table>("splits") { |
| 457 | + for i in 1..=splits_table.len()? { |
| 458 | + if let Ok(split_table) = splits_table.get::<Table>(i) { |
| 459 | + splits.push(self.parse_session_split(&split_table)?); |
| 460 | + } |
| 461 | + } |
| 462 | + } |
| 463 | + |
| 464 | + Ok(SessionTab { title, cwd, cmd, splits }) |
| 465 | + } |
| 466 | + |
| 467 | + /// Parse a session split definition |
| 468 | + fn parse_session_split(&self, table: &Table) -> LuaResult<SessionSplit> { |
| 469 | + let direction = table.get::<String>("direction").unwrap_or_else(|_| "vertical".into()); |
| 470 | + let cwd = table.get::<Option<String>>("cwd").ok().flatten().map(PathBuf::from); |
| 471 | + let cmd = table.get::<Option<String>>("cmd").ok().flatten(); |
| 472 | + |
| 473 | + Ok(SessionSplit { direction, cwd, cmd }) |
| 474 | + } |
| 475 | + |
| 476 | + /// Parse keybinds from gar.terminal.keybinds (supports functions!) |
| 477 | + fn parse_keybinds(&self) -> LuaResult<()> { |
| 478 | + let globals = self.lua.globals(); |
| 479 | + let gar: Table = globals.get("gar")?; |
| 480 | + let terminal: Table = match gar.get("terminal") { |
| 481 | + Ok(t) => t, |
| 482 | + Err(_) => return Ok(()), |
| 483 | + }; |
| 484 | + |
| 485 | + let keybinds: Table = match terminal.get("keybinds") { |
| 486 | + Ok(t) => t, |
| 487 | + Err(_) => return Ok(()), |
| 488 | + }; |
| 489 | + |
| 490 | + for pair in keybinds.pairs::<String, Value>() { |
| 491 | + let (key_combo, value) = pair?; |
| 492 | + |
| 493 | + let lua_keybind = match value { |
| 494 | + Value::String(s) => { |
| 495 | + // String action: "new_tab", "copy", etc. |
| 496 | + LuaKeybind::Action(s.to_str()?.to_string()) |
| 497 | + } |
| 498 | + Value::Function(f) => { |
| 499 | + // Lua function callback - store in registry |
| 500 | + let key = self.lua.create_registry_value(f)?; |
| 501 | + let mut state = self.state.lock().unwrap(); |
| 502 | + let index = state.callbacks.len(); |
| 503 | + state.callbacks.push(key); |
| 504 | + drop(state); |
| 505 | + debug!("Registered Lua callback {} for {}", index, key_combo); |
| 506 | + LuaKeybind::Callback(index) |
| 507 | + } |
| 508 | + Value::Table(t) => { |
| 509 | + // Action table: { action = "load_session", session = "webdev" } |
| 510 | + if let Ok(session) = t.get::<String>("session") { |
| 511 | + LuaKeybind::SessionLoad(session) |
| 512 | + } else if let Ok(action) = t.get::<String>("action") { |
| 513 | + LuaKeybind::Action(action) |
| 514 | + } else { |
| 515 | + continue; |
| 516 | + } |
| 517 | + } |
| 518 | + _ => continue, |
| 519 | + }; |
| 520 | + |
| 521 | + let mut state = self.state.lock().unwrap(); |
| 522 | + state.lua_keybinds.push((key_combo.clone(), lua_keybind)); |
| 523 | + } |
| 524 | + |
| 525 | + let state = self.state.lock().unwrap(); |
| 526 | + info!("Loaded {} Lua keybinds ({} callbacks)", |
| 527 | + state.lua_keybinds.len(), |
| 528 | + state.callbacks.len()); |
| 529 | + Ok(()) |
| 530 | + } |
| 531 | + |
| 532 | + /// Execute a registered callback by index |
| 533 | + pub fn execute_callback(&self, index: usize) -> LuaResult<()> { |
| 534 | + let state = self.state.lock().unwrap(); |
| 535 | + let key = state.callbacks.get(index) |
| 536 | + .ok_or_else(|| mlua::Error::runtime(format!("callback {} not found", index)))?; |
| 537 | + |
| 538 | + let func: Function = self.lua.registry_value(key)?; |
| 539 | + drop(state); // Release lock before calling Lua |
| 540 | + |
| 541 | + func.call::<()>(())?; |
| 542 | + Ok(()) |
| 543 | + } |
| 544 | + |
| 545 | + /// Take pending commands (drains the queue) |
| 546 | + pub fn take_pending_commands(&self) -> Vec<TerminalCommand> { |
| 547 | + let mut state = self.state.lock().unwrap(); |
| 548 | + std::mem::take(&mut state.pending_commands) |
| 549 | + } |
| 550 | + |
| 551 | + /// Get a session by name |
| 552 | + pub fn get_session(&self, name: &str) -> Option<Session> { |
| 553 | + let state = self.state.lock().unwrap(); |
| 554 | + state.sessions.get(name).cloned() |
| 555 | + } |
| 556 | + |
| 557 | + /// Get Lua keybinds to merge with config keybinds |
| 558 | + pub fn get_lua_keybinds(&self) -> Vec<(String, LuaKeybind)> { |
| 559 | + let state = self.state.lock().unwrap(); |
| 560 | + state.lua_keybinds.clone() |
| 561 | + } |
| 562 | + |
| 563 | + /// Check if we have any Lua callbacks (for feature detection) |
| 564 | + pub fn has_callbacks(&self) -> bool { |
| 565 | + let state = self.state.lock().unwrap(); |
| 566 | + !state.callbacks.is_empty() |
| 567 | + } |
| 568 | + |
| 569 | + /// Merge Lua keybinds into an existing KeybindSet |
| 570 | + /// |
| 571 | + /// This converts LuaKeybind variants to Action variants and adds them |
| 572 | + /// to the keybind set, overriding any existing bindings. |
| 573 | + pub fn merge_keybinds(&self, keybinds: &mut KeybindSet) { |
| 574 | + let state = self.state.lock().unwrap(); |
| 575 | + |
| 576 | + for (key_combo, lua_bind) in &state.lua_keybinds { |
| 577 | + // Parse the key combo |
| 578 | + let Some((modifiers, key)) = Keybind::parse_key_combo(key_combo) else { |
| 579 | + warn!("Invalid key combo from Lua: {}", key_combo); |
| 580 | + continue; |
| 581 | + }; |
| 582 | + |
| 583 | + // Convert LuaKeybind to Action |
| 584 | + let action = match lua_bind { |
| 585 | + LuaKeybind::Action(s) => { |
| 586 | + // Parse string action |
| 587 | + if let Some(a) = Action::from_str_loose(s) { |
| 588 | + a |
| 589 | + } else { |
| 590 | + warn!("Unknown action '{}' for Lua keybind '{}'", s, key_combo); |
| 591 | + continue; |
| 592 | + } |
| 593 | + } |
| 594 | + LuaKeybind::Callback(index) => Action::LuaCallback(*index), |
| 595 | + LuaKeybind::SessionLoad(name) => Action::LoadSession(name.clone()), |
| 596 | + }; |
| 597 | + |
| 598 | + // Add to keybind set (overrides existing) |
| 599 | + if let Some(old) = keybinds.add(Keybind::new(modifiers, key, action)) { |
| 600 | + if old.action != Action::None { |
| 601 | + debug!("Lua keybind {} overrides {:?}", key_combo, old.action); |
| 602 | + } |
| 603 | + } |
| 604 | + } |
| 605 | + |
| 606 | + info!("Merged {} Lua keybinds", state.lua_keybinds.len()); |
| 607 | + } |
| 608 | +} |
| 609 | + |
| 610 | +#[cfg(test)] |
| 611 | +mod tests { |
| 612 | + use super::*; |
| 613 | + |
| 614 | + #[test] |
| 615 | + fn test_runtime_creation() { |
| 616 | + let runtime = LuaRuntime::new().unwrap(); |
| 617 | + assert!(!runtime.has_callbacks()); |
| 618 | + } |
| 619 | + |
| 620 | + #[test] |
| 621 | + fn test_terminal_api_registration() { |
| 622 | + let runtime = LuaRuntime::new().unwrap(); |
| 623 | + runtime.setup_gar_stubs().unwrap(); |
| 624 | + runtime.register_terminal_api().unwrap(); |
| 625 | + |
| 626 | + // Execute Lua that calls the API |
| 627 | + runtime.lua.load(r#" |
| 628 | + local tab = gar.terminal.new_tab({ cwd = "/tmp", title = "Test" }) |
| 629 | + gar.terminal.send_text(tab, "echo hello\n") |
| 630 | + "#).exec().unwrap(); |
| 631 | + |
| 632 | + let commands = runtime.take_pending_commands(); |
| 633 | + assert_eq!(commands.len(), 2); |
| 634 | + } |
| 635 | + |
| 636 | + #[test] |
| 637 | + fn test_session_parsing() { |
| 638 | + let runtime = LuaRuntime::new().unwrap(); |
| 639 | + runtime.setup_gar_stubs().unwrap(); |
| 640 | + runtime.register_terminal_api().unwrap(); |
| 641 | + |
| 642 | + runtime.lua.load(r#" |
| 643 | + gar.terminal.sessions = { |
| 644 | + webdev = { |
| 645 | + tabs = { |
| 646 | + { title = "Frontend", cwd = "~/app", cmd = "npm run dev" }, |
| 647 | + { title = "Backend", cmd = "python manage.py runserver" }, |
| 648 | + } |
| 649 | + } |
| 650 | + } |
| 651 | + "#).exec().unwrap(); |
| 652 | + |
| 653 | + runtime.parse_sessions().unwrap(); |
| 654 | + |
| 655 | + let session = runtime.get_session("webdev").unwrap(); |
| 656 | + assert_eq!(session.tabs.len(), 2); |
| 657 | + assert_eq!(session.tabs[0].title, Some("Frontend".into())); |
| 658 | + assert_eq!(session.tabs[0].cmd, Some("npm run dev".into())); |
| 659 | + } |
| 660 | + |
| 661 | + #[test] |
| 662 | + fn test_function_keybind() { |
| 663 | + let runtime = LuaRuntime::new().unwrap(); |
| 664 | + runtime.setup_gar_stubs().unwrap(); |
| 665 | + runtime.register_terminal_api().unwrap(); |
| 666 | + |
| 667 | + runtime.lua.load(r#" |
| 668 | + gar.terminal.keybinds = { |
| 669 | + ["alt+t"] = function() |
| 670 | + gar.terminal.new_tab({ title = "From callback" }) |
| 671 | + end |
| 672 | + } |
| 673 | + "#).exec().unwrap(); |
| 674 | + |
| 675 | + runtime.parse_keybinds().unwrap(); |
| 676 | + |
| 677 | + assert!(runtime.has_callbacks()); |
| 678 | + |
| 679 | + // Execute the callback |
| 680 | + runtime.execute_callback(0).unwrap(); |
| 681 | + |
| 682 | + let commands = runtime.take_pending_commands(); |
| 683 | + assert_eq!(commands.len(), 1); |
| 684 | + match &commands[0] { |
| 685 | + TerminalCommand::NewTab { title, .. } => { |
| 686 | + assert_eq!(title.as_deref(), Some("From callback")); |
| 687 | + } |
| 688 | + _ => panic!("expected NewTab command"), |
| 689 | + } |
| 690 | + } |
| 691 | +} |