Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
justjokiing committed Jan 15, 2025
1 parent fd02d97 commit 6a25b62
Show file tree
Hide file tree
Showing 4 changed files with 262 additions and 220 deletions.
136 changes: 6 additions & 130 deletions src/kshift/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,136 +7,12 @@
import requests
import json

from kshift import utils
from kshift.theme import Theme

from pathlib import Path

from pydantic import BaseModel, Field, field_validator, model_validator
from typing import Dict, Optional, Union, List


class ThemeConfig(BaseModel):
# name: str = Field(description="Name for kshift theme")
colorscheme: Optional[str] = Field(
None, description="The name of the color scheme.")
icontheme: Optional[str] = Field(None,
description="The name of the icon theme.")
wallpaper: Optional[str] = Field(
None, description="Path to the wallpaper image.")
desktoptheme: Optional[str] = Field(None,
description="The desktop theme name.")
command: Optional[str] = Field(
None, description="Command to execute when the theme is applied.")
time: List[Union[str, datetime]] = Field(
[], description="The time when this theme is applied.")
enabled: bool = Field(True, description="Whether the theme is enabled.")

def kshift(self) -> None:

if self.wallpaper:
os.system(f"plasma-apply-wallpaperimage {self.wallpaper}")

if self.colorscheme and self.colorscheme != utils.curr_colorscheme():
os.system(f"plasma-apply-colorscheme {self.colorscheme}")

# if self.icontheme and self.icontheme != utils.curr_icontheme():
if self.icontheme:
plasma_changeicons = utils.find_plasma_changeicons()
if (plasma_changeicons is not None):
os.system(f"{plasma_changeicons} {self.icontheme}")

if self.desktoptheme and self.desktoptheme != utils.curr_desktoptheme(
):
os.system(f"plasma-apply-desktoptheme {self.desktoptheme}")

if self.command:
os.system(self.command)

@field_validator("colorscheme")
def validate_colorscheme(cls, value):
colorschemes = utils.get_colorschemes()
if value and value not in colorschemes:
raise ValueError(
f"Unknown colorscheme: {value}.\nValid options are {colorschemes}"
)
else:
return value

@field_validator("icontheme")
def validate_icontheme(cls, value):
iconthemes = utils.get_iconthemes()
if value and value not in iconthemes:
raise ValueError(
f"Unknown icontheme: {value}.\nValid options are {iconthemes}")
else:
return value

@field_validator("wallpaper")
def validate_wallpaper(cls, value):
if value:
value = Path(value).expanduser()
if value.exists():
return value
else:
raise ValueError(f"Wallpaper does not exist: {value}")

@field_validator("desktoptheme")
def validate_desktoptheme(cls, value):
desktopthemes = utils.get_desktopthemes()
if value and value not in desktopthemes:
raise ValueError(
f"Unknown desktoptheme: {value}.\nValid options are {desktopthemes}"
)
else:
return value

@field_validator("time", mode="before")
def parse_time(cls, value):
if isinstance(value, str):
return [value] # Convert single string to a list
elif isinstance(value, list):
if not all(isinstance(item, str) for item in value):
raise ValueError(
"All elements in the 'time' list must be strings.")
return value
else:
raise TypeError("'time' must be a string or a list of strings.")

@model_validator(mode="after")
def if_disabled(self):
if not self.enabled:
self.time = []

return self

@field_validator("time", mode="after")
def convert_time_strings(cls, times):
new_times = []
for item in times:
if isinstance(item, str):
if re.match(r'^\d{2}:\d{2}$', item):
# Parse "HH:MM" into a datetime object with today's date
now = datetime.now()
hour, minute = map(int, item.split(':'))
dt = now.replace(hour=hour,
minute=minute,
second=0,
microsecond=0)
# If the time has already passed today, schedule for tomorrow
if dt < now:
dt += timedelta(days=1)
item = dt

new_times.append(item)
elif isinstance(item, datetime):
new_times.append(item)
else:
raise TypeError(
"Each time entry must be a string in systemd OnCalendar format."
)

return new_times

from typing import Dict

defaults = {
"latitude": 39,
Expand All @@ -147,8 +23,8 @@ def convert_time_strings(cls, times):
"set_delay": 0,
"net_timeout": 10,
"themes": {
'day': ThemeConfig(colorscheme="BreezeLight", time=["sunrise"]),
'night': ThemeConfig(colorscheme="BreezeDark", time=["sunset"]),
'day': Theme(colorscheme="BreezeLight", time=["sunrise"]),
'night': Theme(colorscheme="BreezeDark", time=["sunset"]),
}
}

Expand Down Expand Up @@ -190,7 +66,7 @@ class Config(BaseModel):
ge=0,
le=60,
description="Network timeout in seconds, between 0 and 60.")
themes: Dict[str, ThemeConfig] = Field(defaults["themes"],
themes: Dict[str, Theme] = Field(defaults["themes"],
description="Dictionary of themes.")

# Environment-based paths
Expand Down Expand Up @@ -229,7 +105,7 @@ class Config(BaseModel):
description="Path to the cache file for sunrise and sunset data.")

@model_validator(mode="after")
def set_dependant(self):
def set_dependant_paths(self):
# Compute dependent paths
self.systemd_loc = self.xdg_data / "systemd/user"
self.config_loc_base = self.xdg_config / "kshift"
Expand Down
6 changes: 3 additions & 3 deletions src/kshift/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from importlib.resources import files

from kshift.conf import ThemeConfig, load_config
from kshift.conf import Theme, load_config

from string import Template

Expand Down Expand Up @@ -54,7 +54,7 @@ def log_theme_change(theme_name):
logging.info(json.dumps(log_data)) # Use JSON for structured logs


def log_element_change(theme: ThemeConfig):
def log_element_change(theme: Theme):
log_data = {"event": "specific_change", "theme": str(theme)}
logging.info(json.dumps(log_data))

Expand Down Expand Up @@ -380,7 +380,7 @@ def theme(theme, colorscheme, icontheme, wallpaper, desktop_theme):

if any([colorscheme, icontheme, wallpaper, desktop_theme]):
# Apply individual theme elements dynamically
custom_theme = ThemeConfig(
custom_theme = Theme(
colorscheme=colorscheme,
icontheme=icontheme,
wallpaper=wallpaper,
Expand Down
Loading

0 comments on commit 6a25b62

Please sign in to comment.