Skip to content

Instantly share code, notes, and snippets.

@josephlim75
Forked from knu/barrier_karabiner.lua
Created April 26, 2021 20:45
Show Gist options
  • Select an option

  • Save josephlim75/4dab8302133914e75a02780968152b51 to your computer and use it in GitHub Desktop.

Select an option

Save josephlim75/4dab8302133914e75a02780968152b51 to your computer and use it in GitHub Desktop.

Revisions

  1. @knu knu created this gist May 14, 2020.
    61 changes: 61 additions & 0 deletions barrier_karabiner.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    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