Skip to content

Commit

Permalink
isolate settings as class
Browse files Browse the repository at this point in the history
  • Loading branch information
amit9838 committed Jun 2, 2024
1 parent ee99640 commit 2ce1fcb
Show file tree
Hide file tree
Showing 18 changed files with 269 additions and 209 deletions.
2 changes: 1 addition & 1 deletion data/io.github.amit9838.mousam.gschema.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<summary>Launch the app in maximized mode.</summary>
</key>

<key name="measure-type" type="s">
<key name="unit" type="s">
<default>"metric"</default>
<summary>Mesaurement sysytem to use - metric,imperial</summary>
<description>metric(km, °C), imperial(mile, °F)</description>
Expand Down
1 change: 0 additions & 1 deletion po/POTFILES
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ src/main.py
src/Models.py
src/mousam.in
src/mousam.py
src/units.py
src/utils.py
src/weatherData.py
src/windowAbout.py
Expand Down
39 changes: 14 additions & 25 deletions src/backendWeather.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import requests
import datetime

from gi.repository import Gio
from .config import settings


base_url = "https://api.open-meteo.com/v1/forecast"
Expand All @@ -13,25 +13,20 @@ class Weather:
"""

def __init__(self) -> None:
global settings, measurement_type, temperature_unit, wind_speed_unit
settings = Gio.Settings(schema_id="io.github.amit9838.mousam")
measurement_type = settings.get_string("measure-type")
if measurement_type == "imperial":
temperature_unit = "fahrenheit"
wind_speed_unit = "mph"
global extend_url
extend_url = ""
if settings.unit == "imperial":
extend_url = f"&temperature_unit=fahrenheit&wind_speed_unit=mph"

# Current Weather =============================================
@staticmethod
def current_weather(latitude: float, longitude: float, **kwargs):
@classmethod
def current_weather(cls,latitude: float, longitude: float, **kwargs):
url = base_url + f"?latitude={latitude}&longitude={longitude}"

# Check for kwargs keyword parameters
if "current" in kwargs:
current_fields = ",".join(kwargs.get("current"))
url = url + f"&current={current_fields}"

if measurement_type == "imperial":
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
url = url + f"&current={current_fields}" + extend_url

try:
url = url + f"&timeformat=unixtime"
Expand All @@ -58,17 +53,14 @@ def _get_current_weather(self, lat, lon):
return self.current_weather(lat, lon, current=current_args)

# Hourly Forecast ==============================================
@staticmethod
def forecast_hourly(latitude: float, longitude: float, **kwargs):
@classmethod
def forecast_hourly(cls,latitude: float, longitude: float, **kwargs):
url = base_url + f"?latitude={latitude}&longitude={longitude}"

# Check for kwargs keyword parameters
if "hourly" in kwargs:
hourly_fields = ",".join(kwargs.get("hourly"))
url = url + f"&hourly={hourly_fields}"

if measurement_type == "imperial":
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
url = url + f"&hourly={hourly_fields}" + extend_url

try:
url = url + f"&timeformat=unixtime"
Expand Down Expand Up @@ -103,8 +95,8 @@ def _get_hourly_forecast(self, lat, lon):
)

# Forecast daily ====================================================
@staticmethod
def forecast_daily(latitude: float, longitude: float, **kwargs):
@classmethod
def forecast_daily(cls,latitude: float, longitude: float, **kwargs):
url = base_url + f"?latitude={latitude}&longitude={longitude}"
if "daily" in kwargs:
hourly_fields = ",".join(kwargs.get("daily"))
Expand All @@ -116,10 +108,7 @@ def forecast_daily(latitude: float, longitude: float, **kwargs):
url = url + f"&start_date={kwargs.get('start_date')}"

if "end_date" in kwargs:
url = url + f"&end_date={kwargs.get('end_date')}"

if measurement_type == "imperial":
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
url = url + f"&end_date={kwargs.get('end_date')}" + extend_url

try:
url = url + f"&timeformat=unixtime"
Expand Down
75 changes: 75 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from gi.repository import Gio

class Settings:
_instance = None
APP_ID = "io.github.amit9838.mousam"

def __new__(cls):
if cls._instance is None:
cls._instance = super(Settings, cls).__new__(cls)
cls._instance.init_settings()
return cls._instance

def init_settings(self):
self.settings = Gio.Settings(self.APP_ID)
self._settings_map = {
"added_cities": "added-cities",
"selected_city": "selected-city",
"is_using_dynamic_bg": "use-gradient-bg",
"is_using_inch_for_prec": "use-inch-for-prec",
"should_launch_maximized": "launch-maximized",
"unit": "unit",
}

@property
def added_cities(self):
return self.settings.get_strv(self._settings_map["added_cities"])

@added_cities.setter
def added_cities(self, value):
self.settings.set_strv(self._settings_map["added_cities"], value)

@property
def selected_city(self):
return self.settings.get_string(self._settings_map["selected_city"])

@selected_city.setter
def selected_city(self, value):
self.settings.set_string(self._settings_map["selected_city"], value)

@property
def is_using_dynamic_bg(self):
return self.settings.get_boolean(self._settings_map["is_using_dynamic_bg"])

@is_using_dynamic_bg.setter
def is_using_dynamic_bg(self, value):
self.settings.set_boolean(self._settings_map["is_using_dynamic_bg"], value)

@property
def is_using_inch_for_prec(self):
return self.settings.get_boolean(self._settings_map["is_using_inch_for_prec"])

@is_using_inch_for_prec.setter
def is_using_inch_for_prec(self, value):
self.settings.set_boolean(self._settings_map["is_using_inch_for_prec"], value)

@property
def should_launch_maximized(self):
return self.settings.get_boolean(self._settings_map["should_launch_maximized"])

@should_launch_maximized.setter
def should_launch_maximized(self, value):
self.settings.set_boolean(self._settings_map["should_launch_maximized"], value)

@property
def unit(self):
return self.settings.get_string(self._settings_map["unit"])

@unit.setter
def unit(self, value):
self.settings.set_string(self._settings_map["unit"], value)

def get_settings():
return Settings()

settings = get_settings()
4 changes: 2 additions & 2 deletions src/frontendCardAirPollution.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from gi.repository import Gtk

from .frontendUiDrawPollutionBar import PollutionBar
from .utils import is_dynamic_bg_enabled
from .config import settings

class CardAirPollution:
def __init__(self):
Expand Down Expand Up @@ -36,7 +36,7 @@ def create_card(self):
card.halign = Gtk.Align.FILL
card.set_row_spacing(5)
card.set_css_classes(["view", "card", "custom_card"])
if is_dynamic_bg_enabled():
if settings.is_using_dynamic_bg:
card.add_css_class("transparent_5")

# Main title of the card
Expand Down
4 changes: 2 additions & 2 deletions src/frontendCardDayNight.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from gi.repository import Gtk

from .frontendUiDrawDayNight import *
from .config import settings
from .utils import (
get_tz_offset_by_cord,
get_cords,
get_my_tz_offset_from_utc,
is_dynamic_bg_enabled,
get_time_difference,
)

Expand Down Expand Up @@ -70,7 +70,7 @@ def create_card(self):
card.set_row_spacing(5)
card.set_css_classes(["view", "card", "custom_card"])

if is_dynamic_bg_enabled():
if settings.is_using_dynamic_bg:
card.add_css_class("transparent_5")

# Main title of the card
Expand Down
4 changes: 2 additions & 2 deletions src/frontendCardSquare.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from gi.repository import Gtk
import gi
from .constants import icons
from .utils import is_dynamic_bg_enabled
from .config import settings
from .frontendUiDrawBar import *
from .frontendUiDrawImageIcon import *

Expand Down Expand Up @@ -53,7 +53,7 @@ def create_card(self):
card.set_size_request(200, 150)
card.set_css_classes(["view", "card", "custom_card"])

if is_dynamic_bg_enabled():
if settings.is_using_dynamic_bg:
card.add_css_class("transparent_5")
self.card = card

Expand Down
15 changes: 7 additions & 8 deletions src/frontendCurrentCond.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import gi
from gi.repository import Gtk, Gio
from gi.repository import Gtk
from .constants import icons, conditon
from .config import settings

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
Expand Down Expand Up @@ -51,7 +52,9 @@ def paint_ui(self):

# Condition temperature
main_temp_label = Gtk.Label(
label="{0:.0f} {1}".format(data.temperature_2m.get("data"),data.temperature_2m.get("unit")),
label="{0:.0f} {1}".format(
data.temperature_2m.get("data"), data.temperature_2m.get("unit")
),
halign=Gtk.Align.START,
valign=Gtk.Align.START,
)
Expand All @@ -64,15 +67,11 @@ def paint_ui(self):
)
self.attach(box_right, 1, 0, 1, 1)

self.settings = Gio.Settings(schema_id="io.github.amit9838.mousam")
self.added_cities = self.settings.get_strv("added-cities")
self.selected_city = self.settings.get_string("selected-city")

self.selected_city_index = list(
map(lambda city: self.selected_city in city, self.added_cities)
map(lambda city: settings.selected_city in city, settings.added_cities)
).index(True)

city_arr = self.added_cities[self.selected_city_index].split(",")
city_arr = settings.added_cities[self.selected_city_index].split(",")

# Delete lat,lon from the array
del city_arr[-1]
Expand Down
4 changes: 2 additions & 2 deletions src/frontendForecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from gi.repository import Gtk
from gettext import gettext as _, pgettext as C_
from .constants import icons
from .utils import is_dynamic_bg_enabled
from .config import settings

gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
Expand All @@ -17,7 +17,7 @@ def __init__(self, *args, **kwargs):
self.set_margin_start(10)
self.set_margin_end(5)
self.set_css_classes(['view', 'card', 'custom_card'])
if is_dynamic_bg_enabled():
if settings.is_using_dynamic_bg:
self.add_css_class("transparent_5")
self.paint_ui()

Expand Down
15 changes: 7 additions & 8 deletions src/frontendHourlyDetails.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import time
import gi
import gettext
from gi.repository import Gtk, Gio
from gi.repository import Gtk

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
Expand All @@ -12,7 +12,7 @@
from .constants import icons, icon_loc
from .frontendUiDrawImageIcon import DrawImage
from .frontendUiDrawbarLine import DrawBar
from .utils import is_dynamic_bg_enabled
from .config import settings

icon_loc += "arrow.svg"

Expand All @@ -22,8 +22,10 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_hexpand(True)
self.set_css_classes(["view", "card", "custom_card"])
if is_dynamic_bg_enabled():

if settings.is_using_dynamic_bg:
self.add_css_class("transparent_5")

self.set_margin_top(20)
self.set_margin_start(5)
self.paint_ui()
Expand Down Expand Up @@ -114,12 +116,9 @@ def create_stack_page(self, page_name):
unit_label.set_text("")

# Precipitation page
settings = Gio.Settings(schema_id="io.github.amit9838.mousam")
use_inch_for_prec = settings.get_boolean("use-inch-for-prec")

max_prec = max(hourly_data.precipitation.get("data")[:24])
unit = hourly_data.precipitation.get("unit")
if use_inch_for_prec:
if settings.is_using_inch_for_prec:
max_prec = max_prec / 25.4
unit = "inch"

Expand Down Expand Up @@ -245,7 +244,7 @@ def create_stack_page(self, page_name):
elif page_name == "prec":
bar_obj = None
prec = hourly_data.precipitation.get("data")[i]
if use_inch_for_prec:
if settings.is_using_inch_for_prec:
prec = hourly_data.precipitation.get("data")[i] / 25.4
if max_prec == 0:
bar_obj = DrawBar(0)
Expand Down
5 changes: 2 additions & 3 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

from gi.repository import Gtk, Gio, Adw, Gdk
from .mousam import WeatherMainWindow
from .config import settings

class WeatherApplication(Adw.Application):
"""The main application singleton class."""
Expand All @@ -34,7 +35,6 @@ def __init__(self):
super().__init__(application_id='io.github.amit9838.mousam',
flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
self.create_action('quit', lambda *_: self.quit(), ['<primary>q'])
self.settings = Gio.Settings(schema_id="io.github.amit9838.mousam")
self.main_window = None

self.set_accels_for_action(f"win.preferences", ['<primary>comma'])
Expand All @@ -52,12 +52,11 @@ def do_activate(self):
css_provider.load_from_data(css,len(css))
Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css_provider, Priority)

launch_maximized = self.settings.get_boolean("launch-maximized")

if not win:
win = WeatherMainWindow(application=self)

if launch_maximized:
if settings.should_launch_maximized:
win.maximize()

win.present()
Expand Down
2 changes: 1 addition & 1 deletion src/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ mousam_sources = [
'frontendUiDrawPollutionBar.py',

'constants.py',
'units.py',
'utils.py',
'config.py',
'windowAbout.py',
'windowPreferences.py',
'windowLocations.py',
Expand Down
Loading

0 comments on commit 2ce1fcb

Please sign in to comment.