feat(utils): add dbus helper and extend utility functions
The changes introduce a new GioDBusHelper class for D-Bus interactions and expand utils/functions.py with utilities for timeout parsing, cursor hover handling, animated scale widgets, and SVG loading, improving functionality and maintainability. - New Features - Add GioDBusHelper for method calls and signal subscription. - Enhancements - Add parse_timeout_string and replace placeholder set_process_name implementation. - Implement AnimatedScale widget and related utilities. - Provide svg_file helper with dynamic style updates. - Bug Fixes - None
This commit is contained in:
6 files changed
+461
-30
No files matched your search
+117
-23
@@ -1,21 +1,50 @@
|
||||
import ctypes
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from fabric.utils import logger, os
|
||||
from fabric.utils import exec_shell_command, exec_shell_command_async, logger
|
||||
|
||||
|
||||
# Function to set the process name
|
||||
def set_process_name(name: str):
|
||||
libc = ctypes.CDLL("libc.so.6")
|
||||
libc.prctl(15, name.encode("utf-8"), 0, 0, 0)
|
||||
libc.prctl(15, name.encode("utf-8"), 0, 0, 0) # 15 = PR_SET_NAME
|
||||
|
||||
|
||||
def parse_timeout_string(timeout_str):
|
||||
"""
|
||||
Parse timeout string in format like '5s', '10m', '30s' etc.
|
||||
Returns timeout in milliseconds.
|
||||
"""
|
||||
if not timeout_str or not isinstance(timeout_str, str):
|
||||
return 5000
|
||||
|
||||
timeout_str = timeout_str.strip().lower()
|
||||
|
||||
if timeout_str.endswith("s"):
|
||||
try:
|
||||
seconds = int(timeout_str[:-1])
|
||||
return seconds * 1000
|
||||
except ValueError:
|
||||
return 5000
|
||||
elif timeout_str.endswith("m"):
|
||||
try:
|
||||
minutes = int(timeout_str[:-1])
|
||||
return minutes * 60 * 1000
|
||||
except ValueError:
|
||||
return 5000
|
||||
else:
|
||||
try:
|
||||
seconds = int(timeout_str)
|
||||
return seconds * 1000
|
||||
except ValueError:
|
||||
return 5000
|
||||
|
||||
|
||||
# Threading helper functions
|
||||
|
||||
|
||||
def thread(target, *args, **kwargs) -> threading.Thread:
|
||||
"""
|
||||
Simply run the given function in a thread.
|
||||
@@ -37,7 +66,7 @@ def run_in_thread(func):
|
||||
return wrapper
|
||||
|
||||
|
||||
@run_in_thread
|
||||
# @run_in_thread
|
||||
def write_json_file(data: Dict, path: str):
|
||||
try:
|
||||
with open(path, "w") as f:
|
||||
@@ -87,7 +116,7 @@ def get_wifi_icon_for_strength(strength: int) -> str:
|
||||
else:
|
||||
icon_name = "network-wireless-0.svg"
|
||||
|
||||
return os.path.join(project_root, "config", "assets", "icons", "wifi", icon_name)
|
||||
return os.path.join(project_root, "assets", "icons", "wifi", icon_name)
|
||||
|
||||
|
||||
def get_wifi_connecting_icon() -> str:
|
||||
@@ -107,8 +136,16 @@ def get_wifi_connecting_icon() -> str:
|
||||
)
|
||||
|
||||
|
||||
# Function to check if a workspace ID is special
|
||||
def is_special_workspace_id(ws_id) -> bool:
|
||||
"""
|
||||
Check if a workspace ID represents a special workspace.
|
||||
|
||||
Args:
|
||||
ws_id: Workspace ID (can be int, string, or other types)
|
||||
|
||||
Returns:
|
||||
True if the workspace is special, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Convert to int if it's a string
|
||||
workspace_id = int(ws_id)
|
||||
@@ -121,8 +158,16 @@ def is_special_workspace_id(ws_id) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Function to check if a client is on a special workspace
|
||||
def is_special_workspace(client: dict) -> bool:
|
||||
"""
|
||||
Check if a client is in a special workspace.
|
||||
|
||||
Args:
|
||||
client: Client data dictionary from Hyprland
|
||||
|
||||
Returns:
|
||||
True if the client is in a special workspace, False otherwise
|
||||
"""
|
||||
if "workspace" not in client:
|
||||
return False
|
||||
|
||||
@@ -130,32 +175,81 @@ def is_special_workspace(client: dict) -> bool:
|
||||
|
||||
# Check workspace name first
|
||||
if "name" in workspace:
|
||||
workspace_name = workspace["name"]
|
||||
if is_special_workspace_id(workspace_name):
|
||||
workspace_name = str(workspace["name"])
|
||||
# Special workspaces typically start with "special:" or have negative IDs
|
||||
if workspace_name.startswith("special:"):
|
||||
return True
|
||||
|
||||
# Check workspace ID
|
||||
if "id" in workspace:
|
||||
workspace_id = workspace["id"]
|
||||
if is_special_workspace_id(workspace_id):
|
||||
# Special workspaces have negative IDs
|
||||
if workspace_id < 0:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def escape_markup_text(text: str) -> str:
|
||||
return html.escape(text.replace("\n", " "))
|
||||
|
||||
|
||||
# Function to toggle a shell command
|
||||
def toggle_command(command: str, full_command: str):
|
||||
if is_app_running(command):
|
||||
kill_process(command)
|
||||
else:
|
||||
subprocess.Popen(
|
||||
full_command.split(" "),
|
||||
stdin=subprocess.DEVNULL, # No input stream
|
||||
stdout=subprocess.DEVNULL, # Optionally discard the output
|
||||
stderr=subprocess.DEVNULL, # Optionally discard the error output
|
||||
start_new_session=True, # This prevents the process from being killed
|
||||
)
|
||||
|
||||
|
||||
# Function to execute a shell command asynchronously
|
||||
def kill_process(process_name: str):
|
||||
exec_shell_command_async(f"pkill {process_name}", lambda *_: None)
|
||||
|
||||
|
||||
# Function to check if an app is running
|
||||
def is_app_running(app_name: str) -> bool:
|
||||
return len(exec_shell_command(f"pidof {app_name}")) != 0
|
||||
|
||||
|
||||
# General utilities
|
||||
def format_duration(seconds: int) -> str:
|
||||
"""
|
||||
Escape special characters in text to make it safe for Pango markup.
|
||||
Convert a duration in seconds to a compact human-friendly string.
|
||||
|
||||
Args:
|
||||
text: Raw text that may contain special characters
|
||||
|
||||
Returns:
|
||||
Escaped text safe for use in Pango markup
|
||||
Examples:
|
||||
0 -> "N/A"
|
||||
59 -> "0m"
|
||||
61 -> "1m"
|
||||
3600 -> "1h 0m"
|
||||
"""
|
||||
if not text or not isinstance(text, str):
|
||||
return ""
|
||||
try:
|
||||
total = int(seconds)
|
||||
except (TypeError, ValueError):
|
||||
return "N/A"
|
||||
|
||||
# Use html.escape to escape XML/HTML special characters
|
||||
# This handles &, <, >, and quotes
|
||||
return html.escape(text)
|
||||
if total <= 0:
|
||||
return "N/A"
|
||||
|
||||
hours = total // 3600
|
||||
minutes = (total % 3600) // 60
|
||||
if hours > 0:
|
||||
return f"{hours}h {minutes}m"
|
||||
return f"{minutes}m"
|
||||
|
||||
|
||||
def clear_children(container) -> None:
|
||||
"""
|
||||
Destroy all children of a GTK container-like widget which exposes get_children().
|
||||
"""
|
||||
try:
|
||||
for child in list(container.get_children()):
|
||||
child.destroy()
|
||||
except Exception as e:
|
||||
logger.warning(f"clear_children failed: {e}")
|
||||
Reference in new issue
Block a user