Skip to content

Instantly share code, notes, and snippets.

@wych42
Created August 4, 2021 05:41
Show Gist options
  • Save wych42/05b8c321da4090140da2e06ada43cbda to your computer and use it in GitHub Desktop.
Save wych42/05b8c321da4090140da2e06ada43cbda to your computer and use it in GitHub Desktop.
-- DISPLAY FOCUS SWITCHING [[[2
-- Copy&Modified from: http://bezhermoso.github.io/2016/01/20/making-perfect-ramen-lua-os-x-automation-with-hammerspoon/
--One hotkey should just suffice for dual-display setups as it will naturally
--cycle through both.
--A second hotkey to reverse the direction of the focus-shift would be handy
--for setups with 3 or more displays.
--Bring focus to next display/screen
local application = require "hs.application"
hs.hotkey.bind({"alt"}, "`", function ()
focusScreen(hs.window.focusedWindow():screen():next())
end)
--Bring focus to previous display/screen
hs.hotkey.bind({"alt", "shift"}, "`", function()
focusScreen(hs.window.focusedWindow():screen():previous())
end)
--Predicate that checks if a window belongs to a screen
function isInScreen(screen, win)
return win:screen() == screen
end
-- Brings focus to the scren by setting focus on the front-most application in it.
-- Also move the mouse cursor to the center of the screen. This is because
-- Mission Control gestures & keyboard shortcuts are anchored, oddly, on where the
-- mouse is focused.
function focusScreen(screen)
--Get windows within screen, ordered from front to back.
--If no windows exist, bring focus to desktop. Otherwise, set focus on
--front-most application window.
local windows = hs.fnutils.filter(
hs.window.orderedWindows(),
hs.fnutils.partial(isInScreen, screen))
local windowToFocus = #windows > 0 and windows[1] or hs.window.desktop()
windowToFocus:focus()
-- Move mouse to center of screen
local pt = hs.geometry.rectMidPoint(screen:fullFrame())
hs.mouse.setAbsolutePosition(pt)
end
-- END DISPLAY FOCUS SWITCHING --
-- 2]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment