-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapslock_indicator.py
More file actions
218 lines (183 loc) · 6.21 KB
/
capslock_indicator.py
File metadata and controls
218 lines (183 loc) · 6.21 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
#!/usr/bin/env python3
"""Small cross-platform Caps Lock indicator window."""
from __future__ import annotations
import ctypes
import glob
import os
import platform
import re
import subprocess
import tempfile
import tkinter as tk
from pathlib import Path
IS_WINDOWS = platform.system() == "Windows"
IS_MACOS = platform.system() == "Darwin"
IS_LINUX = platform.system() == "Linux"
class CapsLockStateProvider:
def __init__(self) -> None:
self.led_paths = self._discover_led_paths() if IS_LINUX else []
@staticmethod
def _discover_led_paths() -> list[Path]:
paths = sorted(glob.glob("/sys/class/leds/*::capslock/brightness"))
return [Path(p) for p in paths]
@staticmethod
def _read_led(path: Path) -> bool:
try:
return path.read_text(encoding="utf-8").strip() == "1"
except OSError:
return False
def _linux_capslock_from_leds(self) -> bool | None:
if not self.led_paths:
return None
for path in self.led_paths:
if self._read_led(path):
return True
return False
@staticmethod
def _linux_capslock_from_xset() -> bool | None:
try:
result = subprocess.run(
["xset", "q"],
check=False,
capture_output=True,
text=True,
timeout=0.4,
)
if result.returncode != 0:
return None
return "Caps Lock: on" in result.stdout
except (OSError, subprocess.SubprocessError):
return None
@staticmethod
def _windows_capslock() -> bool:
try:
return bool(ctypes.windll.user32.GetKeyState(0x14) & 1)
except OSError:
return False
@staticmethod
def _macos_capslock() -> bool:
# CoreGraphics CGEvent flag bit for Caps Lock.
k_cg_event_flag_mask_alpha_shift = 0x10000
k_cg_event_source_state_combined_session_state = 0
try:
app_services = ctypes.CDLL(
"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"
)
app_services.CGEventSourceFlagsState.argtypes = [ctypes.c_uint32]
app_services.CGEventSourceFlagsState.restype = ctypes.c_uint64
flags = app_services.CGEventSourceFlagsState(
k_cg_event_source_state_combined_session_state
)
return bool(flags & k_cg_event_flag_mask_alpha_shift)
except OSError:
return False
def is_capslock_on(self) -> bool:
if IS_LINUX:
led_state = self._linux_capslock_from_leds()
if led_state is not None:
return led_state
xset_state = self._linux_capslock_from_xset()
if xset_state is not None:
return xset_state
return False
if IS_WINDOWS:
return self._windows_capslock()
if IS_MACOS:
return self._macos_capslock()
return False
def primary_display_origin() -> tuple[int, int]:
if IS_LINUX:
try:
result = subprocess.run(
["xrandr", "--query"],
check=False,
capture_output=True,
text=True,
timeout=0.4,
)
if result.returncode != 0:
return 0, 0
for line in result.stdout.splitlines():
if " connected primary " not in line:
continue
match = re.search(r"\d+x\d+\+(-?\d+)\+(-?\d+)", line)
if match:
return int(match.group(1)), int(match.group(2))
except (OSError, subprocess.SubprocessError):
return 0, 0
return 0, 0
class CapsLockIndicator:
def __init__(self) -> None:
self.root = tk.Tk()
self.root.title("Caps Lock Indicator")
self.root.overrideredirect(True)
self.root.attributes("-topmost", True)
self.root.configure(bg="#d62828")
self.window_size = 92
self.margin = 20
self.origin_x, self.origin_y = primary_display_origin()
frame = tk.Frame(
self.root,
bg="#d62828",
highlightbackground="#111111",
highlightthickness=2,
width=self.window_size,
height=self.window_size,
)
frame.pack_propagate(False)
frame.pack(fill="both", expand=True)
label = tk.Label(
frame,
text="CAPS",
fg="#ffffff",
bg="#d62828",
font=("DejaVu Sans", 14, "bold"),
)
label.pack(expand=True)
self.state_provider = CapsLockStateProvider()
self.last_state: bool | None = None
self.root.withdraw()
self.root.after(80, self._poll_loop)
def _place_window(self) -> None:
x = self.origin_x + self.margin
y = self.origin_y + self.margin
self.root.geometry(f"{self.window_size}x{self.window_size}+{x}+{y}")
def _show(self) -> None:
self._place_window()
self.root.deiconify()
self.root.lift()
def _hide(self) -> None:
self.root.withdraw()
def _poll_loop(self) -> None:
state = self.state_provider.is_capslock_on()
if state != self.last_state:
if state:
self._show()
else:
self._hide()
self.last_state = state
self.root.after(80, self._poll_loop)
def run(self) -> None:
self.root.mainloop()
def acquire_single_instance_lock() -> object | None:
lock_path = os.path.join(tempfile.gettempdir(), "capslock-indicator.lock")
lock_file = open(lock_path, "w", encoding="utf-8")
try:
if IS_WINDOWS:
import msvcrt
msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return lock_file
except OSError:
lock_file.close()
return None
def main() -> int:
lock = acquire_single_instance_lock()
if lock is None:
return 0
CapsLockIndicator().run()
return 0
if __name__ == "__main__":
raise SystemExit(main())