summaryrefslogtreecommitdiffstats
path: root/hyprsunset_qt/settings.py
blob: d9cca3921896484dd9a5868bc4b6a83df6c7c0a8 (plain)
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
"""App settings stored in ~/.config/hyprsunset-qt/config (INI)."""

from __future__ import annotations

import configparser
from dataclasses import dataclass
from pathlib import Path

SETTINGS_PATH = Path.home() / ".config" / "hyprsunset-qt" / "config"
DEFAULT_CACHE = "~/.config/hyprsunset-qt/sun.json"


@dataclass
class Settings:
    lat: str = ""
    lon: str = ""
    auto_detect: bool = True
    cache_path: str = DEFAULT_CACHE
    daemon_command: str = "hyprsunset"

    @classmethod
    def load(cls, path: Path = SETTINGS_PATH) -> "Settings":
        path = Path(path)
        if not path.exists():
            s = cls()
            s.save(path)
            return s
        cp = configparser.ConfigParser()
        cp.read(path)
        return cls(
            lat=cp.get("location", "lat", fallback=""),
            lon=cp.get("location", "lon", fallback=""),
            auto_detect=cp.getboolean("location", "auto_detect", fallback=True),
            cache_path=cp.get("cache", "path", fallback=DEFAULT_CACHE),
            daemon_command=cp.get("daemon", "command", fallback="hyprsunset"),
        )

    def save(self, path: Path = SETTINGS_PATH) -> None:
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        cp = configparser.ConfigParser()
        cp["location"] = {
            "lat": self.lat,
            "lon": self.lon,
            "auto_detect": str(self.auto_detect).lower(),
        }
        cp["cache"] = {"path": self.cache_path}
        cp["daemon"] = {"command": self.daemon_command}
        with path.open("w") as f:
            cp.write(f)

    def cache_path_expanded(self) -> Path:
        return Path(self.cache_path).expanduser()