refactor: log swallowed exceptions across src/
Replace silent swallow-excepts (pass/return/continue) with logger.warning recording the caught error, preserving behaviour.
This commit is contained in:
49 files changed
+1004
-363
No files matched your search
@@ -135,9 +135,11 @@ class BluetoothDevice(Service):
|
||||
|
||||
try:
|
||||
self._battery_proxy = _make_proxy(bus, object_path, BLUEZ_BATTERY_IFACE)
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# Battery1 is optional — not all devices expose it
|
||||
pass
|
||||
logger.warning(
|
||||
f"[bluetooth] self._battery_proxy = _make_proxy(bus, object_path, BLUEZ... failed: {e}"
|
||||
)
|
||||
|
||||
# Subscribe to Device1 PropertiesChanged
|
||||
self._prop_sub_id = bus.signal_subscribe(
|
||||
@@ -190,7 +192,10 @@ class BluetoothDevice(Service):
|
||||
try:
|
||||
v = self._battery_proxy.get_cached_property(name)
|
||||
return v.unpack() if v else None
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[bluetooth] v = self._battery_proxy.get_cached_property(name) failed: {e}"
|
||||
)
|
||||
return None
|
||||
|
||||
def _on_properties_changed(
|
||||
@@ -466,8 +471,8 @@ class BluetoothAdapter(Service):
|
||||
if handler_id is not None:
|
||||
try:
|
||||
device.disconnect(handler_id)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(f"[bluetooth] device.disconnect(handler_id) failed: {e}")
|
||||
|
||||
self.emit("device-removed", addr)
|
||||
if device.connected:
|
||||
|
||||
@@ -140,8 +140,10 @@ class Brightness(Service):
|
||||
self._brightness_path = base_path / "brightness"
|
||||
self._max_brightness_path = base_path / "max_brightness"
|
||||
return self._screen_device
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[brightness] devices = os.listdir('/sys/class/backlight') failed: {e}"
|
||||
)
|
||||
return ""
|
||||
|
||||
def _detect_ddcutil_bus(self):
|
||||
@@ -152,7 +154,10 @@ class Brightness(Service):
|
||||
match = re.search(r"I2C bus:\s*/dev/i2c-(\d+)", process.stdout)
|
||||
return int(match.group(1)) if match else -1
|
||||
return -1
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[brightness] process = run_command(['ddcutil', 'detect'], timeout=2) failed: {e}"
|
||||
)
|
||||
return -1
|
||||
|
||||
def _read_max_brightness(self):
|
||||
@@ -185,7 +190,10 @@ class Brightness(Service):
|
||||
try:
|
||||
if self._max_brightness_path and self._max_brightness_path.exists():
|
||||
return int(self._max_brightness_path.read_text().strip())
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[brightness] if self._max_brightness_path and self._max_brightness_pat... failed: {e}"
|
||||
)
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
@@ -64,7 +64,10 @@ class CapsLock(Service):
|
||||
if brightness_path.exists():
|
||||
try:
|
||||
return bool(int(brightness_path.read_text().strip()))
|
||||
except (ValueError, OSError):
|
||||
except (ValueError, OSError) as e:
|
||||
logger.warning(
|
||||
f"[capslock] return bool(int(brightness_path.read_text().strip())) failed: {e}"
|
||||
)
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
@@ -94,10 +94,14 @@ class CachedNotification(Service):
|
||||
self.image_file
|
||||
)
|
||||
return self._cached_image_pixbuf
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[custom_notification] self._cached_image_pixbuf = GdkPixbuf.Pixbuf.new_from_fil... failed: {e}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[custom_notification] if self.image_pixmap: self._cached_image_pixbuf = self.im... failed: {e}"
|
||||
)
|
||||
self._cached_image_pixbuf = None
|
||||
return None
|
||||
|
||||
@@ -136,12 +140,16 @@ class CachedNotification(Service):
|
||||
notification_image_cache_key = (
|
||||
get_notification_image_cache_key(self.id, image_pixbuf)
|
||||
)
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# If temp file is gone or any other error, just mark as None
|
||||
pass
|
||||
except Exception:
|
||||
logger.warning(
|
||||
f"[custom_notification] image_pixbuf = getattr(self._notification, 'image_pixbuf'... failed: {e}"
|
||||
)
|
||||
except Exception as e:
|
||||
# If any error occurs during cache key generation, skip it
|
||||
pass
|
||||
logger.warning(
|
||||
f"[custom_notification] if hasattr(self, 'cache_metadata') and self.cache_metadat... failed: {e}"
|
||||
)
|
||||
|
||||
return {
|
||||
"cached-id": self.cache_id,
|
||||
|
||||
+171
-114
@@ -1,17 +1,19 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
import tomlkit
|
||||
from fabric.core.service import Property, Service, Signal
|
||||
from fabric.hyprland.service import Hyprland
|
||||
from fabric.utils import Gio, GLib, logger
|
||||
|
||||
import shared.data as data
|
||||
from services.config import on_config_change
|
||||
from services.config import get_config, on_config_change
|
||||
|
||||
HYPRCTL_BIN = "hyprctl"
|
||||
DEFAULT_LAYOUTS = ["us", "np"]
|
||||
|
||||
|
||||
class KeyboardLayout(Service):
|
||||
"""Service to manage keyboard layout switching and monitoring via Hyprland."""
|
||||
"""In-memory service that treats Hyprland as the source of truth for the
|
||||
active keyboard layout. All runtime state lives in memory; Hyprland is
|
||||
queried/synced via hyprctl and kept in sync through its event socket."""
|
||||
|
||||
_instance = None
|
||||
|
||||
@@ -28,7 +30,7 @@ class KeyboardLayout(Service):
|
||||
|
||||
@Signal
|
||||
def layout_changed(self, layout: str) -> None:
|
||||
"""Signal emitted when keyboard layout changes."""
|
||||
"""Signal emitted when the active keyboard layout changes."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
if getattr(self, "_initialized", False):
|
||||
@@ -36,143 +38,198 @@ class KeyboardLayout(Service):
|
||||
super().__init__(**kwargs)
|
||||
self._initialized = True
|
||||
|
||||
self.layout_state_file = Path(data.CACHE_DIR) / "kb_layout.toml"
|
||||
self.layout_file = Path(data.CACHE_DIR) / "kb_layout_current.txt"
|
||||
self._last_layout = None
|
||||
self.layouts = []
|
||||
self.current_index = 0
|
||||
self._reload_pending = False
|
||||
self._layouts: list[str] = []
|
||||
self._current_index: int = 0
|
||||
self._current_layout: str | None = None
|
||||
self._sync_pending: bool = False
|
||||
|
||||
self._init_layout_config()
|
||||
self._start_file_monitor()
|
||||
|
||||
self._connect_hyprland_events()
|
||||
on_config_change(self._on_config_change)
|
||||
|
||||
def _init_layout_config(self):
|
||||
config_layouts = data.load_config().get("keyboard_layouts", ["us", "np"])
|
||||
state = self._read_state()
|
||||
# ── hyprctl wrapper ────────────────────────────────────────────────────────
|
||||
|
||||
if state:
|
||||
self.layouts = state.get("layouts", config_layouts)
|
||||
self.current_index = state.get("current_index", 0)
|
||||
else:
|
||||
self.layouts = config_layouts
|
||||
self.current_index = 0
|
||||
self._save_state()
|
||||
def _hyprctl(self, *args, on_reply=None):
|
||||
"""Execute a hyprctl command via Gio.Subprocess.
|
||||
|
||||
Every hyprctl invocation goes through here. The call is asynchronous and
|
||||
never blocks the UI. ``on_reply`` (optional) receives the stripped stdout
|
||||
string, or ``None`` on failure.
|
||||
"""
|
||||
argv = [HYPRCTL_BIN, *[str(arg) for arg in args]]
|
||||
try:
|
||||
proc = Gio.Subprocess.new(
|
||||
argv,
|
||||
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE,
|
||||
)
|
||||
except GLib.Error as error:
|
||||
logger.error(f"[KeyboardLayout] Failed to run {argv}: {error}")
|
||||
if on_reply is not None:
|
||||
on_reply(None)
|
||||
return
|
||||
|
||||
def on_done(process: Gio.Subprocess, task: Gio.Task):
|
||||
try:
|
||||
_, stdout, _ = process.communicate_utf8_finish(task)
|
||||
except GLib.Error:
|
||||
stdout = None
|
||||
if on_reply is not None:
|
||||
on_reply(stdout.strip() if stdout else None)
|
||||
|
||||
proc.communicate_utf8_async(None, None, on_done)
|
||||
|
||||
# ── initialization ─────────────────────────────────────────────────────────
|
||||
|
||||
def _init_layout_config(self):
|
||||
self._layouts = self._load_layouts_from_config()
|
||||
|
||||
if not self._layouts:
|
||||
logger.warning("[KeyboardLayout] No keyboard layouts configured.")
|
||||
return
|
||||
|
||||
self._apply_layouts_to_hyprland()
|
||||
self._apply_current_layout_index()
|
||||
self._sync_from_hyprland()
|
||||
|
||||
def _read_state(self):
|
||||
if not self.layout_state_file.exists():
|
||||
return None
|
||||
try:
|
||||
with open(self.layout_state_file) as f:
|
||||
data = tomlkit.load(f)
|
||||
return dict(data) if data else None
|
||||
except Exception as e:
|
||||
logger.error(f"[KeyboardLayout] Failed to read state: {e}")
|
||||
return None
|
||||
if self._current_layout is None:
|
||||
self._set_current(0, emit=False)
|
||||
|
||||
def _save_state(self):
|
||||
try:
|
||||
self.layout_state_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
doc = tomlkit.document()
|
||||
arr = tomlkit.array()
|
||||
for layout in self.layouts:
|
||||
arr.append(layout)
|
||||
doc["layouts"] = arr
|
||||
doc["current_index"] = self.current_index
|
||||
with open(self.layout_state_file, "w") as f:
|
||||
tomlkit.dump(doc, f)
|
||||
except Exception as e:
|
||||
logger.error(f"[KeyboardLayout] Failed to save state: {e}")
|
||||
def _load_layouts_from_config(self) -> list[str]:
|
||||
layouts = get_config("keyboard_layouts", DEFAULT_LAYOUTS)
|
||||
if not isinstance(layouts, list) or not layouts:
|
||||
return list(DEFAULT_LAYOUTS)
|
||||
return [str(layout).strip() for layout in layouts if str(layout).strip()]
|
||||
|
||||
def _on_config_change(self, new_config, old_config):
|
||||
new_layouts = new_config.get("keyboard_layouts")
|
||||
if new_layouts and new_layouts != self.layouts:
|
||||
self.layouts = new_layouts
|
||||
self._save_state()
|
||||
self._apply_layouts_to_hyprland()
|
||||
logger.info(f"[KeyboardLayout] Layouts updated from config: {self.layouts}")
|
||||
# ── Hyprland synchronization ───────────────────────────────────────────────
|
||||
|
||||
def _start_file_monitor(self):
|
||||
if not self.layout_state_file.exists():
|
||||
def _sync_from_hyprland(self):
|
||||
"""Query Hyprland for the current layout and update in-memory state.
|
||||
|
||||
Prefers the ``active_layout_index`` reported by ``hyprctl -j devices``,
|
||||
falling back to index 0 when the information is unavailable.
|
||||
"""
|
||||
if self._sync_pending:
|
||||
return
|
||||
self._sync_pending = True
|
||||
|
||||
def on_reply(stdout: str | None):
|
||||
self._sync_pending = False
|
||||
if not stdout:
|
||||
return
|
||||
try:
|
||||
devices = json.loads(stdout)
|
||||
except json.JSONDecodeError as error:
|
||||
logger.error(f"[KeyboardLayout] Failed to parse devices: {error}")
|
||||
return
|
||||
|
||||
keyboard = self._pick_keyboard(devices.get("keyboards", []))
|
||||
if keyboard is None:
|
||||
return
|
||||
|
||||
index = keyboard.get("active_layout_index", 0)
|
||||
self._set_current(index, emit=True)
|
||||
|
||||
self._hyprctl("-j", "devices", on_reply=on_reply)
|
||||
|
||||
@staticmethod
|
||||
def _pick_keyboard(keyboards: list[dict]) -> dict | None:
|
||||
if not keyboards:
|
||||
return None
|
||||
for kb in keyboards:
|
||||
if kb.get("main"):
|
||||
return kb
|
||||
return keyboards[0]
|
||||
|
||||
def _connect_hyprland_events(self):
|
||||
try:
|
||||
gio_file = Gio.File.new_for_path(str(self.layout_state_file))
|
||||
self._file_monitor = gio_file.monitor_file(Gio.FileMonitorFlags.NONE, None)
|
||||
self._file_monitor.connect("changed", self._on_file_changed)
|
||||
except Exception as e:
|
||||
logger.error(f"[KeyboardLayout] Failed to start file monitor: {e}")
|
||||
Hyprland().connect("event::activelayout", self._on_hyprland_layout_event)
|
||||
except Exception as error:
|
||||
logger.warning(
|
||||
f"[KeyboardLayout] Could not subscribe to Hyprland layout "
|
||||
f"events (external changes won't be tracked): {error}"
|
||||
)
|
||||
|
||||
def _on_file_changed(self, monitor, file, *args):
|
||||
if not self._reload_pending:
|
||||
self._reload_pending = True
|
||||
GLib.timeout_add(50, self._reload_layout)
|
||||
def _on_hyprland_layout_event(self, _hyprland, _event):
|
||||
self._sync_from_hyprland()
|
||||
|
||||
def _reload_layout(self):
|
||||
self._reload_pending = False
|
||||
new_layout = self._read_layout()
|
||||
if new_layout != self._last_layout:
|
||||
self._last_layout = new_layout
|
||||
self.emit("layout_changed", new_layout)
|
||||
return False
|
||||
# ── state management ───────────────────────────────────────────────────────
|
||||
|
||||
def _read_layout(self):
|
||||
state = self._read_state()
|
||||
if state:
|
||||
layouts = state.get("layouts", [])
|
||||
current_index = state.get("current_index", 0)
|
||||
if layouts and 0 <= current_index < len(layouts):
|
||||
return layouts[current_index]
|
||||
return "us"
|
||||
def _set_current(self, index: int, emit: bool) -> bool:
|
||||
if not self._layouts:
|
||||
return False
|
||||
|
||||
def _write_layout(self, layout: str):
|
||||
try:
|
||||
self.layout_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.layout_file.write_text(layout, encoding="utf-8")
|
||||
except Exception as e:
|
||||
logger.error(f"[KeyboardLayout] Failed writing layout state file: {e}")
|
||||
index = max(0, min(index, len(self._layouts) - 1))
|
||||
layout = self._layouts[index]
|
||||
|
||||
if index == self._current_index and layout == self._current_layout:
|
||||
return False
|
||||
|
||||
self._current_index = index
|
||||
self._current_layout = layout
|
||||
self.notify("current_layout", "current_index", "layouts")
|
||||
|
||||
if emit:
|
||||
self.emit("layout_changed", layout)
|
||||
return True
|
||||
|
||||
# ── Hyprland writes ────────────────────────────────────────────────────────
|
||||
|
||||
def _apply_layouts_to_hyprland(self):
|
||||
if not self.layouts:
|
||||
if not self._layouts:
|
||||
return
|
||||
layouts_str = ",".join(self.layouts)
|
||||
layouts_str = ",".join(self._layouts)
|
||||
lua_eval_cmd = f"hl.config({{ input = {{ kb_layout = '{layouts_str}' }} }})"
|
||||
Gio.Subprocess.new(
|
||||
[HYPRCTL_BIN, "eval", lua_eval_cmd],
|
||||
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE,
|
||||
)
|
||||
self._hyprctl("eval", lua_eval_cmd)
|
||||
|
||||
def _apply_current_layout_index(self):
|
||||
Gio.Subprocess.new(
|
||||
[HYPRCTL_BIN, "switchxkblayout", "all", str(self.current_index)],
|
||||
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE,
|
||||
)
|
||||
# ── public API ─────────────────────────────────────────────────────────────
|
||||
|
||||
def switch_to_next(self):
|
||||
if not self.layouts:
|
||||
def switch_to_next(self) -> bool:
|
||||
if not self._layouts:
|
||||
logger.warning("[KeyboardLayout] No layouts configured, cannot cycle.")
|
||||
return False
|
||||
|
||||
self.current_index = (self.current_index + 1) % len(self.layouts)
|
||||
new_layout = self.layouts[self.current_index]
|
||||
|
||||
self._apply_current_layout_index()
|
||||
self._save_state()
|
||||
self._write_layout(new_layout)
|
||||
|
||||
logger.info(
|
||||
f"[KeyboardLayout] Switched layout successfully to '{new_layout}' "
|
||||
f"(index {self.current_index})"
|
||||
)
|
||||
next_index = (self._current_index + 1) % len(self._layouts)
|
||||
self._hyprctl("switchxkblayout", "all", str(next_index))
|
||||
self._set_current(next_index, emit=True)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def switch_keyboard_layout():
|
||||
KeyboardLayout.get_initial().switch_to_next()
|
||||
|
||||
@Property(str, "readable")
|
||||
def current_layout(self):
|
||||
return self._read_layout()
|
||||
# ── config changes ─────────────────────────────────────────────────────────
|
||||
|
||||
def _on_config_change(self, new_config, old_config):
|
||||
new_layouts = new_config.get("keyboard_layouts")
|
||||
if not isinstance(new_layouts, list) or not new_layouts:
|
||||
return
|
||||
new_layouts = [str(item).strip() for item in new_layouts if str(item).strip()]
|
||||
if new_layouts == self._layouts:
|
||||
return
|
||||
|
||||
previous_layout = self._current_layout
|
||||
self._layouts = new_layouts
|
||||
self._apply_layouts_to_hyprland()
|
||||
|
||||
preserved_index = (
|
||||
self._layouts.index(previous_layout)
|
||||
if previous_layout in self._layouts
|
||||
else 0
|
||||
)
|
||||
self._hyprctl("switchxkblayout", "all", str(preserved_index))
|
||||
self._set_current(preserved_index, emit=True)
|
||||
|
||||
logger.info(f"[KeyboardLayout] Layouts updated from config: {self._layouts}")
|
||||
|
||||
# ── properties ─────────────────────────────────────────────────────────────
|
||||
|
||||
@Property(str, "readable", default_value="")
|
||||
def current_layout(self) -> str:
|
||||
return self._current_layout or ""
|
||||
|
||||
@Property(list, "readable")
|
||||
def layouts(self) -> list[str]:
|
||||
return self._layouts
|
||||
|
||||
@Property(int, "readable", default_value=0)
|
||||
def current_index(self) -> int:
|
||||
return self._current_index
|
||||
@@ -438,7 +438,10 @@ def is_night_light_active() -> bool:
|
||||
try:
|
||||
_night_light_active = bool(find_process_pid("hyprsunset"))
|
||||
return _night_light_active
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[modus] _night_light_active = bool(find_process_pid('hyprsunset')) failed: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
@@ -572,7 +575,10 @@ def open_trash():
|
||||
if find_binary(fm):
|
||||
spawn_detached([fm, trash_path])
|
||||
return
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[modus] if find_binary(fm): spawn_detached([fm, trash_path]) return failed: {e}"
|
||||
)
|
||||
continue
|
||||
|
||||
|
||||
|
||||
+34
-10
@@ -81,28 +81,38 @@ class PlayerService(Service):
|
||||
def player_name(self) -> str:
|
||||
try:
|
||||
return self._player.props.player_name or ""
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] return self._player.props.player_name or '' failed: {e}"
|
||||
)
|
||||
return ""
|
||||
|
||||
@Property(str, "readable", default_value="")
|
||||
def title(self) -> str:
|
||||
try:
|
||||
return self._player.get_title() or ""
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(f"[mpris] return self._player.get_title() or '' failed: {e}")
|
||||
return ""
|
||||
|
||||
@Property(object, "readable")
|
||||
def artist(self) -> list:
|
||||
try:
|
||||
return list(self._player.props.metadata["xesam:artist"]) or []
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] return list(self._player.props.metadata['xesam:artist']) ... failed: {e}"
|
||||
)
|
||||
return []
|
||||
|
||||
@Property(str, "readable", default_value="")
|
||||
def album(self) -> str:
|
||||
try:
|
||||
return self._player.props.metadata["xesam:album"] or ""
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] return self._player.props.metadata['xesam:album'] or '' failed: {e}"
|
||||
)
|
||||
return ""
|
||||
|
||||
@Property(str, "readable", default_value="Stopped")
|
||||
@@ -115,21 +125,30 @@ class PlayerService(Service):
|
||||
return "Paused"
|
||||
else:
|
||||
return "Stopped"
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] val = int(self._player.props.playback_status) failed: {e}"
|
||||
)
|
||||
return "Stopped"
|
||||
|
||||
@Property(int, "readable", default_value=0)
|
||||
def length(self) -> int:
|
||||
try:
|
||||
return int(self._player.props.metadata["mpris:length"])
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] return int(self._player.props.metadata['mpris:length']) failed: {e}"
|
||||
)
|
||||
return 0
|
||||
|
||||
@Property(int, "readable", default_value=0)
|
||||
def position(self) -> int:
|
||||
try:
|
||||
return int(self._player.get_position())
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] return int(self._player.get_position()) failed: {e}"
|
||||
)
|
||||
return 0
|
||||
|
||||
def play_pause(self, *_):
|
||||
@@ -206,7 +225,10 @@ class PlayerService(Service):
|
||||
return False
|
||||
try:
|
||||
metadata = self._player.props.metadata
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[mpris] metadata = self._player.props.metadata failed: {e}"
|
||||
)
|
||||
return False
|
||||
if metadata:
|
||||
# Push full metadata only once to avoid UI churn on every retry.
|
||||
@@ -363,7 +385,8 @@ class PlayerService(Service):
|
||||
def _meta_str(self, metadata, key: str) -> str | None:
|
||||
try:
|
||||
value = metadata[key]
|
||||
except (KeyError, TypeError, GLib.Error):
|
||||
except (KeyError, TypeError, GLib.Error) as e:
|
||||
logger.warning(f"[mpris] value = metadata[key] failed: {e}")
|
||||
return None
|
||||
if isinstance(value, (list, tuple)):
|
||||
return " ".join(str(v) for v in value) if value else None
|
||||
@@ -401,7 +424,8 @@ class PlayerService(Service):
|
||||
return
|
||||
try:
|
||||
art_url = metadata["mpris:artUrl"]
|
||||
except (KeyError, TypeError):
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"[mpris] art_url = metadata['mpris:artUrl'] failed: {e}")
|
||||
return
|
||||
if not art_url:
|
||||
return
|
||||
|
||||
+12
-8
@@ -45,18 +45,22 @@ class Wifi(Service):
|
||||
"""Disconnect all signal handlers so the service can be garbage collected."""
|
||||
try:
|
||||
self._client.disconnect(self._client_handler)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[network] self._client.disconnect(self._client_handler) failed: {e}"
|
||||
)
|
||||
for hid in getattr(self, "_device_handlers", ()):
|
||||
try:
|
||||
self._device.disconnect(hid)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(f"[network] self._device.disconnect(hid) failed: {e}")
|
||||
if getattr(self, "_ap", None) and getattr(self, "_ap_signal", None):
|
||||
try:
|
||||
self._ap.disconnect(self._ap_signal)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[network] self._ap.disconnect(self._ap_signal) failed: {e}"
|
||||
)
|
||||
|
||||
def ap_update(self):
|
||||
self.emit("changed")
|
||||
@@ -287,8 +291,8 @@ class Ethernet(Service):
|
||||
for hid in getattr(self, "_handlers", ()):
|
||||
try:
|
||||
self._device.disconnect(hid)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(f"[network] self._device.disconnect(hid) failed: {e}")
|
||||
|
||||
|
||||
class NetworkClient(Service):
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import re
|
||||
|
||||
from fabric.core.service import Property, Service, Signal
|
||||
from fabric.utils import Gio, GLib, logger
|
||||
|
||||
from services.config import get_config, on_config_change
|
||||
|
||||
_CONFIG_KEY = "night_light_temperature"
|
||||
_DEFAULT_TEMPERATURE = 4500
|
||||
_NEUTRAL_TEMPERATURE = 6000
|
||||
_PROFILE_TEMP_RE = re.compile(r"(\d{3,5})")
|
||||
|
||||
|
||||
def _coerce_temperature(value, fallback: int = _DEFAULT_TEMPERATURE) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as e:
|
||||
logger.warning(f"[nightlight] return int(value) failed: {e}")
|
||||
return fallback
|
||||
|
||||
|
||||
class NightLightService(Service):
|
||||
"""Blue-light filter service backed by a persistent hyprsunset daemon.
|
||||
|
||||
All state changes go through ``hyprctl hyprsunset`` IPC so the daemon is
|
||||
started at most once and never respawned on every toggle.
|
||||
"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
@Signal
|
||||
def night_light_changed(self, active: bool) -> None:
|
||||
"""Emitted when the filter is enabled or disabled."""
|
||||
|
||||
@Signal
|
||||
def temperature_changed(self, value: int) -> None:
|
||||
"""Emitted when the color temperature changes."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
if getattr(self, "_initialized", False):
|
||||
return
|
||||
self._initialized = True
|
||||
super().__init__(**kwargs)
|
||||
self._active = False
|
||||
self._temperature = _coerce_temperature(get_config(_CONFIG_KEY))
|
||||
self._process: Gio.Subprocess | None = None
|
||||
self._daemon_running = False
|
||||
on_config_change(self._on_config_change)
|
||||
self._sync_state()
|
||||
|
||||
@Property(bool, "readable", default_value=False)
|
||||
def active(self) -> bool:
|
||||
return self._active
|
||||
|
||||
@Property(int, "readable", default_value=_DEFAULT_TEMPERATURE)
|
||||
def temperature(self) -> int:
|
||||
return self._temperature
|
||||
|
||||
def is_active(self) -> bool:
|
||||
return self._active
|
||||
|
||||
def enable(self):
|
||||
kelvin = self._temperature or _DEFAULT_TEMPERATURE
|
||||
if self._daemon_running:
|
||||
self._hyprctl("temperature", kelvin)
|
||||
else:
|
||||
self._start_daemon(["-t", str(kelvin)])
|
||||
self._set_temperature(kelvin)
|
||||
self._set_active(True)
|
||||
|
||||
def disable(self):
|
||||
if self._daemon_running:
|
||||
self._hyprctl("identity")
|
||||
self._set_active(False)
|
||||
|
||||
def toggle(self) -> bool:
|
||||
if self._active:
|
||||
self.disable()
|
||||
else:
|
||||
self.enable()
|
||||
return self._active
|
||||
|
||||
def set_temperature(self, kelvin: int):
|
||||
self._set_temperature(kelvin)
|
||||
if not self._active:
|
||||
return
|
||||
if self._daemon_running:
|
||||
self._hyprctl("temperature", kelvin)
|
||||
else:
|
||||
self._start_daemon(["-t", str(kelvin)])
|
||||
|
||||
def set_gamma(self, percent: int):
|
||||
if self._daemon_running:
|
||||
self._hyprctl("gamma", percent)
|
||||
else:
|
||||
self._start_daemon(["-g", str(percent)])
|
||||
|
||||
def reset(self):
|
||||
if self._daemon_running:
|
||||
self._hyprctl("reset")
|
||||
self._sync_state()
|
||||
|
||||
def _on_config_change(self, new_config, old_config):
|
||||
if new_config.get(_CONFIG_KEY) == old_config.get(_CONFIG_KEY):
|
||||
return
|
||||
self.set_temperature(_coerce_temperature(new_config.get(_CONFIG_KEY)))
|
||||
|
||||
def _set_active(self, value: bool):
|
||||
if value != self._active:
|
||||
self._active = value
|
||||
self.emit("night_light_changed", value)
|
||||
|
||||
def _set_temperature(self, value: int):
|
||||
if value != self._temperature:
|
||||
self._temperature = value
|
||||
self.emit("temperature_changed", value)
|
||||
|
||||
def _start_daemon(self, args: list[str]):
|
||||
try:
|
||||
self._process = Gio.Subprocess.new(
|
||||
["hyprsunset", *args],
|
||||
Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE,
|
||||
)
|
||||
except GLib.Error as error:
|
||||
logger.error(f"[NightLightService] Failed to start hyprsunset: {error}")
|
||||
self._process = None
|
||||
return
|
||||
self._daemon_running = True
|
||||
self._process.wait_async(None, self._on_daemon_exit)
|
||||
|
||||
def _on_daemon_exit(self, process: Gio.Subprocess, task: Gio.Task):
|
||||
self._process = None
|
||||
self._daemon_running = False
|
||||
self._set_active(False)
|
||||
|
||||
def _hyprctl(self, *args, on_reply=None):
|
||||
argv = ["hyprctl", "hyprsunset", *[str(arg) for arg in args]]
|
||||
try:
|
||||
proc = Gio.Subprocess.new(
|
||||
argv,
|
||||
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE,
|
||||
)
|
||||
except GLib.Error as error:
|
||||
logger.error(f"[NightLightService] Failed to run {argv}: {error}")
|
||||
if on_reply:
|
||||
on_reply(None)
|
||||
return
|
||||
|
||||
def on_done(process: Gio.Subprocess, task: Gio.Task):
|
||||
try:
|
||||
_, stdout, _ = process.communicate_utf8_finish(task)
|
||||
except GLib.Error:
|
||||
stdout = None
|
||||
if on_reply:
|
||||
on_reply(stdout.strip() if stdout else None)
|
||||
|
||||
proc.communicate_utf8_async(None, None, on_done)
|
||||
|
||||
def _sync_state(self):
|
||||
self._hyprctl("profile", on_reply=self._on_profile_reply)
|
||||
|
||||
def _on_profile_reply(self, reply: str | None):
|
||||
if not self._daemon_alive(reply):
|
||||
self._daemon_running = False
|
||||
return
|
||||
self._daemon_running = True
|
||||
temperature = self._parse_temperature(reply)
|
||||
if temperature is not None:
|
||||
self._apply_synced_temperature(temperature)
|
||||
else:
|
||||
self._hyprctl("temperature", on_reply=self._on_temperature_reply)
|
||||
|
||||
def _on_temperature_reply(self, reply: str | None):
|
||||
if reply is None:
|
||||
return
|
||||
temperature = self._parse_temperature(reply)
|
||||
if temperature is not None:
|
||||
self._apply_synced_temperature(temperature)
|
||||
|
||||
def _apply_synced_temperature(self, temperature: int):
|
||||
active = temperature < _NEUTRAL_TEMPERATURE
|
||||
if active:
|
||||
self._set_temperature(temperature)
|
||||
self._set_active(active)
|
||||
|
||||
@staticmethod
|
||||
def _daemon_alive(reply: str | None) -> bool:
|
||||
if reply is None:
|
||||
return False
|
||||
return "couldn't connect" not in reply.lower()
|
||||
|
||||
@staticmethod
|
||||
def _parse_temperature(reply: str | None) -> int | None:
|
||||
if not reply:
|
||||
return None
|
||||
match = _PROFILE_TEMP_RE.search(reply)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def get_night_light_service() -> NightLightService:
|
||||
return NightLightService()
|
||||
@@ -64,7 +64,10 @@ class NumLock(Service):
|
||||
if brightness_path.exists():
|
||||
try:
|
||||
return bool(int(brightness_path.read_text().strip()))
|
||||
except (ValueError, OSError):
|
||||
except (ValueError, OSError) as e:
|
||||
logger.warning(
|
||||
f"[numlock] return bool(int(brightness_path.read_text().strip())) failed: {e}"
|
||||
)
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import mimetypes
|
||||
|
||||
from fabric.core import Service, Signal
|
||||
from fabric.utils import GdkPixbuf as gdk_pixbuf
|
||||
from fabric.utils import exec_shell_command_async, os
|
||||
from fabric.utils import exec_shell_command_async, logger, os
|
||||
|
||||
from shared.data import (
|
||||
WALLPAPER_PATH,
|
||||
@@ -44,7 +44,10 @@ def create_thumbnail(
|
||||
)
|
||||
)
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[wallpaper] pixbuf = gdk_pixbuf.Pixbuf.new_from_file_at_scale( image_... failed: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user