Skip to content

Instantly share code, notes, and snippets.

@piyushsoni
Forked from knu/barrier_karabiner.lua
Created October 2, 2022 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piyushsoni/c27d1e1ceb777628e6dd57ffa4dab818 to your computer and use it in GitHub Desktop.
Save piyushsoni/c27d1e1ceb777628e6dd57ffa4dab818 to your computer and use it in GitHub Desktop.
Barrier and Karabiner-Elements integration using Hammerspoon
knu = require("knu") -- https://github.com/knu/hs-knu
-- Switch between Karabiner-Elements profiles as Barrier enters a different host
do
-- Configure Barrier (https://github.com/debauchee/barrier) to output log to ~/Library/Logs/barrier.log
local logFile = os.getenv("HOME") .. "/Library/Logs/barrier.log"
local lineNo = 1
local host = nil
local defaultProfile = "Default profile"
local profileForHost = function (host)
-- Return the name of a profile suitable for host
if host == "PISONI2L" then
return "New profile"
elseif host == "PISONI2ML2" then
return "Default profile"
else
-- This function is not called when switching back to this host,
-- but it's good to fall back to the default profile. (or in
-- case you have another Mac host)
return defaultProfile
end
end
local watcher = hs.pathwatcher.new(
logFile,
function (_files, flagTables)
for _, flagTable in ipairs(flagTables) do
if flagTable.itemCreated or flagTable.itemRemoved or flagTable.itemRenamed then
-- itemRenamed occurs when the log file is rotated
lineNo = 1
break
elseif flagTable.itemModified then
break
end
end
local f = io.popen(knu.utils.shelljoin("tail", "-n+" .. lineNo, logFile))
local profile = nil
for line in f:lines() do
lineNo = lineNo + 1
local m = line:match("%] INFO: switch from \".*\" to \"(.*)\" at ")
if m ~= nil then
host = m
goto continue
end
if line:match("%] INFO: entering screen") ~= nil then
profile = defaultProfile
elseif line:match("%] INFO: leaving screen") ~= nil then
profile = profileForHost(host)
end
::continue::
end
f:close()
if profile ~= nil then
knu.keyboard.switchKarabinerProfile(profile)
end
end
)
knu.runtime.guard(watcher)
watcher:start()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment