Hammerspoon / hammerspoon

Staggeringly powerful macOS desktop automation with Lua

Home Page:http://www.hammerspoon.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: `:keydown` callback for `hs.chooser`

hacker-DOM opened this issue · comments

commented

Hi! I was going to build a little Spoon that allows me to close windows. ChatGPT gave me

Code
-- Function to get a list of visible windows for user applications
function getVisibleWindows()
    local windows = {}
    local allWindows = hs.window.allWindows()
    for _, window in ipairs(allWindows) do
        if window:application():kind() == 1 and window:isVisible() then -- Only list windows of user applications that are visible
            table.insert(windows, {text = window:title(), windowObj = window})
        end
    end
    return windows
end

-- Function to close the window
function closeWindow(window)
    if window then
        window:close()
    end
end

-- Function to quit the application of the window
function quitAppOfWindow(window)
    if window then
        window:application():kill()
    end
end

-- Create the chooser
windowChooser = hs.chooser.new(function(choice)
    if not choice then return end
    -- Placeholder for action, actual action is handled in keydown event
end)

-- Set the choices
windowChooser:choices(getVisibleWindows)

-- Handle keydown event for the chooser
windowChooser:keydown(function(chooser, event)
    local choice = chooser:selectedRowContents()
    if event:getCharacters() == "w" and event:getFlags().cmd then
        closeWindow(choice.windowObj)
        chooser:refreshChoicesCallback() -- Refresh the list of windows
    elseif event:getCharacters() == "q" and event:getFlags().cmd then
        quitAppOfWindow(choice.windowObj)
        chooser:refreshChoicesCallback() -- Refresh the list of windows
    end
end)

-- Show the window chooser
hs.hotkey.bind({"cmd"}, "E", function() windowChooser:show() end)

I was surprised that hs.chooser does not allow you to act on key down presses (:keydown in the code). Could this be added to hs.chooser?