-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings_screen.py
More file actions
969 lines (850 loc) · 45 KB
/
Copy pathsettings_screen.py
File metadata and controls
969 lines (850 loc) · 45 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
"""
Settings screen — General | WiFi | Hotspot | Spotify tabs with virtual keyboard.
"""
import threading
import pygame
from keyboard import VirtualKeyboard
import theme as _theme
from hotspot_service import get_interfaces, best_hotspot_iface
try:
import qrcode as _qrcode
_QRCODE_OK = True
except ImportError:
_QRCODE_OK = False
COMMON_TIMEZONES = [
"UTC",
"Europe/London",
"Europe/Oslo",
"Europe/Paris",
"Europe/Berlin",
"Europe/Stockholm",
"Europe/Helsinki",
"Europe/Riga",
"Europe/Vilnius",
"Europe/Warsaw",
"Europe/Bucharest",
"Europe/Athens",
"Europe/Kiev",
"Europe/Moscow",
"Asia/Dubai",
"Asia/Kolkata",
"Asia/Bangkok",
"Asia/Singapore",
"Asia/Tokyo",
"Asia/Seoul",
"Asia/Shanghai",
"Australia/Sydney",
"Pacific/Auckland",
"America/Los_Angeles",
"America/Denver",
"America/Chicago",
"America/New_York",
"America/Sao_Paulo",
"America/Buenos_Aires",
]
def load_font(paths, size):
for p in paths:
try:
return pygame.font.Font(p, size)
except Exception:
pass
return pygame.font.SysFont("sans", size)
UBUNTU_BOLD = "/usr/share/fonts/truetype/ubuntu/Ubuntu-B.ttf"
UBUNTU_REG = "/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf"
ROBOTO_BOLD = "/usr/share/fonts/truetype/roboto/Roboto-Bold.ttf"
ROBOTO_REG = "/usr/share/fonts/truetype/roboto/Roboto-Regular.ttf"
class SettingsScreen:
def __init__(self, surface, config, wifi_service, weather_service,
hotspot_service=None, spotify_service=None):
self.surface = surface
self.config = config
self.wifi = wifi_service
self.weather = weather_service
self.hotspot = hotspot_service
self.spotify = spotify_service
self.W, self.H = surface.get_size()
self.font_title = load_font([UBUNTU_BOLD, ROBOTO_BOLD], 28)
self.font_label = load_font([UBUNTU_REG, ROBOTO_REG], 22)
self.font_input = load_font([UBUNTU_REG, ROBOTO_REG], 24)
self.font_btn = load_font([UBUNTU_BOLD, ROBOTO_BOLD], 22)
self.font_tab = load_font([UBUNTU_BOLD, ROBOTO_BOLD], 20)
self.font_small = load_font([UBUNTU_REG, ROBOTO_REG], 18)
self.font_kbd = load_font([UBUNTU_REG, ROBOTO_REG], 20)
self.font_tiny = load_font([UBUNTU_REG, ROBOTO_REG], 15)
self.tab = "general"
self.focused = None
# General tab state
self.city_input = config.get("city", "Oslo")
self.tz_scroll = 0
self.tz_selected = config.get("timezone", "Europe/Oslo")
self.units = config.get("units", "metric")
self.clock_24h = config.get("clock_24h", False)
self.night_mode = config.get("night_mode", True)
self.theme = config.get("theme", "dark")
# WiFi tab state
self.networks = []
self.wifi_scanning = False
self.wifi_status = {"ssid": "", "signal": 0, "connected": False}
self.wifi_scroll = 0
self.selected_network = None
self.password_input = ""
self.wifi_message = ""
self.wifi_message_color = 'STATUS_OK'
self.connecting = False
# Hotspot tab state
self.hotspot_ssid = config.get("hotspot_ssid", "DeskClock")
self.hotspot_pwd = config.get("hotspot_password", "")
self.hs_pwd_visible = False
self.hs_deps_msg = "" # dependency install hint if missing
self.hs_iface = best_hotspot_iface(config)
self.hs_interfaces = [] # populated lazily in _draw_hotspot
# Spotify tab state
self.sp_id_input = config.get("spotify_client_id", "")
self.sp_secret_input = config.get("spotify_client_secret", "")
self.sp_callback_input = "" # user pastes callback URL here
self._auth_url = None
self._qr_surf = None # cached QR pygame Surface
# Keyboard
self.kbd = VirtualKeyboard(self.W, self.H, self.font_kbd, font_size=20)
self.show_kbd = False
self.status_message = ""
self.status_color = 'STATUS_OK'
self._p = _theme.DARK
self._build_rects()
def _build_rects(self):
tw = self.W // 4 # 4 tabs: General | WiFi | Hotspot | Spotify
self.tab_general_rect = pygame.Rect(0, 50, tw, 44)
self.tab_wifi_rect = pygame.Rect(tw, 50, tw, 44)
self.tab_hotspot_rect = pygame.Rect(tw * 2, 50, tw, 44)
self.tab_spotify_rect = pygame.Rect(tw * 3, 50, self.W - tw*3, 44)
# Spotify tab controls
self.sp_id_rect = pygame.Rect(220, 138, 680, 44)
self.sp_secret_rect = pygame.Rect(220, 200, 680, 44)
self.sp_save_rect = pygame.Rect(220, 258, 140, 38)
self.sp_auth_rect = pygame.Rect(220, 360, 220, 40)
self.sp_disc_rect = pygame.Rect(220, 360, 220, 40)
# "waiting" state: QR on left (x=15), instructions + input on right (x=200+)
self.sp_cancel_rect = pygame.Rect(200, 290, 120, 36)
self.sp_callback_rect = pygame.Rect(200, 236, self.W - 330, 40)
self.sp_submit_rect = pygame.Rect(self.W - 120, 236, 100, 40)
self.back_rect = pygame.Rect(8, 8, 90, 36)
self.save_rect = pygame.Rect(self.W - 170, self.H - 55, 160, 42)
# General tab
self.city_rect = pygame.Rect(200, 150, 400, 44)
self.tz_list_rect = pygame.Rect(200, 230, 400, 200)
self.unit_c_rect = pygame.Rect(200, 448, 90, 40)
self.unit_f_rect = pygame.Rect(305, 448, 90, 40)
self.clock_12h_rect = pygame.Rect(500, 448, 90, 40)
self.clock_24h_rect = pygame.Rect(605, 448, 90, 40)
self.night_rect = pygame.Rect(200, 505, 50, 30)
self.theme_dark_rect = pygame.Rect(395, 503, 72, 34)
self.theme_light_rect = pygame.Rect(475, 503, 72, 34)
self.theme_auto_rect = pygame.Rect(555, 503, 72, 34)
# WiFi tab
self.scan_rect = pygame.Rect(20, 152, 110, 38)
self.disconnect_rect = pygame.Rect(self.W - 160, 152, 145, 36)
self.net_list_rect = pygame.Rect(20, 202, self.W - 40, 170)
self.pwd_rect = pygame.Rect(200, 392, 380, 44)
self.connect_rect = pygame.Rect(595, 392, 140, 44)
# Hotspot tab
self.hs_toggle_rect = pygame.Rect(self.W - 190, 105, 180, 42)
self.hs_ssid_rect = pygame.Rect(200, 230, 400, 44)
self.hs_pwd_rect = pygame.Rect(200, 292, 360, 44)
self.hs_eye_rect = pygame.Rect(568, 292, 40, 44) # show/hide password
# Interface selector buttons — built dynamically in _draw_hotspot
self.hs_iface_rects: list[tuple] = [] # list of (rect, iface_name)
def on_enter(self):
self.city_input = self.config.get("city", "Oslo")
self.tz_selected = self.config.get("timezone", "Europe/Oslo")
self.units = self.config.get("units", "metric")
self.clock_24h = self.config.get("clock_24h", False)
self.night_mode = self.config.get("night_mode", True)
self.theme = self.config.get("theme", "dark")
self.hotspot_ssid = self.config.get("hotspot_ssid", "DeskClock")
self.hotspot_pwd = self.config.get("hotspot_password", "")
self.hs_iface = best_hotspot_iface(self.config)
self.hs_interfaces = [] # will be refreshed when tab is opened
self.status_message = ""
self.focused = None
self.show_kbd = False
self.wifi_status = self.wifi.get_status()
self.wifi_message = ""
self.hs_deps_msg = ""
self.sp_id_input = self.config.get("spotify_client_id", "")
self.sp_secret_input = self.config.get("spotify_client_secret", "")
self.sp_callback_input = ""
if self.tz_selected in COMMON_TIMEZONES:
idx = COMMON_TIMEZONES.index(self.tz_selected)
self.tz_scroll = max(0, idx - 2)
def handle_event(self, event):
pos = None
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
elif event.type == pygame.FINGERDOWN:
pos = (int(event.x * self.W), int(event.y * self.H))
if event.type in (pygame.MOUSEBUTTONUP, pygame.FINGERUP):
self.kbd.handle_release()
if pos:
return self._handle_touch(pos)
return None
def _handle_touch(self, pos):
if self.show_kbd:
if pos[1] >= self.kbd.y:
result = self.kbd.handle_touch(pos)
if result:
self._kbd_input(result)
return None
if pos[1] < self.kbd.y - 10:
self.show_kbd = False
self.focused = None
return None
if self.back_rect.collidepoint(pos):
return "clock"
if self.tab_general_rect.collidepoint(pos):
self.tab = "general"; self.show_kbd = False; self.focused = None
elif self.tab_wifi_rect.collidepoint(pos):
self.tab = "wifi"; self.show_kbd = False; self.focused = None
self.wifi_status = self.wifi.get_status()
elif self.tab_hotspot_rect.collidepoint(pos):
self.tab = "hotspot"; self.show_kbd = False; self.focused = None
if not self.hs_interfaces:
threading.Thread(target=self._refresh_ifaces, daemon=True).start()
elif self.tab_spotify_rect.collidepoint(pos):
self.tab = "spotify"; self.show_kbd = False; self.focused = None
elif self.tab == "general":
self._handle_general_touch(pos)
elif self.tab == "wifi":
self._handle_wifi_touch(pos)
elif self.tab == "hotspot":
self._handle_hotspot_touch(pos)
elif self.tab == "spotify":
self._handle_spotify_touch(pos)
if self.save_rect.collidepoint(pos):
self._save()
return None
# ── General tab ─────────────────────────────────────────────────────
def _handle_general_touch(self, pos):
if self.city_rect.collidepoint(pos):
self.focused = "city"; self.show_kbd = True
elif self.tz_list_rect.collidepoint(pos):
row_h = 38
rel_y = pos[1] - self.tz_list_rect.y
idx = self.tz_scroll + rel_y // row_h
if 0 <= idx < len(COMMON_TIMEZONES):
self.tz_selected = COMMON_TIMEZONES[idx]
elif self.unit_c_rect.collidepoint(pos):
self.units = "metric"
elif self.unit_f_rect.collidepoint(pos):
self.units = "imperial"
elif self.clock_12h_rect.collidepoint(pos):
self.clock_24h = False
elif self.clock_24h_rect.collidepoint(pos):
self.clock_24h = True
elif self.night_rect.collidepoint(pos):
self.night_mode = not self.night_mode
elif self.theme_dark_rect.collidepoint(pos):
self.theme = "dark"
elif self.theme_light_rect.collidepoint(pos):
self.theme = "light"
elif self.theme_auto_rect.collidepoint(pos):
self.theme = "auto"
up = pygame.Rect(self.tz_list_rect.right + 5, self.tz_list_rect.y, 40, 40)
dn = pygame.Rect(self.tz_list_rect.right + 5, self.tz_list_rect.bottom - 40, 40, 40)
if up.collidepoint(pos):
self.tz_scroll = max(0, self.tz_scroll - 1)
if dn.collidepoint(pos):
self.tz_scroll = min(len(COMMON_TIMEZONES) - 5, self.tz_scroll + 1)
# ── WiFi tab ─────────────────────────────────────────────────────────
def _handle_wifi_touch(self, pos):
if self.scan_rect.collidepoint(pos) and not self.wifi_scanning:
self._start_scan()
elif self.net_list_rect.collidepoint(pos):
row_h = 50
idx = self.wifi_scroll + (pos[1] - self.net_list_rect.y) // row_h
if 0 <= idx < len(self.networks):
self.selected_network = self.networks[idx]
self.password_input = ""
elif self.pwd_rect.collidepoint(pos) and self.selected_network:
self.focused = "wifi_pwd"; self.show_kbd = True
elif self.connect_rect.collidepoint(pos):
if self.selected_network and not self.connecting:
self._start_connect()
elif self.disconnect_rect.collidepoint(pos):
if self.wifi_status.get("connected"):
self.wifi.disconnect()
self.wifi_status = self.wifi.get_status()
self.wifi_message = "Disconnected"
self.wifi_message_color = 'STATUS_OK'
su = pygame.Rect(self.net_list_rect.right + 5, self.net_list_rect.y, 35, 35)
sd = pygame.Rect(self.net_list_rect.right + 5, self.net_list_rect.bottom - 35, 35, 35)
if su.collidepoint(pos): self.wifi_scroll = max(0, self.wifi_scroll - 1)
if sd.collidepoint(pos): self.wifi_scroll = min(max(0, len(self.networks) - 4), self.wifi_scroll + 1)
# ── Spotify tab ───────────────────────────────────────────────────────
def _handle_spotify_touch(self, pos):
if self.sp_id_rect.collidepoint(pos):
self.focused = "sp_id"; self.show_kbd = True
elif self.sp_secret_rect.collidepoint(pos):
self.focused = "sp_secret"; self.show_kbd = True
elif self.sp_save_rect.collidepoint(pos):
self._save_spotify_creds()
elif self.spotify:
status = self.spotify.get_auth_status()
if status in ("idle", "error") and self.sp_auth_rect.collidepoint(pos):
self._start_spotify_auth()
elif status == "waiting":
if self.sp_cancel_rect.collidepoint(pos):
self.spotify.cancel_auth()
self._auth_url = None
self._qr_surf = None
elif status == "ok" and self.sp_disc_rect.collidepoint(pos):
self.spotify.logout()
def _save_spotify_creds(self):
self.config.set("spotify_client_id", self.sp_id_input.strip())
self.config.set("spotify_client_secret", self.sp_secret_input.strip())
self.config.save()
if self.spotify:
self.spotify.reload_credentials()
self.status_message = "Spotify credentials saved!"
self.status_color = 'STATUS_OK'
def _start_spotify_auth(self):
if not self.spotify:
return
url = self.spotify.start_auth()
if url:
self._auth_url = url
self._qr_surf = self._make_qr_surf(url)
self.sp_callback_input = ""
else:
self.status_message = "Cannot start auth — check credentials"
self.status_color = 'STATUS_ERR'
def _submit_callback_url(self):
if not self.spotify or not self.sp_callback_input.strip():
return
ok = self.spotify.handle_redirect_url(self.sp_callback_input.strip())
if ok:
self.sp_callback_input = ""
self._auth_url = None
self._qr_surf = None
else:
self.status_message = f"Auth failed: {self.spotify.get_auth_error()}"
self.status_color = 'STATUS_ERR'
def _make_qr_surf(self, url):
if not _QRCODE_OK:
return None
try:
qr = _qrcode.QRCode(border=2)
qr.add_data(url)
qr.make(fit=True)
matrix = qr.get_matrix() # includes quiet-zone border
n = len(matrix)
cell = max(2, min(4, 160 // n))
size = n * cell
surf = pygame.Surface((size, size))
surf.fill((255, 255, 255))
for r, row in enumerate(matrix):
for c, dark in enumerate(row):
if dark:
pygame.draw.rect(surf, (0, 0, 0),
(c * cell, r * cell, cell, cell))
return surf
except Exception:
return None
# ── Hotspot tab ───────────────────────────────────────────────────────
def _refresh_ifaces(self):
ifaces = get_interfaces()
self.hs_interfaces = ifaces
# Auto-correct selected iface if it no longer exists
names = [i["name"] for i in ifaces]
if self.hs_iface not in names and names:
self.hs_iface = names[-1] # prefer last = highest index (USB)
def _handle_hotspot_touch(self, pos):
if self.hs_toggle_rect.collidepoint(pos):
self._hs_toggle()
elif self.hs_ssid_rect.collidepoint(pos):
if self.hotspot and not self.hotspot.is_active():
self.focused = "hs_ssid"; self.show_kbd = True
elif self.hs_pwd_rect.collidepoint(pos):
if self.hotspot and not self.hotspot.is_active():
self.focused = "hs_pwd"; self.show_kbd = True
elif self.hs_eye_rect.collidepoint(pos):
self.hs_pwd_visible = not self.hs_pwd_visible
else:
# Interface selector buttons
for rect, iface_name in self.hs_iface_rects:
if rect.collidepoint(pos) and not (self.hotspot and self.hotspot.is_active()):
self.hs_iface = iface_name
break
def _hs_toggle(self):
if not self.hotspot:
return
if self.hotspot.is_active():
self.hotspot.stop()
else:
# Check deps first (async to avoid blocking UI)
if not self.hotspot.deps_ok():
def check():
msg = self.hotspot.deps_status()
if msg != "ok":
self.hs_deps_msg = msg
threading.Thread(target=check, daemon=True).start()
# Attempt start anyway — service will surface the error
if len(self.hotspot_pwd) < 8:
self.hs_deps_msg = "Password must be at least 8 characters"
return
self.hs_deps_msg = ""
# Save before starting
self.config.set("hotspot_ssid", self.hotspot_ssid)
self.config.set("hotspot_password", self.hotspot_pwd)
self.config.set("hotspot_iface", self.hs_iface)
self.config.save()
self.hotspot.start(self.hotspot_ssid, self.hotspot_pwd, self.hs_iface)
# ── Keyboard input ───────────────────────────────────────────────────
def _kbd_input(self, key):
target = self.focused
if key == "BACKSPACE":
if target == "city" and self.city_input: self.city_input = self.city_input[:-1]
elif target == "wifi_pwd" and self.password_input: self.password_input = self.password_input[:-1]
elif target == "hs_ssid" and self.hotspot_ssid: self.hotspot_ssid = self.hotspot_ssid[:-1]
elif target == "hs_pwd" and self.hotspot_pwd: self.hotspot_pwd = self.hotspot_pwd[:-1]
elif target == "sp_id" and self.sp_id_input: self.sp_id_input = self.sp_id_input[:-1]
elif target == "sp_secret" and self.sp_secret_input: self.sp_secret_input = self.sp_secret_input[:-1]
elif target == "sp_callback" and self.sp_callback_input: self.sp_callback_input = self.sp_callback_input[:-1]
elif key == "ENTER":
self.show_kbd = False; self.focused = None
elif key in ("SHIFT", "MODE"):
pass
else:
if target == "city": self.city_input += key
elif target == "wifi_pwd": self.password_input += key
elif target == "hs_ssid": self.hotspot_ssid += key
elif target == "hs_pwd": self.hotspot_pwd += key
elif target == "sp_id": self.sp_id_input += key
elif target == "sp_secret": self.sp_secret_input += key
elif target == "sp_callback": self.sp_callback_input += key
# ── Background actions ───────────────────────────────────────────────
def _start_scan(self):
self.wifi_scanning = True
self.wifi_message = "Scanning…"
self.wifi_message_color = 'GRAY'
def _t():
self.networks = self.wifi.scan()
self.wifi_scanning = False
self.wifi_message = f"Found {len(self.networks)} network(s)"
self.wifi_message_color = 'STATUS_OK'
threading.Thread(target=_t, daemon=True).start()
def _start_connect(self):
self.connecting = True
ssid = self.selected_network["ssid"]
self.wifi_message = f"Connecting to {ssid}…"
self.wifi_message_color = 'GRAY'
def _t():
ok, msg = self.wifi.connect(ssid, self.password_input)
self.connecting = False
self.wifi_message = msg
self.wifi_message_color = 'STATUS_OK' if ok else 'STATUS_ERR'
import time; time.sleep(3)
self.wifi_status = self.wifi.get_status()
threading.Thread(target=_t, daemon=True).start()
def _save(self):
if self.tab == "spotify":
self._save_spotify_creds()
return
self.config.update({
"city": self.city_input.strip(),
"timezone": self.tz_selected,
"units": self.units,
"clock_24h": self.clock_24h,
"night_mode": self.night_mode,
"theme": self.theme,
"hotspot_ssid": self.hotspot_ssid,
"hotspot_password": self.hotspot_pwd,
"hotspot_iface": self.hs_iface,
})
self.wifi.set_timezone(self.tz_selected)
self.weather.force_refresh()
self.status_message = "Settings saved!"
self.status_color = 'STATUS_OK'
# ── Drawing ──────────────────────────────────────────────────────────
def update(self):
pass
def draw(self):
self._p = _theme.get_palette(self.config)
p = self._p
self.surface.fill(p['BG'])
self._draw_header()
self._draw_tabs()
if self.tab == "general": self._draw_general()
elif self.tab == "wifi": self._draw_wifi()
elif self.tab == "hotspot": self._draw_hotspot()
elif self.tab == "spotify": self._draw_spotify()
if self.status_message:
color = p.get(self.status_color, p['STATUS_OK'])
self._draw_text(self.status_message, self.font_small, color, 10, self.H - 26)
self._draw_button(self.save_rect, "Save & Apply", p['BTN_OK'])
if self.show_kbd:
self.kbd.draw(self.surface)
# ── Drawing helpers ──────────────────────────────────────────────────
def _draw_text(self, text, font, color, x, y):
s = font.render(text, True, color)
self.surface.blit(s, (x, y))
return s.get_width()
def _draw_text_centered(self, text, font, color, cx, y):
s = font.render(text, True, color)
self.surface.blit(s, (cx - s.get_width() // 2, y))
def _draw_button(self, rect, label, color):
p = self._p
pygame.draw.rect(self.surface, color, rect, border_radius=8)
pygame.draw.rect(self.surface, p['DIVIDER'], rect, 1, border_radius=8)
self._draw_text_centered(label, self.font_btn, p['WHITE'], rect.centerx, rect.y + 10)
def _draw_input(self, rect, value, focused, placeholder="", mask=False):
p = self._p
border = p['INPUT_FOCUS'] if focused else p['INPUT_BORDER']
pygame.draw.rect(self.surface, p['INPUT_BG'], rect, border_radius=6)
pygame.draw.rect(self.surface, border, rect, 2, border_radius=6)
display = ("•" * len(value) if mask else value) if value else placeholder
color = p['WHITE'] if value else p['DIM']
txt = self.font_input.render(display, True, color)
self.surface.blit(txt, (rect.x + 10, rect.y + (rect.height - txt.get_height()) // 2))
if focused:
cx = rect.x + 10 + txt.get_width() + 2
pygame.draw.line(self.surface, p['WHITE'],
(cx, rect.y + 8), (cx, rect.y + rect.height - 8), 2)
def _draw_toggle(self, rect, state):
p = self._p
bg = (50, 160, 100) if state else p['BOX_BORDER']
pygame.draw.rect(self.surface, bg, rect, border_radius=rect.height // 2)
cx = rect.x + rect.width - rect.height // 2 - 3 if state else rect.x + rect.height // 2 + 3
pygame.draw.circle(self.surface, p['WHITE'], (cx, rect.centery), rect.height // 2 - 4)
def _draw_seg_button(self, rect, label, selected):
p = self._p
bg = p['BTN_SEL'] if selected else p['INPUT_BG']
border = p['ACCENT'] if selected else p['INPUT_BORDER']
text_c = p['WHITE'] if selected else p['GRAY']
pygame.draw.rect(self.surface, bg, rect, border_radius=6)
pygame.draw.rect(self.surface, border, rect, 2, border_radius=6)
self._draw_text_centered(label, self.font_btn, text_c, rect.centerx, rect.y + 9)
def _draw_header(self):
p = self._p
pygame.draw.line(self.surface, p['DIVIDER'], (0, 46), (self.W, 46), 1)
self._draw_button(self.back_rect, " Back", p['BTN_BACK'])
ax, ay = self.back_rect.x + 10, self.back_rect.centery
pygame.draw.polygon(self.surface, p['WHITE'],
[(ax, ay), (ax + 9, ay - 7), (ax + 9, ay + 7)])
self._draw_text_centered("SETTINGS", self.font_title, p['WHITE'], self.W // 2, 10)
def _draw_tabs(self):
p = self._p
for tab, rect, label in [
("general", self.tab_general_rect, "General"),
("wifi", self.tab_wifi_rect, "WiFi"),
("hotspot", self.tab_hotspot_rect, "Hotspot"),
("spotify", self.tab_spotify_rect, "Spotify"),
]:
bg = p['TAB_ACTIVE'] if self.tab == tab else p['TAB_INACTIVE']
color = p['ACCENT'] if self.tab == tab else p['GRAY']
pygame.draw.rect(self.surface, bg, rect)
self._draw_text_centered(label, self.font_tab, color, rect.centerx, rect.y + 12)
if self.tab == tab:
pygame.draw.line(self.surface, p['ACCENT'],
(rect.x, rect.bottom - 2), (rect.right, rect.bottom - 2), 3)
pygame.draw.line(self.surface, p['DIVIDER'],
(0, self.tab_general_rect.bottom),
(self.W, self.tab_general_rect.bottom), 1)
# ── General tab drawing ───────────────────────────────────────────────
def _draw_general(self):
p = self._p
self._draw_text("City:", self.font_label, p['GRAY'], 30, 114)
self._draw_input(self.city_rect, self.city_input, self.focused == "city", "Enter city name")
# Weather API status indicator (right of city input)
err = self.weather.get_error()
current = self.weather.get_current()
if err:
dot_c = (220, 60, 60)
short_err = err if len(err) <= 40 else err[:37] + "…"
status_text = f"Error: {short_err}"
text_color = p['STATUS_ERR']
elif current and self.weather.is_stale():
dot_c = (220, 160, 40)
status_text = "Weather data stale"
text_color = (220, 160, 40)
elif current:
dot_c = (60, 200, 100)
status_text = "API OK"
text_color = p['STATUS_OK']
else:
dot_c = (120, 120, 135)
status_text = "Waiting for data…"
text_color = p['DIM']
sx = self.city_rect.right + 20
sy = 114
pygame.draw.circle(self.surface, dot_c, (sx + 7, sy + 11), 6)
self._draw_text(status_text, self.font_small, text_color, sx + 20, sy + 2)
self._draw_text("Timezone:", self.font_label, p['GRAY'], 30, 184)
pygame.draw.rect(self.surface, p['INPUT_BG'], self.tz_list_rect, border_radius=6)
pygame.draw.rect(self.surface, p['INPUT_BORDER'], self.tz_list_rect, 1, border_radius=6)
row_h_tz = 38
visible = self.tz_list_rect.height // row_h_tz
for i in range(visible):
idx = self.tz_scroll + i
if idx >= len(COMMON_TIMEZONES): break
tz = COMMON_TIMEZONES[idx]
ry = self.tz_list_rect.y + i * row_h_tz
if tz == self.tz_selected:
pygame.draw.rect(self.surface, p['SEL_ROW'],
(self.tz_list_rect.x, ry, self.tz_list_rect.width, row_h_tz - 2),
border_radius=4)
color = p['WHITE'] if tz == self.tz_selected else p['GRAY']
self._draw_text(tz, self.font_small, color, self.tz_list_rect.x + 10, ry + 10)
ax = self.tz_list_rect.right + 8
pygame.draw.polygon(self.surface, p['GRAY'], [
(ax+15, self.tz_list_rect.y+10), (ax+5, self.tz_list_rect.y+28), (ax+25, self.tz_list_rect.y+28)])
pygame.draw.polygon(self.surface, p['GRAY'], [
(ax+15, self.tz_list_rect.bottom-10), (ax+5, self.tz_list_rect.bottom-28), (ax+25, self.tz_list_rect.bottom-28)])
unit_y = self.tz_list_rect.bottom + 18
self._draw_text("Units:", self.font_label, p['GRAY'], 30, unit_y + 6)
self._draw_seg_button(self.unit_c_rect, "°C", self.units == "metric")
self._draw_seg_button(self.unit_f_rect, "°F", self.units == "imperial")
self._draw_text("Clock:", self.font_label, p['GRAY'], 420, unit_y + 6)
self._draw_seg_button(self.clock_12h_rect, "12h", not self.clock_24h)
self._draw_seg_button(self.clock_24h_rect, "24h", self.clock_24h)
nm_y = unit_y + 58
self._draw_text("Night dimming:", self.font_label, p['GRAY'], 30, nm_y + 2)
self._draw_toggle(self.night_rect, self.night_mode)
self._draw_text("Theme:", self.font_label, p['GRAY'], 310, nm_y + 2)
self._draw_seg_button(self.theme_dark_rect, "Dark", self.theme == "dark")
self._draw_seg_button(self.theme_light_rect, "Light", self.theme == "light")
self._draw_seg_button(self.theme_auto_rect, "Auto", self.theme == "auto")
# ── WiFi tab drawing ──────────────────────────────────────────────────
def _draw_wifi(self):
p = self._p
self._draw_text("Current:", self.font_label, p['GRAY'], 20, 108)
if self.wifi_status.get("connected"):
ssid, sig = self.wifi_status["ssid"], self.wifi_status["signal"]
self._draw_text(f"Connected to \"{ssid}\" ({sig}%)", self.font_label, p['STATUS_OK'], 120, 108)
else:
self._draw_text("Not connected", self.font_label, p['DIM'], 120, 108)
scan_label = "Scanning…" if self.wifi_scanning else "Scan"
self._draw_button(self.scan_rect, scan_label, p['BTN_SCAN'])
if self.wifi_status.get("connected"):
self._draw_button(self.disconnect_rect, "Disconnect", p['BTN_CANCEL'])
if self.wifi_message:
color = p.get(self.wifi_message_color, p['GRAY'])
self._draw_text(self.wifi_message, self.font_small, color, 145, 160)
pygame.draw.rect(self.surface, p['INPUT_BG'], self.net_list_rect, border_radius=6)
pygame.draw.rect(self.surface, p['INPUT_BORDER'], self.net_list_rect, 1, border_radius=6)
if not self.networks:
self._draw_text_centered("No networks — tap Scan", self.font_small, p['DIM'],
self.net_list_rect.centerx, self.net_list_rect.y + 70)
else:
row_h = 50
for i in range(self.net_list_rect.height // row_h):
idx = self.wifi_scroll + i
if idx >= len(self.networks): break
net = self.networks[idx]
ry = self.net_list_rect.y + i * row_h
is_sel = self.selected_network and self.selected_network["ssid"] == net["ssid"]
if is_sel:
pygame.draw.rect(self.surface, p['SEL_ROW'],
(self.net_list_rect.x, ry, self.net_list_rect.width, row_h-2),
border_radius=4)
# Signal bars
bars = max(1, min(4, net["signal"] // 25))
bx = self.net_list_rect.x + 10
for b in range(4):
bar_h = 6 + b * 4
bc = p['WIFI_BAR'] if b < bars else p['BOX_BORDER']
pygame.draw.rect(self.surface, bc, (bx + b*9, ry+row_h-12-bar_h, 7, bar_h), border_radius=1)
self._draw_text(net["ssid"], self.font_label, p['WHITE'] if is_sel else p['GRAY'], bx+44, ry+12)
# Padlock
if net.get("secured"):
lx, ly = self.net_list_rect.right - 44, ry + 14
pygame.draw.rect(self.surface, p['DIM'], (lx, ly+5, 12, 10), border_radius=2)
pygame.draw.arc(self.surface, p['DIM'], pygame.Rect(lx+1, ly-2, 10, 12), 0, 3.14159, 2)
# Connected tick
if self.wifi_status.get("connected") and self.wifi_status["ssid"] == net["ssid"]:
cx2, cy2 = self.net_list_rect.right - 68, ry + row_h // 2
pygame.draw.circle(self.surface, p['WIFI_CON'], (cx2, cy2), 8)
pygame.draw.lines(self.surface, p['WHITE'], False,
[(cx2-4, cy2), (cx2-1, cy2+4), (cx2+4, cy2-4)], 2)
# Scroll arrows
ax = self.net_list_rect.right + 8
pygame.draw.polygon(self.surface, p['GRAY'], [(ax+12, self.net_list_rect.y+8), (ax+2, self.net_list_rect.y+22), (ax+22, self.net_list_rect.y+22)])
pygame.draw.polygon(self.surface, p['GRAY'], [(ax+12, self.net_list_rect.bottom-8), (ax+2, self.net_list_rect.bottom-22), (ax+22, self.net_list_rect.bottom-22)])
if self.selected_network:
pw_y = self.net_list_rect.bottom + 20
self._draw_text(f"Password for \"{self.selected_network['ssid']}\":",
self.font_small, p['GRAY'], 20, pw_y - 20)
self._draw_input(self.pwd_rect, self.password_input,
self.focused == "wifi_pwd", "Tap to enter password", mask=True)
self._draw_button(self.connect_rect, "Connect", p['BTN_OK'])
ax, ay = self.connect_rect.right - 20, self.connect_rect.centery
pygame.draw.polygon(self.surface, p['WHITE'], [(ax, ay-6), (ax, ay+6), (ax+9, ay)])
# ── Hotspot tab drawing ───────────────────────────────────────────────
def _draw_hotspot(self):
p = self._p
hs = self.hotspot
# ── Status row ──
self._draw_text("Status:", self.font_label, p['GRAY'], 20, 112)
if hs:
status = hs.get_status()
active = hs.is_active()
s_color = p['STATUS_OK'] if active else (
p['STATUS_ERR'] if status.startswith("Error") else p['GRAY'])
dot_color = (80, 200, 80) if active else (120, 120, 135)
pygame.draw.circle(self.surface, dot_color, (100, 120), 6)
self._draw_text(status, self.font_label, s_color, 115, 112)
if "Starting" in status or "Stopping" in status:
btn_label, btn_color = status, p['BOX_BORDER']
elif active:
btn_label, btn_color = "Stop Hotspot", p['BTN_CANCEL']
else:
btn_label, btn_color = "Start Hotspot", p['BTN_OK']
self._draw_button(self.hs_toggle_rect, btn_label, btn_color)
else:
self._draw_text("Hotspot service unavailable", self.font_label, p['DIM'], 115, 112)
locked = hs and hs.is_active()
# ── Interface selector ──
ifaces = self.hs_interfaces
if not ifaces:
# Trigger background load once
if not hasattr(self, '_iface_load_started'):
self._iface_load_started = True
threading.Thread(target=self._refresh_ifaces, daemon=True).start()
ifaces = [{"name": "wlan0", "type": "builtin"}] # placeholder
self._draw_text("Adapter:", self.font_label, p['GRAY'], 20, 165)
self.hs_iface_rects = []
btn_x = 140
for iface in ifaces:
name = iface["name"]
kind = iface["type"]
label = f"{name} (USB)" if kind == "usb" else f"{name} (built-in)"
btn_w = self.font_btn.size(label)[0] + 24
rect = pygame.Rect(btn_x, 162, btn_w, 34)
self._draw_seg_button(rect, label, self.hs_iface == name)
self.hs_iface_rects.append((rect, name))
btn_x += btn_w + 10
# Connectivity note right of the buttons
if not locked:
using_usb = any(i["name"] == self.hs_iface and i["type"] == "usb" for i in ifaces)
if using_usb:
note_color = p['STATUS_OK']
note_text = "Client WiFi stays connected"
elif len(ifaces) > 1:
note_color = p['STATUS_ERR']
note_text = "Client WiFi will pause"
else:
note_color = p['DIM']
note_text = "Single adapter — client WiFi pauses"
self._draw_text(note_text, self.font_tiny, note_color, btn_x + 8, 172)
# ── SSID ──
self._draw_text("Network name (SSID):", self.font_label, p['GRAY'], 20, 210)
self._draw_input(self.hs_ssid_rect, self.hotspot_ssid,
self.focused == "hs_ssid", "e.g. DeskClock")
# ── Password + eye toggle ──
self._draw_text("Password (min 8 chars):", self.font_label, p['GRAY'], 20, 272)
self._draw_input(self.hs_pwd_rect, self.hotspot_pwd,
self.focused == "hs_pwd", "Enter WPA2 password",
mask=not self.hs_pwd_visible)
ex, ey = self.hs_eye_rect.centerx, self.hs_eye_rect.centery
eye_col = p['ACCENT'] if self.hs_pwd_visible else p['GRAY']
pygame.draw.arc(self.surface, eye_col, pygame.Rect(ex-10, ey-7, 20, 14), 0, 3.14159, 2)
pygame.draw.arc(self.surface, eye_col, pygame.Rect(ex-10, ey-7, 20, 14), 3.14159, 6.28318, 2)
pygame.draw.circle(self.surface, eye_col, (ex, ey), 4, 2)
if locked:
self._draw_text("Stop hotspot to change settings", self.font_tiny, p['DIM'], 20, 346)
if self.hs_deps_msg:
self._draw_text(self.hs_deps_msg, self.font_small, p['STATUS_ERR'], 20, 346)
if hs and hs.is_active():
self._draw_text(f"Adapter: {hs.get_iface()} · Gateway: 192.168.4.1 · DHCP: .2–.20",
self.font_small, p['DIM_GRAY'], 20, 348)
# ── Connected clients ──
clients_y = 375
pygame.draw.line(self.surface, p['DIVIDER'], (20, clients_y - 6), (self.W - 20, clients_y - 6), 1)
self._draw_text("Connected devices", self.font_label, p['GRAY'], 20, clients_y)
if hs:
clients = hs.get_clients()
if not clients:
msg = "No devices connected" if hs.is_active() else "Start hotspot to accept connections"
self._draw_text(msg, self.font_small, p['DIM'], 20, clients_y + 34)
else:
for i, mac in enumerate(clients[:4]):
cy = clients_y + 34 + i * 32
pygame.draw.rect(self.surface, p['ACCENT'], (20, cy + 4, 18, 12), border_radius=2)
pygame.draw.rect(self.surface, p['BG'], (22, cy + 6, 14, 8), border_radius=1)
self._draw_text(mac, self.font_small, p['WHITE'], 46, cy + 2)
# ── Spotify tab drawing ───────────────────────────────────────────────
def _draw_spotify(self):
from spotify_service import SPOTIPY_AVAILABLE
p = self._p
status = self.spotify.get_auth_status() if self.spotify else "idle"
# ── Waiting state gets the full tab body — no credentials section ──
if status == "waiting":
self._draw_spotify_waiting(p)
return
# ── Credentials section (shown for all non-waiting states) ──
self._draw_text("Client ID:", self.font_label, p['GRAY'], 20, 108)
self._draw_input(self.sp_id_rect, self.sp_id_input,
self.focused == "sp_id", "Paste from developer.spotify.com")
self._draw_text("Client Secret:", self.font_label, p['GRAY'], 20, 172)
self._draw_input(self.sp_secret_rect, self.sp_secret_input,
self.focused == "sp_secret", "Paste secret", mask=True)
self._draw_button(self.sp_save_rect, "Save", p['BTN_OK'])
hint = "Create a free app at developer.spotify.com/dashboard"
self._draw_text(hint, self.font_tiny, p['DIM'], self.sp_save_rect.right + 16,
self.sp_save_rect.y + 11)
if not SPOTIPY_AVAILABLE:
self._draw_text("spotipy not installed — run: pip install spotipy qrcode",
self.font_small, p['STATUS_ERR'], 20, 315)
return
# ── Divider ──
pygame.draw.line(self.surface, p['DIVIDER'], (20, 312), (self.W - 20, 312), 1)
if not self.spotify:
return
if not self.spotify.has_credentials():
self._draw_text_centered("Enter credentials above, then tap Save.",
self.font_small, p['DIM'], self.W // 2, 334)
return
if status == "ok":
# ── Connected ──
pygame.draw.circle(self.surface, (80, 200, 80), (32, 336), 7)
name = self.spotify.get_display_name()
label = f"Connected as {name}" if name else "Connected to Spotify"
self._draw_text(label, self.font_label, p['STATUS_OK'], 50, 326)
self._draw_button(self.sp_disc_rect, "Disconnect", p['BTN_CANCEL'])
else:
# ── idle or error ──
if status == "error":
err = self.spotify.get_auth_error()
short = err if len(err) <= 60 else err[:57] + "…"
self._draw_text(f"Error: {short}", self.font_small, p['STATUS_ERR'], 20, 325)
uri = self.spotify.get_redirect_uri()
note_y = 356 if status == "error" else 325
self._draw_text("Register this Redirect URI in your Spotify app:",
self.font_small, p['GRAY'], 20, note_y)
self._draw_text(uri, self.font_small, p['ACCENT'], 20, note_y + 26)
self._draw_text("developer.spotify.com/dashboard → your app → Edit settings",
self.font_tiny, p['DIM'], 20, note_y + 50)
self._draw_text("(Your phone will show a cert warning — tap Advanced → Proceed)",
self.font_tiny, p['DIM'], 20, note_y + 68)
self._draw_button(self.sp_auth_rect, "Connect to Spotify", p['BTN_OK'])
def _draw_spotify_waiting(self, p):
"""Full-tab waiting layout: QR code on the left, instructions on the right."""
# QR code — left column, x=15
if self._qr_surf:
qw, qh = self._qr_surf.get_size()
qx, qy = 15, 108
pygame.draw.rect(self.surface, (255, 255, 255),
(qx - 4, qy - 4, qw + 8, qh + 8), border_radius=4)
self.surface.blit(self._qr_surf, (qx, qy))
# Instructions — right column, x=200
tx = 200
self._draw_text("1. Scan the QR code with your phone",
self.font_small, p['GRAY'], tx, 108)
self._draw_text("2. Log in to Spotify",
self.font_small, p['GRAY'], tx, 134)
self._draw_text("3. Phone shows a security warning — tap",
self.font_small, p['GRAY'], tx, 160)
self._draw_text(" Advanced → Proceed to continue",
self.font_small, p['ACCENT'], tx, 182)
self._draw_text("4. Done! This screen will update automatically.",
self.font_small, p['GRAY'], tx, 208)
self._draw_button(self.sp_cancel_rect, "Cancel", p['BTN_CANCEL'])