-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxsct_gui.py
More file actions
561 lines (463 loc) · 19.7 KB
/
Copy pathxsct_gui.py
File metadata and controls
561 lines (463 loc) · 19.7 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
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
import os
import shutil
import sys
import subprocess
from PyQt6.QtCore import (
QEvent,
QLibraryInfo,
QLocale,
QStandardPaths,
Qt,
QTranslator,
)
from PyQt6.QtGui import (
QAction,
QActionGroup,
QPixmap,
QPainter,
QLinearGradient,
QColor,
QIcon,
)
SUPPORTED_LANGUAGES = (
("en", "English"),
("de_DE", "Deutsch (Deutschland)"),
("fr_CA", "Français (Canada)"),
("fr_FR", "Français (France)"),
("id_ID", "Bahasa Indonesia"),
("ja_JP", "日本語"),
("ko", "한국어"),
("pt_BR", "Português (Brasil)"),
("pt_PT", "Português (Portugal)"),
("th_TH", "ไทย"),
("tr_TR", "Türkçe"),
("ru_RU", "Русский"),
("zh_HK", "繁體中文(香港)"),
("zh_CN", "简体中文"),
("zh_TW", "繁體中文(台灣)"),
)
class TranslationManager:
def __init__(self, app):
self.app = app
self.system_locale = self.detect_system_locale()
self.current_locale = ""
self.qt_translator = None
self.app_translator = None
source_dir = os.path.dirname(os.path.abspath(__file__))
self.translation_dirs = (
os.path.join(source_dir, "translations"),
"/usr/share/xsct-gui/translations",
)
self.qt_translations_dir = QLibraryInfo.path(
QLibraryInfo.LibraryPath.TranslationsPath
)
@staticmethod
def normalize_locale(locale_name):
"""Return a Qt locale name without encoding or modifier suffixes."""
if not locale_name:
return ""
locale_name = locale_name.split(":", 1)[0]
locale_name = locale_name.split(".", 1)[0]
locale_name = locale_name.split("@", 1)[0]
locale_name = locale_name.replace("-", "_")
if locale_name.upper() in {"C", "POSIX"}:
return ""
normalized = QLocale(locale_name).name()
return "" if normalized == "C" else normalized
@classmethod
def detect_system_locale(cls):
"""Detect the desktop language even when LC_ALL forces the C locale."""
qt_locale = cls.normalize_locale(QLocale.system().name())
if qt_locale:
return qt_locale
# Some display managers preserve the selected language in LANG or
# LANGUAGE while launching applications with LC_ALL=C.UTF-8.
for variable in ("LANGUAGE", "LC_MESSAGES", "LANG"):
locale_name = cls.normalize_locale(os.environ.get(variable, ""))
if locale_name:
return locale_name
return "en_US"
@staticmethod
def locale_candidates(locale_name):
language = locale_name.split("_", 1)[0]
return (locale_name,) if language == locale_name else (locale_name, language)
def compile_source_catalog(self, locale_name):
"""Compile a source-tree TS catalog into the user's cache if needed."""
source_catalog = os.path.join(
self.translation_dirs[0], f"xsct_gui_{locale_name}.ts"
)
if not os.path.isfile(source_catalog):
return ""
lrelease = shutil.which("lrelease")
if lrelease is None and os.path.isfile("/usr/lib/qt6/bin/lrelease"):
lrelease = "/usr/lib/qt6/bin/lrelease"
if lrelease is None:
return ""
cache_dir = os.path.join(
QStandardPaths.writableLocation(QStandardPaths.StandardLocation.CacheLocation),
"translations",
)
compiled_catalog = os.path.join(cache_dir, f"xsct_gui_{locale_name}.qm")
try:
os.makedirs(cache_dir, exist_ok=True)
if (not os.path.isfile(compiled_catalog) or
os.path.getmtime(compiled_catalog) < os.path.getmtime(source_catalog)):
result = subprocess.run(
[lrelease, source_catalog, "-qm", compiled_catalog],
check=False,
capture_output=True,
)
if result.returncode != 0:
return ""
except OSError:
return ""
return compiled_catalog
def load_application_translation(self, requested_locale):
for candidate in self.locale_candidates(requested_locale):
for translations_dir in self.translation_dirs:
if self.app_translator.load(
f"xsct_gui_{candidate}", translations_dir):
return True
compiled_catalog = self.compile_source_catalog(candidate)
if compiled_catalog and self.app_translator.load(compiled_catalog):
return True
return False
def set_language(self, locale_name=""):
requested_locale = locale_name or self.system_locale
for translator in (self.app_translator, self.qt_translator):
if translator is not None:
self.app.removeTranslator(translator)
self.qt_translator = QTranslator(self.app)
self.app_translator = QTranslator(self.app)
for candidate in self.locale_candidates(requested_locale):
if self.qt_translator.load(
f"qtbase_{candidate}", self.qt_translations_dir):
self.app.installTranslator(self.qt_translator)
break
source_language = requested_locale.split("_", 1)[0] == "en"
application_loaded = (
source_language or self.load_application_translation(requested_locale)
)
if application_loaded and not source_language:
self.app.installTranslator(self.app_translator)
QLocale.setDefault(QLocale(requested_locale))
self.current_locale = locale_name
return application_loaded
from PyQt6.QtSvg import QSvgRenderer
from PyQt6.QtWidgets import (
QApplication,
QDialog,
QHBoxLayout,
QLabel,
QMainWindow,
QMessageBox,
QPushButton,
QSlider,
QTextBrowser,
QVBoxLayout,
QWidget,
)
class AboutDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle(self.tr("About xsct_gui"))
self.setMinimumSize(430, 430)
layout = QVBoxLayout(self)
text = QTextBrowser()
text.setOpenExternalLinks(True)
text.setHtml(self.tr(
"<h2>xsct_gui</h2>"
"<p>A <i>GUI</i> (Graphical User Interface) for xsct, "
"to reduce or increase the amount of blue light produced by the screen.</p>"
"<p>Copyright © 2024-2026 Washington Indacochea Delgado.<br>"
"linuxfrontier@proton.me<br>"
"License: GNU GPL3.</p>"
"<p>This program lets you easily adjust the color temperature and brightness "
"of your screen, helping reduce eye strain and improve your computing experience.</p>"
"<p><i>For more information, visit:</i></p>"
"<p>xsct_gui – a GUI for xsct<br>"
"<a href=\"https://github.com/wachin/xsct_gui\">https://github.com/wachin/xsct_gui</a></p>"
"<p>Xsct (X11 set color temperature)<br>"
"<a href=\"https://github.com/faf0/sct\">https://github.com/faf0/sct</a></p>"
))
layout.addWidget(text)
close_button = QPushButton(self.tr("Close"))
close_button.clicked.connect(self.accept)
layout.addWidget(close_button)
class GradientLabel(QLabel):
def __init__(self, width, height, start_color, end_color, parent=None):
super().__init__(parent)
self.setFixedSize(width, height)
self.start_color = QColor(*start_color)
self.end_color = QColor(*end_color)
self.update_gradient()
def update_gradient(self):
pixmap = QPixmap(self.width(), self.height())
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
gradient = QLinearGradient(0, 0, self.width(), 0)
gradient.setColorAt(0.0, self.start_color)
gradient.setColorAt(1.0, self.end_color)
painter.fillRect(0, 0, self.width(), self.height(), gradient)
painter.end()
self.setPixmap(pixmap)
class HelpDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle(self.tr("Help – xsct_gui"))
self.setMinimumSize(520, 480)
layout = QVBoxLayout(self)
text = QTextBrowser()
text.setOpenExternalLinks(True)
text.setHtml(self.tr(
"<h2>xsct_gui Help</h2>"
"<h3>What is xsct_gui?</h3>"
"<p>xsct_gui is a <i>GUI</i> (Graphical User Interface) for "
"<b>xsct</b> (X11 set color temperature). It allows you to easily "
"adjust the color temperature and brightness of your screen to "
"reduce the amount of blue light emitted by your display.</p>"
"<h3>How to use it</h3>"
"<p><b>Temperature slider:</b> Move the slider to the left to "
"lower the color temperature (warmer, reddish tones, less blue "
"light) or to the right to raise it (cooler, bluish tones, more "
"blue light). The range goes from 2000 K (very warm) to "
"6500 K (daylight).</p>"
"<p><b>Brightness slider:</b> Move the slider to the left to "
"reduce brightness or to the right to increase it. The range goes "
"from 0.300 (dim) to 1.000 (full brightness).</p>"
"<h3>Benefits of reducing blue light at night</h3>"
"<p>Electronic screens emit a significant amount of "
"<b>blue light</b>, which can interfere with your body's natural "
"production of <b>melatonin</b> — the hormone responsible for "
"regulating your sleep-wake cycle.</p>"
"<ul>"
"<li><b>Faster sleep onset:</b> By reducing blue light exposure "
"in the evening, your brain can produce melatonin more "
"naturally, helping you fall asleep faster.</li>"
"<li><b>Improved sleep quality:</b> Less blue light before "
"bedtime is associated with deeper, more restorative sleep.</li>"
"<li><b>Reduced eye strain:</b> Warmer color temperatures are "
"gentler on the eyes, especially in low-light environments, "
"reducing fatigue and discomfort.</li>"
"<li><b>Better circadian rhythm:</b> Limiting blue light at "
"night helps maintain a healthy internal clock, making it easier "
"to wake up refreshed and stay alert during the day.</li>"
"<li><b>Long-term health:</b> Chronic disruption of circadian "
"rhythms has been linked to various health issues. Reducing "
"blue light at night is a simple preventive measure.</li>"
"</ul>"
"<p><i>Tip:</i> Set the temperature to around 2000–3500 K "
"about 1–2 hours before bedtime for the best results.</p>"
"<h3>Requirements</h3>"
"<p>This program requires <b>xsct</b> to be installed on your "
"system. You can install it with:</p>"
"<p><code>sudo apt install xsct</code></p>"
"<h3>More information</h3>"
"<p>xsct_gui – a GUI for xsct<br>"
"<a href=\"https://github.com/wachin/xsct_gui\">"
"https://github.com/wachin/xsct_gui</a></p>"
"<p>Xsct (X11 set color temperature)<br>"
"<a href=\"https://github.com/faf0/sct\">"
"https://github.com/faf0/sct</a></p>"
))
layout.addWidget(text)
close_button = QPushButton(self.tr("Close"))
close_button.clicked.connect(self.accept)
layout.addWidget(close_button)
class MainWindow(QMainWindow):
def __init__(self, translation_manager=None):
super().__init__()
self.translation_manager = translation_manager
self.setMinimumSize(420, 285)
self.temp_min = 2000
self.temp_max = 6500
# Store brightness in thousandths to use an integer slider
self.brightness_min = 300
self.brightness_max = 1000
self.central = QWidget()
self.setCentralWidget(self.central)
self.main_layout = QVBoxLayout(self.central)
self.main_layout.setContentsMargins(12, 12, 12, 12)
self.main_layout.setSpacing(12)
self.build_language_menu()
self.build_help_menu()
self.build_temperature_section()
self.build_brightness_section()
self.build_buttons()
self.set_window_icon()
self.retranslate_ui()
self.apply_xsct()
def build_language_menu(self):
self.language_menu = self.menuBar().addMenu("")
self.language_actions = QActionGroup(self)
self.language_actions.setExclusive(True)
self.system_language_action = QAction(self)
self.system_language_action.setCheckable(True)
self.system_language_action.setData("")
self.language_actions.addAction(self.system_language_action)
self.language_menu.addAction(self.system_language_action)
self.language_menu.addSeparator()
for locale_name, native_name in SUPPORTED_LANGUAGES:
action = QAction(native_name, self)
action.setCheckable(True)
action.setData(locale_name)
self.language_actions.addAction(action)
self.language_menu.addAction(action)
selected_locale = (
self.translation_manager.current_locale
if self.translation_manager is not None else ""
)
for action in self.language_actions.actions():
action.setChecked(action.data() == selected_locale)
self.language_actions.triggered.connect(self.change_language)
def build_help_menu(self):
self.help_menu = self.menuBar().addMenu("")
self.help_contents_action = QAction(self)
self.help_contents_action.triggered.connect(self.show_help)
self.help_menu.addAction(self.help_contents_action)
def show_help(self):
dialog = HelpDialog(self)
dialog.exec()
def change_language(self, action):
if self.translation_manager is not None:
self.translation_manager.set_language(action.data())
def changeEvent(self, event):
if event.type() == QEvent.Type.LanguageChange:
self.retranslate_ui()
super().changeEvent(event)
def retranslate_ui(self):
self.setWindowTitle(self.tr("xsct GUI"))
self.language_menu.setTitle(self.tr("Language"))
self.system_language_action.setText(self.tr("System default"))
self.about_button.setText(self.tr("About..."))
self.update_labels()
def build_temperature_section(self):
temp_container = QVBoxLayout()
temp_container.setSpacing(6)
temp_top_row = QHBoxLayout()
temp_min_label = QLabel("2000 K")
self.temperature_label = QLabel(self.tr("Temperature (K): 6500"))
self.temperature_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
temp_top_row.addWidget(temp_min_label)
temp_top_row.addStretch()
temp_top_row.addWidget(self.temperature_label)
temp_top_row.addStretch()
temp_container.addLayout(temp_top_row)
self.temp_gradient = GradientLabel(
380, 20,
(255, 137, 18),
(254, 249, 255)
)
temp_container.addWidget(self.temp_gradient, alignment=Qt.AlignmentFlag.AlignCenter)
self.temperature_slider = QSlider(Qt.Orientation.Horizontal)
self.temperature_slider.setRange(self.temp_min, self.temp_max)
self.temperature_slider.setValue(6500)
self.temperature_slider.valueChanged.connect(self.on_values_changed)
temp_container.addWidget(self.temperature_slider)
self.temperature_value = QLabel("6500")
self.temperature_value.setAlignment(Qt.AlignmentFlag.AlignCenter)
temp_container.addWidget(self.temperature_value)
self.main_layout.addLayout(temp_container)
def build_brightness_section(self):
bright_container = QVBoxLayout()
bright_container.setSpacing(6)
bright_top_row = QHBoxLayout()
bright_min_label = QLabel("0.300")
self.brightness_label = QLabel(self.tr("Brightness: 1.000"))
self.brightness_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
bright_top_row.addWidget(bright_min_label)
bright_top_row.addStretch()
bright_top_row.addWidget(self.brightness_label)
bright_top_row.addStretch()
bright_container.addLayout(bright_top_row)
self.bright_gradient = GradientLabel(
380, 20,
(51, 51, 51),
(255, 255, 255)
)
bright_container.addWidget(self.bright_gradient, alignment=Qt.AlignmentFlag.AlignCenter)
self.brightness_slider = QSlider(Qt.Orientation.Horizontal)
self.brightness_slider.setRange(self.brightness_min, self.brightness_max)
self.brightness_slider.setValue(1000)
self.brightness_slider.valueChanged.connect(self.on_values_changed)
bright_container.addWidget(self.brightness_slider)
self.brightness_value = QLabel("1.000")
self.brightness_value.setAlignment(Qt.AlignmentFlag.AlignCenter)
bright_container.addWidget(self.brightness_value)
self.main_layout.addLayout(bright_container)
def build_buttons(self):
row = QHBoxLayout()
row.addStretch()
self.about_button = QPushButton()
self.about_button.clicked.connect(self.show_about)
row.addWidget(self.about_button)
row.addStretch()
self.main_layout.addLayout(row)
def set_window_icon(self):
icon = QIcon.fromTheme("xsct-gui")
if not icon.isNull():
self.setWindowIcon(icon)
return
local_icon = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "data", "xsct-gui.svg"
)
if os.path.exists(local_icon):
self.setWindowIcon(self.svg_to_icon(local_icon, 64))
def svg_to_icon(self, path, size):
renderer = QSvgRenderer(path)
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
renderer.render(painter)
painter.end()
return QIcon(pixmap)
def get_temperature(self):
return self.temperature_slider.value()
def get_brightness(self):
return self.brightness_slider.value() / 1000.0
def update_labels(self):
temperature = self.get_temperature()
brightness = self.get_brightness()
self.temperature_label.setText(
self.tr("Temperature (K): %1").replace("%1", str(temperature))
)
self.temperature_value.setText(str(temperature))
self.brightness_label.setText(
self.tr("Brightness: %1").replace("%1", f"{brightness:.3f}")
)
self.brightness_value.setText(f"{brightness:.3f}")
def apply_xsct(self):
temperature = self.get_temperature()
brightness = self.get_brightness()
try:
subprocess.run(
["xsct", str(temperature), f"{brightness:.3f}"],
check=False
)
except FileNotFoundError:
QMessageBox.critical(
self,
self.tr("Error"),
self.tr(
"The 'xsct' command was not found.\n\n"
"Install it with:\n"
"sudo apt install xsct"
)
)
def on_values_changed(self):
self.update_labels()
self.apply_xsct()
def show_about(self):
dialog = AboutDialog(self)
dialog.exec()
def main():
app = QApplication(sys.argv)
translation_manager = TranslationManager(app)
translation_manager.set_language()
window = MainWindow(translation_manager)
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()