summaryrefslogtreecommitdiff
path: root/raveos-hyprland-theme/theme-data/DankMaterialShell/quickshell/Services/DisplayService.qml
blob: 553dd26bb0e937196e76af47c67d719af6fc0ee1 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
pragma Singleton
pragma ComponentBehavior: Bound

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

Singleton {
    id: root

    property bool brightnessAvailable: devices.length > 0
    property var devices: []
    property var deviceBrightness: ({})
    property var deviceBrightnessUserSet: ({})
    property var deviceMaxCache: ({})
    property var userControlledDevices: ({})
    property var pendingOsdDevices: ({})
    property int brightnessVersion: 0
    property string currentDevice: ""
    property string lastIpcDevice: ""
    property int brightnessLevel: {
        brightnessVersion;
        const deviceToUse = lastIpcDevice === "" ? getDefaultDevice() : (lastIpcDevice || currentDevice);
        if (!deviceToUse) {
            return 50;
        }

        return getDeviceBrightness(deviceToUse);
    }
    property int maxBrightness: 100
    property bool brightnessInitialized: false
    property bool suppressOsd: true

    signal brightnessChanged(bool showOsd)
    signal deviceSwitched

    property bool nightModeActive: nightModeEnabled

    property bool nightModeEnabled: false
    property bool automationAvailable: false
    property bool gammaControlAvailable: false

    property var gammaState: ({})
    property int gammaCurrentTemp: gammaState?.currentTemp ?? 0
    property string gammaNextTransition: gammaState?.nextTransition ?? ""
    property string gammaSunriseTime: gammaState?.sunriseTime ?? ""
    property string gammaSunsetTime: gammaState?.sunsetTime ?? ""
    property string gammaDawnTime: gammaState?.dawnTime ?? ""
    property string gammaNightTime: gammaState?.nightTime ?? ""
    property bool gammaIsDay: gammaState?.isDay ?? true
    property real gammaSunPosition: gammaState?.sunPosition ?? 0
    property int gammaLowTemp: gammaState?.config?.LowTemp ?? 0
    property int gammaHighTemp: gammaState?.config?.HighTemp ?? 0

    function markDeviceUserControlled(deviceId) {
        const newControlled = Object.assign({}, userControlledDevices);
        newControlled[deviceId] = Date.now();
        userControlledDevices = newControlled;
    }

    function isDeviceUserControlled(deviceId) {
        const controlTime = userControlledDevices[deviceId];
        if (!controlTime) {
            return false;
        }
        return (Date.now() - controlTime) < 1000;
    }

    function clearDeviceUserControlled(deviceId) {
        const newControlled = Object.assign({}, userControlledDevices);
        delete newControlled[deviceId];
        userControlledDevices = newControlled;
    }

    function markDevicePendingOsd(deviceId) {
        const newPending = Object.assign({}, pendingOsdDevices);
        newPending[deviceId] = true;
        pendingOsdDevices = newPending;
    }

    function clearDevicePendingOsd(deviceId) {
        const newPending = Object.assign({}, pendingOsdDevices);
        delete newPending[deviceId];
        pendingOsdDevices = newPending;
    }

    function updateSingleDevice(device) {
        if (device.class === "leds") {
            return;
        }

        const isUserControlled = isDeviceUserControlled(device.id);
        if (isUserControlled) {
            return;
        }

        const deviceIndex = devices.findIndex(d => d.id === device.id);
        if (deviceIndex !== -1) {
            const newDevices = [...devices];
            const cachedMax = deviceMaxCache[device.id];

            let displayMax = cachedMax || (device.class === "ddc" ? device.max : 100);
            if (displayMax > 0 && !cachedMax) {
                const newCache = Object.assign({}, deviceMaxCache);
                newCache[device.id] = displayMax;
                deviceMaxCache = newCache;
            }

            newDevices[deviceIndex] = {
                "id": device.id,
                "name": device.id,
                "class": device.class,
                "current": device.current,
                "percentage": device.currentPercent,
                "max": device.max,
                "backend": device.backend,
                "displayMax": displayMax
            };
            devices = newDevices;
        }

        const isExponential = SessionData.getBrightnessExponential(device.id);
        const userSetValue = deviceBrightnessUserSet[device.id];

        let displayValue = device.currentPercent;
        if (isExponential) {
            if (userSetValue !== undefined) {
                const exponent = SessionData.getBrightnessExponent(device.id);
                const expectedHardware = Math.round(Math.pow(userSetValue / 100.0, exponent) * 100.0);
                if (Math.abs(device.currentPercent - expectedHardware) > 2) {
                    const newUserSet = Object.assign({}, deviceBrightnessUserSet);
                    delete newUserSet[device.id];
                    deviceBrightnessUserSet = newUserSet;
                    SessionData.clearBrightnessUserSetValue(device.id);
                    displayValue = linearToExponential(device.currentPercent, device.id);
                } else {
                    displayValue = userSetValue;
                }
            } else {
                displayValue = linearToExponential(device.currentPercent, device.id);
            }
        }

        const oldValue = deviceBrightness[device.id];
        const newBrightness = Object.assign({}, deviceBrightness);
        newBrightness[device.id] = displayValue;
        deviceBrightness = newBrightness;
        brightnessVersion++;

        const isPendingOsd = pendingOsdDevices[device.id] === true;
        if (isPendingOsd) {
            clearDevicePendingOsd(device.id);
            if (!suppressOsd) {
                brightnessChanged(true);
            }
            return;
        }

        if (!brightnessInitialized || oldValue === displayValue) {
            return;
        }
        if (suppressOsd) {
            return;
        }
        brightnessChanged(true);
    }

    function updateFromBrightnessState(state) {
        if (!state || !state.devices) {
            return;
        }

        const newMaxCache = Object.assign({}, deviceMaxCache);
        devices = state.devices.map(d => {
            const cachedMax = deviceMaxCache[d.id];
            let displayMax = cachedMax || (d.class === "ddc" ? d.max : 100);
            if (displayMax > 0 && !cachedMax) {
                newMaxCache[d.id] = displayMax;
            }
            return {
                "id": d.id,
                "name": d.id,
                "class": d.class,
                "current": d.current,
                "percentage": d.currentPercent,
                "max": d.max,
                "backend": d.backend,
                "displayMax": displayMax
            };
        });
        deviceMaxCache = newMaxCache;

        const newBrightness = {};
        let anyDeviceBrightnessChanged = false;

        for (const device of state.devices) {
            const isExponential = SessionData.getBrightnessExponential(device.id);
            const userSetValue = deviceBrightnessUserSet[device.id];
            const oldValue = deviceBrightness[device.id];

            if (isExponential) {
                if (userSetValue !== undefined) {
                    newBrightness[device.id] = userSetValue;
                } else {
                    newBrightness[device.id] = linearToExponential(device.currentPercent, device.id);
                }
            } else {
                newBrightness[device.id] = device.currentPercent;
            }

            const newValue = newBrightness[device.id];
            if (oldValue !== undefined && oldValue !== newValue) {
                anyDeviceBrightnessChanged = true;
            }
        }
        deviceBrightness = newBrightness;
        brightnessVersion++;

        brightnessAvailable = devices.length > 0;

        if (devices.length > 0 && !currentDevice) {
            const lastDevice = SessionData.lastBrightnessDevice || "";
            const deviceExists = devices.some(d => d.id === lastDevice);
            if (deviceExists) {
                setCurrentDevice(lastDevice, false);
            } else {
                const backlight = devices.find(d => d.class === "backlight");
                const nonKbdDevice = devices.find(d => !d.id.includes("kbd"));
                const defaultDevice = backlight || nonKbdDevice || devices[0];
                setCurrentDevice(defaultDevice.id, false);
            }
        }

        const shouldShowOsd = brightnessInitialized && anyDeviceBrightnessChanged;

        if (!brightnessInitialized) {
            brightnessInitialized = true;
        }

        if (shouldShowOsd) {
            brightnessChanged(true);
        }
    }

    function setBrightness(percentage, device, suppressOsd) {
        const actualDevice = device === "" ? getDefaultDevice() : (device || currentDevice || getDefaultDevice());
        if (!actualDevice) {
            console.warn("DisplayService: No device selected for brightness change");
            return;
        }

        if (actualDevice !== lastIpcDevice) {
            lastIpcDevice = actualDevice;
        }

        const deviceInfo = getCurrentDeviceInfoByName(actualDevice);
        const isExponential = SessionData.getBrightnessExponential(actualDevice);

        let minValue = 0;
        let maxValue = 100;

        switch (true) {
        case isExponential:
            minValue = 1;
            maxValue = 100;
            break;
        default:
            minValue = (deviceInfo && (deviceInfo.class === "backlight" || deviceInfo.class === "ddc")) ? 1 : 0;
            maxValue = deviceInfo?.displayMax || 100;
            break;
        }

        if (maxValue <= 0) {
            console.warn("DisplayService: Invalid max value for device", actualDevice, "- skipping brightness change");
            return;
        }

        const clampedValue = Math.max(minValue, Math.min(maxValue, percentage));

        if (!DMSService.isConnected) {
            console.warn("DisplayService: Not connected to DMS");
            return;
        }

        const isLedDevice = deviceInfo?.class === "leds";

        if (suppressOsd) {
            markDeviceUserControlled(actualDevice);
        } else if (!isLedDevice) {
            markDevicePendingOsd(actualDevice);
        }

        const newBrightness = Object.assign({}, deviceBrightness);
        newBrightness[actualDevice] = clampedValue;
        deviceBrightness = newBrightness;
        brightnessVersion++;

        if (isLedDevice && !suppressOsd) {
            brightnessChanged(true);
        }

        if (isExponential) {
            const newUserSet = Object.assign({}, deviceBrightnessUserSet);
            newUserSet[actualDevice] = clampedValue;
            deviceBrightnessUserSet = newUserSet;
            SessionData.setBrightnessUserSetValue(actualDevice, clampedValue);
        }

        const params = {
            "device": actualDevice,
            "percent": clampedValue
        };
        if (isExponential) {
            params.exponential = true;
            params.exponent = SessionData.getBrightnessExponent(actualDevice);
        }

        DMSService.sendRequest("brightness.setBrightness", params, response => {
            if (response.error) {
                console.error("DisplayService: Failed to set brightness:", response.error);
                ToastService.showError(I18n.tr("Failed to set brightness"), response.error, "", "brightness");
            } else {
                ToastService.dismissCategory("brightness");
            }
        });
    }

    function setCurrentDevice(deviceName, saveToSession = false) {
        if (currentDevice === deviceName) {
            return;
        }

        currentDevice = deviceName;
        lastIpcDevice = deviceName;

        if (saveToSession) {
            SessionData.setLastBrightnessDevice(deviceName);
        }

        deviceSwitched();
    }

    function getDeviceBrightness(deviceName) {
        if (!deviceName) {
            return 50;
        }

        if (deviceName in deviceBrightness) {
            return deviceBrightness[deviceName];
        }

        return 50;
    }

    function linearToExponential(linearPercent, deviceName) {
        const exponent = SessionData.getBrightnessExponent(deviceName);
        const hardwarePercent = linearPercent / 100.0;
        const normalizedPercent = Math.pow(hardwarePercent, 1.0 / exponent);
        return Math.round(normalizedPercent * 100.0);
    }

    function getDefaultDevice() {
        for (const device of devices) {
            if (device.class === "backlight") {
                return device.id;
            }
        }
        return devices.length > 0 ? devices[0].id : "";
    }

    function getPinnedDeviceForFocusedScreen() {
        const focusedScreen = CompositorService.getFocusedScreen();
        if (!focusedScreen)
            return "";

        const pins = SettingsData.brightnessDevicePins || {};
        const screenKey = SettingsData.getScreenDisplayName(focusedScreen);
        if (!screenKey)
            return "";

        const pinnedDevice = pins[screenKey];
        if (!pinnedDevice)
            return "";

        const deviceExists = devices.some(d => d.id === pinnedDevice);
        if (!deviceExists)
            return "";

        return pinnedDevice;
    }

    function getPreferredDevice() {
        const pinned = getPinnedDeviceForFocusedScreen();
        if (pinned)
            return pinned;

        return getDefaultDevice();
    }

    function getCurrentDeviceInfo() {
        const deviceToUse = lastIpcDevice === "" ? getDefaultDevice() : (lastIpcDevice || currentDevice);
        if (!deviceToUse) {
            return null;
        }

        for (const device of devices) {
            if (device.id === deviceToUse) {
                return device;
            }
        }
        return null;
    }

    function isCurrentDeviceReady() {
        const deviceToUse = lastIpcDevice === "" ? getDefaultDevice() : (lastIpcDevice || currentDevice);
        return deviceToUse !== "";
    }

    function getCurrentDeviceInfoByName(deviceName) {
        if (!deviceName) {
            return null;
        }

        for (const device of devices) {
            if (device.id === deviceName) {
                return device;
            }
        }
        return null;
    }

    function getDeviceMax(deviceName) {
        const deviceInfo = getCurrentDeviceInfoByName(deviceName);
        if (!deviceInfo) {
            return 100;
        }
        return deviceInfo.displayMax || 100;
    }

    // Night Mode Functions - Simplified
    function enableNightMode() {
        if (!gammaControlAvailable) {
            ToastService.showWarning("Night mode failed: DMS gamma control not available");
            return;
        }

        nightModeEnabled = true;
        SessionData.setNightModeEnabled(true);

        DMSService.sendRequest("wayland.gamma.setEnabled", {
            "enabled": true
        }, response => {
            if (response.error) {
                console.error("DisplayService: Failed to enable gamma control:", response.error);
                ToastService.showError(I18n.tr("Failed to enable night mode"), response.error, "", "night-mode");
                nightModeEnabled = false;
                SessionData.setNightModeEnabled(false);
                return;
            }
            ToastService.dismissCategory("night-mode");

            if (SessionData.nightModeAutoEnabled) {
                startAutomation();
            } else {
                applyNightModeDirectly();
            }
        });
    }

    function disableNightMode() {
        nightModeEnabled = false;
        SessionData.setNightModeEnabled(false);

        if (!gammaControlAvailable) {
            return;
        }

        DMSService.sendRequest("wayland.gamma.setEnabled", {
            "enabled": false
        }, response => {
            if (response.error) {
                console.error("DisplayService: Failed to disable gamma control:", response.error);
                ToastService.showError(I18n.tr("Failed to disable night mode"), response.error, "", "night-mode");
            } else {
                ToastService.dismissCategory("night-mode");
            }
        });
    }

    function toggleNightMode() {
        if (nightModeEnabled) {
            disableNightMode();
        } else {
            enableNightMode();
        }
    }

    function applyNightModeDirectly() {
        const temperature = SessionData.nightModeTemperature || 4000;

        DMSService.sendRequest("wayland.gamma.setManualTimes", {
            "sunrise": null,
            "sunset": null
        }, response => {
            if (response.error) {
                console.error("DisplayService: Failed to clear manual times:", response.error);
                return;
            }

            DMSService.sendRequest("wayland.gamma.setUseIPLocation", {
                "use": false
            }, response => {
                if (response.error) {
                    console.error("DisplayService: Failed to disable IP location:", response.error);
                    return;
                }

                DMSService.sendRequest("wayland.gamma.setTemperature", {
                    "low": temperature,
                    "high": temperature
                }, response => {
                    if (response.error) {
                        console.error("DisplayService: Failed to set temperature:", response.error);
                        ToastService.showError(I18n.tr("Failed to set night mode temperature"), response.error, "", "night-mode");
                    } else {
                        ToastService.dismissCategory("night-mode");
                    }
                });
            });
        });
    }

    function startAutomation() {
        if (!automationAvailable) {
            return;
        }

        const mode = SessionData.nightModeAutoMode || "time";

        switch (mode) {
        case "time":
            startTimeBasedMode();
            break;
        case "location":
            startLocationBasedMode();
            break;
        }
    }

    function startTimeBasedMode() {
        const temperature = SessionData.nightModeTemperature || 4000;
        const highTemp = SessionData.nightModeHighTemperature || 6500;
        const sunriseHour = SessionData.nightModeEndHour;
        const sunriseMinute = SessionData.nightModeEndMinute;
        const sunsetHour = SessionData.nightModeStartHour;
        const sunsetMinute = SessionData.nightModeStartMinute;

        const sunrise = `${String(sunriseHour).padStart(2, '0')}:${String(sunriseMinute).padStart(2, '0')}`;
        const sunset = `${String(sunsetHour).padStart(2, '0')}:${String(sunsetMinute).padStart(2, '0')}`;

        DMSService.sendRequest("wayland.gamma.setUseIPLocation", {
            "use": false
        }, response => {
            if (response.error) {
                console.error("DisplayService: Failed to disable IP location:", response.error);
                return;
            }

            DMSService.sendRequest("wayland.gamma.setTemperature", {
                "low": temperature,
                "high": highTemp
            }, response => {
                if (response.error) {
                    console.error("DisplayService: Failed to set temperature:", response.error);
                    ToastService.showError(I18n.tr("Failed to set night mode temperature"), response.error, "", "night-mode");
                    return;
                }

                DMSService.sendRequest("wayland.gamma.setManualTimes", {
                    "sunrise": sunrise,
                    "sunset": sunset
                }, response => {
                    if (response.error) {
                        console.error("DisplayService: Failed to set manual times:", response.error);
                        ToastService.showError(I18n.tr("Failed to set night mode schedule"), response.error, "", "night-mode");
                    } else {
                        ToastService.dismissCategory("night-mode");
                    }
                });
            });
        });
    }

    function startLocationBasedMode() {
        const temperature = SessionData.nightModeTemperature || 4000;
        const highTemp = SessionData.nightModeHighTemperature || 6500;

        DMSService.sendRequest("wayland.gamma.setManualTimes", {
            "sunrise": null,
            "sunset": null
        }, response => {
            if (response.error) {
                console.error("DisplayService: Failed to clear manual times:", response.error);
                return;
            }

            DMSService.sendRequest("wayland.gamma.setTemperature", {
                "low": temperature,
                "high": highTemp
            }, response => {
                if (response.error) {
                    console.error("DisplayService: Failed to set temperature:", response.error);
                    ToastService.showError(I18n.tr("Failed to set night mode temperature"), response.error, "", "night-mode");
                    return;
                }

                if (SessionData.nightModeUseIPLocation) {
                    DMSService.sendRequest("wayland.gamma.setUseIPLocation", {
                        "use": true
                    }, response => {
                        if (response.error) {
                            console.error("DisplayService: Failed to enable IP location:", response.error);
                            ToastService.showError(I18n.tr("Failed to enable IP location"), response.error, "", "night-mode");
                        } else {
                            ToastService.dismissCategory("night-mode");
                        }
                    });
                } else if (SessionData.latitude !== 0.0 && SessionData.longitude !== 0.0) {
                    DMSService.sendRequest("wayland.gamma.setUseIPLocation", {
                        "use": false
                    }, response => {
                        if (response.error) {
                            console.error("DisplayService: Failed to disable IP location:", response.error);
                            return;
                        }

                        DMSService.sendRequest("wayland.gamma.setLocation", {
                            "latitude": SessionData.latitude,
                            "longitude": SessionData.longitude
                        }, response => {
                            if (response.error) {
                                console.error("DisplayService: Failed to set location:", response.error);
                                ToastService.showError(I18n.tr("Failed to set night mode location"), response.error, "", "night-mode");
                            } else {
                                ToastService.dismissCategory("night-mode");
                            }
                        });
                    });
                } else {
                    console.warn("DisplayService: Location mode selected but no coordinates set and IP location disabled");
                }
            });
        });
    }

    function setNightModeAutomationMode(mode) {
        SessionData.setNightModeAutoMode(mode);
    }

    function evaluateNightMode() {
        if (!nightModeEnabled) {
            return;
        }

        if (SessionData.nightModeAutoEnabled) {
            restartTimer.nextAction = "automation";
            restartTimer.start();
        } else {
            restartTimer.nextAction = "direct";
            restartTimer.start();
        }
    }

    function checkGammaControlAvailability() {
        if (!DMSService.isConnected) {
            return;
        }

        if (DMSService.apiVersion < 6) {
            gammaControlAvailable = false;
            automationAvailable = false;
            return;
        }

        if (!DMSService.capabilities.includes("gamma")) {
            gammaControlAvailable = false;
            automationAvailable = false;
            return;
        }

        DMSService.sendRequest("wayland.gamma.getState", null, response => {
            if (response.error) {
                gammaControlAvailable = false;
                automationAvailable = false;
                console.error("DisplayService: Gamma control not available:", response.error);
            } else {
                gammaControlAvailable = true;
                automationAvailable = true;

                if (nightModeEnabled) {
                    DMSService.sendRequest("wayland.gamma.setEnabled", {
                        "enabled": true
                    }, enableResponse => {
                        if (enableResponse.error) {
                            console.error("DisplayService: Failed to enable gamma control on startup:", enableResponse.error);
                            return;
                        }

                        evaluateNightMode();
                    });
                }
            }
        });
    }

    Timer {
        id: restartTimer
        property string nextAction: ""
        interval: 250
        repeat: false

        onTriggered: {
            if (nextAction === "automation") {
                startAutomation();
            } else if (nextAction === "direct") {
                applyNightModeDirectly();
            }
            nextAction = "";
        }
    }

    function rescanDevices() {
        if (!DMSService.isConnected) {
            return;
        }

        DMSService.sendRequest("brightness.rescan", null, response => {
            if (response.error) {
                console.error("DisplayService: Failed to rescan brightness devices:", response.error);
            }
        });
    }

    function updateDeviceBrightnessDisplay(deviceName) {
        brightnessVersion++;
        brightnessChanged();
    }

    Timer {
        id: osdSuppressTimer
        interval: 2000
        running: true
        onTriggered: suppressOsd = false
    }

    Component.onCompleted: {
        nightModeEnabled = SessionData.nightModeEnabled;
        deviceBrightnessUserSet = Object.assign({}, SessionData.brightnessUserSetValues);
        if (DMSService.isConnected) {
            checkGammaControlAvailability();
        }
    }

    Timer {
        id: screenChangeRescanTimer
        property int rescanAttempt: 0
        interval: 3000
        repeat: false
        onTriggered: {
            rescanDevices();
            rescanAttempt++;
            if (rescanAttempt < 3) {
                interval = rescanAttempt === 1 ? 5000 : 8000;
                restart();
            } else {
                rescanAttempt = 0;
                interval = 3000;
            }
        }
    }

    Connections {
        target: Quickshell

        function onScreensChanged() {
            screenChangeRescanTimer.rescanAttempt = 0;
            screenChangeRescanTimer.interval = 3000;
            screenChangeRescanTimer.restart();
        }
    }

    Connections {
        target: DMSService

        function onConnectionStateChanged() {
            if (DMSService.isConnected) {
                checkGammaControlAvailability();
            } else {
                brightnessAvailable = false;
                gammaControlAvailable = false;
                automationAvailable = false;
            }
        }

        function onCapabilitiesReceived() {
            checkGammaControlAvailability();
        }

        function onBrightnessStateUpdate(data) {
            updateFromBrightnessState(data);
        }

        function onBrightnessDeviceUpdate(device) {
            updateSingleDevice(device);
        }

        function onLoginctlEvent(event) {
            if (event.event === "unlock" || event.event === "resume") {
                suppressOsd = true;
                osdSuppressTimer.restart();
                evaluateNightMode();
            }
        }

        function onGammaStateUpdate(data) {
            root.gammaState = data;
        }
    }

    // Session Data Connections
    Connections {
        target: SessionData

        function onNightModeEnabledChanged() {
            nightModeEnabled = SessionData.nightModeEnabled;
            evaluateNightMode();
        }

        function onNightModeAutoEnabledChanged() {
            evaluateNightMode();
        }
        function onNightModeAutoModeChanged() {
            evaluateNightMode();
        }
        function onNightModeStartHourChanged() {
            evaluateNightMode();
        }
        function onNightModeStartMinuteChanged() {
            evaluateNightMode();
        }
        function onNightModeEndHourChanged() {
            evaluateNightMode();
        }
        function onNightModeEndMinuteChanged() {
            evaluateNightMode();
        }
        function onNightModeTemperatureChanged() {
            evaluateNightMode();
        }
        function onNightModeHighTemperatureChanged() {
            evaluateNightMode();
        }
        function onLatitudeChanged() {
            evaluateNightMode();
        }
        function onLongitudeChanged() {
            evaluateNightMode();
        }
        function onNightModeUseIPLocationChanged() {
            evaluateNightMode();
        }
    }

    // IPC Handler for external control
    IpcHandler {
        function set(percentage: string, device: string): string {
            if (!root.brightnessAvailable)
                return "Brightness control not available";

            const value = parseInt(percentage);
            if (isNaN(value))
                return "Invalid brightness value: " + percentage;

            const actualDevice = device || root.getPreferredDevice();

            if (actualDevice && !root.devices.some(d => d.id === actualDevice))
                return "Device not found: " + actualDevice;

            const deviceInfo = actualDevice ? root.getCurrentDeviceInfoByName(actualDevice) : null;
            const minValue = (deviceInfo && (deviceInfo.class === "backlight" || deviceInfo.class === "ddc")) ? 1 : 0;
            const clampedValue = Math.max(minValue, Math.min(100, value));

            root.lastIpcDevice = actualDevice;
            if (actualDevice && actualDevice !== root.currentDevice)
                root.setCurrentDevice(actualDevice, false);

            root.setBrightness(clampedValue, actualDevice);

            return actualDevice ? "Brightness set to " + clampedValue + "% on " + actualDevice : "Brightness set to " + clampedValue + "%";
        }

        function increment(step: string, device: string): string {
            if (!root.brightnessAvailable)
                return "Brightness control not available";

            const actualDevice = device || root.getPreferredDevice();

            if (actualDevice && !root.devices.some(d => d.id === actualDevice))
                return "Device not found: " + actualDevice;

            const stepValue = parseInt(step || "5");

            root.lastIpcDevice = actualDevice;
            if (actualDevice && actualDevice !== root.currentDevice)
                root.setCurrentDevice(actualDevice, false);

            const isExponential = SessionData.getBrightnessExponential(actualDevice);
            const currentBrightness = root.getDeviceBrightness(actualDevice);
            const deviceInfo = root.getCurrentDeviceInfoByName(actualDevice);

            const maxValue = isExponential ? 100 : (deviceInfo?.displayMax || 100);
            const newBrightness = Math.min(maxValue, currentBrightness + stepValue);

            root.setBrightness(newBrightness, actualDevice);

            return "Brightness increased by " + stepValue + "%" + (device ? " on " + actualDevice : "");
        }

        function decrement(step: string, device: string): string {
            if (!root.brightnessAvailable)
                return "Brightness control not available";

            const actualDevice = device || root.getPreferredDevice();

            if (actualDevice && !root.devices.some(d => d.id === actualDevice))
                return "Device not found: " + actualDevice;

            const stepValue = parseInt(step || "5");

            root.lastIpcDevice = actualDevice;
            if (actualDevice && actualDevice !== root.currentDevice)
                root.setCurrentDevice(actualDevice, false);

            const isExponential = SessionData.getBrightnessExponential(actualDevice);
            const currentBrightness = root.getDeviceBrightness(actualDevice);
            const deviceInfo = root.getCurrentDeviceInfoByName(actualDevice);

            let minValue = 0;
            switch (true) {
            case isExponential:
                minValue = 1;
                break;
            case deviceInfo && (deviceInfo.class === "backlight" || deviceInfo.class === "ddc"):
                minValue = 1;
                break;
            default:
                minValue = 0;
                break;
            }

            const newBrightness = Math.max(minValue, currentBrightness - stepValue);

            root.setBrightness(newBrightness, actualDevice);

            return "Brightness decreased by " + stepValue + "%" + (device ? " on " + actualDevice : "");
        }

        function status(): string {
            if (!root.brightnessAvailable) {
                return "Brightness control not available";
            }

            return "Device: " + root.currentDevice + " - Brightness: " + root.brightnessLevel + "%";
        }

        function list(): string {
            if (!root.brightnessAvailable) {
                return "No brightness devices available";
            }

            let result = "Available devices:\n";
            for (const device of root.devices) {
                const isExp = SessionData.getBrightnessExponential(device.id);
                result += device.id + " (" + device.class + ")" + (isExp ? " [exponential]" : "") + "\n";
            }
            return result;
        }

        function enableExponential(device: string): string {
            const targetDevice = device || root.currentDevice;
            if (!targetDevice) {
                return "No device specified";
            }

            if (!root.devices.some(d => d.id === targetDevice)) {
                return "Device not found: " + targetDevice;
            }

            SessionData.setBrightnessExponential(targetDevice, true);
            return "Exponential mode enabled for " + targetDevice;
        }

        function disableExponential(device: string): string {
            const targetDevice = device || root.currentDevice;
            if (!targetDevice) {
                return "No device specified";
            }

            if (!root.devices.some(d => d.id === targetDevice)) {
                return "Device not found: " + targetDevice;
            }

            SessionData.setBrightnessExponential(targetDevice, false);
            return "Exponential mode disabled for " + targetDevice;
        }

        function toggleExponential(device: string): string {
            const targetDevice = device || root.currentDevice;
            if (!targetDevice) {
                return "No device specified";
            }

            if (!root.devices.some(d => d.id === targetDevice)) {
                return "Device not found: " + targetDevice;
            }

            const currentState = SessionData.getBrightnessExponential(targetDevice);
            SessionData.setBrightnessExponential(targetDevice, !currentState);
            return "Exponential mode " + (!currentState ? "enabled" : "disabled") + " for " + targetDevice;
        }

        target: "brightness"
    }

    IpcHandler {
        function toggle(): string {
            root.toggleNightMode();
            return root.nightModeEnabled ? "Night mode enabled" : "Night mode disabled";
        }

        function enable(): string {
            root.enableNightMode();
            return "Night mode enabled";
        }

        function disable(): string {
            root.disableNightMode();
            return "Night mode disabled";
        }

        function status(): string {
            if (!root.gammaControlAvailable)
                return "Night mode: unavailable (no gamma control)";

            const parts = ["Night mode: " + (root.nightModeEnabled ? "enabled" : "disabled")];

            if (root.gammaCurrentTemp > 0)
                parts.push("Current temperature: " + root.gammaCurrentTemp + "K");

            parts.push("Target night temperature: " + SessionData.nightModeTemperature + "K");

            if (SessionData.nightModeAutoEnabled) {
                parts.push("Target day temperature: " + SessionData.nightModeHighTemperature + "K");
                parts.push("Automation: " + SessionData.nightModeAutoMode);
                parts.push("Period: " + (root.gammaIsDay ? "day" : "night"));

                if (root.gammaNextTransition)
                    parts.push("Next transition: " + root.gammaNextTransition);
                if (root.gammaSunriseTime)
                    parts.push("Sunrise: " + root.gammaSunriseTime);
                if (root.gammaSunsetTime)
                    parts.push("Sunset: " + root.gammaSunsetTime);
            }

            return parts.join("\n");
        }

        function getCurrentTemp(): string {
            if (!root.gammaControlAvailable)
                return "Gamma control not available";
            if (root.gammaCurrentTemp <= 0)
                return "No current temperature reported";
            return root.gammaCurrentTemp.toString();
        }

        function getTargetTemp(): string {
            return SessionData.nightModeTemperature.toString();
        }

        function getDayTemp(): string {
            return SessionData.nightModeHighTemperature.toString();
        }

        function setTargetTemp(value: string): string {
            if (!value)
                return "Usage: night setTargetTemp <2500-6000>";

            const temp = parseInt(value);
            if (isNaN(temp))
                return "Invalid temperature: " + value;
            if (temp < 2500 || temp > 6000)
                return "Temperature must be between 2500K and 6000K";

            const rounded = Math.round(temp / 500) * 500;
            SessionData.setNightModeTemperature(rounded);

            if (root.nightModeEnabled) {
                switch (true) {
                case SessionData.nightModeAutoEnabled:
                    root.startAutomation();
                    break;
                default:
                    root.applyNightModeDirectly();
                    break;
                }
            }

            if (rounded !== temp)
                return "Night temperature set to " + rounded + "K (rounded from " + temp + "K)";
            return "Night temperature set to " + rounded + "K";
        }

        function setDayTemp(value: string): string {
            if (!value)
                return "Usage: night setDayTemp <2500-6500>";

            const temp = parseInt(value);
            if (isNaN(temp))
                return "Invalid temperature: " + value;
            if (temp < 2500 || temp > 6500)
                return "Temperature must be between 2500K and 6500K";

            const rounded = Math.round(temp / 500) * 500;
            SessionData.setNightModeHighTemperature(rounded);

            if (root.nightModeEnabled && SessionData.nightModeAutoEnabled)
                root.startAutomation();

            if (rounded !== temp)
                return "Day temperature set to " + rounded + "K (rounded from " + temp + "K)";
            return "Day temperature set to " + rounded + "K";
        }

        function getSchedule(): string {
            if (!SessionData.nightModeAutoEnabled)
                return "Automation disabled";

            const parts = ["Mode: " + SessionData.nightModeAutoMode];
            parts.push("Period: " + (root.gammaIsDay ? "day" : "night"));

            if (root.gammaDawnTime)
                parts.push("Dawn: " + root.gammaDawnTime);
            if (root.gammaSunriseTime)
                parts.push("Sunrise: " + root.gammaSunriseTime);
            if (root.gammaSunsetTime)
                parts.push("Sunset: " + root.gammaSunsetTime);
            if (root.gammaNightTime)
                parts.push("Night: " + root.gammaNightTime);
            if (root.gammaNextTransition)
                parts.push("Next transition: " + root.gammaNextTransition);
            if (root.gammaSunPosition > 0)
                parts.push("Sun position: " + root.gammaSunPosition.toFixed(2) + "°");

            return parts.join("\n");
        }

        target: "night"
    }
}