repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

hypr/scripts/cycle_clients.lua

Raw
File outline
#!/usr/bin/env lua

local source = debug.getinfo(1, "S").source:gsub("^@", "")
local script_dir = source:match("(.+)/[^/]+$") or "."
local hypr_dir = script_dir:match("(.+)/[^/]+$") or "."
package.path = hypr_dir .. "/?.lua;" .. hypr_dir .. "/?/init.lua;" .. package.path

local common = require("scripts.common")

local function focus(address)
  if not address:match("^0x") then address = "0x" .. address end
  local expr = "hl.dispatch(hl.dsp.focus({ window = " .. string.format("%q", "address:" .. address) .. " }))"
  os.execute("hyprctl -q eval " .. common.shell_quote(expr))
end

local function parse_active()
  return common.read_command("hyprctl activewindow"):match("^Window%s+(%S+)%s+%-%>")
end

local function parse_clients()
  local clients = {}
  local current

  for line in common.read_command("hyprctl clients"):gmatch("[^\n]+") do
    local address, title = line:match("^Window%s+(%S+)%s+%-%>%s+(.+):$")
    if address then
      current = { address = address, title = title, class = "", workspace = 0, mapped = true, hidden = false }
      clients[#clients + 1] = current
    elseif current then
      local key, value = line:match("^%s*([%w_]+):%s*(.*)$")
      if key == "class" then
        current.class = value
      elseif key == "workspace" then
        current.workspace = tonumber(value:match("^(%-?%d+)")) or 0
      elseif key == "mapped" then
        current.mapped = value == "1"
      elseif key == "hidden" then
        current.hidden = value == "1"
      end
    end
  end

  local filtered = {}
  for _, client in ipairs(clients) do
    if client.mapped and not client.hidden then filtered[#filtered + 1] = client end
  end

  table.sort(filtered, function(a, b)
    if a.workspace ~= b.workspace then return a.workspace < b.workspace end
    if a.class ~= b.class then return a.class < b.class end
    if a.title ~= b.title then return a.title < b.title end
    return a.address < b.address
  end)

  return filtered
end

local direction = arg[1] == "prev" and -1 or 1
local clients = parse_clients()
if #clients < 2 then os.exit(0) end

local active = parse_active()
local index = 1

for i, client in ipairs(clients) do
  if client.address == active then
    index = i
    break
  end
end

local next_index = ((index - 1 + direction) % #clients) + 1
focus(clients[next_index].address)