Last active
April 26, 2024 17:58
-
-
Save knu/8b3b784100bae2f8088ff09afc7c451b to your computer and use it in GitHub Desktop.
Barrier and Karabiner-Elements integration using Hammerspoon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
local profileForHost = function (host) | |
-- Return the name of a profile suitable for host | |
if host == "your-windows-host-name" then | |
return "Windows" | |
elseif host == "your-linux-host-name" then | |
return "Linux" | |
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