Repository navigation
Expand file tree
/
Copy pathService.qml
More file actions
1678 lines (1538 loc) · 66.1 KB
/
Copy pathService.qml
File metadata and controls
1678 lines (1538 loc) · 66.1 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import QtQuick
import Quickshell
import Quickshell.Hyprland
import Quickshell.Io
import "ReprieveModel.js" as Model
// Reprieve service: parks Super+W closes onto a hidden special workspace
// instead of killing the process, and remembers enough to bring them back
// after the shell restarts. Never listens to key events and never binds
// Ctrl+Z.
Item {
id: root
visible: false
property var shell: null
property var manifest: null
readonly property string pluginId: (manifest && manifest.id) ? String(manifest.id) : Model.PLUGIN_ID
// Omarchy strips __sourceDir from third-party manifests; fall back to the
// directory this file was loaded from.
readonly property string pluginDir: {
if (manifest && manifest.__sourceDir) return String(manifest.__sourceDir)
var url = String(Qt.resolvedUrl("."))
if (url.indexOf("file://") === 0) url = url.slice(7)
return url.replace(/\/+$/, "")
}
readonly property string mediaBin: pluginDir + "/bin/reprieve-media"
readonly property string journalBin: pluginDir + "/bin/reprieve-journal"
readonly property string bindsBin: pluginDir + "/bin/reprieve-binds"
readonly property string parkWorkspace: Model.PARK_WORKSPACE
readonly property int maxStack: Model.clampMax(setting("maxStack", Model.DEFAULT_MAX))
readonly property int parkTimeout: Model.clampParkTimeout(setting("parkTimeout", Model.DEFAULT_PARK_TIMEOUT))
readonly property bool trackAppClose: setting("trackAppClose", true) !== false
readonly property bool pauseMediaOnPark: setting("pauseMediaOnPark", true) !== false
readonly property bool showToast: setting("showToast", true) !== false
readonly property bool setupDismissed: setting("setupDismissed", false) === true
// Park/restore effect: off | subtle | angel (see Model.normalizeFlight).
readonly property string flight: Model.normalizeFlight(setting("flight", Model.DEFAULT_FLIGHT))
readonly property string parkFlight: Model.normalizeFlight(setting("parkFlight", flight))
readonly property string restoreFlight: Model.normalizeFlight(setting("restoreFlight", flight))
// Bar widget preferences (also overridable per layout entry in shell.json).
readonly property bool barTray: setting("barTray", true) !== false
readonly property int barMaxIcons: Math.max(1, Math.min(10, Math.floor(Number(setting("barMaxIcons", 5)) || 5)))
// The mark stays in the bar at all times so the safety net is visible
// even when idle; users can still fade it with hideBarWhenIdle.
readonly property bool hideBarWhenIdle: setting("hideBarWhenIdle", false) !== false
readonly property string home: Quickshell.env("HOME") || ""
readonly property string stateHome: Quickshell.env("XDG_STATE_HOME") || (home + "/.local/state")
readonly property string stateDir: stateHome + "/reprieve"
readonly property string configHome: Quickshell.env("XDG_CONFIG_HOME") || (home + "/.config")
readonly property string shellConfigPath: configHome + "/omarchy/shell.json"
// Our plugins[] entry from shell.json. The third-party shell API exposes
// no read surface for it, so it is read (never written) from disk.
property var settingsEntry: ({})
property string entryLocation: ""
readonly property bool showInBar: setting("showInBar", true) !== false
readonly property string session: Quickshell.env("HYPRLAND_INSTANCE_SIGNATURE") || ""
property var model: Model.createState({ max: maxStack, parkTimeout: parkTimeout })
property var snapshots: ({})
property var expected: ({})
property var undoStack: []
property var redoStack: []
property int undoCount: 0
property int redoCount: 0
property int parkedCount: 0
// Live windows on the park workspace that no timeline entry claims.
property int strandedCount: 0
signal windowParked(string address)
// ---- flight: the overlay animates a snapshot of the window into the bar
// mark (and back). The service stays in charge of the actual move: a job
// is handed to the overlay, which calls flightCut(token) at the moment
// the real window should go (park) or arrive (restore). A watchdog cuts
// anyway if the overlay never answers, so a park can never hang.
signal flightPark(var job)
signal flightRestore(var job)
signal flightArrived(string address)
// The overlay registers itself here; without a handler every park and
// restore is a plain cut.
property var flightHandler: null
// Screen-local position of the bar mark, per screen name, published by
// the bar widget. The overlay flies to and from it.
property var barAnchors: ({})
property var pendingFlights: ({})
property int flightSequence: 0
property string lastFlightSkip: ""
property string lastParkRead: ""
property var parkReadQueue: []
property string currentParkRead: ""
function setBarAnchor(screen, x, y, size) {
var name = String(screen || "")
if (!name) return
var anchor = { x: Math.round(Number(x) || 0), y: Math.round(Number(y) || 0), size: Math.round(Number(size) || 0) }
var old = root.barAnchors[name]
// The bar re-publishes after every relayout (each park changes its width);
// an unchanged anchor must not re-evaluate every flight binding.
if (old && old.x === anchor.x && old.y === anchor.y && old.size === anchor.size) return
root.barAnchors = Model.assoc(root.barAnchors, name, anchor)
}
function monitorFor(id) {
try {
var list = Hyprland.monitors ? (Hyprland.monitors.values || []) : []
for (var i = 0; i < list.length; i++) if (list[i] && Number(list[i].id) === Number(id)) return list[i]
} catch (e) {}
return null
}
// A flight job for a live window, or null when neither direction needs
// a frame, nobody draws them, or geometry is unknown. An Off park may
// capture silently for an animated restore. A park reads
// the window's geometry from Hyprland; a restore asks the overlay for the
// place it remembers from the park (the live geometry is the park
// workspace's).
function animationMode(kind) {
return kind === "restore" ? root.restoreFlight : root.parkFlight
}
function flightJob(kind, handle, address, freshIpc) {
var mode = root.animationMode(kind)
// An Off park still captures a frame when restoration needs one.
if ((mode === "off" && (kind === "restore" || root.restoreFlight === "off")) || !root.flightHandler || !handle) return null
var addr = Model.normalizeAddress(address)
var job = { token: "f" + (++root.flightSequence), kind: kind, mode: mode, address: addr, handle: handle }
if (kind === "restore") {
var mem = null
try { mem = root.flightHandler.remembered(addr) } catch (e) {}
if (!mem || !mem.rect || !mem.screen) return null
job.screen = String(mem.screen)
job.rect = mem.rect
return job
}
var ipc = freshIpc || handle.lastIpcObject || {}
var at = ipc.at, size = ipc.size
if (!at || !size || at.length < 2 || size.length < 2) return null
var mon = root.monitorFor(ipc.monitor)
if (!mon || !mon.name) return null
job.screen = String(mon.name)
// Client geometry and monitor positions already use logical pixels.
job.rect = {
x: Math.round(Number(at[0]) - Number(mon.x || 0)),
y: Math.round(Number(at[1]) - Number(mon.y || 0)),
w: Math.max(1, Math.round(Number(size[0]))),
h: Math.max(1, Math.round(Number(size[1])))
}
return job
}
function beginFlight(job, cut) {
root.pendingFlights = Model.assoc(root.pendingFlights, job.token, { job: job, cut: cut, started: Date.now() })
if (job.kind === "park") root.flightPark(job)
else root.flightRestore(job)
}
// Called by the overlay at the cut moment; idempotent.
function flightCut(token) {
var pending = root.pendingFlights[String(token)]
if (!pending) return "unknown"
// The watchdog/settler may run before hyprctl replies. A stale pin
// snapshot is not safe to cut: abandon this unapplied park instead.
if (pending.awaitingRead) {
root.abortParkRead(token)
return "cancelled"
}
root.pendingFlights = Model.dissoc(root.pendingFlights, String(token))
try { pending.cut() } catch (e) { console.warn("reprieve: flight cut failed", e) }
return "ok"
}
// Finish the previous visual and its real-window cut before changing the
// same window again. In particular, an early undo must never leave an old
// park callback able to hide the restored window later.
function settleFlights(address) {
var addr = Model.normalizeAddress(address)
if (!addr) return
try {
if (root.flightHandler && root.flightHandler.finishAddress)
root.flightHandler.finishAddress(addr)
} catch (e) { console.warn("reprieve: settling flight failed", e) }
var tokens = Object.keys(root.pendingFlights)
for (var i = 0; i < tokens.length; i++) {
var pending = root.pendingFlights[tokens[i]]
if (pending && pending.job.address === addr) root.flightCut(tokens[i])
}
}
function flightLanded(address) {
root.flightArrived(Model.normalizeAddress(address))
}
Timer {
id: flightWatchdog
interval: 1500
repeat: true
running: Object.keys(root.pendingFlights).length > 0
onTriggered: {
var now = Date.now()
for (var k in root.pendingFlights) {
if (now - root.pendingFlights[k].started >= 1400) {
console.warn("reprieve: flight", k, "timed out; cutting")
root.flightCut(k)
}
}
}
}
property string lastLabel: ""
property string lastResult: ""
property string recoveryNotice: ""
property bool toastOpen: false
property string toastText: ""
// Journal lifecycle
property string journalStatus: "loading"
property var journalEntries: []
property int journalSequence: 0
property bool journalConsumed: false
property bool journalDirty: false
property string pendingJournalText: ""
property double startedAt: Date.now()
// Bindings / setup
property var bindsStatus: null
property var lastInstallResult: null
property bool setupOffered: false
// Media
property var mediaQueue: []
property string mediaJobKind: ""
property string mediaJobAddress: ""
readonly property bool bindsInstalled: !!(bindsStatus && bindsStatus.installed)
readonly property bool bindsLive: !!(bindsStatus && bindsStatus.live && bindsStatus.live.park)
// Something the bar should point at: setup not done, bindings written but
// not loaded, or windows hidden without an entry. Empty string means all
// is well.
readonly property string attentionReason: {
if (strandedCount > 0) return strandedCount + " hidden window" + (strandedCount === 1 ? "" : "s") + " without a timeline entry — open the timeline to recover"
if (!bindsStatus) return ""
if (!bindsInstalled) return setupDismissed ? "" : "Reprieve is not set up — click to protect Super+W"
if (bindsStatus.hyprland && !bindsLive) return "Bindings are installed but not loaded — run: hyprctl reload"
return ""
}
readonly property bool attention: attentionReason !== ""
onMaxStackChanged: {
if (!root.model) return
var next = Model.cloneState(root.model)
next.max = maxStack
root.model = next
root.publish()
}
onParkTimeoutChanged: {
if (!root.model) return
// The model still holds the previous value: a 0 -> positive transition
// means the user just enabled the timeout. Grant every parked window a
// full timeout from now instead of expiring it on the spot for age
// accrued while the timeout was off. Tightening an active timeout
// keeps the original park times, so it can expire immediately.
var was = Model.clampParkTimeout(root.model.parkTimeout)
var nextTimeout = Model.cloneState(root.model)
nextTimeout.parkTimeout = parkTimeout
if (was <= 0 && parkTimeout > 0)
nextTimeout = Model.restampParked(nextTimeout, Date.now())
root.model = nextTimeout
root.publish()
// shell.json owns the setting, but newly granted park timestamps must
// survive a shell reload as well as the in-memory grace interval.
if (was <= 0 && parkTimeout > 0) root.persist()
if (parkTimeout > 0) root.sweepExpired()
}
// ---------------------------------------------------------------- settings
// Our entry may sit in bar.layout.<section> (a placed bar widget) or in
// plugins[] (service-only). The bar entry wins, matching updateEntryInline.
function reloadSettings() {
var found = {}
var where = ""
var cfg
try {
cfg = JSON.parse(String(shellConfigFile.text() || "{}").slice(0, 1048576) || "{}")
} catch (e) {
// A truncated read (mid-write) must not reset every setting to its
// default: keep the last good entry until the file parses again.
return
}
try {
var sections = ["left", "center", "right"]
var layout = cfg && cfg.bar && cfg.bar.layout ? cfg.bar.layout : {}
for (var s = 0; s < sections.length && !where; s++) {
var arr = Array.isArray(layout[sections[s]]) ? layout[sections[s]] : []
for (var i = 0; i < arr.length; i++) {
if (arr[i] && arr[i].id === root.pluginId) { found = Object.assign({}, arr[i]); where = "bar"; break }
}
}
var plugins = cfg && Array.isArray(cfg.plugins) ? cfg.plugins : []
for (var j = 0; j < plugins.length && !where; j++) {
if (plugins[j] && plugins[j].id === root.pluginId) { found = Object.assign({}, plugins[j]); where = "plugins" }
}
} catch (e) {}
root.settingsEntry = found
root.entryLocation = where
}
// Settings the CLI/bar may change at runtime. Anything else is refused.
function setSetting(name, rawValue) {
var allowed = {
showToast: "bool", pauseMediaOnPark: "bool", trackAppClose: "bool",
showInBar: "bool", barTray: "bool", hideBarWhenIdle: "bool",
maxStack: "int", barMaxIcons: "int", setupDismissed: "bool",
parkTimeout: "int", flight: "flight", parkFlight: "flight", restoreFlight: "flight"
}
var kind = allowed[String(name)]
if (!kind) return "unknown setting"
var value
var asked = null
if (kind === "flight") {
if (Model.FLIGHT_MODES.indexOf(String(rawValue).trim().toLowerCase()) === -1) return "expected off|subtle|angel"
value = Model.normalizeFlight(rawValue)
} else if (kind === "bool") {
var s = String(rawValue).toLowerCase()
if (s === "true" || s === "on" || s === "1" || s === "yes") value = true
else if (s === "false" || s === "off" || s === "0" || s === "no") value = false
else return "expected on|off"
} else {
asked = Math.floor(Number(rawValue))
if (!isFinite(asked)) return "expected a number"
value = asked
if (name === "maxStack") value = Model.clampMax(value)
if (name === "barMaxIcons") value = Math.max(1, Math.min(10, value))
if (name === "parkTimeout") value = Model.clampParkTimeout(value)
}
if (!root.saveSetting(name, value)) return "could not write shell.json"
// Report the effective value: clamps (parkTimeout 3 -> 5) are silent
// surprises otherwise.
return (asked !== null && value !== asked) ? ("ok (using " + value + ")") : "ok"
}
function pluginEntry() {
return Object.assign({ id: root.pluginId }, root.settingsEntry)
}
function setting(name, fallback) {
var entry = root.settingsEntry
if (entry && entry[name] !== undefined && entry[name] !== null) return entry[name]
return fallback
}
function saveSetting(name, value) {
try {
if (!root.shell || typeof root.shell.updateEntryInline !== "function") return false
var next = root.pluginEntry()
// Omarchy reports false for a write that changes nothing.
if (next[name] === value && (name !== "flight" || (next.parkFlight === value && next.restoreFlight === value))) return true
next[name] = value
// The legacy shared setting still changes both directions atomically.
if (name === "flight") { next.parkFlight = value; next.restoreFlight = value }
if (root.shell.updateEntryInline(root.pluginId, next) === false) return false
// Reflect accepted changes immediately; the watcher confirms shortly after.
root.settingsEntry = next
return true
} catch (e) {
console.warn("reprieve: saveSetting failed", e)
return false
}
}
function setShowToast(value) {
var on = value !== false
root.saveSetting("showToast", on)
if (on) root.toast("Toasts on")
else { root.toastOpen = false; root.toastText = "" }
}
function toggleShowToast() { root.setShowToast(!root.showToast) }
function dismissSetup() { root.saveSetting("setupDismissed", true) }
// ---------------------------------------------------------------- publish
function publish() {
root.undoStack = (root.model && root.model.undo) ? root.model.undo.slice() : []
root.redoStack = (root.model && root.model.redo) ? root.model.redo.slice() : []
var summary = Model.statusSummary(root.model)
root.undoCount = summary.undo
root.redoCount = summary.redo
root.parkedCount = summary.parked
root.lastLabel = summary.last
}
function commit(state) {
root.model = state
root.publish()
root.persist()
root.recountStranded()
}
function toast(message) {
var text = String(message || "")
if (!text || !root.showToast) return
root.toastText = text
root.toastOpen = true
toastTimer.restart()
}
// ---------------------------------------------------------------- journal
function persist() {
if (!root.session) return
root.pendingJournalText = JSON.stringify(Model.toJournal(root.model, root.session))
root.journalDirty = true
persistDebounce.restart()
}
function flushJournal() {
if (!root.journalDirty || journalWriter.running) return
// Until reconcile has merged the journal read at startup, the in-memory
// state lacks its entries: writing now would replace the file with a
// partial history. reconcile() commits, and that persists, right after.
if (!root.journalConsumed) return
// Never race a quarantine rename with a fresh write.
if (quarantineProcess.running) { persistDebounce.restart(); return }
root.journalDirty = false
journalWriter.payload = root.pendingJournalText
journalWriter.command = [root.journalBin, "write", "--state-dir", root.stateDir]
journalWriter.running = true
}
function readJournal() {
if (journalReader.running) return
journalReader.command = [root.journalBin, "read", "--state-dir", root.stateDir]
journalReader.running = true
}
function onJournalRead(text) {
var envelope = null
try { envelope = JSON.parse(String(text || "").slice(0, Model.JOURNAL_MAX_BYTES + 4096)) } catch (e) {}
var status = envelope && envelope.status ? String(envelope.status) : "error"
if (status === "ok") {
var parsed = Model.parseJournal(envelope.text, root.session)
root.journalStatus = parsed.status
root.journalEntries = parsed.entries
root.journalSequence = parsed.sequence
if (parsed.status === "invalid") root.quarantineJournal(parsed.reason || "invalid")
else if (parsed.status === "stale") root.quarantineJournal("stale")
} else if (status === "empty") {
root.journalStatus = "empty"
} else {
// symlink / irregular / oversized / unreadable: never trust it.
root.journalStatus = status
root.quarantineJournal(status)
}
root.scheduleReconcile()
}
function quarantineJournal(reason) {
console.warn("reprieve: quarantining recovery journal:", reason)
quarantineProcess.command = [root.journalBin, "quarantine", "--state-dir", root.stateDir, "--reason", String(reason || "damaged").replace(/[^A-Za-z0-9_-]/g, "")]
quarantineProcess.running = true
}
// ------------------------------------------------------------ reconcile
function toplevelsReady() {
try {
var list = Hyprland.toplevels ? (Hyprland.toplevels.values || []) : []
if (list.length === 0) return (Date.now() - root.startedAt) > 4000
for (var i = 0; i < list.length; i++) {
var ipc = list[i] && list[i].lastIpcObject
if (ipc && ipc.class !== undefined) return true
}
} catch (e) {}
return (Date.now() - root.startedAt) > 4000
}
function scheduleReconcile() {
reconcileTimer.restart()
}
function liveWindows() {
var out = []
try {
var list = Hyprland.toplevels ? (Hyprland.toplevels.values || []) : []
for (var i = 0; i < list.length; i++) {
var snap = root.snapshotFromHandle(list[i])
if (snap && snap.address) out.push(snap)
}
} catch (e) {}
return out
}
function reconcile() {
if (!root.toplevelsReady()) {
reconcileTimer.interval = 700
reconcileTimer.restart()
return
}
var entries = root.journalConsumed ? [] : root.journalEntries
var result = Model.reconcile(root.model, entries, root.liveWindows(), root.journalSequence)
root.journalConsumed = true
root.journalEntries = []
var report = result.report
root.commit(result.state)
if (report.recovered.length) {
var n = report.recovered.length
root.recoveryNotice = "Recovered " + n + " parked window" + (n === 1 ? "" : "s") + " after shell reload."
root.toast(root.recoveryNotice + " Super+Shift+Z to review")
noticeTimer.restart()
} else if (report.kept.length) {
root.recoveryNotice = "Restored " + report.kept.length + " parked window" + (report.kept.length === 1 ? "" : "s") + " to the timeline."
noticeTimer.restart()
}
if (report.converted.length || report.dropped.length)
console.log("reprieve: reconcile converted", report.converted.length, "dropped", report.dropped.length)
root.lastResult = "reconciled"
return report
}
// ------------------------------------------------------------- expected
function expect(address, kind) {
var addr = Model.normalizeAddress(address)
if (!addr) return
var slot = Object.assign({ close: 0, move: 0 }, root.expected[addr])
slot[kind] = (slot[kind] || 0) + 1
slot.at = Date.now()
root.expected = Model.assoc(root.expected, addr, slot)
expectSweep.restart()
}
function consume(address, kind) {
var addr = Model.normalizeAddress(address)
var slot = addr ? root.expected[addr] : null
if (!slot || !(slot[kind] > 0)) return false
var copy = Object.assign({}, slot)
copy[kind] -= 1
root.expected = copy.close <= 0 && copy.move <= 0 ? Model.dissoc(root.expected, addr) : Model.assoc(root.expected, addr, copy)
return true
}
function sweepExpected() {
var now = Date.now()
var next = {}
var changed = false
for (var addr in root.expected) {
var slot = root.expected[addr]
if (slot && now - slot.at < 5000) { next[addr] = slot; continue }
changed = true
// An expected close that never came: the app refused to die (unsaved
// changes prompt, say). If it is still parked, keep it recoverable.
if (slot && slot.close > 0) root.adoptIfStranded(addr)
}
if (changed) root.expected = next
if (Object.keys(next).length) expectSweep.restart()
}
function adoptIfStranded(address) {
var handle = root.liveHandle(address)
if (!handle) return
var snap = root.snapshotFromHandle(handle)
if (!snap || snap.workspace !== root.parkWorkspace) return
if (Model.findParked(root.model, snap.address) !== -1) return
snap.recovered = true
snap.workspace = ""
var result = Model.pushRecovered(root.model, snap)
if (result.action) {
root.commit(result.state)
root.toast("Kept " + Model.toastLabel(result.action) + " recoverable")
}
}
// ------------------------------------------------------------- hyprland
function currentWorkspace() {
try {
var name = root.workspaceName(Hyprland.focusedWorkspace)
// An open special workspace (scratchpad) is focused on top of the
// monitor's regular workspace; "here" means the latter.
if (Model.isSpecialWorkspace(name)) name = root.workspaceName(Hyprland.focusedMonitor && Hyprland.focusedMonitor.activeWorkspace)
if (name && !Model.isSpecialWorkspace(name)) return Model.normalizeWorkspace(name)
} catch (e) {}
return ""
}
// Screen name of the monitor showing a workspace, or "" when Hyprland
// does not know it yet (it is created on demand).
function workspaceScreen(workspace) {
try {
var list = Hyprland.workspaces ? (Hyprland.workspaces.values || []) : []
for (var i = 0; i < list.length; i++) {
var ws = list[i]
if (ws && root.workspaceName(ws) === String(workspace)) return ws.monitor && ws.monitor.name ? String(ws.monitor.name) : ""
}
} catch (e) {}
return ""
}
// Omarchy 4 / Hyprland 0.56 is Lua-config only; there is no legacy path.
function hyprDispatch(lua) {
try {
Hyprland.dispatch(lua)
} catch (e) {
console.warn("reprieve: dispatch failed", e)
}
}
function windowSel(addr) {
return 'window = "address:' + addr + '"'
}
// Omarchy's windowsIn/Out use popin — set no_anim before the move so park
// and restore are a cut, not a cartoon.
function setNoAnim(address, on) {
var addr = Model.normalizeAddress(address)
if (!addr) return
var value = on ? "1" : "0"
root.hyprDispatch(
'hl.dsp.window.set_prop({ ' + root.windowSel(addr) + ', prop = "no_anim", value = "' + value + '" })')
}
function moveSilent(address, workspace) {
var addr = Model.normalizeAddress(address)
var ws = Model.normalizeWorkspace(workspace)
if (!addr || !ws) return false
root.expect(addr, "move")
// Own dispatches precede Quickshell's cached workspace refresh.
root.patchSnapshot(addr, { workspace: ws, workspaceKnown: true })
root.setNoAnim(addr, true)
root.hyprDispatch(
'hl.dsp.window.move({ ' + root.windowSel(addr) + ', workspace = "' + ws + '", follow = false })')
return true
}
// Hyprland 0.56's window.float parses "enable"/"disable"/"toggle"; any
// other word (including "set") silently means toggle.
function setFloating(address, floating) {
var addr = Model.normalizeAddress(address)
if (!addr) return
root.hyprDispatch(
'hl.dsp.window.float({ ' + root.windowSel(addr) + ', action = "' + (floating ? "enable" : "disable") + '" })')
}
// A pinned window is fixed to its display: Hyprland silently no-ops a
// move to a special workspace, so park must unpin before hiding and the
// restore re-pins after floating is back (pin requires a floating window).
// window.pin parses "enable"/"disable"/"toggle" like window.float.
function setPinned(address, pinned) {
var addr = Model.normalizeAddress(address)
if (!addr) return
root.hyprDispatch(
'hl.dsp.window.pin({ ' + root.windowSel(addr) + ', action = "' + (pinned ? "enable" : "disable") + '" })')
}
function setFullscreen(address, internal, client) {
var addr = Model.normalizeAddress(address)
if (!addr) return
var i = Math.max(0, Math.min(2, Math.floor(Number(internal) || 0)))
var c = Math.max(0, Math.min(2, Math.floor(Number(client) || 0)))
root.hyprDispatch(
'hl.dsp.window.fullscreen_state({ ' + root.windowSel(addr) + ', internal = ' + i + ', client = ' + c + ', action = "set" })')
}
function focusWindow(address) {
var addr = Model.normalizeAddress(address)
if (!addr) return
root.hyprDispatch('hl.dsp.focus({ ' + root.windowSel(addr) + ' })')
}
function closeWindow(address) {
root.settleFlights(address)
var addr = Model.normalizeAddress(address)
if (!addr) return
root.expect(addr, "close")
root.setNoAnim(addr, true)
root.hyprDispatch('hl.dsp.window.close({ ' + root.windowSel(addr) + ' })')
}
function liveHandle(address) {
var addr = Model.normalizeAddress(address)
if (!addr || !Hyprland.toplevels) return null
try {
var list = Hyprland.toplevels.values || []
for (var i = 0; i < list.length; i++) {
var handle = list[i]
if (handle && Model.normalizeAddress(handle.address) === addr) return handle
}
} catch (e) {}
return null
}
function workspaceName(workspace) {
if (!workspace) return ""
var name = String(workspace.name || "")
return name !== "" ? name : String(workspace.id || "")
}
function snapshotFromHandle(handle) {
if (!handle) return null
var address = Model.normalizeAddress(handle.address)
if (!address) return null
var cached = root.snapshots[address] || {}
var ipc = handle.lastIpcObject || {}
var ipcWs = ipc.workspace && ipc.workspace.name !== undefined ? String(ipc.workspace.name) : ""
return {
address: address,
class: String(ipc.class || cached.class || ""),
title: String(handle.title || ipc.title || cached.title || ""),
workspace: cached.workspaceKnown ? cached.workspace : (root.workspaceName(handle.workspace) || ipcWs || cached.workspace || ""),
floating: cached.floatingKnown ? !!cached.floating : (ipc.floating !== undefined ? !!ipc.floating : !!cached.floating),
pinned: !!ipc.pinned,
fullscreen: Number(ipc.fullscreen !== undefined ? ipc.fullscreen : (cached.fullscreen || 0)),
fullscreenClient: Number(ipc.fullscreenClient !== undefined ? ipc.fullscreenClient : (cached.fullscreenClient || 0)),
pid: Number(ipc.pid || cached.pid || 0),
openedAt: cached.openedAt || 0
}
}
function activeHandle() {
try {
if (Hyprland.activeToplevel) return Hyprland.activeToplevel
// The compositor focus object can be null at startup or between focus
// events. The Wayland activated flag is current from the first frame.
var list = Hyprland.toplevels ? (Hyprland.toplevels.values || []) : []
for (var i = 0; i < list.length; i++) {
if (list[i] && list[i].wayland && list[i].wayland.activated) return list[i]
}
} catch (e) {}
return null
}
function activeSnapshot() {
var handle = root.activeHandle()
return handle ? root.snapshotFromHandle(handle) : null
}
function cacheToplevels() {
var next = {}
try {
var list = Hyprland.toplevels ? (Hyprland.toplevels.values || []) : []
for (var i = 0; i < list.length; i++) {
var snap = root.snapshotFromHandle(list[i])
if (!snap || !snap.address) continue
var previous = root.snapshots[snap.address]
if (previous && previous.openedAt) snap.openedAt = previous.openedAt
// changefloatingmode events keep the cache current between IPC
// refreshes; snapshotFromHandle already preferred that value.
if (previous && previous.floatingKnown) snap.floatingKnown = true
if (previous && previous.workspaceKnown) snap.workspaceKnown = true
next[snap.address] = snap
}
} catch (e) {}
root.snapshots = next
root.recountStranded()
}
function recountStranded() {
var n = 0
for (var addr in root.snapshots) {
var s = root.snapshots[addr]
if (s && s.workspace === root.parkWorkspace && Model.findParked(root.model, addr) === -1) n++
}
root.strandedCount = n
}
function patchSnapshot(address, patch, replace) {
var addr = Model.normalizeAddress(address)
if (!addr) return
var base = root.snapshots[addr] && !replace ? root.snapshots[addr] : { address: addr }
root.snapshots = Model.assoc(root.snapshots, addr, Object.assign({}, base, patch))
if (patch.workspace !== undefined) root.recountStranded()
}
function dropSnapshot(addr) {
if (!root.snapshots[addr]) return
root.snapshots = Model.dissoc(root.snapshots, addr)
root.recountStranded()
}
// A closed window can no longer be moved, and Hyprland may hand its
// address to the next window it maps. Drop every deferred action on it:
// a pending flight cut would otherwise hide that unrelated window.
function forgetWindow(addr) {
var next = {}
var dropped = false
for (var token in root.pendingFlights) {
if (root.pendingFlights[token].job.address === addr) dropped = true
else next[token] = root.pendingFlights[token]
}
if (dropped) root.pendingFlights = next
if (root.expected[addr]) root.expected = Model.dissoc(root.expected, addr)
// The overlay finishes the scene; its cut finds no pending token.
try {
if (dropped && root.flightHandler && root.flightHandler.finishAddress)
root.flightHandler.finishAddress(addr)
} catch (e) { console.warn("reprieve: finishing flight failed", e) }
}
// ---------------------------------------------------------------- media
function enqueueMedia(kind, args, address) {
root.mediaQueue = root.mediaQueue.concat([{ kind: kind, args: args, address: address || "" }])
root.pumpMedia()
}
function pumpMedia() {
while (!mediaProcess.running && root.mediaQueue.length > 0) {
var job = root.mediaQueue[0]
root.mediaQueue = root.mediaQueue.slice(1)
if (job.kind === "close") {
// Queued behind the resume job so the stream is unmuted before it dies.
root.closeWindow(job.address)
continue
}
root.mediaJobKind = job.kind
root.mediaJobAddress = job.address
mediaProcess.command = job.args
mediaProcess.running = true
}
}
// Close a window Reprieve may have muted: unmute first, then close.
function closeAfterMedia(address, media) {
var clean = Model.sanitizeMedia(media)
// Disabling future pauses must not skip cleanup already owed to a window.
if (!clean) { root.closeWindow(address); return }
root.requestResume(clean)
root.mediaQueue = root.mediaQueue.concat([{ kind: "close", address: Model.normalizeAddress(address) }])
root.pumpMedia()
}
function stopMedia() {
mediaTimeout.stop()
try { if (mediaProcess.running) mediaProcess.running = false } catch (e) {}
root.mediaQueue = []
root.mediaJobKind = ""
root.mediaJobAddress = ""
}
function requestPause(snapshot) {
if (!root.pauseMediaOnPark || !snapshot) return
var pid = Number(snapshot.pid || 0)
var klass = Model.sanitizeClass(snapshot.class)
if (!pid && !klass) return
root.enqueueMedia("pause", [
"python3", root.mediaBin, "pause",
"--pid", String(pid),
"--class-name", klass
], snapshot.address)
}
function requestResume(media) {
var clean = Model.sanitizeMedia(media)
if (!clean) return
root.enqueueMedia("resume", [
"python3", root.mediaBin, "resume",
"--payload", JSON.stringify(clean)
], "")
}
// -------------------------------------------------------------- effects
// Before Reprieve closes a window it muted, unmute it: PipeWire's
// stream-restore remembers mute per application, so a stream that dies
// muted would come back muted the next time that app plays.
function mediaFor(state, address) {
var index = Model.findParked(state, address)
if (index === -1) return null
var action = state.undo[index]
return action ? action.media : null
}
function applyKills(addresses, previousState) {
for (var i = 0; i < (addresses || []).length; i++) {
if (!root.liveHandle(addresses[i])) continue
root.closeAfterMedia(addresses[i], previousState ? root.mediaFor(previousState, addresses[i]) : null)
}
}
function applyEffects(effects, opts) {
opts = opts || {}
for (var i = 0; i < (effects || []).length; i++) {
var effect = effects[i]
if (!effect) continue
if (effect.type === "park") {
var handle = root.liveHandle(effect.address)
if (!handle) continue
root.animatePark(root.snapshotFromHandle(handle), handle)
} else if (effect.type === "restore") {
root.restoreWindow(effect, opts.focus !== false)
} else if (effect.type === "relaunch") {
root.relaunch(effect)
} else if (effect.type === "close") {
if (!root.liveHandle(effect.address)) continue
root.closeWindow(effect.address)
}
}
}
function restoreWindow(effect, focus) {
var cancelled = root.cancelUnreadPark(effect.address)
root.settleFlights(effect.address)
if (!root.liveHandle(effect.address)) {
root.relaunch(effect)
return false
}
// Before the read, parking has not touched the real window. Cancelling
// it is already the undo; applying a stale restore could change its pin.
if (cancelled) return true
var workspace = Model.normalizeWorkspace(effect.workspace)
if (!workspace || Model.isSpecialWorkspace(workspace)) workspace = root.currentWorkspace()
if (!workspace) workspace = "1"
var cut = function() {
root.moveSilent(effect.address, workspace)
root.setFloating(effect.address, !!effect.floating)
if (effect.pinned) root.setPinned(effect.address, true)
if (effect.fullscreen > 0 || effect.fullscreenClient > 0)
root.setFullscreen(effect.address, effect.fullscreen, effect.fullscreenClient)
if (focus) root.focusWindow(effect.address)
animClear.queue(effect.address)
root.requestResume(effect.media)
}
// A window coming back to another workspace switches there first (the
// focus would have done that anyway) so the flight happens in view.
var job = root.flightJob("restore", root.liveHandle(effect.address), effect.address)
// The remembered frame belongs to the screen it was parked from. A window
// returning to a workspace on another monitor is a plain cut there.
var screen = job ? root.workspaceScreen(workspace) : ""
if (job && screen && screen !== job.screen) job = null
if (job && focus && workspace !== root.currentWorkspace() && !Model.isSpecialWorkspace(workspace))
root.hyprDispatch('hl.dsp.focus({ workspace = "' + workspace + '" })')
else if (job && !focus && workspace !== root.currentWorkspace())
job = null
if (job) root.beginFlight(job, cut)
else cut()
return true
}
function relaunch(effect) {
var command = Model.relaunchCommand(effect)
if (!command || !command.length) {
root.lastResult = "gone"
root.toast("Cannot restore " + Model.toastLabel(effect) + " — window is gone")
return
}
try {
Quickshell.execDetached(command)
root.lastResult = "relaunched"
} catch (e) {
console.warn("reprieve: relaunch failed", e)
root.lastResult = "error"
}
}
// -------------------------------------------------------------- actions
function parkActive() {
var handle = root.activeHandle()
if (!handle) { root.lastResult = "empty"; return "empty" }
return root.parkWindow(handle.address)
}
// Park a specific window by address (IPC only; used by tests and tools).
function parkWindow(address) {
var handle = root.liveHandle(address)
if (!handle) { root.lastResult = "empty"; return "empty" }
// A tracked park is already owned, even before its cut has run.
if (Model.findParked(root.model, handle.address) !== -1) {
root.lastResult = "empty"
return "empty"
}
root.settleFlights(handle.address)
var snapshot = root.snapshotFromHandle(handle)
var previous = root.model
var result = Model.pushPark(previous, snapshot)
if (result.reason !== "parked") { root.lastResult = "passthrough"; return "passthrough" }
root.commit(result.state)
root.applyKills(result.kills, previous)
root.animatePark(snapshot, handle)
root.lastResult = "parked"
root.toast("Parked " + Model.toastLabel(result.action) + " — Super+Z to undo")
root.windowParked(snapshot.address)
return "parked"
}
function animatePark(snapshot, handle) {
root.settleFlights(snapshot.address)
var cut = function() {
if (snapshot.fullscreen > 0 || snapshot.fullscreenClient > 0)
root.setFullscreen(snapshot.address, 0, 0)
if (snapshot.pinned) root.setPinned(snapshot.address, false)
root.moveSilent(snapshot.address, root.parkWorkspace)
root.requestPause(snapshot)
}
// The cut always waits for the fresh geometry read below: lastIpcObject
// is only refreshed when toplevels are fetched, and a pinned window's
// move to the park workspace is a silent no-op — the unpin decision and