-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather_config_editor.py
More file actions
executable file
·5271 lines (4367 loc) · 217 KB
/
weather_config_editor.py
File metadata and controls
executable file
·5271 lines (4367 loc) · 217 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 python3
"""
Weather & Astronomical Config Editor
A production-grade GNOME GTK4/libadwaita application for managing
environment variables of a weather + astronomical system.
"""
# GSETTINGS_SCHEMA_DIR=. python weather_config_editor.py
# weather-config-editor.desktop:
# [Desktop Entry]
# Name=Weather Config Editor
# Comment=Edit weather & astronomical configuration
# Exec=sh -c 'GSETTINGS_SCHEMA_DIR="$HOME/.local/share/bin/linux-weather-bar" python3 "$HOME/.local/share/bin/linux-weather-bar/weather_config_editor.py"'
# Icon=preferences-system
# Terminal=false
# Type=Application
# Categories=Utility;
# StartupNotify=true
# StartupWMClass=com.weather.ConfigEditor
from __future__ import annotations
import json
import os
import re
import shutil
import subprocess
import threading
import urllib.request
import urllib.error
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum, auto
from pathlib import Path
from typing import Any, Callable, Optional
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, Gdk, Gio, GLib, Gtk, Pango # noqa: E402
# ─── Network Connectivity ─────────────────────────────────────────────────────
class NetworkConnectivityError(RuntimeError):
"""Raised when the connectivity probe finds no network."""
class NetworkConnectivityChecker:
"""
Probes network connectivity before network-dependent operations.
A single probe is performed — no retries.
Strategy:
1. Prefer ``nmcli networking connectivity check`` when nmcli is available;
treat any nmcli failure as "none" so it never blocks the caller.
2. Fall back to a single ICMP ping to 8.8.8.8 when nmcli is absent.
"""
_FALLBACK_HOST = "8.8.8.8"
_PING_TIMEOUT_SECONDS = 2
def __init__(self) -> None:
self._nmcli_available: Optional[bool] = None # lazily resolved
# ── Public API ────────────────────────────────────────────────────────────
def check(self) -> bool:
"""
Run a single connectivity probe.
Returns True when the network is reachable, False otherwise.
"""
return self._probe()
def assert_connected(self) -> None:
"""
Like :meth:`check`, but raises :class:`NetworkConnectivityError` on
failure instead of returning False.
"""
if not self.check():
raise NetworkConnectivityError("No network connectivity.")
# ── Internals ─────────────────────────────────────────────────────────────
def _probe(self) -> bool:
"""Single connectivity probe; delegates to nmcli or ping."""
if self._use_nmcli():
return self._probe_nmcli()
return self._probe_ping()
def _use_nmcli(self) -> bool:
"""Resolve nmcli availability once and cache the result."""
if self._nmcli_available is None:
self._nmcli_available = shutil.which("nmcli") is not None
return self._nmcli_available
@staticmethod
def _probe_nmcli() -> bool:
"""
Run ``nmcli networking connectivity check``.
Any execution failure (CalledProcessError, FileNotFoundError, timeout)
is caught and treated as "none" — mirroring the bash
``connectivity=$(nmcli ...) || connectivity="none"`` pattern.
"""
try:
result = subprocess.run(
["nmcli", "networking", "connectivity", "check"],
capture_output=True,
text=True,
timeout=10,
)
return result.stdout.strip() == "full"
except Exception:
return False
@classmethod
def _probe_ping(cls) -> bool:
"""Fallback: single ICMP ping to a well-known public DNS server."""
try:
result = subprocess.run(
["ping", "-c", "1", "-W", str(cls._PING_TIMEOUT_SECONDS),
cls._FALLBACK_HOST],
capture_output=True,
timeout=cls._PING_TIMEOUT_SECONDS + 2,
)
return result.returncode == 0
except Exception:
return False
# ─── Data Model ──────────────────────────────────────────────────────────────
class VarType(Enum):
"""Variable input types for schema-driven UI rendering."""
STRING = auto()
INTEGER = auto()
FLOAT = auto()
BOOLEAN = auto()
ENUM = auto()
NUMERIC_OR_SENTINEL = auto() # Special: numeric OR sentinel string
@dataclass
class VarSchema:
"""Schema definition for a single config variable."""
key: str
label: str
var_type: VarType
description: str = ""
default: Any = None
choices: list[str] = field(default_factory=list) # for ENUM
# for NUMERIC_OR_SENTINEL
sentinel_label: str = ""
sentinel_value: str = "" # e.g. "moonrise"
group: str = "General"
readonly: bool = False # bash `readonly`
# mask when unfocused
secret: bool = False
@dataclass
class ConfigEntry:
"""Runtime value for a variable loaded from file."""
schema: VarSchema
raw_value: str # raw string as found in file
modified: bool = False
@property
def display_value(self) -> str:
"""Strip surrounding quotes."""
v = self.raw_value.strip()
if len(v) >= 2 and v[0] == v[-1] == '"':
return v[1:-1]
return v
@display_value.setter
def display_value(self, val: str) -> None:
"""Store with quotes if it was originally quoted."""
v = self.raw_value.strip()
quoted = len(v) >= 2 and v[0] == v[-1] == '"'
self.raw_value = f'"{val}"' if quoted else val
self.modified = True
DEPENDENCIES: dict[str, list[str]] = {
"SHOW_SUNRISE_SUNSET": [
"SUNRISE_WARNING_THRESHOLD",
"SUNSET_WARNING_THRESHOLD",
"SHOW_SUNRISE_SUNSET_WITH_RAIN_FORECAST",
"SHOW_SUNRISE_SUNSET_DURING_RAIN"
],
"SHOW_RAIN_FORECAST": [
"RAIN_FORECAST_THRESHOLD",
"RAIN_FORECAST_WINDOW",
"SHOW_SUNRISE_SUNSET_WITH_RAIN_FORECAST",
"SHOW_MOONRISE_MOONSET_WITH_RAIN_FORECAST",
"SHOW_MOON_PHASE_WITH_RAIN_FORECAST",
],
"MOON_PHASE_ENABLED": [
"MOON_PHASE_WINDOW_START",
"MOON_PHASE_WINDOW_DURATION",
"MOON_DATA_CACHE_MAX_AGE",
"SHOW_FULL_MOON_FOLK_NAME",
"SHOW_MOONPHASE_DURING_DAYTIME",
"SUPPRESS_NOT_VISIBLE_MOONPHASE",
"SHOW_MOON_PHASE_DURING_RAIN",
"SHOW_MOON_PHASE_WITH_RAIN_FORECAST",
"SHOW_MOONPHASE_BENGALI",
"SHOW_MOONPHASE_BILINGUAL",
"SHOW_APSIDAL_MOON_EVENTS",
"SUPPRESS_NOT_VISIBLE_NIGHT_APSIDAL_MOON_EVENTS",
],
"SHOW_APSIDAL_MOON_EVENTS": [
"SUPPRESS_NOT_VISIBLE_NIGHT_APSIDAL_MOON_EVENTS",
],
"SHOW_MOONRISE_MOONSET": [
"MOONRISE_WARNING_THRESHOLD",
"MOONSET_WARNING_THRESHOLD",
"SHOW_MOONRISE_MOONSET_DURING_RAIN",
"SHOW_MOONRISE_MOONSET_WITH_RAIN_FORECAST",
],
"SHOW_MOONPHASE_BILINGUAL": [
"SHOW_MOONPHASE_BENGALI",
],
}
INVERSE_DEPENDENCIES: set[str] = {
"SHOW_MOONPHASE_BILINGUAL",
}
# ─── Variable Schema Registry ────────────────────────────────────────────────
SCHEMA: list[VarSchema] = [
# ── Configuration ───────────────────────────────────────────────────
VarSchema("FEELS_LIKE_THRESHOLD", "Feels-Like Threshold", VarType.NUMERIC_OR_SENTINEL,
"Minimum temperature difference (°C) to display 'feels like'", default=10,
sentinel_label="Disable", sentinel_value="disable",
readonly=True, group="Configuration"),
VarSchema("SHOW_RAIN_FORECAST", "Rain Forecast", VarType.BOOLEAN,
"Show rain warnings in the forecast", readonly=True, group="Configuration"),
VarSchema("RAIN_FORECAST_THRESHOLD", "Minimum Precipitation Threshold", VarType.FLOAT,
"Minimum precipitation probability (0.00 – 1.00) to trigger a warning",
default=0.7, readonly=True, group="Configuration"),
VarSchema("RAIN_FORECAST_WINDOW", "Rain Forecast Lookahead Window", VarType.INTEGER,
"How many hours ahead to check for rain", default=3, readonly=True,
group="Configuration"),
# ── Sunrise & Sunset ────────────────────────────────────────────────
VarSchema("SHOW_SUNRISE_SUNSET", "Sunrise & Sunset", VarType.BOOLEAN,
"Show sunrise and sunset times", readonly=True,
group="Sunrise & Sunset"),
VarSchema("SUNRISE_WARNING_THRESHOLD", "Sunrise Lead Time", VarType.INTEGER,
"Alert this many minutes before sunrise", default=30, readonly=True,
group="Sunrise & Sunset"),
VarSchema("SUNSET_WARNING_THRESHOLD", "Sunset Lead Time", VarType.INTEGER,
"Alert this many minutes before sunset", default=30, readonly=True,
group="Sunrise & Sunset"),
VarSchema("SHOW_SUNRISE_SUNSET_DURING_RAIN", "Show While Raining", VarType.BOOLEAN,
"Display even when it's currently raining", readonly=True,
group="Sunrise & Sunset"),
VarSchema("SHOW_SUNRISE_SUNSET_WITH_RAIN_FORECAST", "Show When Rain Expected", VarType.BOOLEAN,
"Display even when rain is in the forecast", readonly=True,
group="Sunrise & Sunset"),
# ── Moonrise & Moonset ────────────────────────────────────────────────────
VarSchema("SHOW_MOONRISE_MOONSET", "Moonrise & Moonset", VarType.BOOLEAN,
"Show moonrise and moonset times", readonly=True, group="Moonrise & Moonset"),
VarSchema("MOONRISE_WARNING_THRESHOLD", "Moonrise Lead Time", VarType.NUMERIC_OR_SENTINEL,
"Minutes before moonrise to alert, or immediately after sunset",
sentinel_label="After Sunset", sentinel_value="sunset",
readonly=True, group="Moonrise & Moonset"),
VarSchema("MOONSET_WARNING_THRESHOLD", "Moonset Lead Time", VarType.NUMERIC_OR_SENTINEL,
"Minutes before moonset to alert, or immediately after sunset",
sentinel_label="After Sunset", sentinel_value="sunset",
readonly=True, group="Moonrise & Moonset"),
VarSchema("SHOW_MOONRISE_MOONSET_DURING_DAYTIME", "Show During Daytime", VarType.BOOLEAN,
"Include moonrise/moonset times that fall during daylight", readonly=True,
group="Moonrise & Moonset"),
VarSchema("SUPPRESS_NOT_VISIBLE_MOONRISE_MOONSET", "Suppress Non-Visible Moonrise/Moonset", VarType.BOOLEAN,
"Suppress moonrise/moonset display when the moon is too dim to be visible",
readonly=True, group="Moonrise & Moonset"),
VarSchema("SHOW_MOONRISE_MOONSET_DURING_RAIN", "Show While Raining", VarType.BOOLEAN,
"Display even when it's currently raining", readonly=True,
group="Moonrise & Moonset"),
VarSchema("SHOW_MOONRISE_MOONSET_WITH_RAIN_FORECAST", "Show When Rain Expected", VarType.BOOLEAN,
"Display even when rain is in the forecast", readonly=True,
group="Moonrise & Moonset"),
# ── Moon Phase ────────────────────────────────────────────────────────────
VarSchema("MOON_PHASE_ENABLED", "Moon Phase", VarType.BOOLEAN,
"Show the current moon phase", readonly=True, group="Moon Phase"),
VarSchema("MOON_DATA_CACHE_MAX_AGE", "Moon Data Cache Max Age", VarType.INTEGER,
"Maximum age of cached moon data in hours during active moon window", default=2, readonly=True,
group="Moon Phase"),
VarSchema("MOON_PHASE_WINDOW_START", "Display Window Start", VarType.NUMERIC_OR_SENTINEL,
"Minutes after sunset/moonrise, or immediately after moonrise",
sentinel_label="Moonrise", sentinel_value="moonrise",
readonly=True, group="Moon Phase"),
VarSchema("MOON_PHASE_WINDOW_DURATION", "Display Window End", VarType.NUMERIC_OR_SENTINEL,
"Window duration in minutes, or until moonset",
sentinel_label="Moonset", sentinel_value="moonset",
readonly=True, group="Moon Phase"),
VarSchema("SHOW_MOONPHASE_DURING_DAYTIME", "Show During Daytime", VarType.BOOLEAN,
"Display moon phase regardless of daylight hours", readonly=True,
group="Moon Phase"),
VarSchema("SUPPRESS_NOT_VISIBLE_MOONPHASE", "Suppress Non-Visible Moon Phases", VarType.BOOLEAN,
"Suppress moon phase display when the moon is too dim to be visible",
readonly=True, group="Moon Phase"),
VarSchema("SHOW_MOON_PHASE_DURING_RAIN", "Show While Raining", VarType.BOOLEAN,
"Display even when it's currently raining", readonly=True,
group="Moon Phase"),
VarSchema("SHOW_MOON_PHASE_WITH_RAIN_FORECAST", "Show When Rain Expected", VarType.BOOLEAN,
"Display even when rain is in the forecast", readonly=True,
group="Moon Phase"),
VarSchema("SHOW_FULL_MOON_FOLK_NAME", "Show Full Moon Traditional Name", VarType.BOOLEAN,
"Display the traditional or cultural name of the Full Moon (e.g., Snow Moon, Pink Moon)",
readonly=True, group="Moon Phase"),
VarSchema("SHOW_MOONPHASE_BILINGUAL", "Bilingual Phase Name", VarType.BOOLEAN,
"Show phase name in both English and Bengali", readonly=True,
group="Moon Phase"),
VarSchema("SHOW_MOONPHASE_BENGALI", "Bengali Phase Name", VarType.BOOLEAN,
"Show phase name in Bengali only", readonly=True, group="Moon Phase"),
VarSchema("SHOW_APSIDAL_MOON_EVENTS", "Apsidal Moon Events", VarType.BOOLEAN,
"Show supermoon, super new moon, or micromoon label when applicable",
readonly=True, group="Moon Phase"),
VarSchema("SUPPRESS_NOT_VISIBLE_NIGHT_APSIDAL_MOON_EVENTS", "Suppress Non-Visible Night Apsidal Moon Events", VarType.BOOLEAN,
"Show apsidal moon events only when the Moon is visibly above the horizon at night",
readonly=True, group="Moon Phase"),
# ── API Keys ──────────────────────────────────────────────────────────────
VarSchema("API_KEY", "OpenWeatherMap API Key", VarType.STRING,
"API key from openweathermap.org", readonly=True, group="API Keys", secret=True),
VarSchema("API_KEY_TYPE", "OpenWeatherMap Plan", VarType.ENUM,
"Your OpenWeatherMap subscription tier",
choices=["FREE", "PRO"], default="FREE", readonly=True, group="API Keys"),
VarSchema("MOON_API_KEY", "Moon API Key", VarType.STRING,
"API key from astroapi.byhrast.com", readonly=True, group="API Keys", secret=True),
# ── Location & Timezone ───────────────────────────────────────────────────
VarSchema("LOCATION", "Coordinates", VarType.STRING,
"Latitude and longitude", readonly=True, group="Location"),
VarSchema("TIMEZONE", "Time Zone", VarType.STRING,
"IANA time zone (e.g. Asia/Dhaka)", readonly=True, group="Location"),
# ── Retry Configuration ───────────────────────────────────────────────────
VarSchema("MAX_CONNECTIVITY_RETRIES", "Max Retries", VarType.INTEGER,
"Number of attempts before giving up on connectivity", default=5, readonly=True,
group="Network"),
VarSchema("CONNECTIVITY_RETRY_DELAY", "Retry Interval", VarType.INTEGER,
"Seconds to wait between each retry attempt", default=5, readonly=True,
group="Network"),
]
SCHEMA_MAP: dict[str, VarSchema] = {s.key: s for s in SCHEMA}
GROUPS: list[str] = list(dict.fromkeys(s.group for s in SCHEMA))
@dataclass(frozen=True)
class LocationEntry:
"""A unique (name, lat, lon) location from location_mappings.csv."""
name: str
lat: str
lon: str
@property
def display_label(self) -> str:
return f"{self.name.title()} ({self.lat},{self.lon})"
@property
def location_value(self) -> str:
return f"lat={self.lat}&lon={self.lon}"
class LocationMappingStore:
"""
Loads location_mappings.csv, deduplicates by (NAME, LATITUDE, LONGITUDE),
and persists the last used CSV path via GSettings (same key namespace).
"""
CSV_FILENAME = "location_mappings.csv"
def __init__(self, settings: Optional[Gio.Settings]) -> None:
self._settings = settings
# ── Discovery (mirrors WeatherConfigApp._get_local_config pattern) ────────
def find_default_csv(self) -> Optional[Path]:
"""Check script directory for location_mappings.csv (auto-load, same as .weather_config)."""
candidate = Path(__file__).resolve().parent / self.CSV_FILENAME
return candidate if candidate.exists() else None
def get_last_csv(self) -> Optional[Path]:
"""Restore last used CSV from GSettings."""
if not self._settings:
return None
path_str = self._settings.get_string("last-location-mapping-path")
if path_str:
p = Path(path_str)
if p.exists():
return p
return None
def save_last_csv(self, path: Path) -> None:
if self._settings:
self._settings.set_string("last-location-mapping-path", str(path))
def resolve_csv(self) -> Optional[Path]:
"""Priority: last saved → auto-detected in script dir."""
return self.get_last_csv() or self.find_default_csv()
# ── Parsing ───────────────────────────────────────────────────────────────
def load(self, path: Path) -> list[LocationEntry]:
"""
Parse CSV, deduplicate by (NAME, LAT, LON), sort by NAME so same
names are grouped, preserve original order within groups.
"""
import csv
seen: set[tuple[str, str, str]] = set()
entries: list[LocationEntry] = []
with path.open(newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
key = (row["NAME"].strip().upper(),
row["LATITUDE"].strip(),
row["LONGITUDE"].strip())
if key not in seen:
seen.add(key)
entries.append(LocationEntry(
name=row["NAME"].strip(),
lat=row["LATITUDE"].strip(),
lon=row["LONGITUDE"].strip(),
))
# Group same names together, stable within groups
entries.sort(key=lambda e: e.name.upper())
return entries
# ─── Timezone Store ───────────────────────────────────────────────────────────
class TimezoneStore:
"""
Loads zone.tab from the script directory and parses IANA timezone identifiers.
Falls back gracefully — if the file is absent or malformed, returns an empty list.
zone.tab format (tab-separated):
col 0: ISO 3166 country code(s)
col 1: coordinates
col 2: TZ identifier ← what we want (e.g. America/New_York)
col 3: optional comment
Lines beginning with '#' are comments and are skipped.
"""
ZONE_TAB_FILENAME = "zone.tab"
def __init__(self) -> None:
self._timezones: list[str] = []
self._loaded = False
def find_zone_tab(self) -> Optional[Path]:
"""Look for zone.tab next to the script (same discovery pattern as location_mappings.csv)."""
candidate = Path(__file__).resolve().parent / self.ZONE_TAB_FILENAME
return candidate if candidate.exists() else None
def load(self) -> list[str]:
"""
Parse zone.tab and return a sorted list of TZ identifiers (3rd column).
Result is cached after the first call.
Returns [] if file not found or entirely unreadable.
"""
if self._loaded:
return self._timezones
self._loaded = True
path = self.find_zone_tab()
if not path:
return self._timezones
try:
tzs: list[str] = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) >= 3:
tz = parts[2].strip()
if tz:
tzs.append(tz)
self._timezones = sorted(set(tzs))
except Exception:
# Malformed or unreadable — degrade silently to plain StringRow
self._timezones = []
return self._timezones
def available(self) -> bool:
"""True if zone.tab was found and yielded at least one entry."""
return bool(self.load())
# ─── Searchable DropDown ─────────────────────────────────────
def _find_search_entry(widget: Gtk.Widget) -> Optional[Gtk.SearchEntry]:
"""Recursively find the first GtkSearchEntry inside *widget*."""
if isinstance(widget, Gtk.SearchEntry):
return widget
child = widget.get_first_child()
while child is not None:
found = _find_search_entry(child)
if found:
return found
child = child.get_next_sibling()
return None
class SearchableDropDown:
"""
GTK4-native DropDown with built-in substring search/filtering.
Wraps Gtk.DropDown + Gtk.StringFilter + Gtk.FilterListModel with a
SignalListItemFactory that renders each item as a plain left-aligned label.
Both ``TimezoneRow`` and ``LocationRow`` use this class so all searchable-
dropdown machinery is defined exactly once (DRY).
Features:
- Fixed, consistent width (does not resize based on selected item)
- Text truncation with ellipsis for items longer than fixed width
- Compact dropdown button that remains consistent
- Stable layout with no horizontal shifting
Parameters
----------
items:
Flat list of strings to display.
on_selected:
Called with the chosen string whenever the user picks an item.
validate:
Optional predicate; receives the current search text and returns True
when it is acceptable. Drives the "error" CSS class on the search
entry for live visual feedback. Defaults to always-valid.
fixed_width:
Optional fixed width in pixels. If None, calculates from average item length.
"""
# Note: GTK4 doesn't use CSS for width constraints via IDs.
# We use set_width_request() directly on the widget instead.
_instance_counter = 0
def __init__(
self,
items: list[str],
on_selected: Callable[[str], None],
validate: Optional[Callable[[str], bool]] = None,
fixed_width: Optional[int] = None,
) -> None:
self._items = items
self._on_selected_cb = on_selected
self._validate = validate if validate is not None else (lambda _: True)
self._search_entry: Optional[Gtk.SearchEntry] = None
self._fixed_width = fixed_width or self._calculate_optimal_width(items)
# Generate unique ID for CSS targeting
SearchableDropDown._instance_counter += 1
self._dropdown_id = f"sd-{SearchableDropDown._instance_counter}"
# ── Model ─────────────────────────────────────────────────────────────
self._string_list = Gtk.StringList.new(items)
self._filter = Gtk.StringFilter.new(
Gtk.PropertyExpression.new(Gtk.StringObject, None, "string")
)
self._filter.set_match_mode(Gtk.StringFilterMatchMode.SUBSTRING)
self._filter.set_ignore_case(True)
filtered_model = Gtk.FilterListModel.new(
self._string_list, self._filter)
selection = Gtk.SingleSelection.new(filtered_model)
selection.set_autoselect(False)
# ── Factory ───────────────────────────────────────────────────────────
factory = Gtk.SignalListItemFactory()
factory.connect("setup", self._on_factory_setup)
factory.connect("bind", self._on_factory_bind)
# ── Widget ────────────────────────────────────────────────────────────
self._widget = Gtk.DropDown.new(selection, None)
self._widget.set_factory(factory)
self._widget.set_enable_search(True)
# Don't expand; use fixed width instead
self._widget.set_hexpand(False)
self._widget.set_valign(Gtk.Align.CENTER)
self._widget.set_name(self._dropdown_id)
# Apply fixed width constraints via size request and CSS
self._widget.set_size_request(self._fixed_width, -1)
self._apply_width_constraints()
self._widget.connect("notify::selected-item",
self._on_dropdown_selected)
self._widget.connect("realize", self._on_realize)
# ── Public API ────────────────────────────────────────────────────────
@property
def widget(self) -> Gtk.DropDown:
"""The underlying Gtk.DropDown; append this to your container."""
return self._widget
@property
def search_entry(self) -> Optional[Gtk.SearchEntry]:
"""The DropDown's internal search entry (available after realise)."""
return self._search_entry
def select(self, value: str) -> None:
"""
Programmatically select the item whose string equals *value* (exact).
Clears any active filter first so StringList indices align correctly.
"""
if not value:
return
self._filter.set_search("")
if self._search_entry is not None:
self._search_entry.handler_block_by_func(self._on_search_changed)
self._search_entry.set_text("")
self._search_entry.handler_unblock_by_func(self._on_search_changed)
n = self._string_list.get_n_items()
for i in range(n):
item = self._string_list.get_item(i)
if item and item.get_string() == value:
self._widget.set_selected(i)
return
def set_error(self, has_error: bool) -> None:
"""Apply or remove the 'error' CSS class on the search entry."""
if self._search_entry is None:
return
if has_error:
self._search_entry.add_css_class("error")
else:
self._search_entry.remove_css_class("error")
# ── Width management ──────────────────────────────────────────────────────
@staticmethod
def _calculate_optimal_width(items: list[str]) -> int:
"""
Calculate fixed width based on average item text length.
Uses Pango metrics to estimate width from character count:
- Assumes monospace or proportional font rendering
- Adds padding for button chrome + search icon
Returns width in pixels (minimum 200px for usability).
"""
if not items:
return 200
# Calculate average text length
avg_length = sum(len(item) for item in items) / len(items)
# Rough estimate: ~7-8 pixels per character in GTK4 default font
# Adjust multiplier based on your font preferences
char_width = 7.5
text_width = int(avg_length * char_width)
# Add padding for dropdown button chrome and icon space
padding = 40
width = text_width + padding
# Enforce minimum and maximum for usability
return max(200, min(width, 400))
def _apply_width_constraints(self) -> None:
"""
Apply width constraints to the dropdown widget using GTK4 API.
Uses set_size_request() to maintain consistent, fixed button size.
"""
# GTK4 native way: set size request directly on widget
# This avoids CSS parsing issues and deprecated API calls
# set_size_request(width, height) where -1 means natural size
self._widget.set_size_request(self._fixed_width, -1)
# ── GTK4 factory callbacks ────────────────────────────────────────────────
def _on_factory_setup(self, _factory: Gtk.SignalListItemFactory,
list_item: Gtk.ListItem) -> None:
label = Gtk.Label(xalign=0)
label.set_ellipsize(Pango.EllipsizeMode.END)
label.set_max_width_chars(40)
list_item.set_child(label)
def _on_factory_bind(self, _factory: Gtk.SignalListItemFactory,
list_item: Gtk.ListItem) -> None:
obj = list_item.get_item()
label: Gtk.Label = list_item.get_child()
if obj is not None:
label.set_label(obj.get_string())
# ── Internal signal handlers ──────────────────────────────────────────────
def _on_realize(self, widget: Gtk.DropDown) -> None:
"""Wire up the DropDown's internal search entry after realisation."""
se = _find_search_entry(widget)
if se is not None:
self._search_entry = se
se.connect("search-changed", self._on_search_changed)
def _on_search_changed(self, search_entry: Gtk.SearchEntry) -> None:
"""
Drives the StringFilter and live error styling as the user types.
Never writes to any ConfigEntry — that is _on_dropdown_selected's job.
Partial search text (e.g. "asia/dha") must never become a saved value.
"""
text = search_entry.get_text().strip()
self._filter.set_search(text)
is_valid = self._validate(text)
if is_valid:
search_entry.remove_css_class("error")
else:
search_entry.add_css_class("error")
def _on_dropdown_selected(self, dropdown: Gtk.DropDown,
_param: object) -> None:
"""Fires when the user picks an item; clears error and invokes callback."""
obj = dropdown.get_selected_item()
if obj is None:
return
text: str = obj.get_string()
if not text:
return
if self._search_entry is not None:
self._search_entry.remove_css_class("error")
self._on_selected_cb(text)
# ─── Rain Forecast Service ────────────────────────────────────────────────────
@dataclass(frozen=True)
class ForecastEntry:
"""A single rain forecast slot parsed from OpenWeather forecast-data.json."""
dt: int # Unix epoch
dt_txt: str # "YYYY-MM-DD HH:MM:SS" (for display)
temp: float # °C
feels_like: float # °C
description: str # e.g. "light rain"
pop: float # 0.0–1.0 probability of precipitation
class RainForecastService:
"""
Parses, caches, and filters rain forecast data from
~/.cache/weather/forecast-data.json.
Responsibilities (Single Responsibility):
• File reading & JSON parsing
• Cache invalidation (by file mtime)
• Filtering by pop threshold and lookahead count
The service is stateless between calls except for the parsed cache,
making it independently testable without any GTK dependency.
"""
def __init__(self) -> None:
self._forecast_path = Path.home() / ".cache" / "weather" / "forecast-data.json"
self._cached_entries: list[ForecastEntry] = []
self._cached_mtime: Optional[float] = None
# ── Public API ────────────────────────────────────────────────────────────
def get_rain_forecasts(
self,
threshold: float,
lookahead: int,
) -> list[ForecastEntry]:
"""
Return up to *lookahead* upcoming rain entries with pop >= threshold,
sorted by earliest occurrence first.
Re-reads the file only when mtime has changed since the last call.
Re-filters always (threshold may change between calls without a file
change).
"""
self._refresh_cache_if_stale()
return self._filter(self._cached_entries, threshold, lookahead)
def load_error(self) -> Optional[str]:
"""Return a human-readable error string if the file is unreadable."""
try:
self._forecast_path.stat()
json.loads(self._forecast_path.read_text(encoding="utf-8"))
return None
except FileNotFoundError:
return "forecast-data.json not found"
except (json.JSONDecodeError, ValueError) as exc:
return f"forecast-data.json is invalid: {exc}"
except Exception as exc:
return str(exc)
# ── Internal helpers ──────────────────────────────────────────────────────
def _refresh_cache_if_stale(self) -> None:
"""Reload and re-parse file only when mtime changed."""
try:
mtime = self._forecast_path.stat().st_mtime
except Exception:
self._cached_entries = []
self._cached_mtime = None
return
if mtime == self._cached_mtime:
return # Cache still valid
try:
raw = json.loads(self._forecast_path.read_text(encoding="utf-8"))
self._cached_entries = self._parse(raw)
self._cached_mtime = mtime
except Exception:
self._cached_entries = []
self._cached_mtime = None
@staticmethod
def _parse(raw: dict[str, Any]) -> list[ForecastEntry]:
"""Convert raw OpenWeather forecast JSON into a list of ForecastEntry."""
entries: list[ForecastEntry] = []
for item in raw.get("list", []):
try:
main = item["main"]
weather = item["weather"][0]
entry = ForecastEntry(
dt=int(item["dt"]),
dt_txt=str(item.get("dt_txt", "")),
temp=float(main["temp"]),
feels_like=float(main["feels_like"]),
description=str(weather.get("description", "")).title(),
pop=float(item.get("pop", 0.0)),
)
entries.append(entry)
except (KeyError, ValueError, TypeError):
continue # Skip malformed slots silently
return entries
@staticmethod
def _filter(
entries: list[ForecastEntry],
threshold: float,
lookahead: int,
) -> list[ForecastEntry]:
"""
Filter entries with pop >= threshold, keep only future timestamps,
sort earliest-first, and return at most *lookahead* results.
This is the single authoritative filter — never duplicated in the UI.
"""
now_ts = int(datetime.now().timestamp())
result = [
e for e in entries
if e.pop >= threshold and e.dt >= now_ts
]
result.sort(key=lambda e: e.dt)
return result[:max(0, lookahead)]
# ─── Config File I/O ─────────────────────────────────────────────────────────
class ConfigParser:
"""Reads and writes bash-style .env / config files."""
# Matches: [readonly] KEY="value" or KEY=value
_LINE_RE = re.compile(
r'^(?P<readonly>readonly\s+)?(?P<key>[A-Z_][A-Z0-9_]*)=(?P<value>.*)$'
)
def load(self, path: Path) -> dict[str, ConfigEntry]:
"""Parse file, return {key: ConfigEntry} only for known schema keys."""
entries: dict[str, ConfigEntry] = {}
text = path.read_text(encoding="utf-8")
for line in text.splitlines():
m = self._LINE_RE.match(line.strip())
if not m:
continue
key = m.group("key")
val = m.group("value").split(
"#")[0].strip() # strip inline comment
if key in SCHEMA_MAP:
entries[key] = ConfigEntry(
schema=SCHEMA_MAP[key], raw_value=val)
# Fill missing keys with defaults
for schema in SCHEMA:
if schema.key not in entries:
default = str(
schema.default) if schema.default is not None else ""
entries[schema.key] = ConfigEntry(
schema=schema, raw_value=default)
return entries
def save(self, path: Path, entries: dict[str, ConfigEntry]) -> None:
"""Rewrite file, updating only the known variables, preserving everything else."""
text = path.read_text(encoding="utf-8")
lines = text.splitlines(keepends=True)
out: list[str] = []
for line in lines:
m = self._LINE_RE.match(line.strip())
if m and (key := m.group("key")) in entries:
entry = entries[key]
prefix = "readonly " if m.group("readonly") else ""
# preserve inline comment if any
comment_match = re.search(r'\s+#.*$', line)
comment = comment_match.group(0) if comment_match else ""
out.append(f"{prefix}{key}={entry.raw_value}{comment}\n")
else:
out.append(line)
path.write_text("".join(out), encoding="utf-8")
# ─── Validation ──────────────────────────────────────────────────────────────
class Validator:
"""Validates entry values; returns error string or empty string."""
def validate(self, entry: ConfigEntry, all_entries: Optional[dict[str, ConfigEntry]] = None) -> str:
schema = entry.schema
val = entry.display_value
vt = schema.var_type
if vt == VarType.INTEGER:
try:
int_val = int(val)
# Special constraint: RAIN_FORECAST_WINDOW minimum 3 hours when API_KEY_TYPE is FREE
if schema.key == "RAIN_FORECAST_WINDOW" and all_entries is not None:
api_type_entry = all_entries.get("API_KEY_TYPE")
if api_type_entry and api_type_entry.display_value == "FREE":
if int_val < 3:
return "FREE plan requires minimum 3-hour forecast window (3-hourly data)"
except ValueError:
return f"Must be a whole number"
elif vt == VarType.FLOAT:
try:
fv = float(val)
if not 0.0 <= fv <= 1.0:
return "Must be between 0.0 and 1.0"
except ValueError:
return "Must be a decimal number"
elif vt == VarType.BOOLEAN:
if val.lower() not in ("true", "false"):
return "Must be true or false"
elif vt == VarType.STRING and schema.key == "TIMEZONE":
# Only validate against zone.tab when it was successfully loaded.
tzs = TimezoneStore().load()
if tzs and val not in tzs:
return "Not a recognised IANA timezone. Check zone.tab for valid values."