feat(root): add keyboard layouts, OSDWindow, and update services & utilities

Introduce a new OSDWindow implementation, expose keyboard layout configuration, and modernize dependency handling and helper utilities.

- **New Features**
  - Added `keyboard_layouts` list (`us`, `np`) to `config.json`
  - Created `OSDWindow` class and updated `main.py` to use it
  - Introduced new service modules (`battery`, `brightness`, `capslock`, `network`, `mpris`, `todo`, `modus`) and expanded `services/__init__.py`
  - Added `CommandResult` and `run_command` helper in `utils/functions.py`

- **Enhancements**
  - Upgraded numerous dependencies to newer versions and switched `fabric` to a git source
  - Replaced bare `except:` with `except Exception:` in `WiFiPasswordDialog`
  - Improved type hints (`NamedTuple`, `TypeVar`) and refactored JSON file helpers
  - Added property notifications for battery percentage, state, and presence

- **Bug Fixes**
  - Fixed incorrect return type annotation in `read_json_file`
  - Corrected tick‑handler logic to avoid double registration
  - Properly notify listeners on battery property changes
  - Ensured proper exception handling and cleanup in utility functions
This commit is contained in:
sankalp committed 2026-03-23 23:33:53 +05:45
1 parent 129906cb9c
commit 34cfb2f49e
12 files changed
+504 -96

No files matched your search

+142 -59
View File
@@ -1,21 +1,108 @@
from typing import cast
# Author: Yousef EL-Darsh
# License (SPDX): AGPL-3.0-or-later
from gi.repository import GLib, Gtk
from functools import cache
from typing import Protocol, cast
from fabric import Property, Service, Signal
from fabric.core.service import Property, Service, Signal
from fabric.utils import GLib, Gtk, clamp
@cache
def lerp(start: float, end: float, progress: float) -> float:
return start + (end - start) * progress
@cache
def steps(n: int, progress: float, start_jump: bool = False) -> float:
if start_jump:
return min(int(progress * n), n - 1) / (n - 1) if n > 1 else 0.0
return min(int(progress * n + 1e-10), n) / n
@cache
def cubic_bezier(
x1: float, y1: float, x2: float, y2: float, progress: float, epsilon=1e-6
) -> float:
# implementation yanked off of the internet, don't blame me about anything.
# Fast-path boundaries to avoid overshoot and unnecessary work
if progress <= 0.0 or progress >= 1.0:
return clamp(progress, 0.0, 1.0)
t_guess = progress
for _ in range(8):
t = t_guess
t_sq = t * t
omt = 1.0 - t
omt_sq = omt * omt
x = 3 * x1 * omt_sq * t + 3 * x2 * omt * t_sq + t * t_sq
dx = 3 * x1 * omt_sq + 6 * (x2 - x1) * omt * t + 3 * (1 - x2) * t_sq
if abs(dx) < epsilon:
break
delta = (x - progress) / dx
t_guess -= delta
t_guess = clamp(t_guess, 0.0, 1.0)
if abs(delta) < epsilon:
break
t = clamp(t_guess, 0.0, 1.0)
t_sq = t * t
omt = 1.0 - t
return 3 * y1 * omt * omt * t + 3 * y2 * omt * t_sq + t * t_sq
def ease_linear(progress: float) -> float:
return cubic_bezier(1, 1, 0, 0, progress)
def ease_in(progress: float) -> float:
return cubic_bezier(0.4, 0, 1, 1, progress)
def ease_out(progress: float) -> float:
return cubic_bezier(0, 0, 0.2, 1, progress)
def ease_in_out(progress: float) -> float:
return cubic_bezier(0.4, 0, 0.2, 1, progress)
class TimingFunctionCallback(Protocol):
def __call__(self, progress: float, *args, **kwargs) -> float: ...
class Animator(Service):
"""
An animator is a simple way for animating a value on
a set timeline based on a given timing function
"""
@Signal
def finished(self) -> None: ...
@Property(tuple[float, float, float, float], "read-write")
def bezier_curve(self) -> tuple[float, float, float, float]:
return self._bezier_curve
@Property(TimingFunctionCallback, "read-write")
def timing_function(self) -> TimingFunctionCallback:
return self._timing_function
@bezier_curve.setter
def bezier_curve(self, value: tuple[float, float, float, float]):
self._bezier_curve = value
@timing_function.setter
def timing_function(self, value: TimingFunctionCallback):
self._timing_function = value
return
@Property(float, "read-write")
def duration(self):
return self._duration
@duration.setter
def duration(self, value: float):
if value <= 0.0:
raise ValueError("duration can't be smaller than or equal to 0.0")
self._duration = value
return
@Property(float, "read-write")
@@ -50,7 +137,7 @@ class Animator(Service):
return self._playing
@playing.setter
def playing(self, value: bool):
def playing(self, value: bool): # this setter is intended for internal usage only
self._playing = value
return
@@ -65,76 +152,68 @@ class Animator(Service):
def __init__(
self,
bezier_curve: tuple[float, float, float, float],
duration: float,
duration: float = 0.8,
timing_function: TimingFunctionCallback = ease_linear,
value: float = 0.0,
min_value: float = 0.0,
max_value: float = 1.0,
repeat: bool = False,
tick_widget: Gtk.Widget | None = None,
tick_interval: int = 16,
**kwargs,
):
super().__init__(**kwargs)
self._bezier_curve = (1, 0, 1, 1)
self._duration = 5
self._value = 0.0
self._playing = False
self._value = value
self._min_value = 0.0
self._max_value = 1.0
self._repeat = False
self._duration = 0.8
self._timing_function = timing_function
self._tick_widget = tick_widget
self._tick_interval = tick_interval
self.bezier_curve = bezier_curve
self.timing_function = timing_function
self.repeat = repeat
self.duration = duration
self.value = min_value
self.min_value = min_value
self.max_value = max_value
self.repeat = repeat
self.value = value
self.playing = False
self._start_time = None
self._tick_handler = None
self._timeline_pos = 0
self._tick_widget = tick_widget
self._timeline_pos = 0.0
def do_get_time_now(self):
return GLib.get_monotonic_time() / 1_000_000
def do_lerp(self, start: float, end: float, time: float) -> float:
return start + (end - start) * time
def do_interpolate_cubic_bezier(self, time: float) -> float:
y_points = (0, self.bezier_curve[1], self.bezier_curve[3], 1)
return (
(1 - time) ** 3 * y_points[0]
+ 3 * (1 - time) ** 2 * time * y_points[1]
+ 3 * (1 - time) * time**2 * y_points[2]
+ time**3 * y_points[3]
)
def do_ease(self, time: float) -> float:
return self.do_lerp(
self.min_value, self.max_value, self.do_interpolate_cubic_bezier(time)
)
def do_update_value(self, delta_time: float):
if not self.playing:
if not self._playing:
return
elapsed_time = delta_time - cast(float, self._start_time)
self._timeline_pos = min(1, elapsed_time / self.duration)
self._timeline_pos = min(1.0, elapsed_time / self._duration)
self.value = self.do_ease(self._timeline_pos)
self.value = lerp(
self._min_value,
self._max_value,
self._timing_function(progress=self._timeline_pos),
)
if not self._timeline_pos >= 1:
if not self._timeline_pos >= 1.0:
return
if not self.repeat:
self.value = self.max_value
if not self._repeat:
# all done..
self.value = self._max_value
self.finished()
self.pause()
return
self._start_time = delta_time
self._timeline_pos = 0
self._timeline_pos = 0.0
return
def do_handle_tick(self, *_):
@@ -143,29 +222,33 @@ class Animator(Service):
return True
def do_remove_tick_handlers(self):
if self._tick_handler:
if self._tick_widget:
self._tick_widget.remove_tick_callback(self._tick_handler)
else:
GLib.source_remove(self._tick_handler)
if not self._tick_handler:
return
if self._tick_widget:
self._tick_widget.remove_tick_callback(self._tick_handler)
else:
GLib.source_remove(self._tick_handler)
self._tick_handler = None
return
def play(self):
if self.playing:
if self._playing:
return
self.playing = True
self._start_time = self.do_get_time_now()
if not self._tick_handler:
if self._tick_widget:
self._tick_handler = self._tick_widget.add_tick_callback(
self.do_handle_tick
)
else:
self._tick_handler = GLib.timeout_add(16, self.do_handle_tick)
if self._tick_handler:
return
self.playing = True
if self._tick_widget:
self._tick_handler = self._tick_widget.add_tick_callback(
self.do_handle_tick
)
return
self._tick_handler = GLib.timeout_add(self._tick_interval, self.do_handle_tick)
return
def pause(self):
+47 -4
View File
@@ -4,9 +4,15 @@ import json
import os
import subprocess
import threading
from typing import Dict, List, Optional
from typing import Dict, NamedTuple, Optional, TypeVar
from fabric.utils import exec_shell_command, exec_shell_command_async, logger
from fabric.utils import (
exec_shell_command,
exec_shell_command_async,
logger,
)
T = TypeVar("T")
def set_process_name(name: str):
@@ -66,7 +72,6 @@ def run_in_thread(func):
return wrapper
# @run_in_thread
def write_json_file(data: Dict, path: str):
try:
with open(path, "w") as f:
@@ -75,7 +80,7 @@ def write_json_file(data: Dict, path: str):
logger.warning(f"Failed to write json: {e}")
def read_json_file(file_path: str) -> Optional[List]:
def read_json_file(file_path: str) -> Optional[Dict]:
if not os.path.exists(file_path):
logger.error(f"JSON file {file_path} does not exist.")
return None
@@ -253,3 +258,41 @@ def clear_children(container) -> None:
child.destroy()
except Exception as e:
logger.warning(f"clear_children failed: {e}")
class CommandResult(NamedTuple):
returncode: int
stdout: bytes | str
stderr: bytes | str
def run_command(
args: list[str],
timeout: float | None = None,
cwd: Optional[str] = None,
env: Optional[Dict[str, str]] = None,
*,
input: bytes | str | None = None,
text: bool = True,
) -> CommandResult:
try:
result = subprocess.run(
args,
capture_output=True,
text=text,
timeout=timeout,
cwd=cwd,
env=env,
input=input,
)
return CommandResult(result.returncode, result.stdout, result.stderr)
except subprocess.TimeoutExpired as e:
return CommandResult(
-1,
(e.stdout or b"" if not text else e.stdout or ""),
(e.stderr or (b"timeout" if not text else "timeout")),
)
except FileNotFoundError as e:
return CommandResult(127, "", str(e))
except Exception as e:
return CommandResult(1, "", str(e))
+3 -3
View File
@@ -5,10 +5,10 @@ import re
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk
from loguru import logger
from gi.repository import GLib, Gtk # noqa: E402
from loguru import logger # noqa: E402
import config.data as data
import config.data as data # noqa: E402
ICON_CACHE_FILE = data.CACHE_DIR + "/icons.json"
if not os.path.exists(data.CACHE_DIR):