Repository navigation
Expand file tree
/
Copy pathinit.lua
More file actions
331 lines (308 loc) · 14.5 KB
/
Copy pathinit.lua
File metadata and controls
331 lines (308 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
--- === WindowSwitcher ===
---
--- Windows-style Alt+Tab for macOS: Cmd+Tab switches between windows on a native Liquid Glass panel.
---
--- It switches *windows*, not apps, so two windows of the same app are separate entries.
--- The panel is a real `NSGlassEffectView` (macOS 26+), not an imitation.
---
--- Keys:
--- * Cmd+Tab - next window (the first press selects the previously used window)
--- * Cmd+Shift+Tab - previous window
--- * release Cmd - switch to the selected window
--- * Esc - cancel
---
--- A quick Cmd+Tab tap switches straight back to the previous window without showing the panel.
--- Each cell shows a thumbnail of its window, as you last left it (turn off with `WindowSwitcher.preview = 0`).
---
--- How it works: this file does all the logic (key interception, window list, focusing).
--- `glass.swift` only draws the panel. It is compiled to `glass` on first start
--- (needs Xcode Command Line Tools), runs in the background, and takes one JSON command per line on stdin.
---
--- Install with SpoonInstall (see README), or `git clone https://github.com/ZachariahJ/WindowSwitcher.spoon ~/.hammerspoon/Spoons/WindowSwitcher.spoon`
---
--- Download: [https://github.com/ZachariahJ/WindowSwitcher.spoon/raw/main/Spoons/WindowSwitcher.spoon.zip](https://github.com/ZachariahJ/WindowSwitcher.spoon/raw/main/Spoons/WindowSwitcher.spoon.zip)
-- Usage (in ~/.hammerspoon/init.lua):
-- hs.loadSpoon("WindowSwitcher")
-- spoon.WindowSwitcher:start()
--
-- Example: temporarily get the system Cmd+Tab back → run spoon.WindowSwitcher:stop() in the Console,
-- and spoon.WindowSwitcher:start() to turn it on again
local types = hs.eventtap.event.types
local TAB = hs.keycodes.map.tab
local ESC = hs.keycodes.map.escape
-- Spoon metadata
local obj = {}
obj.__index = obj
obj.name = "WindowSwitcher"
obj.version = "1.2.1"
obj.author = "ZachariahJ"
obj.homepage = "https://github.com/ZachariahJ/WindowSwitcher.spoon"
obj.license = "MIT - https://opensource.org/licenses/MIT"
-- Settings
--- WindowSwitcher.delay
--- Variable
--- Seconds Cmd+Tab must be held before the panel appears. Default `0.12`.
--- A tap shorter than this switches to the previous window without showing the panel.
---
--- Notes:
--- * Example: show the panel immediately → `spoon.WindowSwitcher.delay = 0` before `:start()`
obj.delay = 0.12
--- WindowSwitcher.preview
--- Variable
--- `1` shows a thumbnail of each window in the panel, `0` shows just app icons. Default `1`.
---
--- Notes:
--- * Thumbnails come from a cache, so the panel shows them instantly: pressing Cmd+Tab captures the
--- current window, any window is captured when it loses focus (mouse click, Dock...), and all windows on
--- the current Space at start and every 300 s. They are kept in memory only.
--- * Needs Screen Recording permission for Hammerspoon (System Settings → Privacy & Security → Screen Recording).
--- Without it, or for a window not captured yet, the cell shows the app icon instead.
--- * Example: icons only, like before → `spoon.WindowSwitcher.preview = 0` before `:start()`
--- * Example: change it later → change the value and reload (capturing is set up in `:start()`)
obj.preview = 1
-- Paths inside this Spoon's folder. glass and glass.sha256 are build outputs (not shipped).
local SRC = hs.spoons.resourcePath("glass.swift")
local BIN = hs.spoons.resourcePath("glass")
local STAMP = hs.spoons.resourcePath("glass.sha256")
-- Which windows to list: normal windows on the current Space, most recently used first.
-- AXDialog is let in here only for minimized windows: some apps (Microsoft Word) report a minimized
-- window as AXDialog instead of AXStandardWindow. step() then drops dialogs that aren't minimized.
-- Check a window's role in the Console: hs.window.focusedWindow():subrole()
--
-- Example: list windows from all Spaces (picking one jumps to its Space) → change
-- setCurrentSpace(true) to setCurrentSpace(nil)
-- Example: hide an app → append :rejectApp("Finder")
-- Example: also list dialogs (preferences windows, pop-ups) → change allowRoles to "*" and, in step(),
-- change `elseif win:subrole() == "AXStandardWindow" then` to `else`
-- (this also lets in things like the Teams notification center or Zoom's floating button)
local wf = hs.window.filter.new():setCurrentSpace(true):setDefaultFilter{ allowRoles = {"AXStandardWindow", "AXDialog"} }
-- Build glass
-- Recompile when glass is missing or glass.swift changed. Changes are detected by content hash
-- rather than modification time, because unzipping an update can leave the source "older" than the old binary.
-- Hammerspoon freezes for a few seconds while compiling; this only happens on first run or after an update.
local function readFile(path)
local f = io.open(path, "r")
if not f then return nil end
local s = f:read("a")
f:close()
return s
end
local function build()
local hash = hs.hash.SHA256(readFile(SRC))
if hs.fs.attributes(BIN) and readFile(STAMP) == hash then return true end
local out, ok = hs.execute(string.format('/usr/bin/swiftc -O "%s" -o "%s" 2>&1', SRC, BIN))
if not ok then
hs.alert.show("WindowSwitcher: failed to compile glass.swift\n"
.. "Needs Xcode Command Line Tools (xcode-select --install). See Console.")
print(out)
return false
end
local f = io.open(STAMP, "w")
f:write(hash)
f:close()
return true
end
-- Talk to glass
-- One JSON object per line on its stdin, e.g. {"cmd":"select","sel":2}
-- hs.task:setInput writes later and keeps only one pending write (a second call drops the first,
-- e.g. "hide" then "snap" lost the hide). So lines are queued and written in one batch, and the next batch
-- waits until glass has read every line of the last (it answers each with {"event":"read"}, see onOutput).
local queue, unread = {}, 0 -- lines waiting / lines written but not yet read by glass
local function flush()
if unread > 0 or #queue == 0 or not (obj.task and obj.task:isRunning()) then return end
unread = #queue
obj.task:setInput(table.concat(queue))
queue = {}
end
local function send(t) queue[#queue + 1] = hs.json.encode(t) .. "\n"; flush() end
-- Thumbnail cache
-- glass keeps the thumbnails in memory; this part decides when to capture, by sending
-- {"cmd":"snap","wids":[...]} (window IDs). Only when obj.preview == 1 (set up in :start()).
-- · Cmd+Tab pressed → capture the current window (in step(), so its cell is up to date)
-- · a window loses focus → capture it (covers leaving by mouse click, Dock, etc.; after a Cmd+Tab
-- switch this captures the same window a second time, a few ms of CPU, not worth special-casing)
-- · at start, then every REFRESH seconds → capture every window on the current Space
-- (catches windows not captured yet, and ones that changed in the background)
--
-- Example: refresh every minute → REFRESH = 60 (a round of 10 windows takes a few ms of CPU)
-- Example: no periodic refresh → delete the `self.sweep` line in :start()
-- Example: only on Cmd+Tab, not on losing focus → delete the wf:subscribe line in :start()
local REFRESH = 300
local function snap(wins)
local ids = {}
for i, win in ipairs(wins) do ids[i] = win:id() end
if #ids > 0 then send({ cmd = "snap", wids = ids }) end
end
local function onUnfocus(win) snap({ win }) end
local function snapAll() snap(wf:getWindows()) end
-- State
obj.windows = nil -- window list while switching; nil when not switching
obj.index = nil -- selected window (Lua index, starts at 1; glass gets index - 1)
obj.timer = nil -- delay before showing the panel
obj.shown = false -- whether glass is currently showing the panel
-- step(dir): move the selection by dir (+1 / -1)
-- First call: grab the window list and start the delay timer; when it fires, send "show".
-- Every call: move the selection, wrapping around; if the panel is visible, send "select".
--
-- The panel goes on the screen under the mouse; glass gets that screen's display ID.
-- Each item also carries the window's ID (wid, a CGWindowID) so glass can capture its thumbnail;
-- preview = true/false comes from obj.preview (1 / 0).
--
-- Example: preview only when there are few windows (big lists get icons) → change the preview line to
-- preview = obj.preview == 1 and #obj.windows <= 8,
-- Example: show something else for untitled windows (e.g. "(untitled)") → change app:name() in the title line
-- Example: show on the focused window's screen instead → change the screen line to
-- local focused = hs.window.focusedWindow()
-- local screen = focused and focused:screen() or hs.mouse.getCurrentScreen()
-- Example: always show on the primary display (the one with the menu bar) → change the screen line to
-- local screen = hs.screen.primaryScreen()
local function step(dir)
if not obj.windows then
-- Minimized windows go to the end of the list; each group keeps its most-recently-used order.
-- Dialogs that aren't minimized are dropped (see the window filter above for why they get this far).
-- Example: also move hidden windows (Cmd+H) to the end → change win:isMinimized() to not win:isVisible()
-- Example: plain MRU order, minimized windows mixed in → change `table.insert(minimized, win)`
-- to `table.insert(windows, win)`
local windows, minimized = {}, {}
for _, win in ipairs(wf:getWindows(hs.window.filter.sortByFocusedLast)) do
if win:isMinimized() then
table.insert(minimized, win)
elseif win:subrole() == "AXStandardWindow" then
table.insert(windows, win)
end
end
table.move(minimized, 1, #minimized, #windows + 1, windows)
obj.windows = windows
if #obj.windows == 0 then obj.windows = nil return end
obj.index = 1
if obj.preview == 1 then snap({ obj.windows[1] }) end -- the current window, as you leave it
obj.timer = hs.timer.doAfter(obj.delay, function()
local items = {}
for i, win in ipairs(obj.windows) do
local app = win:application()
local title = win:title() or ""
if title == "" and app then title = app:name() end
items[i] = { id = app and app:bundleID() or "", title = title, wid = win:id() }
end
local screen = hs.mouse.getCurrentScreen()
send({ cmd = "show", sel = obj.index - 1, screen = screen and screen:id(), items = items,
preview = obj.preview == 1 })
obj.shown = true
end)
end
obj.index = (obj.index - 1 + dir) % #obj.windows + 1
if obj.shown then send({ cmd = "select", sel = obj.index - 1 }) end
end
-- finish(focus): stop switching
-- Stop the timer, hide the panel, and if focus is true, focus the selected window.
local function finish(focus)
if obj.timer then obj.timer:stop() end
if obj.shown then send({ cmd = "hide" }) end
local win = focus and obj.windows[obj.index]
obj.windows, obj.index, obj.timer, obj.shown = nil, nil, nil, false
if win then win:focus() end
end
-- Mouse
-- glass prints {"event":"click","sel":N} on stdout when a cell is clicked (sel starts at 0);
-- that switches to the window, like releasing Cmd on it. The hover box is drawn by glass alone.
--
-- Example: a click only moves the selection (releasing Cmd switches) → replace the two lines in the if with
-- obj.index = m.sel + 1; send({ cmd = "select", sel = m.sel })
-- glass also prints {"event":"read"} for every line it reads (see "Talk to glass").
local function onOutput(_, out)
for line in (out or ""):gmatch("[^\n]+") do
local ok, m = pcall(hs.json.decode, line)
if ok and type(m) == "table" and m.event == "read" then
unread = unread - 1
flush()
elseif ok and type(m) == "table" and m.event == "click" and obj.windows and obj.windows[m.sel + 1] then
obj.index = m.sel + 1
finish(true)
end
end
return true
end
-- Key interception
-- macOS reserves Cmd+Tab, so hs.hotkey can't bind it; an eventtap can.
-- Cmd+Tab / Cmd+Shift+Tab → step(±1) and swallow the key (the system switcher never appears)
-- Esc while switching → cancel
-- Cmd released while switching → switch
-- anything else → passed through
--
-- Example: use Alt+Tab instead → swap f.cmd and f.alt below (in both branches)
-- Example: arrow keys move the selection while the panel is open → add before the Esc check:
-- if obj.windows and key == hs.keycodes.map.left then step(-1) return true end
-- if obj.windows and key == hs.keycodes.map.right then step(1) return true end
-- Example: W closes the selected window → add:
-- if obj.windows and key == hs.keycodes.map.w then obj.windows[obj.index]:close(); finish(false) return true end
obj.tap = hs.eventtap.new({ types.keyDown, types.flagsChanged }, function(e)
local f = e:getFlags()
if e:getType() == types.flagsChanged then
if obj.windows and not f.cmd then finish(true) end
return false
end
local key = e:getKeyCode()
if key == TAB and f.cmd and not f.alt and not f.ctrl then
step(f.shift and -1 or 1)
return true
end
if obj.windows and key == ESC then
finish(false)
return true
end
return false
end)
-- start / stop
--- WindowSwitcher:start()
--- Method
--- Compiles the panel helper if needed, launches it, and starts intercepting Cmd+Tab.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The WindowSwitcher object
---
--- Notes:
--- * Requires macOS 26 or later (Liquid Glass) and Xcode Command Line Tools (to compile `glass.swift`).
function obj:start()
if hs.host.operatingSystemVersion().major < 26 then
hs.alert.show("WindowSwitcher needs macOS 26 or later")
return self
end
if not build() then return self end
queue, unread = {}, 0 -- fresh glass process: nothing pending
-- The third argument (a streaming callback) is required: without it, hs.task closes
-- stdin after the first write, and glass exits on EOF. It also receives glass's stdout (clicks).
self.task = hs.task.new(BIN, function(code)
print("WindowSwitcher: glass exited, code = " .. tostring(code))
end, onOutput)
self.task:start()
self.tap:start()
if self.preview == 1 then
wf:subscribe(hs.window.filter.windowUnfocused, onUnfocus)
self.sweep = hs.timer.doEvery(REFRESH, snapAll)
snapAll()
end
return self
end
--- WindowSwitcher:stop()
--- Method
--- Stops intercepting Cmd+Tab (the system app switcher comes back) and quits the panel helper.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The WindowSwitcher object
function obj:stop()
self.tap:stop()
wf:unsubscribe(onUnfocus)
if self.sweep then self.sweep:stop() end
self.sweep = nil
if self.windows then finish(false) end
if self.task then self.task:terminate() end
self.task = nil
return self
end
return obj