RespectFocus spoon

A hammerspoon that grant focus to focused window/app user had selected not matter what happens aside
 avatar
unknown
lua
6 hours ago
1.6 kB
4
No Index
local switchDelay = 0.5 -- Time window to consider a switch intentional
local lastFocusedWindow = nil
local isUserSwitching = false

-- Detect user-driven switch (keyboard or mouse)
local function markUserSwitch()
    isUserSwitching = true
    hs.timer.doAfter(switchDelay, function()
        isUserSwitching = false
    end)
end

-- Watch for keyboard shortcuts indicating manual switching
local keyEvents = { "cmd", "alt", "ctrl", "shift", "tab" }

local keyEventTap = hs.eventtap.new({ hs.eventtap.event.types.flagsChanged }, function(evt)
    local flags = evt:getFlags()
    for _, key in ipairs(keyEvents) do
        if flags[key] then
            markUserSwitch()
            break
        end
    end
    return false
end)
keyEventTap:start()

-- Watch for mouse clicks as user intent
local mouseEventTap = hs.eventtap.new({ hs.eventtap.event.types.leftMouseDown }, function(evt)
    markUserSwitch()
    return false
end)
mouseEventTap:start()

-- Watch for app focus changes
local appWatcher = hs.application.watcher.new(function(appName, eventType, app)
    if eventType == hs.application.watcher.activated then
        if isUserSwitching then
            lastFocusedWindow = hs.window.focusedWindow()
        elseif lastFocusedWindow and lastFocusedWindow:id() ~= hs.window.focusedWindow():id() then
            -- Focus was stolen, restore last focused window
            hs.timer.doAfter(0.1, function()
                if lastFocusedWindow then
                    lastFocusedWindow:focus()
                end
            end)
        end
    end
end)
appWatcher:start()
Editor is loading...
Leave a Comment