From 3dbad6bdea98be01c6c19a0ca50d8935d7b446ab Mon Sep 17 00:00:00 2001 From: S4NKALP Date: Thu, 9 Jul 2026 18:56:28 +0545 Subject: [PATCH] refactor(src/utils): drop unused AppName methods and simplify DBusMenuClient Removed get_app_exec, get_desktop_file, on_focus, get_revision; renamed parameter format_ to _format_; cleaned up imports and dead code. --- src/utils/app_name_resolver.py | 27 +---- src/utils/conversion.py | 216 --------------------------------- src/utils/dbusmenu.py | 6 - src/utils/functions.py | 10 +- src/utils/occlusion.py | 10 -- src/utils/utils.py | 15 --- 6 files changed, 2 insertions(+), 282 deletions(-) diff --git a/src/utils/app_name_resolver.py b/src/utils/app_name_resolver.py index 18ea367..c372ca5 100644 --- a/src/utils/app_name_resolver.py +++ b/src/utils/app_name_resolver.py @@ -6,7 +6,7 @@ class AppName: self.files = os.listdir(path) self.path = path - def get_app_name(self, wmclass, format_=False): + def get_app_name(self, wmclass, _format_=False): desktop_file = "" for f in self.files: if f.startswith(wmclass + ".desktop"): @@ -24,31 +24,6 @@ class AppName: break return desktop_app_name - def get_app_exec(self, wmclass, format_=False): - desktop_file = "" - for f in self.files: - if f.startswith(wmclass + ".desktop"): - desktop_file = f - - desktop_app_name = wmclass - - if desktop_file == "": - return wmclass - with open(os.path.join(self.path, desktop_file), "r") as f: - lines = f.readlines() - for line in lines: - if line.startswith("Exec="): - desktop_app_name = line.split("=")[1].strip() - break - return desktop_app_name - - def get_desktop_file(self, wmclass): - desktop_file = "" - for f in self.files: - if f.startswith(wmclass + ".desktop"): - desktop_file = f - return desktop_file - def format_app_name(self, title, wmclass, update=False): # Handle case when both title and wmclass are empty (no active window) if not title and not wmclass: diff --git a/src/utils/conversion.py b/src/utils/conversion.py index 05d533e..deb616b 100644 --- a/src/utils/conversion.py +++ b/src/utils/conversion.py @@ -447,219 +447,3 @@ class Units: } # We no longer use currency_converter here. - - -class Conversion: - def __init__(self): - self.units = Units() - self.currency_cache = _currency_cache - - def convert(self, value: float, from_type: str, to_type: str): - """ - Generalized conversion function that works with all categories, - including currency via floatrates.com. - """ - # Collection of all non-currency charts - charts = { - "WEIGHT_CHART": self.units.WEIGHT_CHART, - "LENGTH_CHART": self.units.LENGTH_CHART, - "TEMPERATURE_CHART": self.units.TEMPERATURE_CHART, - "TIME_CHART": self.units.TIME_CHART, - "LIQUID_VOLUME_CHART": self.units.LIQUID_VOLUME_CHART, - "STORAGE_TYPE_CHART": self.units.STORAGE_TYPE_CHART, - "ANGLE_CHART": self.units.ANGLE_CHART, - "ENERGY_CHART": self.units.ENERGY_CHART, - "SPEED_CHART": self.units.SPEED_CHART, - "PRESSURE_CHART": self.units.PRESSURE_CHART, - "FORCE_CHART": self.units.FORCE_CHART, - "POWER_CHART": self.units.POWER_CHART, - "VOLTAGE_CHART": self.units.VOLTAGE_CHART, - "CURRENT_CHART": self.units.CURRENT_CHART, - "RESISTANCE_CHART": self.units.RESISTANCE_CHART, - "CAPACITANCE_CHART": self.units.CAPACITANCE_CHART, - "INDUCTANCE_CHART": self.units.INDUCTANCE_CHART, - "FREQUENCY_CHART": self.units.FREQUENCY_CHART, - "LUMINANCE_CHART": self.units.LUMINANCE_CHART, - "AREA_CHART": self.units.AREA_CHART, - } - - # 1) Check if it's in any of the charts (non-currency) - for chart_name, chart in charts.items(): - if from_type in chart and to_type in chart: - # Temperatures use lambdas - if chart_name == "TEMPERATURE_CHART": - if from_type == to_type: - return value - to_kelvin = chart[from_type][0] - from_kelvin = chart[to_type][1] - return from_kelvin(to_kelvin(value)) - - # Handle WEIGHT_CHART separately (tuple values) - if chart_name == "WEIGHT_CHART": - if from_type == to_type: - return value - to_kg = chart[from_type][0] - from_kg = chart[to_type][1] - return value * to_kg * from_kg - - # Any other numeric chart - if from_type == to_type: - return value - return value * (chart[from_type] / chart[to_type]) - - # 2) If both are currency codes (e.g. “USD”, “ARS”) - # we assume they are uppercase and have 3 letters. - if ( - len(from_type) == 3 - and len(to_type) == 3 - and from_type.isalpha() - and to_type.isalpha() - ): - result = self._convert_currency_fast(value, from_type, to_type) - if result is not None: - return result - # Fallback to slow method if fast method fails - return self._convert_currency_via_floatrates(value, from_type, to_type) - - # 3) If it doesn't fall into any case, error. - raise ValueError(f"Unsupported conversion: {from_type} to {to_type}") - - def _convert_currency_fast( - self, value: float, from_code: str, to_code: str - ) -> Optional[float]: - """ - Fast currency conversion using cached exchange rates. - Returns None if rate is not available in cache. - """ - rate_info = self.currency_cache.get_rate(from_code, to_code) - if rate_info is not None: - rate, _ = rate_info # cache_age not needed here - return value * rate - return None - - def _convert_currency_via_floatrates( - self, value: float, from_code: str, to_code: str - ) -> float: - """ - Converts using the JSON from floatrates.com: - - Makes GET to https://www.floatrates.com/daily/{from_lower}.json - - Takes the rate from the to_lower key and multiplies. - """ - from_lower = from_code.lower() - to_lower = to_code.lower() - - if from_lower == to_lower: - return value - - url = f"https://www.floatrates.com/daily/{from_lower}.json" - try: - resp = httpx.get( - url, - timeout=10, - follow_redirects=True, - headers={ - "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" - }, - ) - if resp.status_code != 200: - raise ValueError( - f"Error getting data from floatrates for {from_code}: Status { - resp.status_code - }" - ) - data = resp.json() - except Exception as e: - raise ValueError(f"Error getting data from floatrates for {from_code}: {e}") - if to_lower not in data: - raise ValueError( - f"Target currency '{to_code}' not found in floatrates response for '{ - from_code - }'" - ) - - rate = data[to_lower]["rate"] - return value * rate - - def parse_input_and_convert(self, input: str): - parts = input.split() - addition = "s" if parts[-1].endswith("s") else "" - - if "and" in parts: # value unit1 and value2 unit2 _ to target_unit - parts.remove("and") - if len(parts) != 6: - raise ValueError( - "Invalid format. Expected: 'value from_type and value2 from_type2 _ to_type'" - ) - - value1, from_type1, value2, from_type2, _, to_type = parts - value1, value2 = float(value1), float(value2) - from_type1 = self.clean_type(from_type1) - from_type2 = self.clean_type(from_type2) - to_type = self.clean_type(to_type) - - if from_type1 == from_type2: - return ( - self.convert(value1 + value2, from_type1, to_type), - to_type + addition, - ) - else: - res = 0 - res += self.convert(value1, from_type1, to_type) - res += self.convert(value2, from_type2, to_type) - return res, to_type + addition - else: - if len(parts) != 4: - raise ValueError( - "Invalid format. Expected: 'value from_type _ to_type'" - ) - value, from_type, _, to_type = parts - value = float(value) - from_type = self.clean_type(from_type) - to_type = self.clean_type(to_type) - return self.convert(value, from_type, to_type), to_type + addition - - def clean_type(self, type: str) -> str: - """ - If it's currency symbol, convert to code. - If it's currency (3 letters), convert to uppercase. - If it ends in 's' (and is not 'celsius'), remove the 's' for - other units.""" - if type in self.units.CURRENCY_SYMBOLS: - return self.units.CURRENCY_SYMBOLS[type] - if len(type) == 3 and type.isalpha(): - return type.upper() - if type.endswith("s") and type.lower() != "celsius": - # For tables that have singular/plural - singular = type[:-1].lower() - # If it exists in STORAGE_TYPE_CHART, we use it; - # if not, we return singular in lowercase for other charts. - if singular in self.units.STORAGE_TYPE_CHART: - return singular - return singular.lower() - return type - - def cleanup(self): - """Cleanup resources.""" - self.currency_cache.cleanup() - - def get_currency_cache_info( - self, from_code: str, to_code: str - ) -> Optional[Tuple[bool, float]]: - """ - Get currency cache information for UI display. - Returns (is_fresh, cache_age_seconds) or None if not cached. - """ - rate_info = self.currency_cache.get_rate(from_code, to_code) - if rate_info is not None: - _, cache_age = rate_info # rate not needed here - is_fresh = cache_age < 300 # Consider fresh if less than 5 minutes old - return is_fresh, cache_age - return None - - -# Quick usage example: -if __name__ == "__main__": - conv = Conversion() - # Convert 10 USD to ARS: - result, suffix = conv.parse_input_and_convert("10 USD _ ARS") - print(f"{result:.2f} {suffix}") # Ex: "10 USD _ ARS" -> "38754.23 ARS" diff --git a/src/utils/dbusmenu.py b/src/utils/dbusmenu.py index c5896ea..f40748e 100644 --- a/src/utils/dbusmenu.py +++ b/src/utils/dbusmenu.py @@ -270,12 +270,6 @@ class DBusMenuClient: target=self.get_layout, kwargs={"force_refresh": True}, daemon=True ).start() - def on_focus(self): - self.prefetch_async() - - def get_revision(self) -> int: - return self._revision - def connect_signals( self, on_layout_updated: Optional[Callable] = None, diff --git a/src/utils/functions.py b/src/utils/functions.py index 077e5e9..13677a8 100644 --- a/src/utils/functions.py +++ b/src/utils/functions.py @@ -2,15 +2,13 @@ import ctypes import html import subprocess import threading -from typing import Dict, NamedTuple, Optional, TypeVar +from typing import Dict, NamedTuple, Optional from fabric.utils import ( exec_shell_command_async, logger, ) -T = TypeVar("T") - def set_process_name(name: str): libc = ctypes.CDLL("libc.so.6") @@ -85,12 +83,6 @@ def get_wifi_icon_for_strength(strength: int) -> str: def get_wifi_connecting_icon() -> str: - """ - Get the WiFi connecting icon path. - - Returns: - Relative path to the WiFi connecting icon - """ return "wifi/wifi-connecting.svg" diff --git a/src/utils/occlusion.py b/src/utils/occlusion.py index e3d20f2..82efa73 100644 --- a/src/utils/occlusion.py +++ b/src/utils/occlusion.py @@ -1,17 +1,7 @@ from services.modus import ( check_occlusion as _check_occlusion, - get_screen_dimensions as _get_screen_dimensions, - get_active_workspace_id, ) -def get_current_workspace(): - return get_active_workspace_id() - - -def get_screen_dimensions(): - return _get_screen_dimensions() - - def check_occlusion(occlusion_region, workspace=None): return _check_occlusion(occlusion_region, workspace) diff --git a/src/utils/utils.py b/src/utils/utils.py index b90a021..d0cd9f9 100644 --- a/src/utils/utils.py +++ b/src/utils/utils.py @@ -72,21 +72,6 @@ def svg_file(relative_path: str, **kwargs) -> Svg: svg.dynamic_file = _dynamic_file # type: ignore[attr-defined] - # Convenience method to update style and return the same instance - def _dynamic_style( - style: str, - *, - compiled: bool = True, - append: bool = False, - add_brackets: bool = True, - ): - svg.set_style( - style, compiled=compiled, append=append, add_brackets=add_brackets - ) - return svg - - svg.dynamic_style = _dynamic_style # type: ignore[attr-defined] - return svg