summaryrefslogtreecommitdiff
path: root/raveos-hyprland-theme/theme-data/DankMaterialShell/quickshell/Services/DwlService.qml
blob: 564e5619beda956933c6b53f8bc0a94377a5550e (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
pragma Singleton
pragma ComponentBehavior: Bound

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

Singleton {
    id: root

    readonly property string configDir: Paths.strip(StandardPaths.writableLocation(StandardPaths.ConfigLocation))
    readonly property string mangoDmsDir: configDir + "/mango/dms"
    readonly property string outputsPath: mangoDmsDir + "/outputs.conf"
    readonly property string layoutPath: mangoDmsDir + "/layout.conf"
    readonly property string cursorPath: mangoDmsDir + "/cursor.conf"

    property int _lastGapValue: -1

    property bool dwlAvailable: false
    property var outputs: ({})
    property var tagCount: 9
    property var layouts: []
    property string activeOutput: ""
    property var outputScales: ({})
    property string currentKeyboardLayout: {
        if (!outputs || !activeOutput)
            return "";
        const output = outputs[activeOutput];
        return (output && output.kbLayout) || "";
    }

    signal stateChanged

    Connections {
        target: SettingsData
        function onBarConfigsChanged() {
            if (!CompositorService.isDwl)
                return;
            const newGaps = Math.max(4, (SettingsData.barConfigs[0]?.spacing ?? 4));
            if (newGaps === root._lastGapValue)
                return;
            root._lastGapValue = newGaps;
            generateLayoutConfig();
        }
    }

    Connections {
        target: CompositorService
        function onIsDwlChanged() {
            if (CompositorService.isDwl)
                generateLayoutConfig();
        }
    }

    Connections {
        target: DMSService
        function onCapabilitiesReceived() {
            checkCapabilities();
        }
        function onConnectionStateChanged() {
            if (DMSService.isConnected) {
                checkCapabilities();
            } else {
                dwlAvailable = false;
            }
        }
        function onDwlStateUpdate(data) {
            if (dwlAvailable) {
                handleStateUpdate(data);
            }
        }
    }

    Component.onCompleted: {
        if (DMSService.dmsAvailable)
            checkCapabilities();
        if (dwlAvailable)
            refreshOutputScales();
        if (CompositorService.isDwl)
            Qt.callLater(generateLayoutConfig);
    }

    function checkCapabilities() {
        if (!DMSService.capabilities || !Array.isArray(DMSService.capabilities)) {
            dwlAvailable = false;
            return;
        }

        const hasDwl = DMSService.capabilities.includes("dwl");
        if (hasDwl && !dwlAvailable) {
            dwlAvailable = true;
            console.info("DwlService: DWL capability detected");
            requestState();
            refreshOutputScales();
        } else if (!hasDwl) {
            dwlAvailable = false;
        }
    }

    function requestState() {
        if (!DMSService.isConnected || !dwlAvailable) {
            return;
        }

        DMSService.sendRequest("dwl.getState", null, response => {
            if (response.result) {
                handleStateUpdate(response.result);
            }
        });
    }

    function handleStateUpdate(state) {
        outputs = state.outputs || {};
        tagCount = state.tagCount || 9;
        layouts = state.layouts || [];
        activeOutput = state.activeOutput || "";
        stateChanged();
    }

    function setTags(outputName, tagmask, toggleTagset) {
        if (!DMSService.isConnected || !dwlAvailable) {
            return;
        }

        DMSService.sendRequest("dwl.setTags", {
            "output": outputName,
            "tagmask": tagmask,
            "toggleTagset": toggleTagset
        }, response => {
            if (response.error) {
                console.warn("DwlService: setTags error:", response.error);
            }
        });
    }

    function setClientTags(outputName, andTags, xorTags) {
        if (!DMSService.isConnected || !dwlAvailable) {
            return;
        }

        DMSService.sendRequest("dwl.setClientTags", {
            "output": outputName,
            "andTags": andTags,
            "xorTags": xorTags
        }, response => {
            if (response.error) {
                console.warn("DwlService: setClientTags error:", response.error);
            }
        });
    }

    function setLayout(outputName, index) {
        if (!DMSService.isConnected || !dwlAvailable) {
            return;
        }

        DMSService.sendRequest("dwl.setLayout", {
            "output": outputName,
            "index": index
        }, response => {
            if (response.error) {
                console.warn("DwlService: setLayout error:", response.error);
            }
        });
    }

    function getOutputState(outputName) {
        if (!outputs || !outputs[outputName]) {
            return null;
        }
        return outputs[outputName];
    }

    function getActiveTags(outputName) {
        const output = getOutputState(outputName);
        if (!output || !output.tags) {
            return [];
        }
        return output.tags.filter(tag => tag.state === 1).map(tag => tag.tag);
    }

    function getTagsWithClients(outputName) {
        const output = getOutputState(outputName);
        if (!output || !output.tags) {
            return [];
        }
        return output.tags.filter(tag => tag.clients > 0).map(tag => tag.tag);
    }

    function getUrgentTags(outputName) {
        const output = getOutputState(outputName);
        if (!output || !output.tags) {
            return [];
        }
        return output.tags.filter(tag => tag.state === 2).map(tag => tag.tag);
    }

    function switchToTag(outputName, tagIndex) {
        const tagmask = 1 << tagIndex;
        setTags(outputName, tagmask, 0);
    }

    function toggleTag(outputName, tagIndex) {
        const output = getOutputState(outputName);
        if (!output || !output.tags) {
            console.log("toggleTag: no output or tags for", outputName);
            return;
        }

        let currentMask = 0;
        output.tags.forEach(tag => {
            if (tag.state === 1) {
                currentMask |= (1 << tag.tag);
            }
        });

        const clickedMask = 1 << tagIndex;
        const newMask = currentMask ^ clickedMask;

        console.log("toggleTag:", outputName, "tag:", tagIndex, "currentMask:", currentMask.toString(2), "clickedMask:", clickedMask.toString(2), "newMask:", newMask.toString(2));

        if (newMask === 0) {
            console.log("toggleTag: newMask is 0, switching to tag", tagIndex);
            setTags(outputName, 1 << tagIndex, 0);
        } else {
            console.log("toggleTag: setting combined mask", newMask);
            setTags(outputName, newMask, 0);
        }
    }

    function quit() {
        Quickshell.execDetached(["mmsg", "-d", "quit"]);
    }

    Process {
        id: scaleQueryProcess
        command: ["mmsg", "-A"]
        running: false

        stdout: StdioCollector {
            onStreamFinished: {
                try {
                    const newScales = {};
                    const lines = text.trim().split('\n');
                    for (const line of lines) {
                        const parts = line.trim().split(/\s+/);
                        if (parts.length >= 3 && parts[1] === "scale_factor") {
                            const outputName = parts[0];
                            const scale = parseFloat(parts[2]);
                            if (!isNaN(scale)) {
                                newScales[outputName] = scale;
                            }
                        }
                    }
                    outputScales = newScales;
                } catch (e) {
                    console.warn("DwlService: Failed to parse mmsg output:", e);
                }
            }
        }

        onExited: exitCode => {
            if (exitCode !== 0) {
                console.warn("DwlService: mmsg failed with exit code:", exitCode);
            }
        }
    }

    function refreshOutputScales() {
        if (!dwlAvailable)
            return;
        scaleQueryProcess.running = true;
    }

    function getOutputScale(outputName) {
        return outputScales[outputName];
    }

    function getVisibleTags(outputName) {
        const output = getOutputState(outputName);
        if (!output || !output.tags) {
            return [];
        }

        const visibleTags = new Set();

        output.tags.forEach(tag => {
            if (tag.state === 1 || tag.clients > 0) {
                visibleTags.add(tag.tag);
            }
        });

        return Array.from(visibleTags).sort((a, b) => a - b);
    }

    function generateOutputsConfig(outputsData) {
        if (!outputsData || Object.keys(outputsData).length === 0)
            return;
        let lines = ["# Auto-generated by DMS - do not edit manually", ""];

        for (const outputName in outputsData) {
            const output = outputsData[outputName];
            if (!output)
                continue;
            let width = 1920;
            let height = 1080;
            let refreshRate = 60;
            if (output.modes && output.current_mode !== undefined) {
                const mode = output.modes[output.current_mode];
                if (mode) {
                    width = mode.width || 1920;
                    height = mode.height || 1080;
                    refreshRate = Math.round((mode.refresh_rate || 60000) / 1000);
                }
            }

            const x = output.logical?.x ?? 0;
            const y = output.logical?.y ?? 0;
            const scale = output.logical?.scale ?? 1.0;
            const transform = transformToMango(output.logical?.transform ?? "Normal");
            const vrr = output.vrr_enabled ? 1 : 0;

            const rule = ["name:" + outputName, "width:" + width, "height:" + height, "refresh:" + refreshRate, "x:" + x, "y:" + y, "scale:" + scale, "rr:" + transform, "vrr:" + vrr].join(",");

            lines.push("monitorrule=" + rule);
        }

        lines.push("");

        const content = lines.join("\n");

        Proc.runCommand("mango-write-outputs", ["sh", "-c", `mkdir -p "${mangoDmsDir}" && cat > "${outputsPath}" << 'EOF'\n${content}EOF`], (output, exitCode) => {
            if (exitCode !== 0) {
                console.warn("DwlService: Failed to write outputs config:", output);
                return;
            }
            console.info("DwlService: Generated outputs config at", outputsPath);
            if (CompositorService.isDwl)
                reloadConfig();
        });
    }

    function reloadConfig() {
        Proc.runCommand("mango-reload", ["mmsg", "-d", "reload_config"], (output, exitCode) => {
            if (exitCode !== 0)
                console.warn("DwlService: mmsg reload_config failed:", output);
        });
    }

    function generateLayoutConfig() {
        if (!CompositorService.isDwl)
            return;

        const defaultRadius = typeof SettingsData !== "undefined" ? SettingsData.cornerRadius : 12;
        const defaultGaps = typeof SettingsData !== "undefined" ? Math.max(4, (SettingsData.barConfigs[0]?.spacing ?? 4)) : 4;
        const defaultBorderSize = 2;

        const cornerRadius = (typeof SettingsData !== "undefined" && SettingsData.mangoLayoutRadiusOverride >= 0) ? SettingsData.mangoLayoutRadiusOverride : defaultRadius;
        const gaps = (typeof SettingsData !== "undefined" && SettingsData.mangoLayoutGapsOverride >= 0) ? SettingsData.mangoLayoutGapsOverride : defaultGaps;
        const borderSize = (typeof SettingsData !== "undefined" && SettingsData.mangoLayoutBorderSize >= 0) ? SettingsData.mangoLayoutBorderSize : defaultBorderSize;

        let content = `# Auto-generated by DMS - do not edit manually
border_radius=${cornerRadius}
gappih=${gaps}
gappiv=${gaps}
gappoh=${gaps}
gappov=${gaps}
borderpx=${borderSize}
`;

        Proc.runCommand("mango-write-layout", ["sh", "-c", `mkdir -p "${mangoDmsDir}" && cat > "${layoutPath}" << 'EOF'\n${content}EOF`], (output, exitCode) => {
            if (exitCode !== 0) {
                console.warn("DwlService: Failed to write layout config:", output);
                return;
            }
            console.info("DwlService: Generated layout config at", layoutPath);
            reloadConfig();
        });
    }

    function transformToMango(transform) {
        switch (transform) {
        case "Normal":
            return 0;
        case "90":
            return 1;
        case "180":
            return 2;
        case "270":
            return 3;
        case "Flipped":
            return 4;
        case "Flipped90":
            return 5;
        case "Flipped180":
            return 6;
        case "Flipped270":
            return 7;
        default:
            return 0;
        }
    }

    function generateCursorConfig() {
        if (!CompositorService.isDwl)
            return;

        console.log("DwlService: Generating cursor config...");

        const settings = typeof SettingsData !== "undefined" ? SettingsData.cursorSettings : null;
        if (!settings) {
            Proc.runCommand("mango-write-cursor", ["sh", "-c", `mkdir -p "${mangoDmsDir}" && : > "${cursorPath}"`], (output, exitCode) => {
                if (exitCode !== 0)
                    console.warn("DwlService: Failed to write cursor config:", output);
            });
            return;
        }

        const themeName = settings.theme === "System Default" ? (SettingsData.systemDefaultCursorTheme || "") : settings.theme;
        const size = settings.size || 24;
        const hideTimeout = settings.dwl?.cursorHideTimeout || 0;

        const isDefaultConfig = !themeName && size === 24 && hideTimeout === 0;
        if (isDefaultConfig) {
            Proc.runCommand("mango-write-cursor", ["sh", "-c", `mkdir -p "${mangoDmsDir}" && : > "${cursorPath}"`], (output, exitCode) => {
                if (exitCode !== 0)
                    console.warn("DwlService: Failed to write cursor config:", output);
            });
            return;
        }

        let content = `# Auto-generated by DMS - do not edit manually
cursor_size=${size}`;

        if (themeName)
            content += `\ncursor_theme=${themeName}`;

        if (hideTimeout > 0)
            content += `\ncursor_hide_timeout=${hideTimeout}`;

        content += `\n`;

        Proc.runCommand("mango-write-cursor", ["sh", "-c", `mkdir -p "${mangoDmsDir}" && cat > "${cursorPath}" << 'EOF'\n${content}EOF`], (output, exitCode) => {
            if (exitCode !== 0) {
                console.warn("DwlService: Failed to write cursor config:", output);
                return;
            }
            console.info("DwlService: Generated cursor config at", cursorPath);
            reloadConfig();
        });
    }
}