Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/bugabinga/sessions.lua

Raw
local wez = require 'wezterm'

local messages = {}
local busy = false
local waiting = {}
local sequence = 0
local mode = 'Session · s save · r restore · Esc cancel'

local function feedback( window, message, persistent )
  messages[window:window_id()] = { text = message, expires = persistent and math.huge or os.time() + 12, }
  window:set_right_status( message )
end

local function dialog( window, pane, title, message )
  window:perform_action( wez.action.InputSelector {
                           title = title,
                           description = message,
                           choices = { { id = 'ok', label = 'OK', }, },
                           action = wez.action_callback( function () end ),
                         }, pane )
end

local function storage( operation, payload )
  local args = { 'nu', '--no-config-file', wez.config_dir .. '/bugabinga/session_storage.nu', operation, }
  if payload then
    assert( #payload <= 8192, 'Session exceeds the 8 KiB snapshot limit; existing save was not changed.' )
    table.insert( args, payload )
  end
  local ok, stdout, stderr = wez.run_child_process( args )
  assert( ok, 'Session storage failed.\n' .. (stderr or 'Check that nu and age are installed and on PATH.') )
  return stdout
end

local function bounds( panes )
  local left, top, right, bottom = math.huge, math.huge, 0, 0
  for _, p in ipairs( panes ) do
    left = math.min( left, p.left )
    top = math.min( top, p.top )
    right = math.max( right, p.left + p.width )
    bottom = math.max( bottom, p.top + p.height )
  end
  return left, top, right - left, bottom - top
end

-- Rectangles include a one-cell separator; pane indexes are not split history.
local function layout( panes )
  assert( #panes > 0, 'Cannot save an empty tab.' )
  local left, top, width, height = bounds( panes )
  if #panes == 1 then
    local p = panes[1]
    return {
      width = width,
      height = height,
      domain = p.domain,
      cwd = p.cwd,
      active = p.active,
      zoomed = p.zoomed,
      text_source = p.text_source,
    }
  end
  for _, axis in ipairs { 'Right', 'Bottom', } do
    local horizontal = axis == 'Right'
    for _, p in ipairs( panes ) do
      local cut = horizontal and (p.left + p.width) or (p.top + p.height)
      local start = horizontal and left or top
      local extent = horizontal and width or height
      if cut > start and cut < start + extent - 1 then
        local first, second, crosses = {}, {}, false
        for _, q in ipairs( panes ) do
          local position = horizontal and q.left or q.top
          local size = horizontal and q.width or q.height
          if position + size <= cut then
            table.insert( first, q )
          elseif position >= cut + 1 then
            table.insert( second, q )
          else
            crosses = true
          end
        end
        if not crosses and #first > 0 and #second > 0 then
          local ok_a, a = pcall( layout, first )
          local ok_b, b = pcall( layout, second )
          if ok_a and ok_b then return { width = width, height = height, direction = axis, first = a, second = b, } end
        end
      end
    end
  end
  error 'Cannot reconstruct this pane layout; existing save was not changed.'
end

local function pane_cwd( pane, domain )
  local url = pane:get_current_working_dir()
  if not url or url.scheme ~= 'file' then return nil end
  local path = url.file_path
  if wez.target_triple:find( 'windows', 1, true ) and domain == 'local' then
    if path:match '^/[A-Za-z]:/' then
      path = path:sub( 2 )
    elseif url.host and url.host ~= '' and not path:match '^/[A-Za-z]:' then
      path = '//' .. url.host .. path
    end
  end
  return path
end

local function capture( window )
  local snapshot = { version = 1, tabs = {}, active_tab = 1, }
  local count = 0
  for _, info in ipairs( window:mux_window():tabs_with_info() ) do
    local panes = {}
    for _, p in ipairs( info.tab:panes_with_info() ) do
      local domain = p.pane:get_domain_name()
      table.insert( panes, {
        left = p.left,
        top = p.top,
        width = p.width,
        height = p.height,
        domain = domain,
        cwd = pane_cwd( p.pane, domain ),
        active = p.is_active,
        zoomed = p.is_zoomed,
        text_source = not p.pane:is_alt_screen_active() and {
          pane_id = p.pane:pane_id(), rows = p.pane:get_dimensions().scrollback_rows,
        } or nil,
      } )
      count = count + 1
    end
    table.insert( snapshot.tabs, { title = info.tab:get_title(), tree = layout( panes ), } )
    if info.is_active then snapshot.active_tab = #snapshot.tabs end
  end
  assert( #snapshot.tabs > 0, 'Cannot save an empty window.' )
  return snapshot, count
end

local function validate( snapshot )
  assert( type( snapshot ) == 'table' and snapshot.version == 1,                             'Unsupported session snapshot.' )
  assert( type( snapshot.tabs ) == 'table' and #snapshot.tabs > 0 and #snapshot.tabs <= 100, 'Invalid session tabs.' )
  local count = 0
  local function node( n, depth )
    assert( type( n ) == 'table' and depth <= 100, 'Invalid session layout.' )
    for _, key in ipairs { 'width', 'height', } do
      assert( type( n[key] ) == 'number' and n[key] % 1 == 0 and n[key] >= 1 and n[key] <= 10000,
              'Invalid pane dimensions.' )
    end
    if n.direction then
      assert( n.direction == 'Right' or n.direction == 'Bottom', 'Invalid split direction.' )
      node( n.first,  depth + 1 )
      node( n.second, depth + 1 )
    else
      count = count + 1
      assert( count <= 256 and type( n.domain ) == 'string', 'Invalid pane domain or pane count.' )
      assert( n.cwd == nil or type( n.cwd ) == 'string',     'Invalid pane directory.' )
      assert( n.text == nil or type( n.text ) == 'string',   'Invalid pane history.' )
    end
  end
  for _, tab in ipairs( snapshot.tabs ) do
    assert( type( tab.title ) == 'string', 'Invalid tab title.' )
    node( tab.tree, 0 )
  end
  assert( type( snapshot.active_tab ) == 'number' and snapshot.active_tab % 1 == 0
          and snapshot.active_tab >= 1 and snapshot.active_tab <= #snapshot.tabs, 'Invalid active tab.' )
end

local function first_leaf( tree )
  return tree.first and first_leaf( tree.first ) or tree
end

local function minimum( tree, horizontal )
  if not tree.direction then return 1 end
  local a, b = minimum( tree.first, horizontal ), minimum( tree.second, horizontal )
  if (tree.direction == 'Right') == horizontal then return a + b + 1 end
  return math.max( a, b )
end

-- C1 controls are UTF-8 C2 80..9F, not arbitrary continuation bytes.
local function plain_text( text )
  return (text:gsub( '\r\n', '\n' ):gsub( '\t', '    ' )
    :gsub( '[%z\1-\8\11-\31\127]', '' ):gsub( '\194[\128-\159]', '' ):gsub( '\n', '\r\n' ))
end

local function release( gate )
  if gate.finished or not gate.context.constructed or not gate.ready then return end
  gate.finished = true
  waiting[gate.token] = nil
  -- The waiting bootstrap reads a framed DATA response, prints it via stdout,
  -- then starts the shell. No saved text is evaluated or sent to a live shell.
  -- BEL cannot occur in the sanitized payload, so it uniquely ends the frame.
  local sent, send_error = pcall( function ()
    -- JSON framing preserves newlines across ConPTY input translation.
    gate.pane:send_text( 'wezterm-session:' .. gate.token .. ':' .. wez.json_encode( plain_text( gate.text ) ) .. '\7' )
  end )
  if not sent then table.insert( gate.context.warnings, 'Shell startup: ' .. tostring( send_error ) ) end
  gate.context.remaining = gate.context.remaining - 1
  if gate.context.remaining == 0 then gate.context.done() end
end

wez.on( 'user-var-changed', function ( _, pane, name, value )
  if name ~= 'SESSION_RESTORE' then return end
  local gate = waiting[value]
  if not gate then return end
  gate.ready = true
  gate.pane = pane
  release( gate )
end )

local function bootstrap( token, program )
  -- term query drains old input BEFORE publishing readiness, unlike Nu input.
  local query = '"1337;SetUserVar=SESSION_RESTORE=" + ("' .. token .. '" | encode base64)'
  return 'let history = (term query ((ansi --osc (' .. query .. ')) + (char bel)) '
    .. '--prefix "wezterm-session:' .. token .. ':" --terminator (char bel) | decode utf-8 | from json); '
    .. 'print --no-newline $history; print ""; print "──────── New session ────────"; let shell = ('
    .. wez.json_encode( wez.json_encode( program or { 'nu', '--login', } ) )
    .. ' | from json); exec ...$shell'
end

local function restore( snapshot, source_window, done )
  validate( snapshot )
  local warnings, restored_tabs, restored_panes = {}, 0, 0
  local target, active_tab
  local context = { gates = {}, remaining = 0, constructed = false, warnings = warnings, done = function () end, }
  local function options( leaf )
    local cwd = leaf.cwd
    if leaf.domain == 'local' and cwd then
      local exists = pcall( wez.read_dir, cwd )
      if not exists then
        table.insert( warnings, 'Directory unavailable: ' .. cwd .. '; using home.' )
        cwd = wez.home_dir
      end
    end
    local opts = { domain = { DomainName = leaf.domain, }, cwd = cwd, }
    if leaf.text and leaf.text ~= '' then
      if leaf.domain == 'local' or leaf.domain:match '^WSL:' then
        sequence = sequence + 1
        local token = tostring( os.time() ) .. '-' .. tostring( sequence )
        local gate = { token = token, text = leaf.text, context = context, }
        leaf.gate = gate
        waiting[token] = gate
        table.insert( context.gates, gate )
        context.remaining = context.remaining + 1
        local program = leaf.domain == 'local' and source_window:effective_config().default_prog or nil
        opts.args = { 'nu', '--no-config-file', '--commands', bootstrap( token, program ), }
      else
        table.insert( warnings, 'History skipped for unsupported domain: ' .. leaf.domain )
      end
    end
    return opts
  end
  local function bind( leaf, pane )
    if leaf.gate then leaf.gate.pane = pane end
  end
  local function build( tree, pane, selected )
    if not tree.direction then
      restored_panes = restored_panes + 1
      if tree.active then selected.pane = pane end
      if tree.zoomed then selected.zoomed = pane end
      return
    end
    local horizontal = tree.direction == 'Right'
    local size
    for _, info in ipairs( pane:tab():panes_with_info() ) do
      if info.pane:pane_id() == pane:pane_id() then size = horizontal and info.width or info.height end
    end
    assert( size, 'Cannot determine restored pane size.' )
    local dimension = horizontal and 'width' or 'height'
    local a, b = tree.first[dimension], tree.second[dimension]
    local min_a, min_b = minimum( tree.first, horizontal ), minimum( tree.second, horizontal )
    assert( size >= min_a + min_b + 1, 'Window too small for saved splits.' )
    local split = options( first_leaf( tree.second ) )
    split.direction = tree.direction
    split.size = math.max( min_b, math.min( size - 1 - min_a, math.floor( (size - 1) * b / (a + b) + 0.5 ) ) )
    local other = pane:split( split )
    bind( first_leaf( tree.second ), other )
    build( tree.first,  pane,  selected )
    build( tree.second, other, selected )
  end
  for index, saved in ipairs( snapshot.tabs ) do
    local ok, err = pcall( function ()
      local opts = options( first_leaf( saved.tree ) )
      local tab, pane
      if not target then
        opts.width, opts.height = saved.tree.width, saved.tree.height
        opts.workspace = source_window:active_workspace()
        tab, pane, target = wez.mux.spawn_window( opts )
      else
        tab, pane = target:spawn_tab( opts )
      end
      bind( first_leaf( saved.tree ), pane )
      tab:set_title( saved.title )
      local selected = {}
      build( saved.tree, pane, selected )
      if selected.pane then selected.pane:activate() end
      if selected.zoomed then
        selected.zoomed:activate()
        tab:set_zoomed( true )
      end
      if index == snapshot.active_tab then active_tab = tab end
      restored_tabs = restored_tabs + 1
    end )
    if not ok then table.insert( warnings, 'Tab ' .. index .. ': ' .. tostring( err ) ) end
  end
  if active_tab then active_tab:activate() end
  assert( target, 'No tabs could be restored.\n' .. table.concat( warnings, '\n' ) )
  context.done = function () done( restored_tabs, restored_panes, warnings, target:gui_window() ) end
  context.constructed = true
  for _, gate in ipairs( context.gates ) do
    if not gate.pane then
      waiting[gate.token] = nil
      gate.finished = true
      context.remaining = context.remaining - 1
    end
  end
  if context.remaining == 0 then
    context.done()
  else
    for _, gate in ipairs( context.gates ) do release( gate ) end
    wez.time.call_after( 20, function ()
      if context.remaining == 0 then return end
      for _, gate in ipairs( context.gates ) do
        if not gate.finished then
          gate.finished = true
          waiting[gate.token] = nil
          pcall( gate.pane.inject_output, gate.pane,
                 '\r\nHistory restore timed out. Close this pane and retry restore.\r\n' )
          table.insert( warnings, 'History startup timed out; close the waiting pane and retry restore.' )
        end
      end
      context.remaining = 0
      context.done()
    end )
  end
end

local function run( operation, window, pane )
  if busy then
    dialog( window, pane, 'Session busy', 'A session operation is already running.' )
    return
  end
  busy = true
  feedback( window, operation == 'save' and 'Saving session…' or 'Restoring session…', true )
  -- Let the GUI render the progress label before starting storage work.
  wez.time.call_after( 0.1, function ()
    local ok, err = pcall( function ()
      if operation == 'save' then
        local snapshot, count = capture( window )
        storage( 'save', wez.json_encode( snapshot ) )
        feedback( window, string.format( 'Saved %d tabs, %d panes', #snapshot.tabs, count ) )
      else
        local snapshot = wez.json_parse( storage 'load' )
        restore( snapshot, window, function ( tabs, panes, warnings, target )
          busy = false
          local message = string.format( 'Restored %d tabs, %d panes', tabs, panes )
          if #warnings > 0 then message = message .. ' · warnings' end
          feedback( window, message )
          if target then feedback( target, message ) end
          if #warnings > 0 then dialog( window, pane, 'Session restored partially', table.concat( warnings, '\n' ) ) end
        end )
      end
    end )
    if operation == 'save' or not ok then busy = false end
    if not ok then
      feedback( window, 'Session ' .. operation .. ' failed', true )
      dialog( window, pane, 'Session ' .. operation .. ' failed', tostring( err ) )
    end
  end )
end

return {
  mode = mode,
  save = function ( window, pane ) run( 'save', window, pane ) end,
  restore = function ( window, pane ) run( 'restore', window, pane ) end,
  cancel = function ( window ) feedback( window, 'Session cancelled' ) end,
  status = function ( window )
    local message = messages[window:window_id()]
    return message and message.expires >= os.time() and message.text or nil
  end,
  -- Pure functions also exercised by the layout regression tests.
  layout = layout,
  validate = validate,
  plain_text = plain_text,
  bootstrap = bootstrap,
}