feat(hammerspoon): add app_hider.lua which allows hiding apps on loss of focus

This commit is contained in:
2025-01-13 19:57:57 +00:00
parent 10144dfa16
commit ffe5933b17
2 changed files with 96 additions and 0 deletions

91
hammerspoon/app_hider.lua Normal file
View File

@@ -0,0 +1,91 @@
--- === app_hider ===
---
--- A Hammerspoon module which hides specified applications when they are
--- deactivated (lose focus).
local obj = {}
local autoHideApps = {}
local function shouldAutoHide(appName)
for _, name in ipairs(autoHideApps) do
if appName == name then
return true
end
end
return false
end
local function appWatcherCallback(appName, eventType, appObject)
if eventType == hs.application.watcher.deactivated and shouldAutoHide(appName) then
appObject:hide()
end
end
local appWatcher = hs.application.watcher.new(appWatcherCallback)
obj.started = false
function obj:start()
if obj.started then
return
end
appWatcher:start()
obj.started = true
end
function obj:stop()
if not obj.started then
return
end
appWatcher:stop()
obj.started = false
end
--- app_hider:autoHide(appName)
--- Method
--- Adds an application to the auto-hide list.
---
--- Parameters:
--- * appName - A string with the name of the application to auto-hide.
function obj:autoHide(appName)
if not appName or type(appName) ~= "string" then
print("Error: Invalid app name provided to autoHide.")
return
end
obj:start() -- Ensure the watcher is running
-- Prevent duplicates in the autoHideApps table
for _, name in ipairs(autoHideApps) do
if name == appName then
print("App already in auto-hide list: " .. appName)
return
end
end
table.insert(autoHideApps, appName)
end
--- app_hider:remove(appName)
--- Method
--- Removes an application from the auto-hide list.
---
--- Parameters:
--- * appName - A string with the name of the application to remove from the
--- auto-hide list.
function obj:remove(appName)
for i, name in ipairs(autoHideApps) do
if name == appName then
table.remove(autoHideApps, i)
break
end
end
-- Stop the watcher if the list is empty
if #autoHideApps == 0 and obj.started then
obj:stop()
end
end
return obj

View File

@@ -5,6 +5,7 @@ local obj = {}
--------------------------------------------------------------------------------
local apptoggle = require('app_toggle')
local apphider = require('app_hider')
local function init_hotkeys()
hs.hotkey.bind({ 'cmd', 'alt', 'ctrl' }, 'S', apptoggle.showAppInfo)
@@ -32,6 +33,10 @@ local function init_hotkeys()
{ 'Code - Insiders', '/Applications/Visual Studio Code - Insiders.app' },
{ 'Code', '/Applications/Visual Studio Code.app' }
)
-- Use Ghostty as my primary terminal application.
-- apptoggle:bind({ 'cmd', 'ctrl' }, 'R', { 'Ghostty' })
-- apphider:autoHide('Ghostty') -- auto-hide Ghostty when it loses focus
end
--------------------------------------------------------------------------------