-- last window quit program --
-- Initialize the watcher and menubar
local windowWatcher = nil
local menubar = nil
-- List of apps to exclude from auto-quitting
local excludedApps = {
"Hammerspoon",
"Spotlight",
"Finder" -- It's generally a good idea to exclude Finder as well
}
-- Function to check if an app should be excluded
local function isExcluded(appName)
for _, excludedApp in ipairs(excludedApps) do
if appName == excludedApp then
return true
end
end
return false
end
-- Function to check and quit the application if the last window is closed
local function checkAndQuitApp(window)
local app = window:application()
if not app then return end
local appName = app:name()
-- Don't quit excluded apps
if isExcluded(appName) then return end
-- Check if the application has any windows left
local allWindows = app:allWindows()
-- If there are no windows left, quit the app
if #allWindows == 0 then
-- Delay the quit operation slightly to ensure the window closes first
hs.timer.doAfter(0.1, function()
app:kill()
end)
end
end
-- Function to start the watcher
local function startWatcher()
if windowWatcher then
windowWatcher:stop()
end
windowWatcher = hs.window.filter.new(true)
windowWatcher:subscribe(hs.window.filter.windowDestroyed, checkAndQuitApp)
end
-- Function to create menu
local function createMenu()
local menuItems = {
{title = "Last Window Quit Enabled", checked = true, fn = function() end},
{title = "-"}, -- Separator
{title = "About Last Window Quit", fn = function()
hs.alert.show("Last Window Quit: Quits apps when closing the last window (except excluded apps)")
end},
{title = "-"}, -- Separator
{title = "Quit Menu", fn = function()
if menubar then
menubar:delete()
menubar = nil
end
end}
}
if not menubar then
menubar = hs.menubar.new()
end
menubar:setTitle("LWQ") -- LWQ for "Last Window Quit"
menubar:setMenu(menuItems)
end
-- Function to toggle the menubar
local function toggleMenubar()
if menubar then
menubar:delete()
menubar = nil
hs.alert.show("Last Window Quit menubar removed")
else
createMenu()
hs.alert.show("Last Window Quit menubar restored")
end
end
-- Start the watcher when the script loads
startWatcher()
-- Create the menu initially
createMenu()
-- Bind hotkey to toggle menubar
hs.hotkey.bind({"alt", "shift"}, "Q", toggleMenubar)
-- Log that the script has loaded
print("Last Window Quit script loaded")