summaryrefslogtreecommitdiff
path: root/raveos-hyprland-theme/theme-data/DankMaterialShell/quickshell/Services/DMSService.qml
blob: 217b96a0eaad4f7c53f5c1b9c730d4f25bcd7499 (plain)
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
pragma Singleton
pragma ComponentBehavior: Bound

import QtQuick
import Quickshell
import Quickshell.Io
import qs.Common

Singleton {
    id: root

    property bool dmsAvailable: false
    property var capabilities: []
    property int apiVersion: 0
    property string cliVersion: ""
    readonly property int expectedApiVersion: 1
    property var availablePlugins: []
    property var installedPlugins: []
    property var availableThemes: []
    property var installedThemes: []
    property bool isConnected: false
    property bool isConnecting: false
    property bool subscribeConnected: false
    readonly property bool forceExtWorkspace: false

    readonly property string socketPath: Quickshell.env("DMS_SOCKET")

    property var pendingRequests: ({})
    property var clipboardRequestIds: ({})
    property int requestIdCounter: 0
    property bool shownOutdatedError: false
    property string updateCommand: "dms update"
    property bool checkingUpdateCommand: false

    signal pluginsListReceived(var plugins)
    signal installedPluginsReceived(var plugins)
    signal searchResultsReceived(var plugins)
    signal themesListReceived(var themes)
    signal installedThemesReceived(var themes)
    signal themeSearchResultsReceived(var themes)
    signal operationSuccess(string message)
    signal operationError(string error)
    signal connectionStateChanged

    signal networkStateUpdate(var data)
    signal cupsStateUpdate(var data)
    signal loginctlStateUpdate(var data)
    signal loginctlEvent(var event)
    signal capabilitiesReceived
    signal credentialsRequest(var data)
    signal bluetoothPairingRequest(var data)
    signal dwlStateUpdate(var data)
    signal brightnessStateUpdate(var data)
    signal brightnessDeviceUpdate(var device)
    signal extWorkspaceStateUpdate(var data)
    signal wlrOutputStateUpdate(var data)
    signal evdevStateUpdate(var data)
    signal gammaStateUpdate(var data)
    signal themeAutoStateUpdate(var data)
    signal openUrlRequested(string url)
    signal appPickerRequested(var data)
    signal screensaverStateUpdate(var data)
    signal clipboardStateUpdate(var data)
    signal locationStateUpdate(var data)

    property bool capsLockState: false
    property bool screensaverInhibited: false
    property var screensaverInhibitors: []

    property var activeSubscriptions: ["network", "network.credentials", "loginctl", "freedesktop", "freedesktop.screensaver", "gamma", "theme.auto", "bluetooth", "bluetooth.pairing", "dwl", "brightness", "wlroutput", "evdev", "browser", "dbus", "clipboard", "location"]

    Component.onCompleted: {
        if (socketPath && socketPath.length > 0) {
            detectUpdateCommand();
        }
    }

    function detectUpdateCommand() {
        checkingUpdateCommand = true;
        checkAurHelper.running = true;
    }

    function startSocketConnection() {
        if (socketPath && socketPath.length > 0) {
            testProcess.running = true;
        }
    }

    Process {
        id: checkAurHelper
        command: ["sh", "-c", "command -v paru || command -v yay"]
        running: false

        stdout: StdioCollector {
            onStreamFinished: {
                const helper = text.trim();
                if (helper.includes("paru")) {
                    checkDmsPackage.helper = "paru";
                    checkDmsPackage.running = true;
                } else if (helper.includes("yay")) {
                    checkDmsPackage.helper = "yay";
                    checkDmsPackage.running = true;
                } else {
                    updateCommand = "dms update";
                    checkingUpdateCommand = false;
                    startSocketConnection();
                }
            }
        }

        onExited: exitCode => {
            if (exitCode !== 0) {
                updateCommand = "dms update";
                checkingUpdateCommand = false;
                startSocketConnection();
            }
        }
    }

    Process {
        id: checkDmsPackage
        property string helper: ""
        command: ["sh", "-c", "pacman -Qi dms-shell-git 2>/dev/null || pacman -Qi dms-shell-bin 2>/dev/null"]
        running: false

        stdout: StdioCollector {
            onStreamFinished: {
                if (text.includes("dms-shell-git")) {
                    updateCommand = checkDmsPackage.helper + " -S dms-shell-git";
                } else if (text.includes("dms-shell-bin")) {
                    updateCommand = checkDmsPackage.helper + " -S dms-shell-bin";
                } else {
                    updateCommand = "dms update";
                }
                checkingUpdateCommand = false;
                startSocketConnection();
            }
        }

        onExited: exitCode => {
            if (exitCode !== 0) {
                updateCommand = "dms update";
                checkingUpdateCommand = false;
                startSocketConnection();
            }
        }
    }

    Process {
        id: testProcess
        command: ["test", "-S", root.socketPath]

        onExited: exitCode => {
            if (exitCode === 0) {
                root.dmsAvailable = true;
                connectSocket();
            } else {
                root.dmsAvailable = false;
            }
        }
    }

    function connectSocket() {
        if (!dmsAvailable || isConnected || isConnecting) {
            return;
        }

        isConnecting = true;
        requestSocket.connected = true;
    }

    DankSocket {
        id: requestSocket
        path: root.socketPath
        connected: false

        onConnectionStateChanged: {
            if (connected) {
                root.isConnected = true;
                root.isConnecting = false;
                root.connectionStateChanged();
                subscribeSocket.connected = true;
            } else {
                root.isConnected = false;
                root.isConnecting = false;
                root.apiVersion = 0;
                root.capabilities = [];
                root.connectionStateChanged();
            }
        }

        parser: SplitParser {
            onRead: line => {
                if (!line || line.length === 0)
                    return;

                let response;
                try {
                    response = JSON.parse(line);
                } catch (e) {
                    console.warn("DMSService: Failed to parse request response:", line.substring(0, 100));
                    return;
                }
                const isClipboard = clipboardRequestIds[response.id];
                if (isClipboard)
                    delete clipboardRequestIds[response.id];
                else
                    console.log("DMSService: Request socket <<", line);
                handleResponse(response);
            }
        }
    }

    DankSocket {
        id: subscribeSocket
        path: root.socketPath
        connected: false

        onConnectionStateChanged: {
            root.subscribeConnected = connected;
            if (connected) {
                sendSubscribeRequest();
            }
        }

        parser: SplitParser {
            onRead: line => {
                if (!line || line.length === 0)
                    return;

                let response;
                try {
                    response = JSON.parse(line);
                } catch (e) {
                    console.warn("DMSService: Failed to parse subscription event:", line.substring(0, 100));
                    return;
                }
                if (!line.includes("clipboard"))
                    console.log("DMSService: Subscribe socket <<", line);
                handleSubscriptionEvent(response);
            }
        }
    }

    function sendSubscribeRequest() {
        const request = {
            "method": "subscribe"
        };

        if (activeSubscriptions.length > 0) {
            request.params = {
                "services": activeSubscriptions
            };
            console.log("DMSService: Subscribing to services:", JSON.stringify(activeSubscriptions));
        } else {
            console.log("DMSService: Subscribing to all services");
        }

        subscribeSocket.send(request);
    }

    function subscribe(services) {
        if (!Array.isArray(services)) {
            services = [services];
        }

        activeSubscriptions = services;

        if (subscribeConnected) {
            subscribeSocket.connected = false;
            Qt.callLater(() => {
                subscribeSocket.connected = true;
            });
        }
    }

    function addSubscription(service) {
        if (activeSubscriptions.includes("all"))
            return;
        if (!activeSubscriptions.includes(service)) {
            const newSubs = [...activeSubscriptions, service];
            subscribe(newSubs);
        }
    }

    function removeSubscription(service) {
        if (activeSubscriptions.includes("all")) {
            const allServices = ["network", "loginctl", "freedesktop", "gamma", "bluetooth", "dwl", "brightness", "extworkspace", "browser", "location"];
            const filtered = allServices.filter(s => s !== service);
            subscribe(filtered);
        } else {
            const filtered = activeSubscriptions.filter(s => s !== service);
            if (filtered.length === 0) {
                console.warn("DMSService: Cannot remove last subscription");
                return;
            }
            subscribe(filtered);
        }
    }

    function subscribeAll() {
        subscribe(["all"]);
    }

    function subscribeAllExcept(excludeServices) {
        if (!Array.isArray(excludeServices)) {
            excludeServices = [excludeServices];
        }

        const allServices = ["network", "loginctl", "freedesktop", "gamma", "theme.auto", "bluetooth", "cups", "dwl", "brightness", "extworkspace", "browser", "dbus", "location"];
        const filtered = allServices.filter(s => !excludeServices.includes(s));
        subscribe(filtered);
    }

    function handleSubscriptionEvent(response) {
        if (response.error) {
            if (response.error.includes("unknown method") && response.error.includes("subscribe")) {
                if (!shownOutdatedError) {
                    console.error("DMSService: Server does not support subscribe method");
                    ToastService.showError(I18n.tr("DMS out of date"), I18n.tr("To update, run the following command:"), updateCommand);
                    shownOutdatedError = true;
                }
            }
            return;
        }

        if (!response.result) {
            return;
        }

        const service = response.result.service;
        const data = response.result.data;

        if (service === "server") {
            apiVersion = data.apiVersion || 0;
            cliVersion = data.cliVersion || "";
            capabilities = data.capabilities || [];

            console.info("DMSService: Connected (API v" + apiVersion + ", CLI " + cliVersion + ") -", JSON.stringify(capabilities));

            if (apiVersion < expectedApiVersion) {
                ToastService.showError("DMS server is outdated (API v" + apiVersion + ", expected v" + expectedApiVersion + ")");
            }

            capabilitiesReceived();
        } else if (service === "network") {
            networkStateUpdate(data);
        } else if (service === "network.credentials") {
            credentialsRequest(data);
        } else if (service === "loginctl") {
            if (data.event) {
                loginctlEvent(data);
            } else {
                loginctlStateUpdate(data);
            }
        } else if (service === "bluetooth.pairing") {
            bluetoothPairingRequest(data);
        } else if (service === "cups") {
            cupsStateUpdate(data);
        } else if (service === "dwl") {
            dwlStateUpdate(data);
        } else if (service === "brightness") {
            brightnessStateUpdate(data);
        } else if (service === "brightness.update") {
            if (data.device) {
                brightnessDeviceUpdate(data.device);
            }
        } else if (service === "extworkspace") {
            extWorkspaceStateUpdate(data);
        } else if (service === "wlroutput") {
            wlrOutputStateUpdate(data);
        } else if (service === "evdev") {
            if (data.capsLock !== undefined) {
                capsLockState = data.capsLock;
            }
            evdevStateUpdate(data);
        } else if (service === "gamma") {
            gammaStateUpdate(data);
        } else if (service === "theme.auto") {
            themeAutoStateUpdate(data);
        } else if (service === "browser.open_requested") {
            if (data.target) {
                if (data.requestType === "url" || !data.requestType) {
                    openUrlRequested(data.target);
                } else {
                    appPickerRequested(data);
                }
            } else if (data.url) {
                openUrlRequested(data.url);
            }
        } else if (service === "freedesktop.screensaver") {
            screensaverInhibited = data.inhibited || false;
            screensaverInhibitors = data.inhibitors || [];
            screensaverStateUpdate(data);
        } else if (service === "dbus") {
            dbusSignalReceived(data.subscriptionId || "", data);
        } else if (service === "clipboard") {
            clipboardStateUpdate(data);
        } else if (service === "location") {
            locationStateUpdate(data);
        }
    }

    function sendRequest(method, params, callback) {
        if (!isConnected) {
            console.warn("DMSService.sendRequest: Not connected, method:", method);
            if (callback) {
                callback({
                    "error": "not connected to DMS socket"
                });
            }
            return;
        }

        requestIdCounter++;
        const id = Date.now() + requestIdCounter;
        const request = {
            "id": id,
            "method": method
        };

        if (params) {
            request.params = params;
        }

        if (callback)
            pendingRequests[id] = callback;

        if (method.startsWith("clipboard")) {
            clipboardRequestIds[id] = true;
        } else {
            console.log("DMSService.sendRequest: Sending request id=" + id + " method=" + method);
        }
        requestSocket.send(request);
    }

    function handleResponse(response) {
        const callback = pendingRequests[response.id];

        if (callback) {
            delete pendingRequests[response.id];
            callback(response);
        }
    }

    function ping(callback) {
        sendRequest("ping", null, callback);
    }

    function listPlugins(callback) {
        sendRequest("plugins.list", null, response => {
            if (response.result) {
                availablePlugins = response.result;
                pluginsListReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function listInstalled(callback) {
        sendRequest("plugins.listInstalled", null, response => {
            if (response.result) {
                installedPlugins = response.result;
                installedPluginsReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function search(query, category, compositor, capability, callback) {
        const params = {
            "query": query
        };
        if (category) {
            params.category = category;
        }
        if (compositor) {
            params.compositor = compositor;
        }
        if (capability) {
            params.capability = capability;
        }

        sendRequest("plugins.search", params, response => {
            if (response.result) {
                searchResultsReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function install(pluginName, callback) {
        sendRequest("plugins.install", {
            "name": pluginName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalled();
            }
        });
    }

    function uninstall(pluginName, callback) {
        sendRequest("plugins.uninstall", {
            "name": pluginName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalled();
            }
        });
    }

    function update(pluginName, callback) {
        sendRequest("plugins.update", {
            "name": pluginName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalled();
            }
        });
    }

    function listThemes(callback) {
        sendRequest("themes.list", null, response => {
            if (response.result) {
                availableThemes = response.result;
                themesListReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function listInstalledThemes(callback) {
        sendRequest("themes.listInstalled", null, response => {
            if (response.result) {
                installedThemes = response.result;
                installedThemesReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function searchThemes(query, callback) {
        sendRequest("themes.search", {
            "query": query
        }, response => {
            if (response.result) {
                themeSearchResultsReceived(response.result);
            }
            if (callback) {
                callback(response);
            }
        });
    }

    function installTheme(themeName, callback) {
        sendRequest("themes.install", {
            "name": themeName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalledThemes();
            }
        });
    }

    function uninstallTheme(themeName, callback) {
        sendRequest("themes.uninstall", {
            "name": themeName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalledThemes();
            }
        });
    }

    function updateTheme(themeName, callback) {
        sendRequest("themes.update", {
            "name": themeName
        }, response => {
            if (callback) {
                callback(response);
            }
            if (!response.error) {
                listInstalledThemes();
            }
        });
    }

    function lockSession(callback) {
        sendRequest("loginctl.lock", null, callback);
    }

    function unlockSession(callback) {
        sendRequest("loginctl.unlock", null, callback);
    }

    function bluetoothPair(devicePath, callback) {
        sendRequest("bluetooth.pair", {
            "device": devicePath
        }, callback);
    }

    function bluetoothConnect(devicePath, callback) {
        sendRequest("bluetooth.connect", {
            "device": devicePath
        }, callback);
    }

    function bluetoothDisconnect(devicePath, callback) {
        sendRequest("bluetooth.disconnect", {
            "device": devicePath
        }, callback);
    }

    function bluetoothRemove(devicePath, callback) {
        sendRequest("bluetooth.remove", {
            "device": devicePath
        }, callback);
    }

    function bluetoothTrust(devicePath, callback) {
        sendRequest("bluetooth.trust", {
            "device": devicePath
        }, callback);
    }

    function bluetoothSubmitPairing(token, secrets, accept, callback) {
        sendRequest("bluetooth.pairing.submit", {
            "token": token,
            "secrets": secrets,
            "accept": accept
        }, callback);
    }

    function bluetoothCancelPairing(token, callback) {
        sendRequest("bluetooth.pairing.cancel", {
            "token": token
        }, callback);
    }

    signal dbusSignalReceived(string subscriptionId, var data)

    property var dbusSubscriptions: ({})

    function dbusCall(bus, dest, path, iface, method, args, callback) {
        sendRequest("dbus.call", {
            "bus": bus,
            "dest": dest,
            "path": path,
            "interface": iface,
            "method": method,
            "args": args || []
        }, callback);
    }

    function dbusGetProperty(bus, dest, path, iface, property, callback) {
        sendRequest("dbus.getProperty", {
            "bus": bus,
            "dest": dest,
            "path": path,
            "interface": iface,
            "property": property
        }, callback);
    }

    function dbusSetProperty(bus, dest, path, iface, property, value, callback) {
        sendRequest("dbus.setProperty", {
            "bus": bus,
            "dest": dest,
            "path": path,
            "interface": iface,
            "property": property,
            "value": value
        }, callback);
    }

    function dbusGetAllProperties(bus, dest, path, iface, callback) {
        sendRequest("dbus.getAllProperties", {
            "bus": bus,
            "dest": dest,
            "path": path,
            "interface": iface
        }, callback);
    }

    function dbusIntrospect(bus, dest, path, callback) {
        sendRequest("dbus.introspect", {
            "bus": bus,
            "dest": dest,
            "path": path || "/"
        }, callback);
    }

    function dbusListNames(bus, callback) {
        sendRequest("dbus.listNames", {
            "bus": bus
        }, callback);
    }

    function dbusSubscribe(bus, sender, path, iface, member, callback) {
        sendRequest("dbus.subscribe", {
            "bus": bus,
            "sender": sender || "",
            "path": path || "",
            "interface": iface || "",
            "member": member || ""
        }, response => {
            if (!response.error && response.result?.subscriptionId) {
                dbusSubscriptions[response.result.subscriptionId] = true;
            }
            if (callback)
                callback(response);
        });
    }

    function dbusUnsubscribe(subscriptionId, callback) {
        sendRequest("dbus.unsubscribe", {
            "subscriptionId": subscriptionId
        }, response => {
            if (!response.error) {
                delete dbusSubscriptions[subscriptionId];
            }
            if (callback)
                callback(response);
        });
    }

    function renameWorkspace(name, callback) {
        sendRequest("extworkspace.renameWorkspace", {
            "name": name
        }, callback);
    }
}