Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

neovim/lua/std/const.lua

Raw
local executable = require 'std.executable'

local uname = vim.uv.os_uname()
local win32 = uname.sysname:match 'Win' and true or false
local wsl = uname.release:match 'WSL2' and true or false

local cache_path = vim.fn.stdpath('cache') .. '/os_background'
local CACHE_MAX_AGE = 3600

local function read_cache()
  local stat = vim.uv.fs_stat(cache_path)
  if not stat then
    return nil
  end
  if os.time() - stat.mtime.sec > CACHE_MAX_AGE then
    return nil
  end
  local f = io.open(cache_path, 'r')
  if not f then
    return nil
  end
  local cached = f:read('*l')
  f:close()
  if cached == 'dark' or cached == 'light' then
    return cached
  end
  return nil
end

local function write_cache(value)
  local f = io.open(cache_path, 'w')
  if not f then
    return
  end
  f:write(value, '\n')
  f:close()
end

local function query_os_background()
  if win32 or wsl then
    return 'light'
  elseif executable 'busctl' then
    local cmd = {
      'busctl', '--user', '--expect-reply=true', 'call',
      'org.freedesktop.portal.Desktop',
      '/org/freedesktop/portal/desktop',
      'org.freedesktop.portal.Settings',
      'Read', 'ss',
      'org.freedesktop.appearance', 'color-scheme',
    }
    local obj = vim.system(cmd, { text = true, timeout = 2000 })
    local result = obj:wait()
    if result.code ~= 0 then
      return 'dark'
    end
    local output = result.stdout or ''
    local color_scheme = output:match 'u%s+(%d+)'
    if color_scheme == '2' or color_scheme == '0' then
      return 'light'
    else
      return 'dark'
    end
  end
  return 'dark'
end

local os_background = function()
  local override = os.getenv 'NVIM_BACKGROUND'
  if override then
    return override
  end
  local cached = read_cache()
  if cached then
    return cached
  end
  local result = query_os_background()
  write_cache(result)
  return result
end

local function invalidate_os_background()
  os.remove(cache_path)
end

return {
  uname = uname,
  win32 = win32,
  wsl = wsl,
  os_background = os_background(),
  invalidate_os_background = invalidate_os_background,
}