-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.swift
More file actions
1435 lines (1294 loc) · 65.9 KB
/
Copy pathmain.swift
File metadata and controls
1435 lines (1294 loc) · 65.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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
import AppKit
import CoreGraphics
import ServiceManagement
// SleepBar — a menu-bar tool for temporarily scheduling "screen off time".
//
// Semantics:
// · "Screen Off Timer" picks one duration → the screen stays awake for that long
// (caffeinate -dis), then the "When Time's Up" action runs. "Never" = stay awake
// indefinitely. Clicking the selected item again = cancel (back to system defaults).
// · "When Time's Up" is a remembered preference: lock & turn off display /
// lock, turn off & sleep.
enum EndAction: String {
case lockOnly = "lockOnly" // lock the screen
case lockOff = "lockOff" // lock & turn off the display
case lockSleep = "lockSleep" // lock, turn off & sleep
case lockOffNoSleep = "lockOffNoSleep" // lock & turn off the display but keep the system awake
case screenOff = "screenOff" // dim the built-in display to 0 (no lock), keep awake, auto-restore on return
}
enum Lang: String, CaseIterable {
case zh, en, es, ar, pt, ja, de // pt = Brazilian Portuguese
// Shown in the Language submenu, always in the language itself
var nativeName: String {
switch self {
case .zh: return "中文"
case .en: return "English"
case .es: return "Español"
case .ar: return "العربية"
case .pt: return "Português (Brasil)"
case .ja: return "日本語"
case .de: return "Deutsch"
}
}
// Best match for the system's preferred language; English if none matches
static var systemDefault: Lang {
let pref = Locale.preferredLanguages.first ?? "en"
for l in Lang.allCases where pref.hasPrefix(l.rawValue) { return l }
return .en
}
}
// MARK: - Localization tables
// UI strings for every supported language, keyed by a stable identifier.
// %d / %@ placeholders are filled via String(format:).
private let l10n: [Lang: [String: String]] = [
.zh: [
"section.screenOff": "屏幕关闭时间",
"menu.now": "立即",
"menu.custom": "自定义时长…",
"menu.customFmt": "自定义 (%@)",
"menu.never": "永不",
"section.endAction": "到时间后",
"menu.lockOnly": "锁定屏幕",
"menu.lockOff": "锁定并息屏",
"menu.lockSleep": "锁定、息屏并休眠",
"menu.lockOffNoSleep": "锁定、息屏且不休眠",
"menu.screenOff": "息屏",
"section.timedLock": "定时锁屏",
"menu.language": "语言",
"menu.keepAwake": "不休眠",
"menu.launchAtLogin": "开机自启",
"menu.quit": "退出",
"unit.min": "%d 分钟",
"unit.hour": "%d 小时",
"unit.hours": "%d 小时",
"custom.title": "自定义屏幕关闭时间",
"custom.prompt": "输入分钟数,回车确认:",
"custom.placeholder": "分钟,例如 45",
"btn.start": "开始",
"btn.cancel": "取消",
"btn.ok": "好",
"tl.ellipsis": "定时锁屏…",
"tl.activeFmt": "定时锁屏:每 %d 分 · 剩 %@",
"tl.savedFmt": "定时锁屏 (%d 分 / %@)…",
"tl.note": "锁屏、解锁都不会影响「持续」倒计时。",
"tl.lockAfter": "无操作",
"tl.minIdle": "分钟即锁屏",
"tl.runFor": "持续",
"tl.thenStop": "分钟后自动停止",
"login.errTitle": "无法设置开机自启",
"login.errMsg": "请将 SleepBar.app 移动到「应用程序」文件夹后再试。",
"section.sysOff": "系统关屏",
"sys.offAfterFmt": "关屏时间: %@",
"sys.autoOff": "提前 1 分钟自动息屏",
],
.en: [
"section.screenOff": "Screen Off Timer",
"menu.now": "Now",
"menu.custom": "Custom…",
"menu.customFmt": "Custom (%@)",
"menu.never": "Never",
"section.endAction": "When Time's Up",
"menu.lockOnly": "Lock Screen",
"menu.lockOff": "Lock & Turn Off Display",
"menu.lockSleep": "Lock, Off & Sleep",
"menu.lockOffNoSleep": "Lock, Off & Stay Awake",
"menu.screenOff": "Screen Off",
"section.timedLock": "Timed Lock",
"menu.language": "Language",
"menu.keepAwake": "Keep Awake",
"menu.launchAtLogin": "Launch at Login",
"menu.quit": "Quit",
"unit.min": "%d min",
"unit.hour": "%d hour",
"unit.hours": "%d hours",
"custom.title": "Custom Screen-Off Time",
"custom.prompt": "Enter minutes, press Return:",
"custom.placeholder": "minutes, e.g. 45",
"btn.start": "Start",
"btn.cancel": "Cancel",
"btn.ok": "OK",
"tl.ellipsis": "Timed Lock…",
"tl.activeFmt": "Timed Lock: every %dm · %@ left",
"tl.savedFmt": "Timed Lock (%dm / %@)…",
"tl.note": "Locking or unlocking won't affect the countdown.",
"tl.lockAfter": "Lock after",
"tl.minIdle": "min idle",
"tl.runFor": "Run for",
"tl.thenStop": "min, then stop",
"login.errTitle": "Couldn't set Launch at Login",
"login.errMsg": "Move SleepBar.app to your Applications folder and try again.",
"section.sysOff": "System Display Off",
"sys.offAfterFmt": "Turn Off After: %@",
"sys.autoOff": "Auto Screen Off 1 Min Early",
],
.es: [
"section.screenOff": "Temporizador de pantalla",
"menu.now": "Ahora",
"menu.custom": "Personalizado…",
"menu.customFmt": "Personalizado (%@)",
"menu.never": "Nunca",
"section.endAction": "Al terminar",
"menu.lockOnly": "Bloquear pantalla",
"menu.lockOff": "Bloquear y apagar pantalla",
"menu.lockSleep": "Bloquear, apagar y suspender",
"menu.lockOffNoSleep": "Bloquear, apagar, sin suspender",
"menu.screenOff": "Apagar pantalla",
"section.timedLock": "Bloqueo programado",
"menu.language": "Idioma",
"menu.keepAwake": "Mantener activo",
"menu.launchAtLogin": "Abrir al iniciar sesión",
"menu.quit": "Salir",
"unit.min": "%d min",
"unit.hour": "%d hora",
"unit.hours": "%d horas",
"custom.title": "Tiempo personalizado",
"custom.prompt": "Introduce los minutos y pulsa Intro:",
"custom.placeholder": "minutos, p. ej. 45",
"btn.start": "Iniciar",
"btn.cancel": "Cancelar",
"btn.ok": "Aceptar",
"tl.ellipsis": "Bloqueo programado…",
"tl.activeFmt": "Bloqueo: cada %d min · quedan %@",
"tl.savedFmt": "Bloqueo programado (%d min / %@)…",
"tl.note": "Bloquear o desbloquear no afecta a la cuenta atrás.",
"tl.lockAfter": "Bloquear tras",
"tl.minIdle": "min inactivo",
"tl.runFor": "Durante",
"tl.thenStop": "min, luego parar",
"login.errTitle": "No se pudo configurar el inicio de sesión",
"login.errMsg": "Mueve SleepBar.app a la carpeta Aplicaciones e inténtalo de nuevo.",
"section.sysOff": "Apagado del sistema",
"sys.offAfterFmt": "Apagar tras: %@",
"sys.autoOff": "Apagar pantalla 1 min antes",
],
.ar: [
"section.screenOff": "مؤقّت إطفاء الشاشة",
"menu.now": "الآن",
"menu.custom": "مخصّص…",
"menu.customFmt": "مخصّص (%@)",
"menu.never": "أبدًا",
"section.endAction": "عند انتهاء الوقت",
"menu.lockOnly": "قفل الشاشة",
"menu.lockOff": "قفل وإطفاء الشاشة",
"menu.lockSleep": "قفل وإطفاء وسبات",
"menu.lockOffNoSleep": "قفل وإطفاء دون سبات",
"menu.screenOff": "إطفاء الشاشة",
"section.timedLock": "قفل دوري",
"menu.language": "اللغة",
"menu.keepAwake": "منع السكون",
"menu.launchAtLogin": "الفتح عند تسجيل الدخول",
"menu.quit": "إنهاء",
"unit.min": "%d دقيقة",
"unit.hour": "%d ساعة",
"unit.hours": "%d ساعات",
"custom.title": "وقت مخصّص لإطفاء الشاشة",
"custom.prompt": "أدخل عدد الدقائق ثم اضغط Return:",
"custom.placeholder": "دقائق، مثل 45",
"btn.start": "بدء",
"btn.cancel": "إلغاء",
"btn.ok": "حسنًا",
"tl.ellipsis": "قفل دوري…",
"tl.activeFmt": "قفل دوري: كل %dد · متبقٍ %@",
"tl.savedFmt": "قفل دوري (%d دقيقة / %@)…",
"tl.note": "القفل أو فتح القفل لا يؤثّر على العدّاد.",
"tl.lockAfter": "القفل بعد",
"tl.minIdle": "دقيقة خمول",
"tl.runFor": "التشغيل لمدة",
"tl.thenStop": "دقيقة ثم التوقّف",
"login.errTitle": "تعذّر تفعيل الفتح عند تسجيل الدخول",
"login.errMsg": "انقل SleepBar.app إلى مجلد التطبيقات وحاول مجددًا.",
"section.sysOff": "إطفاء شاشة النظام",
"sys.offAfterFmt": "الإطفاء بعد: %@",
"sys.autoOff": "إطفاء تلقائي قبل دقيقة",
],
.pt: [
"section.screenOff": "Temporizador de tela",
"menu.now": "Agora",
"menu.custom": "Personalizado…",
"menu.customFmt": "Personalizado (%@)",
"menu.never": "Nunca",
"section.endAction": "Ao terminar",
"menu.lockOnly": "Bloquear tela",
"menu.lockOff": "Bloquear e desligar a tela",
"menu.lockSleep": "Bloquear, desligar e suspender",
"menu.lockOffNoSleep": "Bloquear, desligar, sem suspender",
"menu.screenOff": "Desligar a tela",
"section.timedLock": "Bloqueio programado",
"menu.language": "Idioma",
"menu.keepAwake": "Manter ativo",
"menu.launchAtLogin": "Abrir ao fazer login",
"menu.quit": "Encerrar",
"unit.min": "%d min",
"unit.hour": "%d hora",
"unit.hours": "%d horas",
"custom.title": "Tempo personalizado",
"custom.prompt": "Digite os minutos e pressione Return:",
"custom.placeholder": "minutos, ex.: 45",
"btn.start": "Iniciar",
"btn.cancel": "Cancelar",
"btn.ok": "OK",
"tl.ellipsis": "Bloqueio programado…",
"tl.activeFmt": "Bloqueio: a cada %d min · faltam %@",
"tl.savedFmt": "Bloqueio programado (%d min / %@)…",
"tl.note": "Bloquear ou desbloquear não afeta a contagem.",
"tl.lockAfter": "Bloquear após",
"tl.minIdle": "min inativo",
"tl.runFor": "Durante",
"tl.thenStop": "min, depois parar",
"login.errTitle": "Não foi possível ativar a abertura ao fazer login",
"login.errMsg": "Mova o SleepBar.app para a pasta Aplicativos e tente novamente.",
"section.sysOff": "Desligamento do sistema",
"sys.offAfterFmt": "Desligar após: %@",
"sys.autoOff": "Desligar a tela 1 min antes",
],
.ja: [
"section.screenOff": "画面オフタイマー",
"menu.now": "今すぐ",
"menu.custom": "カスタム…",
"menu.customFmt": "カスタム (%@)",
"menu.never": "オフにしない",
"section.endAction": "時間になったら",
"menu.lockOnly": "画面をロック",
"menu.lockOff": "ロックして画面をオフ",
"menu.lockSleep": "ロック・オフしてスリープ",
"menu.lockOffNoSleep": "ロック・オフ(スリープしない)",
"menu.screenOff": "画面オフ",
"section.timedLock": "定期ロック",
"menu.language": "言語",
"menu.keepAwake": "スリープしない",
"menu.launchAtLogin": "ログイン時に起動",
"menu.quit": "終了",
"unit.min": "%d 分",
"unit.hour": "%d 時間",
"unit.hours": "%d 時間",
"custom.title": "カスタム画面オフ時間",
"custom.prompt": "分数を入力し、Return キーを押してください:",
"custom.placeholder": "分(例: 45)",
"btn.start": "開始",
"btn.cancel": "キャンセル",
"btn.ok": "OK",
"tl.ellipsis": "定期ロック…",
"tl.activeFmt": "定期ロック:%d 分ごと · 残り %@",
"tl.savedFmt": "定期ロック (%d 分 / %@)…",
"tl.note": "ロック/ロック解除してもカウントダウンは止まりません。",
"tl.lockAfter": "無操作",
"tl.minIdle": "分でロック",
"tl.runFor": "継続",
"tl.thenStop": "分後に自動停止",
"login.errTitle": "ログイン時の起動を設定できません",
"login.errMsg": "SleepBar.app を「アプリケーション」フォルダに移動してからもう一度お試しください。",
"section.sysOff": "システムの画面オフ",
"sys.offAfterFmt": "オフまでの時間: %@",
"sys.autoOff": "1分前に自動で画面オフ",
],
.de: [
"section.screenOff": "Bildschirm-Timer",
"menu.now": "Jetzt",
"menu.custom": "Eigene Dauer…",
"menu.customFmt": "Eigene Dauer (%@)",
"menu.never": "Nie",
"section.endAction": "Nach Ablauf",
"menu.lockOnly": "Bildschirm sperren",
"menu.lockOff": "Sperren und Bildschirm ausschalten",
"menu.lockSleep": "Sperren, ausschalten & Ruhezustand",
"menu.lockOffNoSleep": "Sperren, ausschalten, wach bleiben",
"menu.screenOff": "Bildschirm aus",
"section.timedLock": "Zeitgesteuerte Sperre",
"menu.language": "Sprache",
"menu.keepAwake": "Wach bleiben",
"menu.launchAtLogin": "Bei der Anmeldung öffnen",
"menu.quit": "Beenden",
"unit.min": "%d Min.",
"unit.hour": "%d Stunde",
"unit.hours": "%d Stunden",
"custom.title": "Eigene Ausschaltzeit",
"custom.prompt": "Minuten eingeben, Eingabetaste drücken:",
"custom.placeholder": "Minuten, z. B. 45",
"btn.start": "Starten",
"btn.cancel": "Abbrechen",
"btn.ok": "OK",
"tl.ellipsis": "Zeitgesteuerte Sperre…",
"tl.activeFmt": "Sperre: alle %d Min. · noch %@",
"tl.savedFmt": "Zeitgesteuerte Sperre (%d Min. / %@)…",
"tl.note": "Sperren oder Entsperren beeinflusst den Countdown nicht.",
"tl.lockAfter": "Sperren nach",
"tl.minIdle": "Min. Inaktivität",
"tl.runFor": "Dauer",
"tl.thenStop": "Min., dann stoppen",
"login.errTitle": "„Bei der Anmeldung öffnen“ konnte nicht aktiviert werden",
"login.errMsg": "Verschiebe SleepBar.app in den Ordner „Programme“ und versuche es erneut.",
"section.sysOff": "System-Bildschirm aus",
"sys.offAfterFmt": "Ausschalten nach: %@",
"sys.autoOff": "1 Min. vorher Bildschirm aus",
],
]
// Built-in keyboard backlight control via CoreBrightness's private KeyboardBrightnessClient.
@objc private protocol KeyboardBacklight {
func brightnessForKeyboard(_ keyboard: Int64) -> Float
func setBrightness(_ brightness: Float, forKeyboard keyboard: Int64) -> Bool
}
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
private var statusItem: NSStatusItem!
private var task: Process? // current caffeinate process
private var endDate: Date? // countdown end time (nil for never/idle)
private var ticker: Timer?
// activeMinutes: nil = idle (system defaults); -1 = never (always awake); >0 = countdown minutes
private var activeMinutes: Int?
private var endAction: EndAction = .lockOff
private var customMinutes: Int = 0 // last custom duration in minutes (0 = never set)
private var lang: Lang = .en
// —— Timed Lock ——
// Within the window, lock the screen every time idle input reaches "interval".
// The window is a fixed countdown; locking/unlocking never resets it.
private var tlActive = false
private var tlInterval: Int = 0 // lock interval (minutes), also remembers the last value
private var tlWindowMin: Int = 0 // window length (minutes), also remembers the last value
private var tlWindowEnd: Date? // absolute end time of the window
private var tlTimer: Timer? // adaptive idle check (not a per-second poll)
private var tlWindowTimer: Timer? // one-shot stop when the window ends
private var tlItem: NSMenuItem!
private var launchItem: NSMenuItem! // "Launch at Login" toggle (.app builds only)
// —— Keep Awake ——
// An always-on toggle (no trigger logic): while checked, a standalone caffeinate
// process blocks idle/system sleep (but not display sleep). Independent of the
// Screen Off Timer; persists across launches.
private var keepAwake = false
private var keepAwakeTask: Process?
private var keepAwakeItem: NSMenuItem!
// —— System display-off time (pmset displaysleep) ——
// Reading the current power source's displaysleep needs no privileges; changing it
// goes through pmset behind a one-time admin-password prompt (root is required to
// write power settings). autoOff triggers the "息屏" action (no lock, mouse wakes it)
// one minute before the system would sleep the display, so the system's
// "require password after display off" lock never engages.
private var sysOffMinutes: Int = -1 // current-source displaysleep; -1 = not read yet, 0 = never
private var sysOffOnAC = true // which power source the value (and a write) applies to
private var sysOffItem: NSMenuItem!
private var sysOffPresetItems: [(min: Int, item: NSMenuItem)] = []
private let sysOffPresets = [1, 2, 5, 10, 15, 20, 30, 45, 60, 180, 0] // System Settings pillars; 0 = never
private var autoOffEnabled = false
private var autoOffTimer: Timer? // adaptive idle check, same pattern as Timed Lock
private var autoOffItem: NSMenuItem!
// —— Screen off via brightness (the "息屏" / Screen Off end action) ——
// Instead of sleeping the display (which stalls GPU rendering), drop the built-in
// display brightness to 0 and keep things awake; the watcher restores it on return.
private var savedBrightness: [CGDirectDisplayID: Float] = [:]
private var screenOffMonitor: Any? // global mouse monitor: restore on user return
private var screenOffActive = false
// Keyboard backlight (built-in keyboard = id 1). The client is held for the app's
// lifetime so the level we set actually sticks. savedKeyboardBrightness = pre-dim level.
private let keyboardID: Int64 = 1
private lazy var keyboardClientObj: NSObject? = {
guard dlopen("/System/Library/PrivateFrameworks/CoreBrightness.framework/CoreBrightness", RTLD_NOW) != nil,
let cls = NSClassFromString("KeyboardBrightnessClient") as? NSObject.Type else { return nil }
return cls.init()
}()
private var keyboardBacklight: KeyboardBacklight? { keyboardClientObj.map { unsafeBitCast($0, to: KeyboardBacklight.self) } }
private var savedKeyboardBrightness: Float?
// Preset durations (minutes); titles are generated per language
private let presets: [Int] = [5, 10, 15, 30, 60]
// Menu item references (for updating checkmarks)
private var presetItems: [(min: Int, item: NSMenuItem)] = []
private var customItem: NSMenuItem!
private var neverItem: NSMenuItem!
private var lockOnlyItem: NSMenuItem!
private var lockOffItem: NSMenuItem!
private var lockSleepItem: NSMenuItem!
private var lockOffNoSleepItem: NSMenuItem!
private var screenOffItem: NSMenuItem!
func applicationDidFinishLaunching(_ note: Notification) {
if let saved = UserDefaults.standard.string(forKey: "endAction"),
let a = EndAction(rawValue: saved) { endAction = a }
customMinutes = UserDefaults.standard.integer(forKey: "customMinutes")
if let s = UserDefaults.standard.string(forKey: "lang"), let l = Lang(rawValue: s) {
lang = l
} else {
lang = Lang.systemDefault
}
tlInterval = UserDefaults.standard.integer(forKey: "tlInterval")
tlWindowMin = UserDefaults.standard.integer(forKey: "tlWindowMin")
keepAwake = UserDefaults.standard.bool(forKey: "keepAwake")
autoOffEnabled = UserDefaults.standard.bool(forKey: "autoScreenOff")
// Observe lock/unlock (event-driven; zero polling while locked)
let dc = DistributedNotificationCenter.default()
dc.addObserver(self, selector: #selector(screenDidLock),
name: NSNotification.Name("com.apple.screenIsLocked"), object: nil)
dc.addObserver(self, selector: #selector(screenDidUnlock),
name: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil)
// install.sh passes --register-login on the first launch after installing:
// register as a Login Item (SMAppService; uncheck anytime via "Launch at Login")
if CommandLine.arguments.contains("--register-login"), isAppBundle,
#available(macOS 13.0, *) {
try? SMAppService.mainApp.register()
}
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
buildMenu()
refreshUI()
if keepAwake { startKeepAwake() } // restore the always-on keep-awake assertion
readSysOff { [weak self] _ in self?.rearmAutoOff() } // populate the menu; arm auto screen-off
}
// MARK: - Localization
private func t(_ key: String) -> String {
l10n[lang]?[key] ?? l10n[.en]?[key] ?? key
}
// Minutes → localized title: "5 min" / "1 hour" (or their localized equivalents)
private func durationTitle(_ minutes: Int) -> String {
if minutes >= 60 && minutes % 60 == 0 {
let h = minutes / 60
return String(format: t(h == 1 ? "unit.hour" : "unit.hours"), h)
}
return String(format: t("unit.min"), minutes)
}
private func customLabel() -> String {
guard customMinutes > 0 else { return t("menu.custom") }
return String(format: t("menu.customFmt"), durationTitle(customMinutes))
}
// MARK: - Menu building
private func icon(_ name: String) -> NSImage? {
NSImage(systemSymbolName: name, accessibilityDescription: nil)
}
private func buildMenu() {
let menu = NSMenu()
menu.delegate = self
presetItems = []
// —— Screen Off Timer ——
menu.addItem(.sectionHeader(title: t("section.screenOff")))
let nowItem = NSMenuItem(title: t("menu.now"), action: #selector(pickNow), keyEquivalent: "")
nowItem.target = self
nowItem.image = icon("bolt")
menu.addItem(nowItem)
for minutes in presets {
let item = NSMenuItem(title: durationTitle(minutes), action: #selector(pickPreset(_:)), keyEquivalent: "")
item.target = self
item.tag = minutes
item.image = icon("clock")
menu.addItem(item)
presetItems.append((minutes, item))
}
customItem = NSMenuItem(title: customLabel(), action: #selector(pickCustom), keyEquivalent: "")
customItem.target = self
customItem.image = icon("slider.horizontal.3")
menu.addItem(customItem)
neverItem = NSMenuItem(title: t("menu.never"), action: #selector(pickNever), keyEquivalent: "")
neverItem.target = self
neverItem.image = icon("nosign")
menu.addItem(neverItem)
// —— When Time's Up ——
menu.addItem(.sectionHeader(title: t("section.endAction")))
// Items are ordered shortest-label-first, so "息屏" (Screen Off) comes first.
screenOffItem = NSMenuItem(title: t("menu.screenOff"), action: #selector(pickScreenOff), keyEquivalent: "")
screenOffItem.target = self
screenOffItem.image = icon("sun.min")
menu.addItem(screenOffItem)
lockOnlyItem = NSMenuItem(title: t("menu.lockOnly"), action: #selector(pickLockOnly), keyEquivalent: "")
lockOnlyItem.target = self
lockOnlyItem.image = icon("lock")
menu.addItem(lockOnlyItem)
lockOffItem = NSMenuItem(title: t("menu.lockOff"), action: #selector(pickLockOff), keyEquivalent: "")
lockOffItem.target = self
lockOffItem.image = icon("lock.display")
menu.addItem(lockOffItem)
lockSleepItem = NSMenuItem(title: t("menu.lockSleep"), action: #selector(pickLockSleep), keyEquivalent: "")
lockSleepItem.target = self
lockSleepItem.image = icon("powersleep")
menu.addItem(lockSleepItem)
lockOffNoSleepItem = NSMenuItem(title: t("menu.lockOffNoSleep"), action: #selector(pickLockOffNoSleep), keyEquivalent: "")
lockOffNoSleepItem.target = self
lockOffNoSleepItem.image = icon("lock.open.display")
menu.addItem(lockOffNoSleepItem)
// —— Timed Lock ——
menu.addItem(.sectionHeader(title: t("section.timedLock")))
tlItem = NSMenuItem(title: tlLabel(), action: #selector(toggleTimedLock), keyEquivalent: "")
tlItem.target = self
tlItem.image = icon("lock.rotation")
menu.addItem(tlItem)
// —— System Display Off (read/write pmset displaysleep + auto early screen-off) ——
menu.addItem(.sectionHeader(title: t("section.sysOff")))
sysOffItem = NSMenuItem(title: sysOffLabel(), action: nil, keyEquivalent: "")
sysOffItem.image = icon("timer")
let sysMenu = NSMenu()
sysOffPresetItems = []
for minutes in sysOffPresets {
let title = (minutes == 0) ? t("menu.never") : durationTitle(minutes)
let item = NSMenuItem(title: title, action: #selector(pickSysOff(_:)), keyEquivalent: "")
item.target = self
item.tag = minutes
sysMenu.addItem(item)
sysOffPresetItems.append((minutes, item))
}
sysOffItem.submenu = sysMenu
menu.addItem(sysOffItem)
autoOffItem = NSMenuItem(title: t("sys.autoOff"), action: #selector(toggleAutoOff), keyEquivalent: "")
autoOffItem.target = self
autoOffItem.image = icon("moon")
menu.addItem(autoOffItem)
// —— Language ——
menu.addItem(.separator())
let langItem = NSMenuItem(title: t("menu.language"), action: nil, keyEquivalent: "")
langItem.image = icon("globe")
let langMenu = NSMenu()
for l in Lang.allCases {
let item = NSMenuItem(title: l.nativeName, action: #selector(pickLang(_:)), keyEquivalent: "")
item.target = self
item.representedObject = l.rawValue
item.state = (lang == l) ? .on : .off
langMenu.addItem(item)
}
langItem.submenu = langMenu
menu.addItem(langItem)
// —— Keep Awake (always-on toggle; no trigger logic) ——
keepAwakeItem = NSMenuItem(title: t("menu.keepAwake"),
action: #selector(toggleKeepAwake), keyEquivalent: "")
keepAwakeItem.target = self
keepAwakeItem.image = icon("cup.and.saucer")
menu.addItem(keepAwakeItem)
// —— Launch at Login (shown when running as .app; both install.sh and the DMG
// install an .app — only run.sh's bare-binary dev mode hides it) ——
if isAppBundle {
launchItem = NSMenuItem(title: t("menu.launchAtLogin"),
action: #selector(toggleLaunchAtLogin), keyEquivalent: "")
launchItem.target = self
launchItem.image = icon("power.circle")
menu.addItem(launchItem)
}
// —— Quit ——
let quit = NSMenuItem(title: t("menu.quit"), action: #selector(quit), keyEquivalent: "q")
quit.target = self
quit.image = icon("power")
menu.addItem(quit)
statusItem.menu = menu
updateChecks()
}
func menuWillOpen(_ menu: NSMenu) {
updateChecks()
readSysOff() // async refresh; the submenu label updates in place when it lands
}
private func updateChecks() {
let m = activeMinutes
for (min, item) in presetItems { item.state = (m == min) ? .on : .off }
customItem.title = customLabel()
customItem.state = isCustomActive() ? .on : .off
neverItem.state = (m == -1) ? .on : .off
lockOnlyItem.state = (endAction == .lockOnly) ? .on : .off
lockOffItem.state = (endAction == .lockOff) ? .on : .off
lockSleepItem.state = (endAction == .lockSleep) ? .on : .off
lockOffNoSleepItem.state = (endAction == .lockOffNoSleep) ? .on : .off
screenOffItem.state = (endAction == .screenOff) ? .on : .off
if tlItem != nil { // remaining time is computed only when the menu opens (saves power)
tlItem.title = tlLabel()
tlItem.state = tlActive ? .on : .off
}
if keepAwakeItem != nil {
keepAwakeItem.state = keepAwake ? .on : .off
}
if autoOffItem != nil {
autoOffItem.state = autoOffEnabled ? .on : .off
}
updateSysOffUI()
if launchItem != nil {
launchItem.state = launchAtLoginEnabled() ? .on : .off
}
}
// MARK: - Screen-off timer actions
// "Now": run the configured end action immediately; any running countdown
// has served its purpose, so cancel it (Timed Lock keeps running — this is
// just like a manual lock, which never affects its window)
@objc private func pickNow() {
if activeMinutes != nil { goIdle() }
performEndAction()
}
@objc private func pickPreset(_ sender: NSMenuItem) {
if activeMinutes == sender.tag { goIdle() } // clicking again = cancel
else { startTimed(minutes: sender.tag) }
}
@objc private func pickCustom() {
if isCustomActive() { goIdle(); return } // clicking mid-countdown = cancel
promptCustom() // idle = show input dialog (pre-filled, Return confirms)
}
// Whether a "custom duration" countdown is running (as opposed to a preset or never)
private func isCustomActive() -> Bool {
guard let m = activeMinutes, m != -1 else { return false }
return !presets.contains(m)
}
private func promptCustom() {
let alert = NSAlert()
alert.icon = NSImage(systemSymbolName: "clock", accessibilityDescription: nil)
alert.messageText = t("custom.title")
alert.informativeText = t("custom.prompt")
alert.addButton(withTitle: t("btn.start"))
alert.addButton(withTitle: t("btn.cancel"))
let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 220, height: 26))
field.alignment = .center
field.font = .systemFont(ofSize: 15)
field.placeholderString = t("custom.placeholder")
if customMinutes > 0 { field.stringValue = "\(customMinutes)" } // pre-fill the last value
let fmt = NumberFormatter()
fmt.numberStyle = .none
fmt.minimum = 1
fmt.maximum = 1440
fmt.allowsFloats = false
field.formatter = fmt
alert.accessoryView = field
NSApp.activate(ignoringOtherApps: true)
alert.window.initialFirstResponder = field // ready for typing as soon as it appears
if alert.runModal() == .alertFirstButtonReturn {
if let mins = Int(field.stringValue.trimmingCharacters(in: .whitespaces)), mins > 0 {
customMinutes = mins
UserDefaults.standard.set(mins, forKey: "customMinutes") // remember
startTimed(minutes: mins)
}
}
}
@objc private func pickNever() {
if activeMinutes == -1 { goIdle() } else { startForever() }
}
// MARK: - When Time's Up (preference)
@objc private func pickLockOnly() { setEndAction(.lockOnly) }
@objc private func pickLockOff() { setEndAction(.lockOff) }
@objc private func pickLockSleep() { setEndAction(.lockSleep) }
@objc private func pickLockOffNoSleep() { setEndAction(.lockOffNoSleep) }
@objc private func pickScreenOff() { setEndAction(.screenOff) }
private func setEndAction(_ a: EndAction) {
endAction = a
UserDefaults.standard.set(a.rawValue, forKey: "endAction")
updateChecks()
}
// MARK: - Language
@objc private func pickLang(_ sender: NSMenuItem) {
guard let raw = sender.representedObject as? String,
let l = Lang(rawValue: raw) else { return }
setLang(l)
}
private func setLang(_ l: Lang) {
guard l != lang else { return }
lang = l
UserDefaults.standard.set(l.rawValue, forKey: "lang")
buildMenu() // rebuild the whole menu in the new language
refreshUI()
}
// MARK: - Keep Awake (always-on, independent of the Screen Off Timer)
@objc private func toggleKeepAwake() { setKeepAwake(!keepAwake) }
// Set the always-on Keep Awake state, persist it, start/stop the caffeinate, and
// sync the checkmark. Also called by the .lockSleep end action to drop the assertion
// (it would otherwise fight pmset sleepnow and keep the machine dark-wake-thrashing).
private func setKeepAwake(_ on: Bool) {
keepAwake = on
UserDefaults.standard.set(keepAwake, forKey: "keepAwake")
if keepAwake { startKeepAwake() } else { stopKeepAwake() }
updateChecks()
}
private func startKeepAwake() {
stopKeepAwake()
// -is: block idle/system sleep (but not display sleep), with no -t so it
// lasts until the toggle is switched off or the app quits.
let p = makeCaffeinate(args: ["-is"]) { _ in }
if launch(p) { keepAwakeTask = p }
}
private func stopKeepAwake() {
if let p = keepAwakeTask { p.terminationHandler = nil; p.terminate() }
keepAwakeTask = nil
}
@objc private func quit() { wakeFromScreenOff(); stopKeepAwake(); NSApp.terminate(nil) }
// MARK: - caffeinate control
private func startTimed(minutes: Int) {
stopTimedLock() // mutually exclusive with Timed Lock (one keeps awake, the other locks on idle)
killTask()
let seconds = minutes * 60
let p = makeCaffeinate(args: ["-dis", "-t", "\(seconds)"]) { [weak self] proc in
guard let self = self, self.task === proc else { return }
// Reset to idle first (the timer process already ended), then run the
// end action — so an action that installs its own task (lockOffNoSleep)
// isn't immediately torn down.
self.task = nil
self.activeMinutes = nil
self.endDate = nil
self.stopTicker()
self.performEndAction() // run the action when time is up
self.refreshUI(); self.updateChecks()
}
if launch(p) {
task = p
activeMinutes = minutes
endDate = Date().addingTimeInterval(TimeInterval(seconds))
startTicker()
}
refreshUI(); updateChecks()
}
private func startForever() {
stopTimedLock() // mutually exclusive with Timed Lock
killTask()
let p = makeCaffeinate(args: ["-dis"]) { _ in } // no -t: stay awake until cancelled
if launch(p) {
task = p
activeMinutes = -1
endDate = nil
}
stopTicker()
refreshUI(); updateChecks()
}
private func goIdle() {
killTask()
activeMinutes = nil
endDate = nil
stopTicker()
refreshUI(); updateChecks()
}
private func makeCaffeinate(args: [String], onEnd: @escaping (Process) -> Void) -> Process {
let p = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/caffeinate")
p.arguments = args
p.terminationHandler = { proc in DispatchQueue.main.async { onEnd(proc) } }
return p
}
private func launch(_ p: Process) -> Bool {
do { try p.run(); return true } catch { return false }
}
// End the current process manually: detach the handler first so the end action doesn't fire
private func killTask() {
if let t = task { t.terminationHandler = nil; t.terminate() }
task = nil
}
// MARK: - End-of-countdown actions
private func performEndAction() {
switch endAction {
case .lockOnly:
lockScreen()
case .lockOff:
// Drop any lingering per-run caffeinate first: a leftover "息屏" assertion
// (caffeinate -dis) blocks display sleep, so displaysleepnow would be fought.
if screenOffActive { wakeFromScreenOff() } else { killTask() }
lockScreen()
runPmset("displaysleepnow")
case .lockSleep:
// A forced sleep can't hold against a live "prevent sleep" assertion: pmset
// sleepnow with a caffeinate still running makes the Mac dark-wake-thrash (fans
// ramp on an idle, cool CPU) instead of staying asleep. Release every sleep
// blocker first — any per-run caffeinate (task) and the always-on Keep Awake
// toggle, which directly contradicts "sleep now".
if screenOffActive { wakeFromScreenOff() } else { killTask() }
if keepAwake { setKeepAwake(false) }
lockScreen()
runPmset("sleepnow")
case .lockOffNoSleep:
// Lock, turn the display off, but keep the system awake: start a lingering
// caffeinate that blocks idle/system sleep (but not display sleep).
// Cancelled by killTask() on the next screen-off action or on quit.
lockScreen()
killTask()
runPmset("displaysleepnow")
let keep = makeCaffeinate(args: ["-is"]) { _ in }
if launch(keep) { task = keep }
case .screenOff:
activateScreenOff()
}
}
// "Screen off" (no lock): built-in brightness → 0, external display → DDC
// power-off, and keyboard backlight → 0 — all a true black that, unlike display
// sleep, keeps the GPU rendering (the built-in stays on at brightness 0 as the
// GPU's wake anchor). Keep the system awake (caffeinate -dis). The watcher
// restores brightness + keyboard and re-lights the external when the user returns.
// Called by the .screenOff end action and by the auto-early-screen-off trigger.
private func activateScreenOff() {
killTask()
stopScreenOffWatch()
dimBuiltInToZero()
externalDisplayOff()
dimKeyboardToZero()
let keep = makeCaffeinate(args: ["-dis"]) { _ in }
if launch(keep) { task = keep }
startScreenOffWatch()
}
private func lockScreen() {
typealias LockFn = @convention(c) () -> Int32
guard let h = dlopen("/System/Library/PrivateFrameworks/login.framework/login", RTLD_NOW),
let sym = dlsym(h, "SACLockScreenImmediate") else { return }
_ = unsafeBitCast(sym, to: LockFn.self)()
}
private func runPmset(_ arg: String) {
let p = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/pmset")
p.arguments = [arg]
try? p.run()
}
// MARK: - Screen off via brightness (keep rendering alive instead of sleeping the display)
// Private DisplayServices: control the real panel backlight on Apple Silicon. The
// built-in display dims to (near) black; external displays are best-effort — many
// ignore software brightness and only respond to DDC. Resolved once, like the
// login.framework lookup in lockScreen().
private typealias DSGetFn = @convention(c) (CGDirectDisplayID, UnsafeMutablePointer<Float>) -> Int32
private typealias DSSetFn = @convention(c) (CGDirectDisplayID, Float) -> Int32
private static let dsHandle = dlopen("/System/Library/PrivateFrameworks/DisplayServices.framework/DisplayServices", RTLD_NOW)
private static let dsGet: DSGetFn? = dsHandle.flatMap { dlsym($0, "DisplayServicesGetBrightness") }.map { unsafeBitCast($0, to: DSGetFn.self) }
private static let dsSet: DSSetFn? = dsHandle.flatMap { dlsym($0, "DisplayServicesSetBrightness") }.map { unsafeBitCast($0, to: DSSetFn.self) }
private func activeDisplays() -> [CGDirectDisplayID] {
var count: UInt32 = 0
guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else { return [] }
var ids = [CGDirectDisplayID](repeating: 0, count: Int(count))
guard CGGetActiveDisplayList(count, &ids, &count) == .success else { return [] }
return Array(ids.prefix(Int(count)))
}
// Save the built-in display's current brightness, then set it to 0. Only the built-in
// panel is touched — external displays (which can't be reliably restored over DDC) are
// left alone. Re-entry keeps the first-saved value so a second call can't record 0.
private func dimBuiltInToZero() {
guard let get = Self.dsGet, let set = Self.dsSet else { return }
for id in activeDisplays() where CGDisplayIsBuiltin(id) != 0 {
if savedBrightness[id] != nil { _ = set(id, 0); continue } // re-entry: keep first-saved level
var cur: Float = 0
guard get(id, &cur) == 0 else { continue } // can't read it → can't guarantee restore → leave it alone
savedBrightness[id] = cur
_ = set(id, 0)
}
}
private func restoreBrightness() {
if let set = Self.dsSet {
for (id, value) in savedBrightness { _ = set(id, value) }
}
savedBrightness.removeAll()
}
// Save the keyboard backlight level and turn it off. Re-entry keeps the first saved value.
private func dimKeyboardToZero() {
guard let kb = keyboardBacklight else { return }
let cur = kb.brightnessForKeyboard(keyboardID)
guard cur >= 0 else { return } // no controllable backlight on this machine
if savedKeyboardBrightness == nil { savedKeyboardBrightness = cur }
_ = kb.setBrightness(0, forKeyboard: keyboardID)
}
private func restoreKeyboardBrightness() {
guard let kb = keyboardBacklight, let saved = savedKeyboardBrightness else { return }
_ = kb.setBrightness(saved, forKeyboard: keyboardID)
savedKeyboardBrightness = nil
}
// After "息屏", restore the moment the user comes back. A short grace period skips the
// input that triggered the action (and any immediate residual); then a global event
// monitor fires on the first real mouse input. Event-driven, so the intermittent activity
// that defeated idle-polling can't defeat it. (Mouse events need no Accessibility permission.)
private func startScreenOffWatch() {
stopScreenOffWatch()
screenOffActive = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
guard let self = self, self.screenOffActive, self.screenOffMonitor == nil else { return }
self.screenOffMonitor = NSEvent.addGlobalMonitorForEvents(
matching: [.mouseMoved, .leftMouseDown, .rightMouseDown, .otherMouseDown, .scrollWheel]
) { [weak self] _ in self?.wakeFromScreenOff() }
}
}
private func stopScreenOffWatch() {
screenOffActive = false
if let m = screenOffMonitor { NSEvent.removeMonitor(m); screenOffMonitor = nil }
}
// User returned: restore built-in brightness + keyboard backlight, re-light the external
// display, and drop the keep-awake caffeinate we started.
private func wakeFromScreenOff() {
stopScreenOffWatch()
restoreBrightness()
restoreKeyboardBrightness()
externalDisplayWake()
killTask()
rearmAutoOff() // idle just reset; schedule the next early-screen-off check
}
// MARK: - System display-off time (pmset displaysleep) + auto early screen-off
private func sysOffLabel() -> String {
let value: String
if sysOffMinutes < 0 { value = "…" }
else if sysOffMinutes == 0 { value = t("menu.never") }
else { value = durationTitle(sysOffMinutes) }
return String(format: t("sys.offAfterFmt"), value)
}
private func updateSysOffUI() {
guard sysOffItem != nil else { return }
sysOffItem.title = sysOffLabel()
for (min, item) in sysOffPresetItems { item.state = (min == sysOffMinutes) ? .on : .off }
}
private static func runCapture(_ path: String, _ args: [String]) -> String {
let p = Process()
p.executableURL = URL(fileURLWithPath: path)