Repository navigation
Expand file tree
/
Copy pathService.qml
More file actions
663 lines (594 loc) · 26.5 KB
/
Copy pathService.qml
File metadata and controls
663 lines (594 loc) · 26.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
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
import QtQuick
import Quickshell
import Quickshell.Io
import qs.Commons
import "Model.js" as Model
// Talks to the docker CLI. Every host — local socket or a remote daemon over
// ssh — is a docker *context*, so `docker --context <name>` is the only
// dispatch mechanism the plugin needs. Status polling is delegated to
// bin/dockarchy-status so many contexts can be queried in parallel by one
// process and land as a single JSON document.
Item {
id: root
property var settings: ({})
property bool installed: true
property bool refreshing: false
property bool everRefreshed: false
property var hosts: []
property var counts: Model.emptyCounts()
property string lastError: ""
property string actionStatus: ""
// "<context>/<container id>" (or "<context>//<project>" for a whole compose
// group) while a start/stop/restart is in flight.
property string pendingActionKey: ""
// Previous poll, for change detection. Null until the first good poll so a
// shell restart never fires a burst of "X is running" notifications.
property var _lastSnapshot: null
// "host/id" -> {until, verb} for containers the user just acted on; the
// transition they asked for is theirs, not an incident.
property var _userTouched: ({})
// "type:key" -> last notified ms, to tame flapping health checks.
property var _notified: ({})
readonly property int refreshIntervalSec: intSetting("refreshIntervalSec", 15, 5, 3600)
readonly property int timeoutSec: intSetting("timeoutSec", 10, 2, 120)
readonly property bool showAll: boolSetting("showAll", true)
readonly property bool showStats: boolSetting("showStats", true)
readonly property bool groupByProject: boolSetting("groupByProject", true)
readonly property bool showSparklines: boolSetting("showSparklines", true)
readonly property var sparkMetrics: validMetrics(listSetting("sparkMetrics"))
readonly property int sparkSamples: intSetting("sparkSamples", 20, 5, 240)
readonly property bool runningAccent: boolSetting("runningAccent", false)
// Hours between registry checks for newer images; 0 disables.
readonly property int updateCheckHours: intSetting("updateCheckHours", 6, 0, 168)
property var updates: ({})
property int updateCount: 0
property double updatesCheckedAt: 0
property bool checkingUpdates: false
property string updatesError: ""
// "host/id" -> {cpu: [], mem: []}, the last HISTORY_LENGTH polls.
property var history: ({})
// "Off" | "Problems" | "Problems and recoveries"
readonly property string notifications: stringSetting("notifications", "Problems")
readonly property var contexts: listSetting("contexts")
// "local" and/or "[user@]host[:port]" entries polled with podman.
readonly property var podmanHosts: listSetting("podmanHosts")
readonly property bool busy: statusProcess.running || actionProcess.running
readonly property bool actionRunning: actionProcess.running
readonly property bool healthy: counts.unhealthy === 0 && counts.unreachable === 0
readonly property var countsWithUpdates: {
var c = {}
for (var k in counts) c[k] = counts[k]
c.updates = updateCount
return c
}
readonly property string summaryText: Model.summaryText(everRefreshed ? countsWithUpdates : null, installed)
// Notification icons are Nerd Font glyphs rendered to PNG in the theme's
// colours at startup (and again when the theme changes). Until that has
// happened, or if ImageMagick is missing, the PNGs shipped in assets/ serve.
readonly property string iconDir: (Quickshell.env("XDG_CACHE_HOME") || (Quickshell.env("HOME") + "/.cache")) + "/dockarchy"
property bool iconsRendered: false
readonly property string iconProblem: (iconsRendered ? iconDir : pluginDir + "/assets") + "/problem.png"
readonly property string iconRecovery: (iconsRendered ? iconDir : pluginDir + "/assets") + "/recovery.png"
function hexColor(c) {
function h(v) { var s = Math.round(v * 255).toString(16); return s.length < 2 ? "0" + s : s }
return "#" + h(c.r) + h(c.g) + h(c.b)
}
function renderIcons() {
if (iconProcess.running) { iconRenderRetry.restart(); return }
var fg = Color.foreground
var urgent = Color.urgent
var warn = Qt.rgba(fg.r + (urgent.r - fg.r) * 0.55, fg.g + (urgent.g - fg.g) * 0.55, fg.b + (urgent.b - fg.b) * 0.55, 1)
iconProcess.command = [pluginDir + "/assets/render-icons", "--out", iconDir,
"--fg", hexColor(fg), "--warn", hexColor(warn), "--ok", hexColor(Color.accent)]
iconProcess.running = true
}
Component.onCompleted: renderIcons()
Connections {
target: Color
function onForegroundChanged() { iconRenderRetry.restart() }
function onAccentChanged() { iconRenderRetry.restart() }
}
Process {
id: iconProcess
running: false
command: []
onExited: function(exitCode) { root.iconsRendered = exitCode === 0 }
}
// Theme changes fire several colour signals in a row; render once.
Timer {
id: iconRenderRetry
interval: 800
repeat: false
onTriggered: root.renderIcons()
}
// Every process the widget spawns runs under bin/dockarchy-exec, which caps
// stdout/stderr while streaming, so a hostile daemon or ssh peer can never
// grow the StdioCollectors below beyond a few dozen KiB (actions) or the
// documented ceilings (status, updates).
function bounded(timeoutSec, maxBytes, argv) {
return [pluginDir + "/bin/dockarchy-exec", "--timeout", String(timeoutSec), "--max-bytes", String(maxBytes), "--"].concat(argv)
}
readonly property string pluginDir: {
var url = Qt.resolvedUrl(".").toString()
return url.replace(/^file:\/\//, "").replace(/\/$/, "")
}
property string _statusOutput: ""
property string _statusError: ""
property string _actionOutput: ""
property string _actionError: ""
function setting(name, fallback) {
var value = settings ? settings[name] : undefined
return value === undefined || value === null ? fallback : value
}
function intSetting(name, fallback, min, max) {
var n = parseInt(String(setting(name, fallback)), 10)
if (!isFinite(n)) n = fallback
return Math.max(min, Math.min(max, n))
}
function stringSetting(name, fallback) {
var v = setting(name, fallback)
return v === undefined || v === null ? String(fallback) : String(v)
}
function boolSetting(name, fallback) {
var v = setting(name, fallback)
if (typeof v === "boolean") return v
return String(v).toLowerCase() === "true"
}
// Multiselect values arrive as JS arrays or QML JSValue lists from the
// settings form, but `omarchy bar set` flattens them to a comma-separated
// string. Check for strings first: they have a numeric .length too, and
// iterating one yields its characters.
function listSetting(name) {
var v = setting(name, [])
var out = []
if (typeof v === "string") {
var parts = v.split(",")
for (var j = 0; j < parts.length; j++) if (parts[j].trim() !== "") out.push(parts[j].trim())
} else if (v && typeof v.length === "number") {
for (var i = 0; i < v.length; i++) {
var s = String(v[i] || "").trim()
if (s !== "") out.push(s)
}
}
return out
}
// Set when a refresh was asked for mid-poll; honoured as soon as it ends so
// a start/stop never waits a whole interval to show up.
property bool _refreshPending: false
function refresh() {
if (statusProcess.running) { _refreshPending = true; return }
_refreshPending = false
_statusOutput = ""
_statusError = ""
refreshing = true
var cmd = [pluginDir + "/bin/dockarchy-status", "--timeout", String(timeoutSec)]
if (showAll) cmd.push("--all")
if (showStats) cmd.push("--stats")
if (podmanHosts.length > 0) cmd.push("--podman", podmanHosts.join(","))
if (contexts.length > 0) {
cmd.push("--")
for (var i = 0; i < contexts.length; i++) cmd.push(contexts[i])
}
// The collector already bounds each host at 8 MiB; this is the overall lid.
statusProcess.command = bounded(timeoutSec + 20, 32 * 1024 * 1024, cmd)
statusProcess.running = true
// refresh() bails while a poll is in flight, so this only re-arms when a
// fresh process actually starts — a hung one can never push the deadline.
pollWatchdog.restart()
}
function applyStatus(raw) {
var parsed = Model.parseStatus(raw)
if (!parsed.ok) {
lastError = parsed.error || "Failed to read docker status"
console.warn("dockarchy", lastError)
return
}
installed = parsed.installed !== false
hosts = parsed.hosts
counts = parsed.counts
everRefreshed = true
lastError = ""
if (showStats) history = Model.pushHistory(history, hosts, sparkSamples, Date.now())
var snap = Model.snapshot(hosts)
if (_lastSnapshot) notifyChanges(Model.diffSnapshots(_lastSnapshot, snap, currentUserTouched()))
_lastSnapshot = snap
}
// Drop expired entries and return a plain key -> verb map for
// Model.diffSnapshots.
function currentUserTouched() {
var now = Date.now()
var live = {}
var verbs = {}
for (var k in _userTouched) if (_userTouched[k].until > now) { live[k] = _userTouched[k]; verbs[k] = _userTouched[k].verb }
_userTouched = live
return verbs
}
function markUserTouched(host, containers, verb) {
var until = Date.now() + 90000
currentUserTouched()
var next = {}
for (var k in _userTouched) next[k] = _userTouched[k]
for (var i = 0; i < containers.length; i++) next[String(host.name) + "/" + String(containers[i].id)] = { until: until, verb: String(verb) }
_userTouched = next
}
function notifyChanges(events) {
if (notifications === "Off") return
var now = Date.now()
// Forget debounce entries older than the longest quiet period so the map
// does not grow for the lifetime of the shell.
var kept = {}
for (var k in _notified) if (now - _notified[k] < 130000) kept[k] = _notified[k]
_notified = kept
for (var i = 0; i < events.length; i++) {
var e = events[i]
if (e.kind === "recovery" && notifications !== "Problems and recoveries") continue
var dedupe = e.type + ":" + (e.key || e.host)
// Health checks flap; stops and host outages are discrete events.
var quiet = (e.type === "unhealthy" || e.type === "healthy") ? 120000 : 20000
if (_notified[dedupe] && now - _notified[dedupe] < quiet) continue
_notified[dedupe] = now
Quickshell.execDetached(["notify-send", "-a", "Dockarchy", "-u", e.kind === "problem" ? "critical" : "normal",
"-i", e.kind === "problem" ? iconProblem : iconRecovery,
"-h", "string:x-canonical-private-synchronous:dockarchy-" + dedupe,
Model.escapeMarkup(e.title), Model.escapeMarkup(e.body || "")])
}
}
function findContainer(contextName, ref) {
var ctx = String(contextName || "")
var wanted = String(ref || "")
for (var h = 0; h < hosts.length; h++) {
var host = hosts[h]
if (ctx !== "" && host.name !== ctx) continue
for (var c = 0; c < host.containers.length; c++) {
var container = host.containers[c]
if (container.name === wanted || container.id === wanted || container.shortId === wanted) return { host: host, container: container }
}
}
return null
}
// Keep only known metric names, in the canonical order; default CPU+Memory.
function validMetrics(names) {
var out = []
for (var i = 0; i < Model.METRIC_NAMES.length; i++) {
if (names.indexOf(Model.METRIC_NAMES[i]) !== -1) out.push(Model.METRIC_NAMES[i])
}
return out.length > 0 ? out : ["CPU", "Memory"]
}
// ---- image updates
function checkUpdates(force) {
if (updatesProcess.running || !installed) return
if (updateCheckHours <= 0 && !force) return
checkingUpdates = true
var cmd = [pluginDir + "/bin/dockarchy-updates", "--timeout", "150",
"--cache", iconDir + "/updates.json", "--max-age", String(force ? 0 : updateCheckHours * 3600)]
if (podmanHosts.length > 0) cmd.push("--podman", podmanHosts.join(","))
if (contexts.length > 0) { cmd.push("--"); for (var i = 0; i < contexts.length; i++) cmd.push(contexts[i]) }
updatesProcess.command = bounded(180, 8 * 1024 * 1024, cmd)
updatesProcess.running = true
}
function applyUpdates(raw) {
var parsed = Model.parseUpdates(raw)
if (!parsed.ok) { updatesError = parsed.error; return }
updates = parsed.byKey
updateCount = parsed.count
updatesCheckedAt = parsed.checkedAt
var msgs = []
for (var h in parsed.errors) msgs.push(h + ": " + parsed.errors[h])
updatesError = msgs.join(" · ")
}
// The update entry for a container's image, or null when unknown.
function updateFor(host, container) {
if (!host || !container) return null
var entry = updates[String(host.name) + "/" + String(container.image)]
return entry && entry.update === true ? entry : null
}
function groupHasUpdate(host, group) {
if (!host || !group) return false
for (var i = 0; i < group.containers.length; i++) if (updateFor(host, group.containers[i])) return true
return false
}
// Pull the newer image and recreate, in a terminal so the user sees the
// progress and any error. Compose containers use their project directory
// (docker compose pull/up -d for that service); standalone ones can only be
// pulled — recreating them needs their original run arguments.
// What pullAndRecreate would run, for the confirmation dialog: the compose
// directory comes from a container label, i.e. from whoever created the
// container on that host, so the user sees it before compose runs there.
function pullDescription(host, container) {
if (!host || !container) return ""
if (container.project && container.workingDir)
return "cd " + container.workingDir + " && " + engineName(host) + " compose pull" + (container.service ? " " + container.service : "") + " && " + engineName(host) + " compose up -d" + (container.service ? " " + container.service : "")
return engineName(host) + " pull " + container.image
}
function pullProjectDescription(host, group) {
if (!host || !group || !group.workingDir) return ""
return "cd " + group.workingDir + " && " + engineName(host) + " compose pull && " + engineName(host) + " compose up -d"
}
function pullAndRecreate(host, container) {
if (!host || !container) return
var body
if (container.project && container.workingDir) {
var svc = container.service ? " " + Model.shellQuote(container.service) : ""
var eng = engineName(host)
body = "cd " + Model.shellQuote(container.workingDir) + " && " + eng + " compose pull" + svc + " && " + eng + " compose up -d" + svc
} else {
body = engineName(host) + " pull " + Model.shellQuote(container.image) + " && echo && echo 'Pulled. Recreate " + container.name + " yourself: this container is not managed by compose.'"
}
runInTerminalThenRecheck(host, body)
}
function pullProject(host, group) {
if (!host || !group || !group.workingDir) return
var eng = engineName(host)
runInTerminalThenRecheck(host, "cd " + Model.shellQuote(group.workingDir) + " && " + eng + " compose pull && " + eng + " compose up -d")
}
function runInTerminalThenRecheck(host, body) {
var ssh = Model.sshArgv(host.endpoint)
var inner
if (ssh) {
var argv = ssh.slice(0, 1).concat(["-t"]).concat(ssh.slice(1)).concat([body])
inner = argv.map(Model.shellQuote).join(" ")
} else if (engineName(host) === "podman") {
inner = "sh -c " + Model.shellQuote(body)
} else {
inner = "DOCKER_CONTEXT=" + Model.shellQuote(String(host.name)) + " sh -c " + Model.shellQuote(body)
}
var script = inner + "; status=$?; echo; if [ $status -eq 0 ]; then echo 'Done. Re-checking images…'; else echo \"Failed (exit $status).\"; fi; omarchy-shell x99.dockarchy checkUpdates >/dev/null 2>&1; sleep 3"
Quickshell.execDetached(["omarchy-launch-tui", "--app-id=org.omarchy.dockarchy-pull", "sh", "-c", script])
}
function historyFor(host, container) {
if (!host || !container) return null
var series = history[String(host.name) + "/" + String(container.id)]
return series && series.cpu.length > 0 ? series : null
}
function actionKey(host, container) {
if (!host || !container) return ""
return String(host.name) + "/" + String(container.id)
}
function isPending(host, container) {
var key = actionKey(host, container)
return key !== "" && key === pendingActionKey
}
function groupActionKey(host, group) {
if (!host || !group) return ""
return String(host.name) + "//" + String(group.project)
}
function isGroupPending(host, group) {
var key = groupActionKey(host, group)
return key !== "" && key === pendingActionKey
}
// argv for a one-shot engine command run from this machine: docker goes
// through its context (one request, fine over ssh); podman runs locally or
// over the user's ssh config.
function engineCommand(host, argv) {
var engine = host && host.engine === "podman" ? "podman" : "docker"
var ssh = host ? Model.sshArgv(host.endpoint) : null
if (engine === "podman") {
if (ssh) return ssh.concat([["podman"].concat(argv.map(Model.shellQuote)).join(" ")])
return ["podman"].concat(argv)
}
return ["docker", "--context", String(host.name)].concat(argv)
}
function containerAction(host, container, verb) {
if (!host || !container || actionProcess.running) return
var allowed = ["start", "stop", "restart", "pause", "unpause", "kill", "rm"]
if (allowed.indexOf(verb) === -1) return
if (verb === "rm" && container.running) return
_actionOutput = ""
_actionError = ""
pendingActionKey = actionKey(host, container)
markUserTouched(host, [container], verb)
actionStatus = (verb === "rm" ? "Removing " : verb === "stop" ? "Stopping " : capitalize(verb) + "ing ") + container.name + "…"
actionProcess.command = bounded(Math.max(timeoutSec, 30), 65536, engineCommand(host, [verb, String(container.id)]))
actionProcess.running = true
}
// One docker invocation for the whole group, so a remote host sees a single
// request rather than one per container.
function groupAction(host, group, verb) {
if (!host || !group || actionProcess.running) return
var targets = []
for (var i = 0; i < group.containers.length; i++) {
var c = group.containers[i]
if (verb === "start" && c.running) continue
if ((verb === "stop" || verb === "restart") && !c.running) continue
targets.push(c)
}
if (targets.length === 0) return
_actionOutput = ""
_actionError = ""
pendingActionKey = groupActionKey(host, group)
markUserTouched(host, targets, verb)
actionStatus = capitalize(verb) + "ing " + (group.project || "standalone containers") + " (" + targets.length + ")…"
var argv = [verb]
for (var t = 0; t < targets.length; t++) argv.push(String(targets[t].id))
actionProcess.command = bounded(Math.max(timeoutSec, 60), 65536, engineCommand(host, argv))
actionProcess.running = true
}
// Terminal command for a host: docker is run on the server over the user's
// ssh config for remote contexts, locally otherwise. `argv` is the docker
// argv without the leading "docker".
function engineName(host) {
return host && host.engine === "podman" ? "podman" : "docker"
}
function dockerTerminalCommand(host, argv) {
var engine = engineName(host)
var ssh = host ? Model.sshArgv(host.endpoint) : null
if (ssh) {
var quoted = [engine]
for (var i = 0; i < argv.length; i++) quoted.push(Model.shellQuote(argv[i]))
// -t so an interactive exec gets a TTY through ssh.
return ssh.slice(0, 1).concat(["-t"]).concat(ssh.slice(1)).concat([quoted.join(" ")])
}
var local = [engine]
if (engine === "docker" && host && host.name) local.push("--context", String(host.name))
return local.concat(argv)
}
// `docker inspect` is long: page it. The pipe means a shell on either side.
function openInspect(host, container) {
if (!host || !container) return
var ssh = Model.sshArgv(host.endpoint)
var cmd
var engine = engineName(host)
if (ssh) cmd = ssh.slice(0, 1).concat(["-t"]).concat(ssh.slice(1)).concat([engine + " inspect " + Model.shellQuote(String(container.id)) + " | less -R"])
else if (engine === "podman") cmd = ["sh", "-c", "podman inspect " + Model.shellQuote(String(container.id)) + " | less -R"]
else cmd = ["sh", "-c", "docker --context " + Model.shellQuote(String(host.name)) + " inspect " + Model.shellQuote(String(container.id)) + " | less -R"]
Quickshell.execDetached(["omarchy-launch-tui", "--app-id=org.omarchy.dockarchy-inspect"].concat(cmd))
}
function openUrl(url) {
var u = String(url || "")
if (u === "") return
Quickshell.execDetached(["omarchy-launch-browser", u])
}
function openPort(host, port) {
if (!host || !port) return
openUrl(Model.portUrl(host.endpoint, port))
}
function openGroupLogs(host, group) {
if (!host || !group || !group.project) return
Quickshell.execDetached(["omarchy-launch-tui", "--app-id=org.omarchy.dockarchy-logs"]
.concat(dockerTerminalCommand(host, ["compose", "-p", String(group.project), "logs", "--follow", "--tail", "100"])))
}
function toggleContainer(host, container) {
if (!container) return
if (container.state === "paused") containerAction(host, container, "unpause")
else containerAction(host, container, container.running ? "stop" : "start")
}
function restartContainer(host, container) {
containerAction(host, container, "restart")
}
// Terminal-bound actions: reuse Omarchy's TUI launcher so the window gets the
// same styling and app-id handling as btop, lazydocker and friends.
function openLogs(host, container) {
if (!host || !container) return
Quickshell.execDetached(["omarchy-launch-tui", "--app-id=org.omarchy.dockarchy-logs"]
.concat(dockerTerminalCommand(host, ["logs", "--follow", "--tail", "200", String(container.id)])))
}
function openShell(host, container) {
if (!host || !container || !container.running) return
Quickshell.execDetached(["omarchy-launch-tui", "--app-id=org.omarchy.dockarchy-shell"]
.concat(dockerTerminalCommand(host, ["exec", "-it", String(container.id),
"sh", "-c", "command -v bash >/dev/null 2>&1 && exec bash || exec sh"])))
}
function openLazydocker(host) {
var cmd = ["omarchy-launch-tui", "--app-id=org.omarchy.lazydocker", "env"]
if (host && host.engine === "podman") return
if (host && host.name) cmd.push("DOCKER_CONTEXT=" + String(host.name))
cmd.push("lazydocker")
Quickshell.execDetached(cmd)
}
function copyToClipboard(value) {
var text = String(value || "")
if (text === "") return
Quickshell.execDetached(["bash", "-c", "printf %s " + Util.shellQuote(text) + " | wl-copy"])
}
function capitalize(s) {
s = String(s || "")
return s.length === 0 ? s : s.charAt(0).toUpperCase() + s.substring(1)
}
function elide(text) {
var value = String(text || "").replace(/\s+/g, " ").trim()
return value.length > 140 ? value.substring(0, 137) + "…" : value
}
onRefreshIntervalSecChanged: refreshTimer.restart()
onShowAllChanged: refresh()
onShowStatsChanged: refresh()
onContextsChanged: refresh()
Process {
id: statusProcess
running: false
command: []
stdout: StdioCollector { id: statusStdout; waitForEnd: true; onStreamFinished: root._statusOutput = text }
stderr: StdioCollector { id: statusStderr; waitForEnd: true; onStreamFinished: root._statusError = text }
onExited: function(exitCode) {
root.refreshing = false
var stdout = String(statusStdout.text || root._statusOutput || "")
var stderr = String(statusStderr.text || root._statusError || "")
if (exitCode === 0 && stdout.trim() !== "") root.applyStatus(stdout)
else root.lastError = root.elide(stderr || stdout || "dockarchy-status exited with " + exitCode)
if (root._refreshPending) delayedRefresh.restart()
}
}
Process {
id: updatesProcess
running: false
command: []
stdout: StdioCollector { id: updatesStdout; waitForEnd: true }
stderr: StdioCollector { id: updatesStderr; waitForEnd: true }
onExited: function(exitCode) {
root.checkingUpdates = false
if (exitCode === 0) root.applyUpdates(String(updatesStdout.text || ""))
else root.updatesError = root.elide(String(updatesStderr.text || "") || "dockarchy-updates exited with " + exitCode)
}
}
// Registry checks are slow-ish and rate-limited; run them well apart from
// the status poll: once shortly after startup (served from cache when it
// is fresh), then hourly — the cache's max-age enforces updateCheckHours.
Timer {
id: updatesTimer
interval: 3600 * 1000
repeat: true
running: root.updateCheckHours > 0
onTriggered: root.checkUpdates(false)
}
Timer {
id: updatesKickoff
interval: 20000
repeat: false
running: true
onTriggered: root.checkUpdates(false)
}
Process {
id: actionProcess
running: false
command: []
stdout: StdioCollector { id: actionStdout; waitForEnd: true; onStreamFinished: root._actionOutput = text }
stderr: StdioCollector { id: actionStderr; waitForEnd: true; onStreamFinished: root._actionError = text }
onExited: function(exitCode) {
var stdout = String(actionStdout.text || root._actionOutput || "")
var stderr = String(actionStderr.text || root._actionError || "")
root.pendingActionKey = ""
if (exitCode === 125) {
root.actionStatus = "Command output exceeded the size limit; state refreshed anyway"
} else if (exitCode !== 0) {
root.actionStatus = root.elide(Model.shortError(stderr || stdout) || "docker command failed")
} else {
root.actionStatus = ""
}
actionStatusTimer.restart()
delayedRefresh.restart()
}
}
Timer {
id: refreshTimer
interval: root.refreshIntervalSec * 1000
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refresh()
}
Timer {
id: delayedRefresh
interval: 700
repeat: false
onTriggered: root.refresh()
}
Timer {
id: actionStatusTimer
interval: 6000
repeat: false
onTriggered: root.actionStatus = ""
}
// A poll is skipped while the previous one still runs, so a collector that
// never returns (a wedged ssh session, say) would silently freeze the widget.
// The script already bounds each docker call; this is the belt to its braces.
Timer {
id: pollWatchdog
interval: (root.timeoutSec + 15) * 1000
repeat: false
onTriggered: {
if (!statusProcess.running) return
console.warn("dockarchy: status collector hung, killing it")
statusProcess.running = false
root.refreshing = false
}
}
}