Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/bugabinga/instances.lua

Raw
local wez = require 'wezterm'

local function script_path()
  return (wez.config_dir or '.') .. '/bugabinga/wezterm_instances.nu'
end

local function enabled()
  return wez.target_triple:find( 'linux', 1, true ) ~= nil and os.getenv 'NIRI_SOCKET' ~= nil
end

local function current_pid()
  local ok, pid = pcall( wez.procinfo.pid )
  return ok and pid or nil
end

local function list()
  if not enabled() then return nil end

  local success, stdout, stderr = wez.run_child_process { 'nu', '--no-config-file', script_path(), 'list', }
  if not success then
    wez.log_error( 'failed to list WezTerm GUI instances: ' .. (stderr or '') )
    return nil
  end

  local ok, rows = pcall( wez.json_parse, stdout )
  if not ok or type( rows ) ~= 'table' then
    wez.log_error 'invalid WezTerm GUI instance list'
    return nil
  end
  return rows
end

local function activate( gui_pid, pane_id )
  if not enabled() then return false end

  local success, _, stderr = wez.run_child_process {
    'nu', '--no-config-file', script_path(), 'activate', tostring( gui_pid ), tostring( pane_id ),
  }
  if not success then
    wez.log_error( 'failed to activate WezTerm pane: ' .. (stderr or '') )
  end
  return success
end

local function target_id( gui_pid, pane_id )
  return string.format( 'niri:%d:%d', gui_pid, pane_id )
end

local function parse_target_id( id )
  local gui_pid, pane_id = id:match '^niri:(%d+):(%d+)$'
  return tonumber( gui_pid ), tonumber( pane_id )
end

return {
  enabled = enabled,
  current_pid = current_pid,
  list = list,
  activate = activate,
  target_id = target_id,
  parse_target_id = parse_target_id,
}