-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathService.qml
More file actions
603 lines (512 loc) · 20 KB
/
Copy pathService.qml
File metadata and controls
603 lines (512 loc) · 20 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Wayland
import Quickshell.Hyprland
// Shared state for the bar popup and the full overlay. Both show the same
// binds, so the sources are read once here rather than once per surface.
//
// Hyprland's binds come live from `hyprctl binds -j` and Neovim's from a
// headless keymap dump; the rest are hand-copied defaults in data/*.json.
// Nothing outside Hyprland, Quickshell, coreutils, and an optional nvim is needed.
Item {
id: root
visible: false
width: 0
height: 0
property var shell: null
property var manifest: null
property var pluginRegistry: null
readonly property string pluginDir: Quickshell.env("HOME") + "/.config/omarchy/plugins/harbefas.keybinds"
// Flattens a tab into the {section, keys, action} rows both surfaces render.
function flatRows(tab) {
if (!tab) return []
var out = []
for (var s = 0; s < tab.sections.length; s++) {
var section = tab.sections[s]
for (var b = 0; b < section.binds.length; b++) {
out.push({
section: section.name,
keys: section.binds[b].keys,
action: section.binds[b].action
})
}
}
return out
}
// Surfaces call this when they open, so a refresh costs nothing while idle.
function refresh() {
root.refreshHyprland()
root.loadNeovim()
}
// Every tab: { app, aliases: [], windowClass: [], binaries: [], sections: [] }.
// Hyprland and Neovim are placeheld at fixed indices so their async loads
// can drop straight into place without reshuffling the strip.
property var allTabs: []
// A tab declaring `binaries` is only shown when one of them is on PATH, so
// installing the plugin does not hand you a reference to somebody else's
// tools. Tabs with no `binaries` (Hyprland, Neovim) always show.
property var installedBinaries: null
readonly property var tabs: {
if (root.installedBinaries === null) return root.allTabs
return root.allTabs.filter(function (tab) {
var needed = tab.binaries || []
if (needed.length === 0) return true
return needed.some(function (b) { return root.installedBinaries[b] === true })
})
}
// ------------------------------------------------------------- onboarding
// Nothing writes to the user's Hyprland config, so a fresh install has no
// shortcut. Both surfaces offer one until a binding referencing this plugin
// shows up, at which point the hint retires itself.
readonly property string suggestedKey: "SUPER + SHIFT + H"
readonly property string suggestedBind:
'o.bind("' + root.suggestedKey + '", "Keybinds", "omarchy-shell harbefas.keybinds.widget toggle")'
property bool keybindConfigured: false
// The files are read asynchronously, so a surface opening right after a
// shell restart would otherwise see "no keybind" and suggest one to someone
// who already has it. Wait until both have been accounted for.
property int bindingsScanned: 0
readonly property bool bindingsReady: root.bindingsScanned >= 2
function noteBindings(text) {
if (String(text || "").indexOf("harbefas.keybinds") >= 0) root.keybindConfigured = true
root.bindingsScanned += 1
}
FileView {
path: Quickshell.env("HOME") + "/.config/hypr/bindings.lua"
watchChanges: true
onLoaded: root.noteBindings(text())
onLoadFailed: root.bindingsScanned += 1
}
// Pre-Quattro setups still keep their bindings here.
FileView {
path: Quickshell.env("HOME") + "/.config/hypr/bindings.conf"
watchChanges: true
onLoaded: root.noteBindings(text())
onLoadFailed: root.bindingsScanned += 1
}
// ------------------------------------------------------------------- ipc
// The bar widget registers itself here so the popup can be driven from a
// keybind or a script, the same way the overlay is summoned.
property var widget: null
function openWidget() {
if (!root.widget) return false
root.widget.openPopup()
return true
}
function closeWidget() {
if (!root.widget) return false
root.widget.closePopup()
return true
}
function isWidgetOpen() {
return !!(root.widget && root.widget.popupOpen)
}
IpcHandler {
target: "harbefas.keybinds.widget"
function open(): string {
return root.openWidget() ? "opened" : "unavailable"
}
function close(): string {
return root.closeWidget() ? "closed" : "unavailable"
}
function toggle(): string {
return root.isWidgetOpen()
? (root.closeWidget() ? "closed" : "unavailable")
: (root.openWidget() ? "opened" : "unavailable")
}
}
// --------------------------------------------------------------- untrusted
// Binds reach us from the compositor, from a headless Neovim dump written by
// whatever plugins the user has installed, and from process names — none of
// it under our control. Bound the length and drop control characters here,
// and render every one of these strings as PlainText, so a hostile value
// cannot smuggle markup into the long-lived shell UI.
readonly property int maxFieldLength: 200
function clean(value, limit) {
var text = String(value === undefined || value === null ? "" : value)
// Strip C0/C7 control characters, including the ESC that starts an
// terminal escape sequence, plus the Unicode line/paragraph separators.
text = text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ")
text = text.replace(/\s+/g, " ").replace(/^ | $/g, "")
var max = limit || root.maxFieldLength
return text.length > max ? text.slice(0, max) + "…" : text
}
function cleanSections(sections) {
var out = []
for (var s = 0; s < sections.length; s++) {
var binds = sections[s].binds || []
var cleanBinds = []
for (var b = 0; b < binds.length; b++) {
var keys = root.clean(binds[b].keys, 80)
var action = root.clean(binds[b].action)
if (!keys && !action) continue
cleanBinds.push({ keys: keys, action: action })
}
if (cleanBinds.length === 0) continue
out.push({ name: root.clean(sections[s].name, 60), binds: cleanBinds })
}
return out
}
// ------------------------------------------------------------------- tabs
function tabIndexByApp(app) {
for (var i = 0; i < root.tabs.length; i++)
if (root.tabs[i].app === app) return i
return -1
}
// Replaces a tab in place when its async source resolves, or appends it
// keeping `order` (lower first) so the strip does not jump around.
function upsertTab(tab, order) {
tab.app = root.clean(tab.app, 40)
tab.sections = root.cleanSections(tab.sections || [])
if (!tab.app) return
var next = root.allTabs.slice()
var at = -1
for (var i = 0; i < next.length; i++)
if (next[i].app === tab.app) { at = i; break }
tab.order = order
if (at >= 0) next[at] = tab
else next.push(tab)
next.sort(function (a, b) { return a.order - b.order })
root.allTabs = next
}
// The overlay takes keyboard focus as a layer surface, not a toplevel, so
// the active toplevel is still whatever the user was in. No env-var handoff
// needed, unlike the terminal build.
function guessAppForFocus() {
var fallback = root.tabs.length > 0 ? root.tabs[0].app : ""
var toplevel = null
try { toplevel = ToplevelManager.activeToplevel } catch (e) { toplevel = null }
if (!toplevel) return fallback
var appId = (toplevel.appId || "").toLowerCase()
if (!appId) return fallback
for (var i = 0; i < root.tabs.length; i++) {
var classes = root.tabs[i].windowClass || []
for (var c = 0; c < classes.length; c++)
if (appId.indexOf(classes[c].toLowerCase()) >= 0) return root.tabs[i].app
}
if (!["ghostty", "com.mitchellh.ghostty", "kitty", "alacritty", "foot"].some(function (t) {
return appId.indexOf(t) >= 0
})) return fallback
// A terminal window does not say which TUI is running inside it. The title
// usually does — scratchpad launchers and most TUIs set it — so try that
// before paying for a process-tree walk.
var title = (toplevel.title || "").toLowerCase()
for (var name in root.terminalApps) {
if (title.indexOf(name) >= 0 && root.tabIndexByApp(root.terminalApps[name]) >= 0)
return root.terminalApps[name]
}
// Otherwise ask the process tree; the answer arrives async and re-selects.
activeWindowProbe.running = true
return fallback
}
// ------------------------------------------------------- static data files
readonly property var staticSlugs: [
"tridactyl", "spotify_player", "lazygit", "yazi", "glow", "tuicr"
]
function loadStaticTab(raw, order) {
var parsed = null
try { parsed = JSON.parse(raw) } catch (e) { return }
if (parsed && parsed.app) root.upsertTab(parsed, order)
}
readonly property var candidateBinaries: [
"herdr", "spotify_player", "lazygit", "yazi", "glow", "tuicr",
"librewolf", "firefox", "zen-browser", "floorp"
]
function recordInstalled(paths) {
var found = {}
var lines = String(paths || "").split("\n")
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim()
if (!line) continue
found[line.split("/").pop()] = true
}
root.installedBinaries = found
}
Process {
running: true
command: ["which"].concat(root.candidateBinaries)
stdout: StdioCollector { onStreamFinished: root.recordInstalled(text) }
}
Instantiator {
model: root.staticSlugs
delegate: FileView {
required property string modelData
required property int index
path: root.pluginDir + "/data/" + modelData + ".json"
// Hyprland is 0 and Herdr 1; static tables follow, Neovim last.
onLoaded: root.loadStaticTab(text(), 2 + index)
}
}
// ------------------------------------------------------------------ herdr
// Defaults ship in data/herdr.json; ~/.config/herdr/config.toml's [keys]
// table overrides individual binds, so it is merged on top when present.
property var herdrDefaults: null
property var herdrOverrides: ({})
function actionId(action) {
return action.toLowerCase().replace(/ /g, "_")
}
function rebuildHerdr() {
if (!root.herdrDefaults) return
var tab = JSON.parse(JSON.stringify(root.herdrDefaults))
for (var s = 0; s < tab.sections.length; s++) {
var binds = tab.sections[s].binds
for (var b = 0; b < binds.length; b++) {
var override = root.herdrOverrides[actionId(binds[b].action)]
if (override) binds[b].keys = override
}
}
root.upsertTab(tab, 1)
}
// Small [keys] reader — `key = "value"` or `key = ["alt", "alt"]`; quoted
// substrings cover both without pulling in a TOML parser.
function parseHerdrKeys(content) {
var out = {}
var inKeys = false
var lines = content.split("\n")
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim()
if (line.charAt(0) === "[") { inKeys = line === "[keys]"; continue }
if (!inKeys) continue
var eq = line.indexOf("=")
if (eq < 0) continue
var key = line.slice(0, eq).trim()
var quoted = line.slice(eq + 1).split('"').filter(function (_, idx) { return idx % 2 === 1 })
if (quoted.length === 0) continue
out[key] = quoted.map(function (v) {
return v.replace(/prefix/g, "Prefix").replace(/\+/g, " + ")
}).join(" / ")
}
return out
}
FileView {
path: root.pluginDir + "/data/herdr.json"
onLoaded: {
try { root.herdrDefaults = JSON.parse(text()) } catch (e) { return }
root.rebuildHerdr()
}
}
FileView {
path: Quickshell.env("HOME") + "/.config/herdr/config.toml"
watchChanges: true
onLoaded: {
root.herdrOverrides = root.parseHerdrKeys(text())
root.rebuildHerdr()
}
onLoadFailed: root.rebuildHerdr()
}
// --------------------------------------------------------------- hyprland
// `hyprctl binds -j` beats parsing ~/.config/hypr/*.conf: it reports what
// the compositor actually has bound, including binds from any include the
// parser would have to chase, plus the submap each one belongs to.
readonly property var modNames: [
{ mask: 64, name: "SUPER" }, { mask: 4, name: "CTRL" },
{ mask: 8, name: "ALT" }, { mask: 1, name: "SHIFT" }
]
function formatBindKeys(bind) {
var parts = []
for (var i = 0; i < root.modNames.length; i++)
if (bind.modmask & root.modNames[i].mask) parts.push(root.modNames[i].name)
var key = bind.key || (bind.keycode ? "code:" + bind.keycode : "")
if (bind.mouse && !key) key = "mouse"
if (key) parts.push(key)
return parts.join(" + ")
}
function buildHyprlandTab(raw) {
var binds = []
try { binds = JSON.parse(raw) } catch (e) { return }
var bySubmap = {}
var order = []
for (var i = 0; i < binds.length; i++) {
var bind = binds[i]
var keys = formatBindKeys(bind)
if (!keys) continue
var action = bind.description || ""
if (!action) {
action = (bind.dispatcher || "").replace(/^__/, "")
if (bind.arg) action += " " + bind.arg
}
if (!action) continue
var name = bind.submap ? "submap: " + bind.submap : "Global"
if (!bySubmap[name]) { bySubmap[name] = []; order.push(name) }
bySubmap[name].push({ keys: keys, action: action })
}
var sections = order.map(function (name) {
return { name: name, binds: bySubmap[name] }
})
root.upsertTab({
app: "Hyprland",
aliases: ["compositor", "wm", "wayland"],
windowClass: [],
sections: sections
}, 0)
}
function refreshHyprland() {
hyprBinds.running = true
}
Process {
id: hyprBinds
command: ["hyprctl", "binds", "-j"]
stdout: StdioCollector { onStreamFinished: root.buildHyprlandTab(text) }
}
// ----------------------------------------------------------------- neovim
// The dump is read straight off the child's stdout. An earlier version wrote
// it to a fixed path in /tmp, which another local user could pre-create as a
// symlink so this user's Neovim overwrote a file of their choosing — and the
// dump itself, containing the user's mappings, would have been left readable
// on disk. There is no file now.
readonly property string nvimDumpLua:
'local out = {} ' +
'for _, mode in ipairs({"n", "i", "v", "x"}) do ' +
' for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do ' +
' table.insert(out, {mode = mode, lhs = m.lhs, rhs = m.rhs or "", desc = m.desc}) ' +
' end ' +
'end ' +
'io.stdout:write("\\30" .. vim.json.encode(out) .. "\\30") ' +
'io.stdout:flush() ' +
'vim.cmd("qa!")'
// Refuse a dump larger than any real keymap set, rather than parsing whatever
// a wedged child decides to print. The process wrapper lets only this many
// bytes plus one through, so StdioCollector itself never grows unbounded.
readonly property int maxDumpBytes: 4 * 1024 * 1024
readonly property int maxDumpCollectorBytes: maxDumpBytes + 1
property bool nvimLoaded: false
readonly property var nvimModeNames: ({
"n": "Normal", "i": "Insert", "v": "Visual", "x": "Visual (block)"
})
function placeholderNeovimTab(message) {
return {
app: "Neovim",
aliases: ["vim", "editor"],
windowClass: [],
sections: [{ name: "status", binds: [{ keys: "-", action: message }] }]
}
}
function neovimTabFrom(sections) {
root.upsertTab({
app: "Neovim",
aliases: ["vim", "editor"],
windowClass: [],
sections: sections
}, 99)
root.nvimLoaded = true
return true
}
// Headless Neovim prints its own noise, so the payload is fenced in RS
// (0x1e) markers and everything outside them is discarded.
function extractDump(raw, rawBytes) {
if (Number(rawBytes) > root.maxDumpBytes) return ""
var text = String(raw || "")
if (text.length > root.maxDumpBytes) return ""
var first = text.indexOf("\u001e")
var last = text.lastIndexOf("\u001e")
if (first < 0 || last <= first) return ""
return text.slice(first + 1, last)
}
function buildNeovimTab(raw, rawBytes) {
var payload = root.extractDump(raw, rawBytes)
if (!payload) return false
var entries = []
try { entries = JSON.parse(payload) } catch (e) { return false }
if (!entries.length) return false
var byMode = {}
var order = []
for (var i = 0; i < entries.length; i++) {
var entry = entries[i]
if (!entry.lhs || !entry.lhs.trim()) continue
var mode = root.nvimModeNames[entry.mode] || entry.mode
var action = entry.desc || entry.rhs || "<cmd lua>"
if (!byMode[mode]) { byMode[mode] = []; order.push(mode) }
byMode[mode].push({ keys: entry.lhs, action: action })
}
if (order.length === 0) return false
order.sort()
return root.neovimTabFrom(order.map(function (mode) {
return { name: mode, binds: byMode[mode] }
}))
}
// The tab is placeheld until the dump lands; the service outlives every
// surface, so this is paid once per shell session rather than per open.
property bool nvimDumpedThisSession: false
function loadNeovim() {
if (root.nvimDumpedThisSession) return
root.nvimDumpedThisSession = true
nvimDump.running = true
}
// The wrapper pipes the noisy child through `head -c max+1`, which puts the
// byte ceiling before the StdioCollector. `timeout` still guards against
// plugins that hang headless startup waiting on a UI that never attaches.
Process {
id: nvimDump
command: [
Quickshell.env("HOME") + "/.config/omarchy/plugins/harbefas.keybinds/bin/nvim-keymap-dump",
String(root.maxDumpCollectorBytes),
root.nvimDumpLua
]
stdout: StdioCollector {
id: nvimDumpStdout
onStreamFinished: {
var rawBytes = nvimDumpStdout.data.byteLength
var overflowed = Number(rawBytes) > root.maxDumpBytes
if (!root.buildNeovimTab(text, rawBytes) && !root.nvimLoaded)
root.upsertTab(root.placeholderNeovimTab(overflowed ? "nvim dump exceeded 4 MiB" : "no keymaps found in the nvim dump"), 99)
}
}
onExited: function (code, status) {
if (!root.nvimLoaded)
root.upsertTab(root.placeholderNeovimTab("failed to run `nvim --headless` (binary in PATH?)"), 99)
}
}
// --------------------------------------------------- terminal focus probe
// Walks the process tree under the focused terminal looking for a TUI whose
// tab we carry, so opening on top of `yazi` lands on the Yazi tab.
readonly property var terminalApps: ({
"nvim": "Neovim", "herdr": "Herdr", "spotify_player": "Spotify",
"lazygit": "Lazygit", "yazi": "Yazi", "glow": "Glow", "tuicr": "Tuicr"
})
property int focusedPid: 0
// Published for the surfaces to watch: the process-tree walk finishes after
// they have already opened on a best guess.
property string detectedApp: ""
function setFocusedPid(raw) {
try { root.focusedPid = JSON.parse(raw).pid || 0 } catch (e) { root.focusedPid = 0 }
if (root.focusedPid) terminalProbe.running = true
}
function resolveTerminalTab(psOutput) {
var focusedPid = root.focusedPid
if (!focusedPid) return
var children = {}
var names = {}
var lines = psOutput.split("\n")
for (var i = 0; i < lines.length; i++) {
var parts = lines[i].trim().split(/\s+/)
if (parts.length < 3) continue
var pid = parseInt(parts[0])
var ppid = parseInt(parts[1])
if (!pid) continue
if (!children[ppid]) children[ppid] = []
children[ppid].push(pid)
names[pid] = root.clean(parts.slice(2).join(" "), 64)
}
var queue = [focusedPid]
while (queue.length) {
var pid = queue.pop()
var app = root.terminalApps[names[pid]]
if (app) {
if (root.tabIndexByApp(app) >= 0) root.detectedApp = app
return
}
if (children[pid]) queue = queue.concat(children[pid])
}
}
Process {
id: activeWindowProbe
command: ["hyprctl", "-j", "activewindow"]
stdout: StdioCollector { onStreamFinished: root.setFocusedPid(text) }
}
Process {
id: terminalProbe
command: ["ps", "-e", "-o", "pid=,ppid=,comm="]
stdout: StdioCollector { onStreamFinished: root.resolveTerminalTab(text) }
}
}