-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
1131 lines (945 loc) · 37.5 KB
/
init.lua
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
local obj = {
__index = obj,
-- Metadata
name = "ScreenDimmer",
version = "4.5",
author = "Ville Walveranta",
license = "MIT",
-- Cache the display mappings
displayMappings = nil,
-- Configuration
config = {
-- Number of seconds of user inactivity before screens dim
idleTimeout = 300, -- 5 minutes
-- Target brightness level (-100 to 100)
-- Negative values use subzero (gamma mode)
-- Positive values use regular (hardware) brightness
dimLevel = 10,
-- Internal display ± gain level (added to dimLevel)
internalDisplayGainLevel = 0, -- No gain by default
-- The default path for Lunar CLI command
lunarPath = "~/.local/bin/lunar",
-- Enable/disable expanded debug logging output
logging = false,
-- How often (in seconds) to check system state for idle timeout
checkInterval = 5,
-- Minimum time (in seconds) between processing unlock events
unlockDebounceInterval = 0.5,
-- Optional dimming/undimmg priorities for specific displays
displayPriorities = {},
-- Example:
-- displayPriorities = {
-- ["Built-in"] = 1,
-- ["BenQ PD3225U"] = 2,
-- ["LG Ultra HD"] = 3
-- }
-- Default priority for displays not specified in displayPriorities
defaultDisplayPriority = 999
},
-- State variables
state = {
originalBrightness = {},
isDimmed = false,
isEnabled = false,
isInitialized = false,
isRestoring = false,
isUnlocking = false,
lockState = false,
lastWakeTime = 0,
lastUserAction = 0,
lastUnlockTime = 0,
lastUnlockEventTime = 0,
screenWatcher = nil,
unlockTimer = nil,
isHotkeyDimming = false,
isScreenSaverActive = false,
inScreenSaverRecovery = false,
lastScreenSaverEvent = hs.timer.secondsSinceEpoch()
}
}
-- Logging function
local function log(message, force)
if force or obj.config.logging then
print(os.date("%Y-%m-%d %H:%M:%S: ") .. message)
end
end
function obj:getLunarDisplayNames()
-- Return cached mappings if available
if self.displayMappings then
return self.displayMappings
end
local command = string.format("%s displays", self.lunarPath)
local output, status = hs.execute(command)
if not status then
log("Failed to get display list from Lunar", true)
return {}
end
local displays = {}
for line in output:gmatch("[^\r\n]+") do
local num, name = line:match("^(%d+):%s+(.+)$")
if num and name then
displays[name] = name -- Direct mapping
if name == "Built-in" then
displays["Built-in Retina Display"] = "Built-in"
end
log(string.format("Added display mapping: %s -> %s", name, displays[name]))
end
end
-- Cache the mappings
self.displayMappings = displays
return displays
end
function obj:sortScreensByPriority(screens)
-- If no priorities configured, return screens in original order
if not self.config.displayPriorities or not next(self.config.displayPriorities) then
return screens
end
local prioritizedScreens = {}
for _, screen in ipairs(screens) do
table.insert(prioritizedScreens, screen)
end
table.sort(prioritizedScreens, function(a, b)
local priorityA = self.config.displayPriorities[a:name()] or self.config.defaultDisplayPriority
local priorityB = self.config.displayPriorities[b:name()] or self.config.defaultDisplayPriority
return priorityA < priorityB
end)
-- Log the priority order if logging is enabled
if self.config.logging then
log("Display priority order:")
for i, screen in ipairs(prioritizedScreens) do
local priority = self.config.displayPriorities[screen:name()] or self.config.defaultDisplayPriority
log(string.format(" %d. %s (priority: %d)", i, screen:name(), priority))
end
end
return prioritizedScreens
end
-- Get hardware brightness (without subzero/gamma effects)
function obj:getHardwareBrightness(screen)
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if not lunarName then
log(string.format("Display '%s' not found in Lunar display list", screenName), true)
return nil
end
-- First ensure subzero is disabled temporarily
local cmdDisableSubzero = string.format("%s displays \"%s\" subzero false",
self.lunarPath, lunarName)
pcall(hs.execute, cmdDisableSubzero)
-- Small delay to let changes take effect
hs.timer.usleep(200000) -- 0.2 seconds
-- Now get the actual hardware brightness
local command = string.format("%s displays \"%s\" brightness --read",
self.lunarPath, lunarName)
local success, output, status = pcall(hs.execute, command)
if not success or not status then
log(string.format("Error reading hardware brightness: %s", output), true)
return nil
end
local brightness = output:match("brightness:%s*(%d+)")
return brightness and tonumber(brightness)
end
-- Set brightness for a screen
function obj:setBrightness(screen, targetValue)
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if not lunarName then
log(string.format("Display '%s' not found in Lunar display list", screenName), true)
return
end
if targetValue < 0 then
-- For negative values, just set subzero dimming
local cmd = string.format("%s displays \"%s\" subzeroDimming %.2f",
self.lunarPath, lunarName, (100 + targetValue) / 100)
local success, result = pcall(hs.execute, cmd)
if not success then
log(string.format("Error executing Lunar command: %s", result), true)
return false
end
log(string.format("Set subzero brightness for '%s': %.2f",
screenName, (100 + targetValue) / 100))
else
-- For regular brightness, disable subzero and set brightness
local commands = {
string.format("%s displays \"%s\" subzero false",
self.lunarPath, lunarName),
string.format("%s displays \"%s\" brightness %d",
self.lunarPath, lunarName, targetValue)
}
for _, cmd in ipairs(commands) do
local success, result = pcall(hs.execute, cmd)
if not success then
log(string.format("Error executing Lunar command: %s", result), true)
return false
end
end
log(string.format("Set regular brightness for '%s': %d",
screenName, targetValue))
end
end
-- Get current subzero dimming level
function obj:getSubzeroDimming(screen)
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if not lunarName then
log(string.format("Display '%s' not found in Lunar display list", screenName), true)
return nil
end
local command = string.format("%s displays \"%s\" subzeroDimming",
self.lunarPath, lunarName)
local success, output, status = pcall(hs.execute, command)
if not success or not status then
log(string.format("Error reading subzero dimming: %s", output), true)
return nil
end
-- The output should be a decimal between 0 and 1
-- Convert it to our -100 to 0 scale
local dimming = output:match("subzeroDimming:%s*([%d%.]+)")
if dimming then
local value = tonumber(dimming)
-- Convert from 0-1 range to our -100-0 range
return math.floor((value * 100) - 100)
end
return nil
end
-- Set subzero dimming level
function obj:setSubzeroDimming(screen, level)
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if not lunarName then return false end
-- Enable subzero mode
local cmdEnableSubzero = string.format("%s displays \"%s\" subzero true",
self.lunarPath, lunarName)
pcall(hs.execute, cmdEnableSubzero)
-- Set dimming level (convert from -100..0 to 0..1 range)
local dimming = (100 + level) / 100 -- level is negative
local cmdSetDimming = string.format("%s displays \"%s\" subzeroDimming %.2f",
self.lunarPath, lunarName, dimming)
local success = pcall(hs.execute, cmdSetDimming)
return success
end
-- Disable subzero dimming
function obj:disableSubzero(screen)
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if not lunarName then return false end
local cmd = string.format("%s displays \"%s\" subzero false",
self.lunarPath, lunarName)
return pcall(hs.execute, cmd)
end
-- Clear the cache when needed
function obj:clearDisplayCache()
self.displayMappings = nil
end
-- Dim screens function
function obj:dimScreens()
if self.state.isDimmed or not self.state.isEnabled then
log("dimScreens called but already dimmed or not enabled")
return
end
log("dimScreens called")
local screens = self:sortScreensByPriority(hs.screen.allScreens())
if #screens == 0 then
log("No screens to dim")
return
end
-- Show priority order in log
log("Display priority order:")
for i, screen in ipairs(screens) do
log(string.format(" %d. %s (priority: %d)",
i, screen:name(), self.config.displayPriorities[screen:name()] or 999))
end
-- Pre-calculate dim levels and determine transition strategy
local screenSettings = {}
for _, screen in ipairs(screens) do
local screenName = screen:name()
local baseLevel = self.config.dimLevel
local finalLevel = baseLevel
local needsTransitionStrategy = false
if screenName:match("Built%-in") then
finalLevel = baseLevel + (self.config.internalDisplayGainLevel or 0)
finalLevel = math.max(-100, math.min(100, finalLevel))
-- Determine if we need special transition handling
-- (when crossing from negative to less negative)
if baseLevel < 0 and finalLevel < 0 and finalLevel > baseLevel then
needsTransitionStrategy = true
end
if self.config.logging then
log(string.format("Pre-calculated internal display: base=%d, final=%d, needs transition=%s",
baseLevel, finalLevel, tostring(needsTransitionStrategy)))
end
end
screenSettings[screenName] = {
finalLevel = finalLevel,
needsTransitionStrategy = needsTransitionStrategy
}
end
self.state.originalBrightness = {}
self.state.originalSubzero = {}
for _, screen in ipairs(screens) do
local screenName = screen:name()
local settings = screenSettings[screenName]
local finalLevel = settings.finalLevel
local needsTransitionStrategy = settings.needsTransitionStrategy
-- First get the subzero state while it's still in original state
local currentSubzero = self:getSubzeroDimming(screen)
-- Then get hardware brightness
local currentBrightness = self:getHardwareBrightness(screen)
if currentBrightness then
self.state.originalBrightness[screenName] = currentBrightness
self.state.originalSubzero[screenName] = currentSubzero
log(string.format("Stored original state for %s: brightness=%d, subzero=%s",
screenName, currentBrightness, tostring(currentSubzero)))
-- Don't dim if target is brighter than current
if finalLevel >= currentBrightness then
log(string.format("Skipping dim for %s - target %d >= current %d",
screenName, finalLevel, currentBrightness))
goto continue
end
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
if needsTransitionStrategy then
-- For transitions that might cause the "dip", go directly to final state
if finalLevel < 0 then
-- Set subzero directly to final value
self:setSubzeroDimming(screen, finalLevel)
else
-- Disable subzero and set brightness in one quick sequence
self:disableSubzero(screen)
hs.timer.usleep(100000) -- Quick 0.1s delay
if lunarName then
local cmd = string.format("%s displays \"%s\" brightness %d",
self.lunarPath, lunarName, finalLevel)
pcall(hs.execute, cmd)
end
end
else
-- For other cases, use normal transition
if finalLevel < 0 then
self:setSubzeroDimming(screen, finalLevel)
else
self:disableSubzero(screen)
hs.timer.usleep(200000) -- Normal 0.2s delay
if lunarName then
local cmd = string.format("%s displays \"%s\" brightness %d",
self.lunarPath, lunarName, finalLevel)
pcall(hs.execute, cmd)
end
end
end
::continue::
end
end
-- Create a verification tracker
local screensToVerify = #screens
local verificationsPassed = 0
-- Verify each screen independently
for _, screen in ipairs(screens) do
hs.timer.doAfter(0.5, function()
local screenName = screen:name()
local targetLevel = screenSettings[screenName].finalLevel
local currentBrightness
if targetLevel < 0 then
currentBrightness = self:getSubzeroDimming(screen)
else
currentBrightness = self:getHardwareBrightness(screen)
end
-- Check if brightness is within acceptable range
if currentBrightness and math.abs(currentBrightness - targetLevel) <= 5 then
verificationsPassed = verificationsPassed + 1
-- If all screens verified, update state
if verificationsPassed == screensToVerify then
self.state.isDimmed = true
self.state.dimmedBeforeSleep = true
self.state.failedRestoreAttempts = 0
log("Screens dimmed")
end
else
log(string.format("Verification failed for %s: target=%d, current=%s",
screenName, targetLevel, tostring(currentBrightness)), true)
end
end)
end
end
-- Restore brightness function
function obj:restoreBrightness()
if self.state.failedRestoreAttempts and self.state.failedRestoreAttempts >= 2 then
log("Multiple restore attempts failed, performing emergency reset", true)
self:emergencyReset()
self.state.failedRestoreAttempts = 0
return
end
if self.state.lockState then
log("Skipping brightness restore while system is locked")
return
end
if not self.state.isDimmed then
log("Not currently dimmed, ignoring restore request")
return
end
log("restoreBrightness called")
self.state.isRestoring = true
local screens = self:sortScreensByPriority(hs.screen.allScreens())
for _, screen in ipairs(screens) do
local screenName = screen:name()
local lunarDisplays = self:getLunarDisplayNames()
local lunarName = lunarDisplays[screenName]
local originalBrightness = self.state.originalBrightness[screenName]
local originalSubzero = self.state.originalSubzero[screenName]
if originalBrightness and lunarName then
log(string.format("Restoring state for '%s': brightness=%d, subzero=%s",
screenName, originalBrightness, tostring(originalSubzero)))
-- First restore any subzero state if it existed
if originalSubzero and originalSubzero < 0 then
self:setSubzeroDimming(screen, originalSubzero)
else
self:disableSubzero(screen)
end
-- Small delay after subzero changes
hs.timer.usleep(300000) -- 0.3 seconds
-- Then restore hardware brightness
local cmdBrightness = string.format("%s displays \"%s\" brightness %d",
self.lunarPath, lunarName, originalBrightness)
log("Executing: " .. cmdBrightness)
local success, result = pcall(hs.execute, cmdBrightness)
if not success then
log(string.format("Error setting brightness: %s", result), true)
self:resetDisplayState(lunarName)
end
-- Verify the changes took effect
hs.timer.doAfter(0.5, function()
local currentBrightness = self:getHardwareBrightness(screen)
if currentBrightness and math.abs(currentBrightness - originalBrightness) > 5 then
log(string.format("Brightness verification failed for %s. Attempting recovery...", screenName), true)
self:resetDisplayState(lunarName)
end
end)
-- Wait between screens if there are multiple
hs.timer.usleep(300000) -- 0.3 seconds
end
end
-- Reset most state immediately
self.state.isDimmed = false
self.state.dimmedBeforeLock = false
self.state.dimmedBeforeSleep = false
-- Create a verification tracker
local screensToVerify = #screens
local verificationsPassed = 0
-- Final verification pass
for _, screen in ipairs(screens) do
local screenName = screen:name()
local originalBrightness = self.state.originalBrightness[screenName]
hs.timer.doAfter(0.5, function()
local currentBrightness = self:getHardwareBrightness(screen)
if currentBrightness and math.abs(currentBrightness - originalBrightness) > 5 then
log(string.format("Final brightness verification failed for %s. Attempting recovery...", screenName), true)
self.state.failedRestoreAttempts = (self.state.failedRestoreAttempts or 0) + 1
self:resetDisplayState(lunarName)
else
verificationsPassed = verificationsPassed + 1
-- If all screens verified successfully, reset the failure counter
if verificationsPassed == screensToVerify then
log("All screens verified successfully, resetting failure counter")
self.state.failedRestoreAttempts = 0
-- Only clear state storage after successful verification
self.state.originalBrightness = {}
self.state.originalSubzero = {}
end
end
end)
end
-- Clear the restoration flag after all verifications should be complete
hs.timer.doAfter(1.5, function()
self.state.isRestoring = false
end)
log("Brightness restore completed")
end
-- Failsafe to make sure subzero (gamma) is disabled
function obj:resetDisplayState(lunarName)
log(string.format("Attempting failsafe reset for display: %s", lunarName), true)
-- First try the normal reset commands
local resetCommands = {
string.format("%s displays \"%s\" subzero false", self.lunarPath, lunarName),
string.format("%s displays \"%s\" gamma reset", self.lunarPath, lunarName),
string.format("%s displays \"%s\" brightness 50", self.lunarPath, lunarName)
}
for _, cmd in ipairs(resetCommands) do
log("Executing failsafe command: " .. cmd)
local success, result = pcall(hs.execute, cmd)
if not success then
log(string.format("Failsafe command failed: %s", result), true)
end
hs.timer.usleep(200000)
end
self.state.failedRestoreAttempts = 0
end
function obj:emergencyReset()
local now = hs.timer.secondsSinceEpoch()
-- Prevent restarts more frequent than every 30 seconds
if (now - self.state.lastLunarRestart) < 30 then
log("Skipping Lunar restart - too soon since last restart", true)
hs.alert.show("⚠️ Lunar restart skipped (cooling down)", 2)
return
end
log("Performing emergency Lunar reset", true)
hs.alert.show("🚨 Emergency Lunar reset in progress...", 3)
-- Kill Lunar
hs.execute("killall Lunar")
-- Update last restart time
self.state.lastLunarRestart = now
-- Wait and restart
hs.timer.doAfter(2, function()
hs.execute("open -a Lunar")
-- Clear our display cache
self:clearDisplayCache()
hs.alert.show("🌙 Lunar restarted", 3)
end)
end
-- Initialize ScreenDimmer
function obj:init()
if self.state.isInitialized then
if self.config.logging then
log("Already initialized, returning")
end
return self
end
if self.config.logging then
log("Initializing ScreenDimmer", true)
end
if not self:checkAccessibility() then
log("Waiting for accessibility permissions...", true)
return self
end
-- Initialize basic state
self.state = {
isInitialized = false, -- Will be set to true after successful configuration
isDimmed = false,
isEnabled = false,
isRestoring = false,
isUnlocking = false,
lockState = false,
originalBrightness = {},
lastWakeTime = hs.timer.secondsSinceEpoch(),
lastUserAction = hs.timer.secondsSinceEpoch(),
lastUnlockTime = hs.timer.secondsSinceEpoch(),
lastUnlockEventTime = 0,
lastHotkeyTime = 0,
lastRestoreTime = 0,
failedRestoreAttempts = 0,
lastLunarRestart = 0,
screenWatcher = nil,
unlockTimer = nil
}
-- Setup screen watcher
self:setupScreenWatcher()
-- Create state checker timer
self.stateChecker = hs.timer.new(
self.config.checkInterval,
function() self:checkAndUpdateState() end
)
-- Setup user activity watcher
self.userActionWatcher = hs.eventtap.new({
hs.eventtap.event.types.keyDown,
hs.eventtap.event.types.flagsChanged,
hs.eventtap.event.types.leftMouseDown,
hs.eventtap.event.types.rightMouseDown,
hs.eventtap.event.types.mouseMoved
}, function(event)
if self.state.lockState or self.state.isUnlocking or self.state.isRestoring then
return false
end
local now = hs.timer.secondsSinceEpoch()
-- Add safety check for lastScreenSaverEvent
local screenSaverCooldown = (self.state.lastScreenSaverEvent and
(now - self.state.lastScreenSaverEvent) < 3.0)
-- Strict ignore period after hotkey or screen events
if (now - self.state.lastHotkeyTime) < 2.0 or screenSaverCooldown then
if self.config.logging then
log("Ignoring user activity during cooldown period")
end
return false
end
-- Only process events if enough time has passed since last action
if (now - self.state.lastUserAction) > 0.1 then
self.state.lastUserAction = now
if self.state.isDimmed and not self.state.isHotkeyDimming then
if self.config.logging then
log("User action while dimmed, restoring brightness")
end
self:restoreBrightness()
end
end
return false
end)
if not self.userActionWatcher then
log("Failed to create eventtap. Please check Accessibility permissions.", true)
end
-- Setup caffeine watcher
self.caffeineWatcher = hs.caffeinate.watcher.new(function(eventType)
self:caffeineWatcherCallback(eventType)
end)
if self.config.logging then
log("Basic initialization complete")
end
return self
end
-- Setup screen watcher
function obj:setupScreenWatcher()
self.state.lastScreenChangeTime = 0
self.state.screenChangeDebounceInterval = 1.0 -- 1 second
self.state.screenWatcher = hs.screen.watcher.new(function()
local now = hs.timer.secondsSinceEpoch()
-- Debounce rapid screen change events
if (now - self.state.lastScreenChangeTime) < self.state.screenChangeDebounceInterval then
if self.config.logging then
log("Debouncing rapid screen configuration change")
end
return
end
self.state.lastScreenChangeTime = now
log("Screen configuration changed", true)
-- Clear the display mappings cache
self:clearDisplayCache()
-- Log current screen configuration
local screens = hs.screen.allScreens()
log(string.format("New screen configuration detected: %d display(s)", #screens))
for _, screen in ipairs(screens) do
log(string.format("- Display: %s", screen:name()))
end
-- Wait a brief moment for the system to stabilize
hs.timer.doAfter(2, function()
-- If screens were dimmed, reapply dimming to all screens
if self.state.isDimmed then
log("Reapplying dim settings to new screen configuration")
-- Store current dim state
local wasDimmed = self.state.isDimmed
-- Reset dim state temporarily
self.state.isDimmed = false
-- Reapply dimming
if wasDimmed then
self:dimScreens()
end
else
log("Screens were not dimmed, no action needed")
end
end)
end)
self.state.screenWatcher:start()
log("Screen watcher initialized and started")
end
-- Check and update state function
function obj:checkAndUpdateState()
if not self.state.isEnabled then
return
end
if self.state.lockState or self.state.isUnlocking then
log("Skipping state check due to lock/unlock state")
return
end
local now = hs.timer.secondsSinceEpoch()
local timeSinceLastAction = now - self.state.lastUserAction
if self.config.logging then
log(string.format("timeSinceLastAction = %.1f seconds (timeout: %d)",
timeSinceLastAction, self.config.idleTimeout))
end
if timeSinceLastAction >= self.config.idleTimeout then
if not self.state.isDimmed then
self:dimScreens()
end
end
end
-- Configuration function
function obj:configure(config)
log("Configuring variables...")
if config then
log(".. with overriding values:")
-- Apply all configurations
for k, v in pairs(config) do
self.config[k] = v
end
end
-- Verify lunar CLI path
if not self.config.lunarPath then
log("ERROR: Lunar CLI path not configured! Please set config.lunarPath.", true)
return self
end
-- Test if lunar command works - using a simple --help command
local testCmd = string.format("%s --help", self.config.lunarPath)
local output, status = hs.execute(testCmd)
if not status then
log("ERROR: Unable to execute lunar command. Please verify the configured lunar path: " .. self.config.lunarPath, true)
return self
end
-- Store the lunar path for future use
self.lunarPath = self.config.lunarPath
if self.config.logging then
log("Successfully initialized Lunar CLI at: " .. self.lunarPath, true)
end
-- Mark as initialized only after successful configuration
self.state.isInitialized = true
if self.config.logging then
log("Configuration now:", true)
for k, v in pairs(self.config) do
log(string.format(" - %s: %s", k, tostring(v)), true)
end
end
return self
end
-- Start the ScreenDimmer
function obj:start(showAlert)
if not self.state.isInitialized then
log("ERROR: Cannot start ScreenDimmer - not properly initialized", true)
return self
end
if self.state.isEnabled then
return self
end
log("Starting ScreenDimmer", true)
self.state.isEnabled = true
-- Try to start the userActionWatcher with retries
local maxRetries = 3
local retryDelay = 2 -- seconds
local retryCount = 0
local function startWatcher()
if not self.userActionWatcher then
retryCount = retryCount + 1
if retryCount <= maxRetries then
log(string.format("Retry %d/%d: Eventtap not available, retrying creation in %d seconds...",
retryCount, maxRetries, retryDelay))
-- Try to recreate the eventtap
self.userActionWatcher = hs.eventtap.new({
hs.eventtap.event.types.keyDown,
hs.eventtap.event.types.flagsChanged,
hs.eventtap.event.types.leftMouseDown,
hs.eventtap.event.types.rightMouseDown,
hs.eventtap.event.types.mouseMoved
}, function(event)
-- ... event handling code ...
end)
hs.timer.doAfter(retryDelay, startWatcher)
else
log("Failed to create eventtap after all retries. Please check Accessibility permissions.", true)
hs.alert.show("⚠️ Failed to start user activity monitoring\nPlease check Accessibility permissions", 5)
end
else
-- If we have a valid eventtap object, start it
self.userActionWatcher:start()
log("User activity watcher started successfully")
end
end
startWatcher()
-- Start all other watchers
if self.stateChecker then
self.stateChecker:start()
end
if self.caffeineWatcher then
self.caffeineWatcher:start()
end
if self.state.screenWatcher then
self.state.screenWatcher:start()
end
-- Reset state
self:resetState()
self.state.lastUserAction = hs.timer.secondsSinceEpoch()
if showAlert ~= false then
hs.alert.show("Screen Dimmer Started")
end
return self
end
-- Stop the ScreenDimmer
function obj:stop(showAlert)
if not self.state.isEnabled then
return self
end
log("Stopping ScreenDimmer", true)
self.state.isEnabled = false
-- Stop all watchers
if self.stateChecker then
self.stateChecker:stop()
end
if self.userActionWatcher then
self.userActionWatcher:stop()
end
if self.caffeineWatcher then
self.caffeineWatcher:stop()
end
if self.state.screenWatcher then
self.state.screenWatcher:stop()
end
-- Restore brightness if dimmed
if self.state.isDimmed then
self:restoreBrightness()
end
-- Reset state
self:resetState()
if showAlert ~= false then
hs.alert.show("Screen Dimmer Stopped")
end
return self
end
-- Toggle the ScreenDimmer
function obj:toggle()
if self.state.isEnabled then
self:stop()
else
self:start()
end
end
-- Toggle between dimmed and normal brightness states
function obj:toggleDim()
local now = hs.timer.secondsSinceEpoch()
self.state.lastHotkeyTime = now
-- Set flag to indicate dimming was triggered by hotkey
self.state.isHotkeyDimming = true
-- If we're coming from screensaver, ensure proper state reset
if self.state.isScreenSaverActive then
self.state.isScreenSaverActive = false
self.state.lastUserAction = now
-- Ensure any existing dimming is cleared
if self.state.isDimmed then
self:restoreBrightness()
end
end
if self.state.isDimmed then
self:restoreBrightness()
else
self:dimScreens()
end
-- Clear the hotkey dimming flag after a short delay
hs.timer.doAfter(2.0, function()
self.state.isHotkeyDimming = false
end)
end
-- Bind hotkeys
-- In your bindHotkeys function:
function obj:bindHotkeys(mapping)
local spec = {
toggle = function() self:toggle() end,
dim = function() self:toggleDim() end,
reset = function()
-- Force reset all displays
local lunarDisplays = self:getLunarDisplayNames()
for _, lunarName in pairs(lunarDisplays) do
self:resetDisplayState(lunarName)
end
end
}
hs.spoons.bindHotkeysToSpec(spec, mapping)
end
-- Reset state function
function obj:resetState()
self.state.isDimmed = false