Repository navigation
Expand file tree
/
Copy pathService.qml
More file actions
419 lines (377 loc) · 14.8 KB
/
Copy pathService.qml
File metadata and controls
419 lines (377 loc) · 14.8 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
import QtQuick 6.11
import Quickshell
import Quickshell.Io
import "Model.js" as Model
// Background service for the shutdown-timer bar widget. Owns the daemon
// lifecycle, polls state.json, and sends commands to the daemon via control.sh.
Item {
id: root
property var settings: ({})
property bool notifyInstance: true
// Quickshell's Process ignores a new command while it is running, so a burst
// (wheel notches, pause then cancel) used to keep only the first one. Every
// command is queued and started in order when the previous process exits.
property var pendingCommands: []
// ---------- state ----------
property bool loaded: false
property bool ok: true
property string error: ""
property var lastEnsureAt: 0
property string status: "IDLE" // IDLE | ACTIVE | COUNTDOWN | COUNTDOWN_SCHED | PAUSED
property string action: ""
property int timeLeft: 0
property var targetTime: 0
property string mode: ""
property var startTime: 0
property int snoozeCount: 0
property string reason: ""
property int scheduleCount: 0
property bool dnd: false
readonly property string omarchyPath: Quickshell.env("OMARCHY_PATH") || "/usr/share/omarchy"
// Overlay summonsing is handled by Panel.qml via Connections so the
// Service itself stays stateless about which surface owns it.
// ---------- settings ----------
readonly property int refreshIntervalSec: intSetting("refreshIntervalSec", 1, 1, 60)
readonly property int notifyEarlyMins: intSetting("notifyEarlyMins", 5, 0, 60)
readonly property int overlaySeconds: intSetting("overlaySeconds", 30, 5, 120)
readonly property string defaultAction: String(setting("defaultAction", "poweroff"))
readonly property int snoozeMins: intSetting("snoozeMins", 5, 1, 60)
readonly property int presetsRaw: 0
readonly property string presets: String(setting("presets", "15,30,45,60,90,120"))
// `omarchy bar set <id> <key> true` stores the STRING "true", so a strict
// === true comparison silently reports every toggle as off.
function boolSetting(name, fallback) {
var v = setting(name, fallback)
if (v === true || v === false) return v
return String(v).toLowerCase() === "true"
}
readonly property bool quiet: boolSetting("quiet", false)
readonly property bool batteryGuard: boolSetting("batteryGuard", false)
readonly property int batteryThreshold: intSetting("batteryThreshold", 20, 5, 50)
readonly property bool waitForInhibitors: boolSetting("waitForInhibitors", false)
readonly property bool ambientFade: boolSetting("ambientFade", false)
readonly property int fadeMinutes: intSetting("fadeMinutes", 5, 1, 30)
readonly property string waitForProcesses: String(setting("waitForProcesses", ""))
readonly property string webhookUrl: String(setting("webhookUrl", ""))
readonly property bool reducedMotion: boolSetting("reducedMotion", false)
readonly property var presetList: {
var out = []
var parts = presets.split(",")
for (var i = 0; i < parts.length && i < 6; i++) {
var n = parseInt(String(parts[i]).trim(), 10)
if (isFinite(n) && n >= 1 && n <= 1440) out.push(n)
}
return out.length > 0 ? out : [15, 30, 45, 60, 90, 120]
}
// ---------- language ----------
// "auto" follows the session locale; anything else is taken literally and
// resolved through Model.resolveLang, so a stale value cannot blank the UI.
readonly property string systemLang: Quickshell.env("LC_ALL") || Quickshell.env("LC_MESSAGES") || Quickshell.env("LANG") || "en"
readonly property string language: {
var configured = String(setting("language", "auto"))
if (configured === "auto" || configured === "") return Model.resolveLang(systemLang, "en")
return Model.resolveLang(configured, Model.resolveLang(systemLang, "en"))
}
function tr(key, args) {
return Model.t(key, language, args)
}
// ---------- dry run (live) ----------
// The daemon reads <state>/action-override on every firing; surface the same
// file here so the UI can say "the PC will not actually power off".
property string overrideCommand: ""
FileView {
path: root.stateDir + "/action-override"
watchChanges: true
printErrors: false
onFileChanged: reload()
onLoaded: root.overrideCommand = String(text() || "").trim()
onLoadFailed: root.overrideCommand = ""
}
// ---------- paths ----------
readonly property string pluginDir: String(Qt.resolvedUrl("control.sh")).replace(/^file:\/\//, "").replace(/\/control\.sh$/, "")
readonly property string controlPath: pluginDir + "/control.sh"
readonly property string writeSettingsScript: pluginDir + "/write-settings.sh"
// True when the settings could not be saved after several retries. The shell
// keeps the widget's own state; the failure is visible here, not swallowed.
property bool settingsFailed: false
readonly property string stateDir: (Quickshell.env("XDG_STATE_HOME") || (Quickshell.env("HOME") + "/.local/state")) + "/omarchy/plugins/shutdown-timer"
// ---------- settings helpers ----------
function setting(name, fallback) {
var value = settings ? settings[name] : undefined
return value === undefined || value === null ? fallback : value
}
function numSetting(name, fallback, min, max) {
var value = parseFloat(String(setting(name, fallback)))
if (!isFinite(value)) value = fallback
return Model.clamp(value, min, max)
}
function intSetting(name, fallback, min, max) {
return Math.round(numSetting(name, fallback, min, max))
}
// ---------- write settings for daemon ----------
// One place builds the JSON, and it reaches the file through the writer's
// stdin — never through its command line. `/proc/<pid>/cmdline` is readable
// by every local account (no hidepid on a stock desktop) and this JSON holds
// the webhook URL, so the payload is not an argument any more. JSON.stringify
// never emits a raw newline, so the writer reads exactly one line and quits;
// the write lands on a temp file and is renamed, so the daemon never reads
// half a settings file.
function settingsJson(overrides) {
var o = overrides || {}
return JSON.stringify({
notifyEarlyMins: notifyEarlyMins,
overlaySeconds: overlaySeconds,
language: language,
snoozeMins: snoozeMins,
quiet: quiet,
batteryGuard: batteryGuard,
batteryThreshold: batteryThreshold,
waitForInhibitors: waitForInhibitors,
ambientFade: ambientFade,
fadeMinutes: fadeMinutes,
waitForProcesses: waitForProcesses,
webhookUrl: o.webhookUrl !== undefined ? o.webhookUrl : webhookUrl,
reducedMotion: reducedMotion
})
}
Process {
id: writeSettingsProc
running: false
// The payload goes over stdin as ONE line. Not as an argument: a webhook URL
// in argv is world-readable in /proc/<pid>/cmdline. And one line, not until
// EOF: Quickshell keeps stdin open, so the writer reads a single line and
// returns at the newline instead of blocking on EOF.
stdinEnabled: true
command: ["bash", "-c", "true"]
// A settings slider fires several writes in a row: one write at a time, and
// a change that arrives mid-write is folded into one more write afterwards.
property string pendingPayload: ""
property var pendingOverrides: null
property bool dirty: false
// A permanently failing write (read-only state dir) must not spin: retry a
// few times, then stop and report the failure instead of retrying forever.
property int retries: 0
readonly property int maxRetries: 5
onStarted: {
if (pendingPayload !== "") {
write(pendingPayload + "\n")
pendingPayload = ""
}
}
onExited: function(exitCode) {
if (exitCode !== 0) {
retries += 1
if (retries > maxRetries) {
// Give up until the next real change; surface it instead of hiding it.
settingsFailed = true
dirty = false
return
}
dirty = true
} else {
retries = 0
settingsFailed = false
}
if (dirty) { dirty = false; root.startSettingsWrite() }
}
}
function startSettingsWrite() {
writeSettingsProc.command = ["bash", writeSettingsScript, stateDir]
writeSettingsProc.pendingPayload = settingsJson(writeSettingsProc.pendingOverrides)
writeSettingsProc.running = true
}
function writeSettings(overrides) {
if (writeSettingsProc.running) {
writeSettingsProc.pendingOverrides = overrides || null
writeSettingsProc.dirty = true
return
}
writeSettingsProc.pendingOverrides = overrides || null
startSettingsWrite()
}
// ---------- daemon lifecycle ----------
// SHUTDOWN_TIMER_UI marks a daemon that belongs to this widget: it refuses to
// fire once the plugin is no longer enabled in the shell (the widget and the
// overlay are gone, so a fire would be invisible). A daemon started from a
// terminal is a headless timer and keeps working without the widget.
function ensureDaemon() {
if (controlPath === "") return
ensureProc.command = ["env", "SHUTDOWN_TIMER_UI=1", "bash", controlPath, "ensure"]
ensureProc.running = true
}
Process {
id: ensureProc
running: false
stdout: StdioCollector { waitForEnd: true }
stderr: StdioCollector { waitForEnd: true }
onExited: {}
}
// ---------- polling state.json ----------
function refresh() {
if (proc.running || controlPath === "") return
// Read the file directly: `control.sh get-state` synthesizes an IDLE
// object when the file is missing, which made a dead daemon look live.
proc.command = ["bash", "-c", "cat '" + stateDir + "/state.json' 2>/dev/null || true"]
proc.running = true
}
function sendCommand(cmd) {
if (controlPath === "") return
if (cmdProc.running) {
var q = pendingCommands.slice()
q.push(cmd)
pendingCommands = q
return
}
runCommand(cmd)
}
function runCommand(cmd) {
cmdProc.command = ["env", "SHUTDOWN_TIMER_UI=1", "bash", controlPath, "send", cmd]
cmdProc.running = true
}
function setTimer(mins, act) {
if (act === undefined || act === "") act = defaultAction
sendCommand("set:" + String(mins) + ":" + act)
}
// The short end of the range: 30 s, 1:30, 90 s.
function setTimerSeconds(secs, act) {
if (act === undefined || act === "") act = defaultAction
sendCommand("set-secs:" + String(Math.round(secs)) + ":" + act)
}
function setTimerAbsolute(hhmm, act) {
if (act === undefined || act === "") act = defaultAction
sendCommand("set-abs:" + hhmm + ":" + act)
}
function cancel() {
sendCommand("cancel")
}
function snooze(mins) {
sendCommand("snooze:" + String(mins === undefined ? 5 : mins))
}
function pause() {
sendCommand("pause")
}
function resume() {
sendCommand("resume")
}
function reset() {
sendCommand("reset")
}
function setOverride(cmd) {
overrideProc.command = ["bash", controlPath, "override", cmd]
overrideProc.running = true
}
Process {
id: overrideProc
running: false
stdout: StdioCollector { waitForEnd: true }
stderr: StdioCollector { waitForEnd: true }
}
function scheduleAdd(hhmm, days, act) {
sendCommand("schedule-add:" + String(Date.now()).slice(-6) + ":" + hhmm + ":" + days + ":" + (act || defaultAction))
}
function scheduleRemove(id) {
sendCommand("schedule-remove:" + String(id))
}
Process {
id: proc
running: false
stdout: StdioCollector { id: stateOut; waitForEnd: true }
stderr: StdioCollector { waitForEnd: true }
onExited: function(exitCode) {
if (exitCode === 0) {
applyState(stateOut.text)
} else {
loaded = true
ok = false
error = "Could not read shutdown-timer state"
}
}
}
Process {
id: cmdProc
running: false
stdout: StdioCollector { waitForEnd: true }
stderr: StdioCollector { waitForEnd: true }
onExited: {
if (root.pendingCommands.length > 0) {
var q = root.pendingCommands.slice()
var next = q.shift()
root.pendingCommands = q
root.runCommand(next)
} else {
// Force a refresh so the bar reflects the new state quickly
root.refresh()
}
}
}
function applyState(raw) {
var parsed = null
try {
parsed = JSON.parse(String(raw || ""))
} catch (e) {
parsed = null
}
loaded = true
if (!parsed || typeof parsed !== "object") {
ok = false
error = "Could not read shutdown-timer state"
// A missing/broken state file usually means the daemon is gone (SIGKILL,
// a crash, a removed build). The README promises the widget brings it
// back; rate-limit ensure so a persistent failure does not fork a
// process every second.
var now = Date.now()
if (now - lastEnsureAt > 5000) {
lastEnsureAt = now
ensureDaemon()
}
return
}
ok = true
error = ""
status = String(parsed.status || "IDLE")
action = String(parsed.action || "")
timeLeft = Model.known(parsed.timeLeft) ? parsed.timeLeft : 0
targetTime = parsed.targetTime || 0
mode = String(parsed.mode || "")
startTime = parsed.startTime || 0
snoozeCount = Model.known(parsed.snoozeCount) ? parsed.snoozeCount : 0
reason = String(parsed.reason || "")
scheduleCount = Model.known(parsed.scheduleCount) ? parsed.scheduleCount : 0
dnd = parsed.dnd === true
}
// ---------- periodic poll ----------
Timer {
interval: root.refreshIntervalSec * 1000
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refresh()
}
// ---------- startup ----------
// There is deliberately no matching stop here. `omarchy plugin remove` has
// no hook into the plugin, and QML destruction is not a removal signal: the
// shell destroys this object on every restart, while a timer must survive
// that. Removal is handled where the evidence is — daemon.sh watches its own
// directory and disarms instead of firing once the files are gone. The
// documented clean path is `control.sh uninstall` (cancel, stop, verify).
Component.onCompleted: {
writeSettings()
// Give it a moment then ensure daemon
Qt.callLater(function() { root.ensureDaemon() })
}
// The daemon reads settings.json for its notification language and timings;
// a settings change must reach that file, or a language switch would only
// apply to the QML surfaces and the alerts would stay in the old language.
onLanguageChanged: writeSettings()
onNotifyEarlyMinsChanged: writeSettings()
onOverlaySecondsChanged: writeSettings()
onSnoozeMinsChanged: writeSettings()
onQuietChanged: writeSettings()
onAmbientFadeChanged: writeSettings()
onFadeMinutesChanged: writeSettings()
onWaitForProcessesChanged: writeSettings()
onWebhookUrlChanged: writeSettings()
onBatteryGuardChanged: writeSettings()
onBatteryThresholdChanged: writeSettings()
onWaitForInhibitorsChanged: writeSettings()
}