-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfigure.py
More file actions
executable file
·1752 lines (1492 loc) · 67.3 KB
/
configure.py
File metadata and controls
executable file
·1752 lines (1492 loc) · 67.3 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
#!/usr/bin/env python
# SPDX-License-Identifier: GPL-3.0-or-later
#
# turing-smart-screen-python - a Python system monitor and library for USB-C displays like Turing Smart Screen or XuanFang
# https://github.com/mathoudebine/turing-smart-screen-python/
#
# Copyright (C) 2021 Matthieu Houdebine (mathoudebine)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# This file is the system monitor configuration GUI
from library.pythoncheck import check_python_version
check_python_version()
import glob
import hashlib
import os
import platform
import shutil
import subprocess
import sys
import webbrowser
import requests
import babel
from datetime import datetime, timezone
from library.smartmonitor_compile import compile_theme_file
from library.smartmonitor_ui import encode_ui_file
try:
import tkinter.ttk as ttk
from tkinter import *
from tkinter import filedialog, messagebox, simpledialog
from PIL import ImageTk
import psutil
import ruamel.yaml
import sv_ttk
from pathlib import Path
from PIL import Image
from serial.tools.list_ports import comports
from tktooltip import ToolTip
except Exception as e:
print("""Import error: %s
Please see README.md / README_RU.md in the repository root for installation steps.
If the GUI still does not start, check repository issues or discussions.""" % str(
e))
try:
sys.exit(0)
except:
os._exit(0)
from library.sensors.sensors_python import sensors_fans, is_cpu_fan
TURING_MODEL = "Turing Smart Screen"
USBPCMONITOR_MODEL = "UsbPCMonitor"
XUANFANG_MODEL = "XuanFang rev. B & flagship"
KIPYE_MODEL = "Kipye Qiye Smart Display"
USB_HID_MODEL = "SmartMonitor HID (experimental)"
WEACT_MODEL = "WeAct Studio Display FS V1"
SIMULATED_MODEL = "Simulated screen"
SIZE_3_5_INCH = "3.5\""
SIZE_5_INCH = "5\""
SIZE_8_8_INCH = "8.8\""
SIZE_2_1_INCH = "2.1\"" # Only for retro compatibility
SIZE_2_x_INCH = "2.1\" / 2.8\""
SIZE_0_96_INCH = "0.96\""
size_list = (SIZE_0_96_INCH, SIZE_2_x_INCH, SIZE_3_5_INCH, SIZE_5_INCH, SIZE_8_8_INCH)
# Maps between config.yaml values and GUI description
revision_and_size_to_model_map = {
('A', SIZE_3_5_INCH): TURING_MODEL, # Can also be UsbPCMonitor 3.5, does not matter since protocol is the same
('A_HID', SIZE_3_5_INCH): USB_HID_MODEL,
('A', SIZE_5_INCH): USBPCMONITOR_MODEL,
('B', SIZE_3_5_INCH): XUANFANG_MODEL,
('C', SIZE_2_x_INCH): TURING_MODEL,
('C', SIZE_5_INCH): TURING_MODEL,
('C', SIZE_8_8_INCH): TURING_MODEL,
('D', SIZE_3_5_INCH): KIPYE_MODEL,
('WEACT_A', SIZE_3_5_INCH): WEACT_MODEL,
('WEACT_B', SIZE_0_96_INCH): WEACT_MODEL,
('SIMU', SIZE_0_96_INCH): SIMULATED_MODEL,
('SIMU', SIZE_2_x_INCH): SIMULATED_MODEL,
('SIMU', SIZE_3_5_INCH): SIMULATED_MODEL,
('SIMU', SIZE_5_INCH): SIMULATED_MODEL,
('SIMU', SIZE_8_8_INCH): SIMULATED_MODEL,
}
model_and_size_to_revision_map = {
(TURING_MODEL, SIZE_3_5_INCH): 'A',
(USBPCMONITOR_MODEL, SIZE_3_5_INCH): 'A',
(USB_HID_MODEL, SIZE_3_5_INCH): 'A_HID',
(USBPCMONITOR_MODEL, SIZE_5_INCH): 'A',
(XUANFANG_MODEL, SIZE_3_5_INCH): 'B',
(TURING_MODEL, SIZE_2_x_INCH): 'C',
(TURING_MODEL, SIZE_5_INCH): 'C',
(TURING_MODEL, SIZE_8_8_INCH): 'C',
(KIPYE_MODEL, SIZE_3_5_INCH): 'D',
(WEACT_MODEL, SIZE_3_5_INCH): 'WEACT_A',
(WEACT_MODEL, SIZE_0_96_INCH): 'WEACT_B',
(SIMULATED_MODEL, SIZE_0_96_INCH): 'SIMU',
(SIMULATED_MODEL, SIZE_2_x_INCH): 'SIMU',
(SIMULATED_MODEL, SIZE_3_5_INCH): 'SIMU',
(SIMULATED_MODEL, SIZE_5_INCH): 'SIMU',
(SIMULATED_MODEL, SIZE_8_8_INCH): 'SIMU',
}
hw_lib_map = {"AUTO": "Automatic", "LHM": "LibreHardwareMonitor (admin.)", "PYTHON": "Python libraries",
"STUB": "Fake random data", "STATIC": "Fake static data"}
reverse_map = {False: "classic", True: "reverse"}
weather_unit_map = {"metric": "metric - °C", "imperial": "imperial - °F", "standard": "standard - °K"}
weather_lang_map = {"sq": "Albanian", "af": "Afrikaans", "ar": "Arabic", "az": "Azerbaijani", "eu": "Basque",
"be": "Belarusian", "bg": "Bulgarian", "ca": "Catalan", "zh_cn": "Chinese Simplified",
"zh_tw": "Chinese Traditional", "hr": "Croatian", "cz": "Czech", "da": "Danish", "nl": "Dutch",
"en": "English", "fi": "Finnish", "fr": "French", "gl": "Galician", "de": "German", "el": "Greek",
"he": "Hebrew", "hi": "Hindi", "hu": "Hungarian", "is": "Icelandic", "id": "Indonesian",
"it": "Italian", "ja": "Japanese", "kr": "Korean", "ku": "Kurmanji (Kurdish)", "la": "Latvian",
"lt": "Lithuanian", "mk": "Macedonian", "no": "Norwegian", "fa": "Persian (Farsi)", "pl": "Polish",
"pt": "Portuguese", "pt_br": "Português Brasil", "ro": "Romanian", "ru": "Russian", "sr": "Serbian",
"sk": "Slovak", "sl": "Slovenian", "sp": "Spanish", "sv": "Swedish", "th": "Thai", "tr": "Turkish",
"ua": "Ukrainian", "vi": "Vietnamese", "zu": "Zulu"}
MAIN_DIRECTORY = str(Path(__file__).parent.resolve()) + "/"
THEMES_DIR = MAIN_DIRECTORY + 'res/themes'
SMARTMONITOR_THEMES_DIR = MAIN_DIRECTORY + 'res/smartmonitor/themes'
AUTOSTART_SERVICE_NAME = "turing-smart-screen-python.service"
DEFAULT_SMARTMONITOR_VENDOR_THEME_ROOT = (
os.path.join(MAIN_DIRECTORY, "vendor", "themefor3.5")
if os.path.isdir(os.path.join(MAIN_DIRECTORY, "vendor", "themefor3.5"))
else os.path.join(MAIN_DIRECTORY, "vendor", "themefor3.5")
)
DEFAULT_SMARTMONITOR_PROJECTS_DIR = os.path.join(MAIN_DIRECTORY, "res", "smartmonitor", "projects")
SMARTMONITOR_UI_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<ui>
<widgetParent objectName="background" type="1">
<geometry>
<x>0</x>
<y>0</y>
<width>480</width>
<height>320</height>
</geometry>
<backgroundType>1</backgroundType>
<backgroundColor>0xff0f1720</backgroundColor>
<backgroundImagePath>./images/background.png</backgroundImagePath>
<imageDelay>100</imageDelay>
</widgetParent>
<widget globalID="0" sameTypeID="0" parentName="background" objectName="DateTime 0" type="6">
<geometry>
<x>24</x>
<y>18</y>
<width>150</width>
<height>28</height>
</geometry>
<font>
<text>12:00:00</text>
<fontName>Arial</fontName>
<fontColor>0xffffffff</fontColor>
<fontSize>18</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<dateTimeFormat>hh:nn:ss</dateTimeFormat>
<hAlign>1</hAlign>
</widget>
<widget globalID="1" sameTypeID="1" parentName="background" objectName="DateTime 1" type="6">
<geometry>
<x>24</x>
<y>50</y>
<width>170</width>
<height>24</height>
</geometry>
<font>
<text>2026-01-01</text>
<fontName>Arial</fontName>
<fontColor>0xffcbd5e1</fontColor>
<fontSize>14</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<dateTimeFormat>yyyy-mm-dd</dateTimeFormat>
<hAlign>1</hAlign>
</widget>
<widget globalID="2" sameTypeID="0" parentName="background" objectName="Number 0" type="5">
<geometry>
<x>32</x>
<y>110</y>
<width>96</width>
<height>48</height>
</geometry>
<font>
<text>42</text>
<fontName>Arial</fontName>
<fontColor>0xffffffff</fontColor>
<fontSize>26</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<sensor>
<fastSensor>1</fastSensor>
<sensorTypeName>Temperature</sensorTypeName>
<sensorName>CPU</sensorName>
<readingName>CPU Package</readingName>
<isDiv1204>0</isDiv1204>
</sensor>
<hAlign>1</hAlign>
</widget>
<widget globalID="3" sameTypeID="1" parentName="background" objectName="Number 1" type="5">
<geometry>
<x>176</x>
<y>110</y>
<width>96</width>
<height>48</height>
</geometry>
<font>
<text>42</text>
<fontName>Arial</fontName>
<fontColor>0xffffffff</fontColor>
<fontSize>26</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<sensor>
<fastSensor>5</fastSensor>
<sensorTypeName>Temperature</sensorTypeName>
<sensorName>GPU</sensorName>
<readingName>GPU Temperature</readingName>
<isDiv1204>0</isDiv1204>
</sensor>
<hAlign>1</hAlign>
</widget>
<widget globalID="4" sameTypeID="2" parentName="background" objectName="Number 2" type="5">
<geometry>
<x>320</x>
<y>110</y>
<width>96</width>
<height>48</height>
</geometry>
<font>
<text>42</text>
<fontName>Arial</fontName>
<fontColor>0xffffffff</fontColor>
<fontSize>26</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<sensor>
<fastSensor>12</fastSensor>
<sensorTypeName>Other</sensorTypeName>
<sensorName>System</sensorName>
<readingName>Physical Memory Load</readingName>
<isDiv1204>0</isDiv1204>
</sensor>
<hAlign>1</hAlign>
</widget>
<widget globalID="5" sameTypeID="3" parentName="background" objectName="Number 3" type="5">
<geometry>
<x>32</x>
<y>220</y>
<width>96</width>
<height>48</height>
</geometry>
<font>
<text>42</text>
<fontName>Arial</fontName>
<fontColor>0xffffffff</fontColor>
<fontSize>26</fontSize>
<bold>1</bold>
<italic>0</italic>
</font>
<sensor>
<fastSensor>3</fastSensor>
<sensorTypeName>Usage</sensorTypeName>
<sensorName>CPU</sensorName>
<readingName>Total CPU Usage</readingName>
<isDiv1204>0</isDiv1204>
</sensor>
<hAlign>1</hAlign>
</widget>
</ui>
"""
circular_mask = Image.open(MAIN_DIRECTORY + "res/backgrounds/circular-mask.png")
def get_theme_data(name: str):
dir = os.path.join(THEMES_DIR, name)
# checking if it is a directory
if os.path.isdir(dir):
# Check if a theme.yaml file exists
theme = os.path.join(dir, 'theme.yaml')
if os.path.isfile(theme):
# Get display size from theme.yaml
with open(theme, "rt", encoding='utf8') as stream:
theme_data, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(stream)
return theme_data
return None
def get_themes(size: str):
themes = []
for filename in os.listdir(THEMES_DIR):
theme_data = get_theme_data(filename)
if theme_data and theme_data['display'].get("DISPLAY_SIZE", '3.5"') == size:
themes.append(filename)
return sorted(themes, key=str.casefold)
def get_theme_size(name: str) -> str:
theme_data = get_theme_data(name)
return theme_data['display'].get("DISPLAY_SIZE", '3.5"')
def get_sizes_for_model(model: str):
return [size for size in size_list if (model, size) in model_and_size_to_revision_map]
def sanitize_smartmonitor_theme_name(name: str) -> str:
name = name.strip()
if not name:
return ""
safe = []
for ch in name:
if ch.isalnum() or ch in ("-", "_", ".", " "):
safe.append(ch)
else:
safe.append("_")
return "".join(safe).strip()
def autostart_supported() -> bool:
return platform.system() == "Linux"
def autostart_service_dir() -> Path:
return Path.home() / ".config" / "systemd" / "user"
def autostart_service_path() -> Path:
return autostart_service_dir() / AUTOSTART_SERVICE_NAME
def render_autostart_service() -> str:
python_exec = Path(sys.executable).resolve()
main_script = Path(MAIN_DIRECTORY) / "main.py"
working_dir = Path(MAIN_DIRECTORY).resolve()
return "\n".join([
"[Unit]",
"Description=Turing Smart Screen Python HIDdev",
"After=graphical-session.target network-online.target",
"Wants=graphical-session.target network-online.target",
"",
"[Service]",
"Type=simple",
f"WorkingDirectory={working_dir}",
f"ExecStart={python_exec} {main_script}",
"Restart=on-failure",
"RestartSec=3",
"Environment=PYTHONUNBUFFERED=1",
"",
"[Install]",
"WantedBy=default.target",
"",
])
def write_autostart_service_file() -> Path:
service_dir = autostart_service_dir()
service_dir.mkdir(parents=True, exist_ok=True)
service_path = autostart_service_path()
service_path.write_text(render_autostart_service(), encoding="utf-8")
return service_path
def is_autostart_enabled() -> bool:
if not autostart_supported():
return False
try:
result = subprocess.run(
["systemctl", "--user", "is-enabled", AUTOSTART_SERVICE_NAME],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
return result.returncode == 0 and result.stdout.strip() == "enabled"
except Exception:
return autostart_service_path().is_file()
def enable_autostart_service():
service_path = write_autostart_service_file()
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
subprocess.run(["systemctl", "--user", "enable", "--now", AUTOSTART_SERVICE_NAME], check=True)
return service_path
def disable_autostart_service():
subprocess.run(["systemctl", "--user", "disable", "--now", AUTOSTART_SERVICE_NAME], check=False)
service_path = autostart_service_path()
if service_path.exists():
service_path.unlink()
subprocess.run(["systemctl", "--user", "daemon-reload"], check=False)
def smartmonitor_theme_dir(name: str) -> str:
return os.path.join(SMARTMONITOR_THEMES_DIR, name)
def smartmonitor_theme_img(name: str) -> str:
return os.path.join(smartmonitor_theme_dir(name), "img.dat")
def smartmonitor_theme_metadata(name: str) -> str:
return os.path.join(smartmonitor_theme_dir(name), "metadata.yaml")
def smartmonitor_bundled_dat_path(name: str) -> str:
return os.path.join(THEMES_DIR, f"{name}.dat")
def write_smartmonitor_theme_metadata(theme_name: str, metadata: dict):
with open(smartmonitor_theme_metadata(theme_name), "w", encoding="utf-8") as stream:
ruamel.yaml.YAML().dump(metadata, stream)
def import_smartmonitor_img_dat(theme_name: str, source_img_path: str, metadata: dict | None = None):
os.makedirs(smartmonitor_theme_dir(theme_name), exist_ok=True)
target_img = smartmonitor_theme_img(theme_name)
shutil.copy2(source_img_path, target_img)
shutil.copy2(source_img_path, smartmonitor_bundled_dat_path(theme_name))
info = {
"name": theme_name,
"source_file": str(Path(source_img_path).resolve()),
"imported_at": datetime.now(timezone.utc).isoformat(),
"size": os.path.getsize(target_img),
"sha256": compute_file_sha256(target_img),
}
if metadata:
info.update(metadata)
write_smartmonitor_theme_metadata(theme_name, info)
return target_img
def find_vendor_theme_ui(theme_dir: str) -> str | None:
try:
ui_files = sorted(
filename for filename in os.listdir(theme_dir)
if filename.lower().endswith(".ui") and os.path.isfile(os.path.join(theme_dir, filename))
)
except OSError:
return None
if not ui_files:
return None
return os.path.join(theme_dir, ui_files[0])
def compile_and_import_smartmonitor_ui(theme_name: str, ui_path: str):
compiled_dir = smartmonitor_theme_dir(theme_name)
os.makedirs(compiled_dir, exist_ok=True)
target_img = smartmonitor_theme_img(theme_name)
compiled = compile_theme_file(ui_path)
with open(target_img, "wb") as stream:
stream.write(compiled)
shutil.copy2(target_img, smartmonitor_bundled_dat_path(theme_name))
write_smartmonitor_theme_metadata(
theme_name,
{
"name": theme_name,
"source_ui": str(Path(ui_path).resolve()),
"compiled_at": datetime.now(timezone.utc).isoformat(),
"compiler": "experimental_ui_to_imgdat",
"size": os.path.getsize(target_img),
"sha256": compute_file_sha256(target_img),
},
)
return target_img
def create_smartmonitor_ui_project(project_dir: str, project_name: str):
project_path = Path(project_dir)
images_dir = project_path / "images"
images_dir.mkdir(parents=True, exist_ok=True)
background_path = images_dir / "background.png"
if not background_path.exists():
background = Image.new("RGB", (480, 320), color="#0f1720")
background.save(background_path)
config_path = project_path / "config.ini"
if not config_path.exists():
config_path.write_text(
"[StartupPic]\n"
"path=./images/background.png\n"
"totalMs=1000\n"
"delayMs=1000\n"
"bgColor=0xff0f1720\n",
encoding="utf-8",
)
ui_path = project_path / f"{project_name}.ui"
encode_ui_file(ui_path, SMARTMONITOR_UI_TEMPLATE)
readme_path = project_path / "README.txt"
if not readme_path.exists():
readme_path.write_text(
"SmartMonitor custom UI project\n\n"
"Files:\n"
"- *.ui: encrypted vendor-style UI source\n"
"- config.ini: startup image settings\n"
"- images/background.png: initial background\n\n"
"Workflow:\n"
"1. Edit the UI source or replace images.\n"
"2. In configure.py choose SmartMonitor HID.\n"
"3. Click 'Convert UI->DAT' and select this .ui file.\n"
"4. Save and run to upload the compiled theme.\n",
encoding="utf-8",
)
return ui_path
def import_all_smartmonitor_vendor_themes(vendor_root: str) -> tuple[list[str], list[str]]:
imported = []
failed = []
if not os.path.isdir(vendor_root):
return imported, [f"Vendor theme root not found: {vendor_root}"]
for entry in sorted(os.listdir(vendor_root), key=str.casefold):
theme_dir = os.path.join(vendor_root, entry)
if not os.path.isdir(theme_dir) or not entry.startswith("theme"):
continue
ui_path = find_vendor_theme_ui(theme_dir)
if not ui_path:
failed.append(f"{entry}: missing .ui")
continue
theme_name = sanitize_smartmonitor_theme_name(entry)
try:
compile_and_import_smartmonitor_ui(theme_name, ui_path)
imported.append(theme_name)
except Exception as exc:
failed.append(f"{entry}: {exc}")
return imported, failed
def get_smartmonitor_library_themes():
themes = []
if not os.path.isdir(SMARTMONITOR_THEMES_DIR):
return themes
for filename in os.listdir(SMARTMONITOR_THEMES_DIR):
if os.path.isfile(smartmonitor_theme_img(filename)):
themes.append(filename)
return sorted(themes, key=str.casefold)
def get_smartmonitor_bundled_dat_themes():
themes = []
if not os.path.isdir(THEMES_DIR):
return themes
for filename in os.listdir(THEMES_DIR):
full_path = os.path.join(THEMES_DIR, filename)
if os.path.isfile(full_path) and filename.lower().endswith(".dat"):
themes.append(filename)
return sorted(themes, key=str.casefold)
def get_smartmonitor_themes():
names = list(get_smartmonitor_library_themes())
for filename in get_smartmonitor_bundled_dat_themes():
if filename not in names:
names.append(filename)
return sorted(names, key=str.casefold)
def resolve_smartmonitor_theme_path(name: str):
if not name:
return ""
library_path = smartmonitor_theme_img(name)
if os.path.isfile(library_path):
return library_path
bundled_path = os.path.join(THEMES_DIR, name)
if os.path.isfile(bundled_path) and bundled_path.lower().endswith(".dat"):
return bundled_path
return ""
def get_smartmonitor_theme_info(name: str):
resolved_path = resolve_smartmonitor_theme_path(name)
if not resolved_path:
return {}
if os.path.abspath(resolved_path).startswith(os.path.abspath(SMARTMONITOR_THEMES_DIR) + os.sep):
metadata_file = smartmonitor_theme_metadata(name)
if not os.path.isfile(metadata_file):
return {}
with open(metadata_file, "rt", encoding="utf8") as stream:
info, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(stream)
return info or {}
return {
"name": name,
"source_file": resolved_path,
"size": os.path.getsize(resolved_path),
"sha256": compute_file_sha256(resolved_path),
}
def get_smartmonitor_theme_source_ui(name: str):
info = get_smartmonitor_theme_info(name)
source_ui = info.get("source_ui")
if source_ui and os.path.isfile(source_ui):
return source_ui
return ""
def get_smartmonitor_theme_name_from_path(path: str):
if not path:
return None
try:
wanted = Path(path).expanduser().resolve()
except Exception:
return None
for theme_name in get_smartmonitor_themes():
try:
candidate_path = resolve_smartmonitor_theme_path(theme_name)
if not candidate_path:
continue
candidate = Path(candidate_path).resolve()
except Exception:
continue
if candidate == wanted:
return theme_name
return None
def compute_file_sha256(path: str) -> str:
digest = hashlib.sha256()
with open(path, "rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def get_com_ports():
com_ports_names = ["Automatic detection"] # Add manual entry on top for automatic detection
com_ports = comports()
for com_port in com_ports:
com_ports_names.append(com_port.name)
if platform.system() == "Linux":
for hidraw_path in sorted(glob.glob("/dev/hidraw*")):
com_ports_names.append(hidraw_path)
return com_ports_names
def get_net_if():
if_list = list(psutil.net_if_addrs().keys())
if_list.insert(0, "None") # Add manual entry on top for unavailable/not selected interface
return if_list
def get_fans():
fan_list = list()
auto_detected_cpu_fan = "None"
for name, entries in sensors_fans().items():
for entry in entries:
fan_list.append("%s/%s (%d%% - %d RPM)" % (name, entry.label, entry.percent, entry.current))
if (is_cpu_fan(entry.label) or is_cpu_fan(name)) and auto_detected_cpu_fan == "None":
auto_detected_cpu_fan = "Auto-detected: %s/%s" % (name, entry.label)
fan_list.insert(0, auto_detected_cpu_fan) # Add manual entry on top if auto-detection succeeded
return fan_list
class TuringConfigWindow:
def __init__(self):
self.window = Tk()
self.window.title('Turing System Monitor configuration')
self.window.geometry("940x580")
self.window.iconphoto(True, PhotoImage(file=MAIN_DIRECTORY + "res/icons/monitor-icon-17865/64.png"))
# When window gets focus again, reload theme preview in case it has been updated by theme editor
self.window.bind("<FocusIn>", self.on_theme_change)
self.window.after(0, self.on_fan_speed_update)
# Subwindow for weather/ping config.
self.more_config_window = MoreConfigWindow(self)
# Make TK look better with Sun Valley ttk theme
sv_ttk.set_theme("light")
self.theme_preview_img = None
self.theme_preview = ttk.Label(self.window)
self.theme_preview.place(x=10, y=10)
self.theme_author = ttk.Label(self.window)
sysmon_label = ttk.Label(self.window, text='Display configuration', font='bold')
sysmon_label.place(x=370, y=0)
self.model_label = ttk.Label(self.window, text='Smart screen model')
self.model_label.place(x=370, y=35)
self.model_cb = ttk.Combobox(self.window, values=list(dict.fromkeys((revision_and_size_to_model_map.values()))),
state='readonly')
self.model_cb.bind('<<ComboboxSelected>>', self.on_model_change)
self.model_cb.place(x=550, y=30, width=250)
self.size_label = ttk.Label(self.window, text='Smart screen size')
self.size_label.place(x=370, y=75)
self.size_cb = ttk.Combobox(self.window, values=size_list, state='readonly')
self.size_cb.bind('<<ComboboxSelected>>', self.on_size_change)
self.size_cb.place(x=550, y=70, width=250)
self.com_label = ttk.Label(self.window, text='COM port')
self.com_label.place(x=370, y=115)
self.com_cb = ttk.Combobox(self.window, values=get_com_ports(), state='readonly')
self.com_cb.place(x=550, y=110, width=250)
self.orient_label = ttk.Label(self.window, text='Orientation')
self.orient_label.place(x=370, y=155)
self.orient_cb = ttk.Combobox(self.window, values=list(reverse_map.values()), state='readonly')
self.orient_cb.place(x=550, y=150, width=250)
self.brightness_string = StringVar()
self.brightness_label = ttk.Label(self.window, text='Brightness')
self.brightness_label.place(x=370, y=195)
self.brightness_slider = ttk.Scale(self.window, from_=0, to=100, orient=HORIZONTAL,
command=self.on_brightness_change)
self.brightness_slider.place(x=600, y=195, width=180)
self.brightness_val_label = ttk.Label(self.window, textvariable=self.brightness_string)
self.brightness_val_label.place(x=550, y=195)
self.brightness_warning_label = ttk.Label(self.window,
text="⚠ Turing 3.5\" displays can get hot at high brightness!",
foreground='#ff8c00')
sysmon_label = ttk.Label(self.window, text='System Monitor Configuration', font='bold')
sysmon_label.place(x=370, y=260)
self.theme_label = ttk.Label(self.window, text='Theme')
self.theme_label.place(x=370, y=300)
self.theme_cb = ttk.Combobox(self.window, state='readonly')
self.theme_cb.place(x=550, y=295, width=250)
self.theme_cb.bind('<<ComboboxSelected>>', self.on_theme_change)
self.hwlib_label = ttk.Label(self.window, text='Hardware monitoring')
self.hwlib_label.place(x=370, y=340)
if sys.platform != "win32":
del hw_lib_map["LHM"] # LHM is for Windows platforms only
self.hwlib_cb = ttk.Combobox(self.window, values=list(hw_lib_map.values()), state='readonly')
self.hwlib_cb.place(x=550, y=335, width=250)
self.hwlib_cb.bind('<<ComboboxSelected>>', self.on_hwlib_change)
self.eth_label = ttk.Label(self.window, text='Ethernet interface')
self.eth_label.place(x=370, y=380)
self.eth_cb = ttk.Combobox(self.window, values=get_net_if(), state='readonly')
self.eth_cb.place(x=550, y=375, width=250)
self.wl_label = ttk.Label(self.window, text='Wi-Fi interface')
self.wl_label.place(x=370, y=420)
self.wl_cb = ttk.Combobox(self.window, values=get_net_if(), state='readonly')
self.wl_cb.place(x=550, y=415, width=250)
# For Windows platform only
self.lhm_admin_warning = ttk.Label(self.window,
text="❌ Restart as admin. or select another Hardware monitoring",
foreground='#f00')
# For platform != Windows
self.cpu_fan_label = ttk.Label(self.window, text='CPU fan (?)')
self.cpu_fan_label.config(foreground="#a3a3ff", cursor="hand2")
self.cpu_fan_cb = ttk.Combobox(self.window, values=get_fans(), state='readonly')
self.tooltip = ToolTip(self.cpu_fan_label,
msg="If \"None\" is selected, CPU fan was not auto-detected.\n"
"Manually select your CPU fan from the list.\n\n"
"Fans missing from the list? Install lm-sensors package\n"
"and run 'sudo sensors-detect' command, then reboot.")
self.weather_ping_btn = ttk.Button(self.window, text="Weather & ping",
command=lambda: self.on_weatherping_click())
self.weather_ping_btn.place(x=20, y=520, height=50, width=100)
self.open_theme_folder_btn = ttk.Button(self.window, text="Open themes\nfolder",
command=lambda: self.on_open_theme_folder_click())
self.open_theme_folder_btn.place(x=130, y=520, height=50, width=100)
self.edit_theme_btn = ttk.Button(self.window, text="Edit theme", command=lambda: self.on_theme_editor_click())
self.edit_theme_btn.place(x=240, y=520, height=50, width=100)
self.edit_ui_btn = ttk.Button(
self.window,
text="Edit UI",
command=lambda: self.on_edit_ui_click(),
)
self.edit_ui_btn.place(x=350, y=520, height=50, width=100)
self.convert_theme_btn = ttk.Button(
self.window,
text="Convert",
command=lambda: self.on_theme_convert_click(),
)
self.convert_theme_btn.place(x=460, y=520, height=50, width=100)
self.new_ui_btn = ttk.Button(
self.window,
text="New UI",
command=lambda: self.on_new_ui_project_click(),
)
self.new_ui_btn.place(x=570, y=520, height=50, width=100)
self.autostart_enable_btn = ttk.Button(
self.window,
text="Enable\nautostart",
command=lambda: self.on_enable_autostart_click(),
)
self.autostart_enable_btn.place(x=680, y=520, height=50, width=100)
self.autostart_disable_btn = ttk.Button(
self.window,
text="Disable\nautostart",
command=lambda: self.on_disable_autostart_click(),
)
self.autostart_disable_btn.place(x=790, y=520, height=50, width=100)
self.save_btn = ttk.Button(self.window, text="Save settings", command=lambda: self.on_save_click())
self.save_btn.place(x=900, y=520, height=50, width=110)
self.save_run_btn = ttk.Button(self.window, text="Save and run", command=lambda: self.on_saverun_click())
self.save_run_btn.place(x=1020, y=520, height=50, width=110)
self.config = None
self.load_config_values()
def run(self):
self.window.mainloop()
def is_smartmonitor_model(self):
return self.model_cb.get() == USB_HID_MODEL
def refresh_theme_selector(self):
if self.is_smartmonitor_model():
themes = get_smartmonitor_themes()
self.theme_label.config(text='SmartMonitor theme')
self.open_theme_folder_btn.config(text="Import vendor\nset")
self.edit_theme_btn.config(text="Import\n.dat")
self.edit_ui_btn.config(text="Open/Edit\nUI", state="normal")
self.convert_theme_btn.config(text="Convert\nUI->DAT", state="normal")
self.new_ui_btn.config(text="New UI\nproject", state="normal")
else:
size = self.size_cb.get().replace(SIZE_2_x_INCH, SIZE_2_1_INCH)
themes = get_themes(size)
self.theme_label.config(text='Theme')
self.open_theme_folder_btn.config(text="Open themes\nfolder")
self.edit_theme_btn.config(text="Edit theme")
self.edit_ui_btn.config(text="Open/Edit UI", state="disabled")
self.convert_theme_btn.config(text="Convert", state="disabled")
self.new_ui_btn.config(text="New UI", state="disabled")
self.theme_cb.config(values=themes)
if not themes:
self.theme_cb.set("")
elif self.theme_cb.get() not in themes:
self.theme_cb.set(themes[0])
self.refresh_autostart_buttons()
def load_theme_preview(self):
if self.is_smartmonitor_model():
theme_name = self.theme_cb.get()
theme_preview = Image.open(MAIN_DIRECTORY + "res/docs/no-preview.png")
theme_preview.thumbnail((320, 480), Image.Resampling.LANCZOS)
self.theme_preview_img = ImageTk.PhotoImage(theme_preview)
self.theme_preview.config(image=self.theme_preview_img)
info = get_smartmonitor_theme_info(theme_name) if theme_name else {}
if theme_name:
source_file = info.get("source_file")
if source_file:
author_text = f"SmartMonitor img.dat: {theme_name} ({Path(source_file).name})"
else:
author_text = f"SmartMonitor img.dat: {theme_name}"
else:
author_text = "SmartMonitor img.dat theme is not selected. Import one with the GUI button."
self.theme_author.config(text=author_text, foreground="#a3a3a3", cursor="")
self.theme_author.unbind("<Button-1>")
self.theme_author.place(x=10, y=self.theme_preview_img.height() + 15)
return
theme_data = get_theme_data(self.theme_cb.get())
try:
theme_preview = Image.open(MAIN_DIRECTORY + "res/themes/" + self.theme_cb.get() + "/preview.png")
if theme_data['display'].get("DISPLAY_SIZE", '3.5"') == SIZE_2_1_INCH:
# This is a circular screen: apply a circle mask over the preview
theme_preview.paste(circular_mask, mask=circular_mask)
except:
theme_preview = Image.open(MAIN_DIRECTORY + "res/docs/no-preview.png")
finally:
theme_preview.thumbnail((320, 480), Image.Resampling.LANCZOS)
self.theme_preview_img = ImageTk.PhotoImage(theme_preview)
self.theme_preview.config(image=self.theme_preview_img)
author_name = theme_data.get('author', 'unknown')
self.theme_author.config(text="Author: " + author_name)
if author_name.startswith("@"):
self.theme_author.config(foreground="#a3a3ff", cursor="hand2")
self.theme_author.bind("<Button-1>",
lambda e: webbrowser.open_new_tab("https://github.com/" + author_name[1:]))
else:
self.theme_author.config(foreground="#a3a3a3", cursor="")
self.theme_author.unbind("<Button-1>")
self.theme_author.place(x=10, y=self.theme_preview_img.height() + 15)
def load_config_values(self):
with open(MAIN_DIRECTORY + "config.yaml", "rt", encoding='utf8') as stream:
self.config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(stream)
revision = self.config['display']['REVISION']
# Check if theme is valid for classic framebuffer-driven models
if revision != "A_HID" and get_theme_data(self.config['config']['THEME']) is None:
# Theme from config.yaml is not valid: use first theme available default size 3.5"
self.config['config']['THEME'] = get_themes(SIZE_3_5_INCH)[0]
try:
self.hwlib_cb.set(hw_lib_map[self.config['config']['HW_SENSORS']])
except:
self.hwlib_cb.current(0)
try:
if self.config['config']['ETH'] == "":
self.eth_cb.current(0)
else:
self.eth_cb.set(self.config['config']['ETH'])
except:
self.eth_cb.current(0)
try:
if self.config['config']['WLO'] == "":
self.wl_cb.current(0)
else:
self.wl_cb.set(self.config['config']['WLO'])
except:
self.wl_cb.current(0)
try:
if self.config['config']['COM_PORT'] == "AUTO":
self.com_cb.current(0)
else:
self.com_cb.set(self.config['config']['COM_PORT'])
except:
self.com_cb.current(0)
# Guess display size from the configured model.
if revision == "A_HID":
size = SIZE_3_5_INCH
else:
size = get_theme_size(self.config['config']['THEME'])
size = size.replace(SIZE_2_1_INCH, SIZE_2_x_INCH) # If a theme is for 2.1" then it also is for 2.8"
try:
self.size_cb.set(size)
except:
self.size_cb.current(0)
# Guess model from revision and size
try:
self.model_cb.set(revision_and_size_to_model_map[(revision, size)])
except:
self.model_cb.current(0)
try:
self.orient_cb.set(reverse_map[self.config['display']['DISPLAY_REVERSE']])
except:
self.orient_cb.current(0)
try:
self.brightness_slider.set(int(self.config['display']['BRIGHTNESS']))
except:
self.brightness_slider.set(50)