This commit is contained in:
sankalp committed 2025-06-26 16:10:17 +05:45
1 parent d684916f14
commit 96434bd036
55 files changed
+724 -543

No files matched your search

-1
View File
@@ -1,6 +1,5 @@
from typing import cast
import fabric
from fabric import Property, Service, Signal
from gi.repository import GLib, Gtk
+25 -7
View File
@@ -16,12 +16,14 @@ from loguru import logger
def get_bars(file_path):
config = configparser.ConfigParser()
config.read(file_path)
return int(config['general']['bars'])
return int(config["general"]["bars"])
CAVA_CONFIG = get_relative_path("../config/cavalcade/cava.ini")
bars = get_bars(CAVA_CONFIG)
def set_death_signal():
"""
Set the death signal of the child process to SIGTERM so that if the parent
@@ -31,11 +33,13 @@ def set_death_signal():
PR_SET_PDEATHSIG = 1
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM)
class Cava:
"""
CAVA wrapper.
Launch cava process with certain settings and read output.
"""
NONE = 0
RUNNING = 1
RESTARTING = 2
@@ -54,7 +58,9 @@ class Cava:
self.env["LC_ALL"] = "en_US.UTF-8" # not sure if it's necessary
is_16bit = True
self.byte_type, self.byte_size, self.byte_norm = ("H", 2, 65535) if is_16bit else ("B", 1, 255)
self.byte_type, self.byte_size, self.byte_norm = (
("H", 2, 65535) if is_16bit else ("B", 1, 255)
)
if not os.path.exists(self.path):
os.mkfifo(self.path)
@@ -71,7 +77,8 @@ class Cava:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=self.env,
preexec_fn=set_death_signal # Ensure cava gets killed when the parent dies.
# Ensure cava gets killed when the parent dies.
preexec_fn=set_death_signal,
)
logger.debug("cava successfully launched!")
self.state = self.RUNNING
@@ -84,13 +91,15 @@ class Cava:
self.fifo_fd = os.open(self.path, os.O_RDONLY | os.O_NONBLOCK)
# Open dummy write end to prevent getting an EOF on our FIFO
self.fifo_dummy_fd = os.open(self.path, os.O_WRONLY | os.O_NONBLOCK)
self.io_watch_id = GLib.io_add_watch(self.fifo_fd, GLib.IO_IN, self._io_callback)
self.io_watch_id = GLib.io_add_watch(
self.fifo_fd, GLib.IO_IN, self._io_callback
)
def _io_callback(self, source, condition):
chunk = self.byte_size * self.bars # number of bytes for given format
try:
data = os.read(self.fifo_fd, chunk)
except OSError as e:
except OSError:
# logger.error("Error reading FIFO: {}".format(e))
return False
@@ -145,16 +154,20 @@ class Cava:
if os.path.exists(self.path):
os.remove(self.path)
class AttributeDict(dict):
"""Dictionary with keys as attributes. Does nothing but easy reading"""
def __getattr__(self, attr):
return self.get(attr, 3)
def __setattr__(self, attr, value):
self[attr] = value
class Spectrum:
"""Spectrum drawing"""
def __init__(self):
self.silence_value = 0
self.audio_sample = []
@@ -242,6 +255,7 @@ class Spectrum:
blue = int(color[5:7], 16) / 255
self.color = Gdk.RGBA(red=red, green=green, blue=blue, alpha=1.0)
class SpectrumRender:
def __init__(self, mode=None, **kwargs):
self.mode = mode
@@ -252,7 +266,7 @@ class SpectrumRender:
def get_spectrum_box(self):
# Get the spectrum box
box = Overlay(name="cavalcade", h_align='center', v_align='center')
box = Overlay(name="cavalcade", h_align="center", v_align="center")
box.set_size_request(90, 34) # Better size for music player
box.add_overlay(self.draw.area)
box.show_all() # Ensure everything is visible
@@ -264,6 +278,7 @@ class AudioVisualizer(Overlay):
Simple AudioVisualizer wrapper around existing spectrum components
for compatibility with the music player component.
"""
def __init__(self, name=None, width=150, height=24, bars=20, **kwargs):
super().__init__(name=name, **kwargs)
@@ -291,7 +306,10 @@ class AudioVisualizer(Overlay):
super().set_visible(visible)
if visible and self.is_playing:
# Ensure spectrum is active when visible and playing
if hasattr(self.spectrum_render, 'cava') and self.spectrum_render.cava.state == 0: # NONE
if (
hasattr(self.spectrum_render, "cava")
and self.spectrum_render.cava.state == 0
): # NONE
self.spectrum_render.cava.start()
elif not visible:
# Optionally pause spectrum when not visible to save resources
+67 -30
View File
@@ -1,19 +1,23 @@
import requests
import time
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, Optional, Tuple
import requests
class CurrencyCache:
"""Thread-safe currency exchange rate cache with background updates."""
def __init__(self):
self._cache: Dict[str, Dict] = {} # {base_currency: {rates_data, timestamp}}
# {base_currency: {rates_data, timestamp}}
self._cache: Dict[str, Dict] = {}
self._cache_lock = threading.Lock()
self._cache_ttl = 3600 # 1 hour in seconds
self._request_timeout = 2 # 2 seconds for faster response
self._executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="currency")
self._executor = ThreadPoolExecutor(
max_workers=2, thread_name_prefix="currency"
)
self._pending_requests: Dict[str, threading.Event] = {}
def get_rate(self, from_code: str, to_code: str) -> Optional[Tuple[float, float]]:
@@ -33,19 +37,22 @@ class CurrencyCache:
# Check if we have fresh cached data
if from_lower in self._cache:
cache_entry = self._cache[from_lower]
cache_age = current_time - cache_entry['timestamp']
cache_age = current_time - cache_entry["timestamp"]
if cache_age < self._cache_ttl and to_lower in cache_entry['rates']:
rate = cache_entry['rates'][to_lower]['rate']
if cache_age < self._cache_ttl and to_lower in cache_entry["rates"]:
rate = cache_entry["rates"][to_lower]["rate"]
return rate, cache_age
# Check if we're already fetching this currency
if from_lower in self._pending_requests:
# Don't wait, return cached data if available (even if stale)
if from_lower in self._cache and to_lower in self._cache[from_lower]['rates']:
if (
from_lower in self._cache
and to_lower in self._cache[from_lower]["rates"]
):
cache_entry = self._cache[from_lower]
cache_age = current_time - cache_entry['timestamp']
rate = cache_entry['rates'][to_lower]['rate']
cache_age = current_time - cache_entry["timestamp"]
rate = cache_entry["rates"][to_lower]["rate"]
return rate, cache_age
return None
@@ -57,10 +64,13 @@ class CurrencyCache:
# Return stale cached data if available
with self._cache_lock:
if from_lower in self._cache and to_lower in self._cache[from_lower]['rates']:
if (
from_lower in self._cache
and to_lower in self._cache[from_lower]["rates"]
):
cache_entry = self._cache[from_lower]
cache_age = current_time - cache_entry['timestamp']
rate = cache_entry['rates'][to_lower]['rate']
cache_age = current_time - cache_entry["timestamp"]
rate = cache_entry["rates"][to_lower]["rate"]
return rate, cache_age
return None
@@ -77,8 +87,8 @@ class CurrencyCache:
with self._cache_lock:
self._cache[from_code] = {
'rates': rates_data,
'timestamp': current_time
"rates": rates_data,
"timestamp": current_time,
}
except Exception as e:
@@ -102,7 +112,7 @@ class CurrencyCache:
_currency_cache = CurrencyCache()
class Units():
class Units:
def __init__(self):
self.WEIGHT_CHART: dict[str, tuple[float, float]] = {
"kilogram": (1, 1),
@@ -198,12 +208,18 @@ class Units():
self.TEMPERATURE_CHART = {
"celsius": (lambda v: v + 273.15, lambda v: v - 273.15),
"c": (lambda v: v + 273.15, lambda v: v - 273.15),
"fahrenheit": (lambda v: (v - 32) * 5/9 + 273.15, lambda v: (v - 273.15) * 9/5 + 32),
"f": (lambda v: (v - 32) * 5/9 + 273.15, lambda v: (v - 273.15) * 9/5 + 32),
"fahrenheit": (
lambda v: (v - 32) * 5 / 9 + 273.15,
lambda v: (v - 273.15) * 9 / 5 + 32,
),
"f": (
lambda v: (v - 32) * 5 / 9 + 273.15,
lambda v: (v - 273.15) * 9 / 5 + 32,
),
"kelvin": (lambda v: v, lambda v: v),
"k": (lambda v: v, lambda v: v),
"rankine": (lambda v: v * 5/9, lambda v: v * 9/5),
"reaumur": (lambda v: v * 5/4 + 273.15, lambda v: (v - 273.15) * 4/5),
"rankine": (lambda v: v * 5 / 9, lambda v: v * 9 / 5),
"reaumur": (lambda v: v * 5 / 4 + 273.15, lambda v: (v - 273.15) * 4 / 5),
}
self.TIME_CHART: dict[str, float] = {
@@ -404,7 +420,7 @@ class Units():
# We no longer use currency_converter here.
class Conversion():
class Conversion:
def __init__(self):
self.units = Units()
self.currency_cache = _currency_cache
@@ -464,7 +480,12 @@ class Conversion():
# 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():
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
@@ -474,7 +495,9 @@ class Conversion():
# 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]:
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.
@@ -485,7 +508,9 @@ class Conversion():
return value * rate
return None
def _convert_currency_via_floatrates(self, value: float, from_code: str, to_code: str) -> float:
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
@@ -504,7 +529,11 @@ class Conversion():
data = resp.json()
if to_lower not in data:
raise ValueError(f"Target currency '{to_code}' not found in floatrates response for '{from_code}'")
raise ValueError(
f"Target currency '{to_code}' not found in floatrates response for '{
from_code
}'"
)
rate = data[to_lower]["rate"]
return value * rate
@@ -516,7 +545,9 @@ class Conversion():
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'")
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)
@@ -525,7 +556,9 @@ class Conversion():
to_type = self.clean_type(to_type)
if from_type1 == from_type2:
return self.convert(value1 + value2, from_type1, to_type), to_type + addition
return self.convert(
value1 + value2, from_type1, to_type
), to_type + addition
else:
res = 0
res += self.convert(value1, from_type1, to_type)
@@ -533,7 +566,9 @@ class Conversion():
return res, to_type + addition
else:
if len(parts) != 4:
raise ValueError("Invalid format. Expected: 'value from_type _ to_type'")
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)
@@ -544,7 +579,7 @@ class Conversion():
"""
If it's currency (3 letters), convert to uppercase.
If it ends in 's' (and is not 'celsius'), remove the 's' for
other units. """
other units."""
if len(type) == 3 and type.isalpha():
return type.upper()
if type.endswith("s") and type.lower() != "celsius":
@@ -561,7 +596,9 @@ class Conversion():
"""Cleanup resources."""
self.currency_cache.cleanup()
def get_currency_cache_info(self, from_code: str, to_code: str) -> Optional[Tuple[bool, float]]:
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.
+1 -2
View File
@@ -2,9 +2,8 @@ import math
from typing import cast
import cairo
from gi.repository import Gtk
from fabric.widgets.image import Image
from gi.repository import Gtk
class CustomImage(Image):
+26 -16
View File
@@ -1,19 +1,19 @@
# From https://github.com/stwa/wayland-idle-inhibitor
# License: WTFPL Version 2
import sys
import os
import time
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
from signal import SIGINT, SIGTERM, signal
from threading import Event, Timer
import setproctitle
from pywayland.client.display import Display
from pywayland.protocol.idle_inhibit_unstable_v1.zwp_idle_inhibit_manager_v1 import \
ZwpIdleInhibitManagerV1
from pywayland.protocol.idle_inhibit_unstable_v1.zwp_idle_inhibit_manager_v1 import (
ZwpIdleInhibitManagerV1,
)
from pywayland.protocol.wayland.wl_compositor import WlCompositor
from pywayland.protocol.wayland.wl_registry import WlRegistryProxy
from pywayland.protocol.wayland.wl_surface import WlSurface
@@ -30,18 +30,20 @@ def parse_duration(duration_str: str) -> int:
Examples: '1h', '30m', '45s', '1.5h', '1.5m', '30.5s', 'on', 'off'
"""
try:
if duration_str.lower() in ['on', 'off']:
if duration_str.lower() in ["on", "off"]:
return 0
elif duration_str.endswith('h'):
elif duration_str.endswith("h"):
return int(float(duration_str[:-1]) * 3600)
elif duration_str.endswith('m'):
elif duration_str.endswith("m"):
return int(float(duration_str[:-1]) * 60)
elif duration_str.endswith('s'):
elif duration_str.endswith("s"):
return int(float(duration_str[:-1]))
else:
return int(duration_str)
except ValueError:
raise ValueError("Invalid duration format. Use '1h', '30m', '45s', 'on', 'off', etc.")
raise ValueError(
"Invalid duration format. Use '1h', '30m', '45s', 'on', 'off', etc."
)
def kill_existing_inhibit_processes():
@@ -49,7 +51,7 @@ def kill_existing_inhibit_processes():
try:
# Find all modus-inhibit processes except the current one
output = subprocess.check_output(["pgrep", "-f", "modus-inhibit"], text=True)
pids = output.strip().split('\n')
pids = output.strip().split("\n")
current_pid = str(os.getpid())
killed_count = 0
@@ -92,13 +94,19 @@ def handle_registry_global(
def main() -> None:
parser = argparse.ArgumentParser(description='Inhibit system idle for a specified duration')
parser.add_argument('duration', nargs='?', default='0',
help='Duration to inhibit (e.g., "1h", "30m", "45s", "on", "off"). Use "on" for indefinite, "off" to stop.')
parser = argparse.ArgumentParser(
description="Inhibit system idle for a specified duration"
)
parser.add_argument(
"duration",
nargs="?",
default="0",
help='Duration to inhibit (e.g., "1h", "30m", "45s", "on", "off"). Use "on" for indefinite, "off" to stop.',
)
args = parser.parse_args()
# Handle "off" argument - kill existing processes and exit
if args.duration.lower() == 'off':
if args.duration.lower() == "off":
kill_existing_inhibit_processes()
sys.exit(0)
@@ -132,7 +140,9 @@ def main() -> None:
if global_registry.inhibit_manager is None:
print("Error: Your Wayland compositor does not support idle inhibition.")
print("This usually means either:")
print("1. Your compositor (like Hyprland) doesn't support the idle-inhibit protocol")
print(
"1. Your compositor (like Hyprland) doesn't support the idle-inhibit protocol"
)
print("2. The protocol is not enabled in your compositor")
print("\nFor Hyprland, you can enable it by adding to your config:")
print("misc:disable_autoreload = true")
+25 -22
View File
@@ -1,61 +1,64 @@
import subprocess
import json
import subprocess
import config.data as data
def get_current_workspace():
"""
Get the current workspace ID using hyprctl.
"""
try:
result = subprocess.run(
["hyprctl", "activeworkspace"],
capture_output=True,
text=True
["hyprctl", "activeworkspace"], capture_output=True, text=True
)
# Assume the output similar to: "ID <number>"
# Extracting the number from the output
parts = result.stdout.split()
for i, part in enumerate(parts):
if part == "ID" and i + 1 < len(parts):
return int(parts[i+1])
return int(parts[i + 1])
except Exception as e:
print(f"Error getting current workspace: {e}")
return -1
def get_screen_dimensions():
"""
Get screen dimensions from hyprctl.
Returns:
tuple: (width, height) of the monitor containing the current workspace
"""
try:
# Get current workspace
workspace_id = get_current_workspace()
# Get monitor information
result = subprocess.run(
["hyprctl", "-j", "monitors"],
capture_output=True,
text=True
["hyprctl", "-j", "monitors"], capture_output=True, text=True
)
monitors = json.loads(result.stdout)
# Find the monitor containing our workspace
for monitor in monitors:
if monitor.get("activeWorkspace", {}).get("id") == workspace_id:
return monitor.get("width", data.CURRENT_WIDTH), monitor.get("height", data.CURRENT_HEIGHT)
return monitor.get("width", data.CURRENT_WIDTH), monitor.get(
"height", data.CURRENT_HEIGHT
)
# Fallback to first monitor
if monitors:
return monitors[0].get("width", data.CURRENT_WIDTH), monitors[0].get("height", data.CURRENT_HEIGHT)
return monitors[0].get("width", data.CURRENT_WIDTH), monitors[0].get(
"height", data.CURRENT_HEIGHT
)
except Exception as e:
print(f"Error getting screen dimensions: {e}")
# Default fallback values
return data.CURRENT_WIDTH, data.CURRENT_HEIGHT
def check_occlusion(occlusion_region, workspace=None):
"""
Check if a region is occupied by any window on a given workspace.
@@ -72,14 +75,14 @@ def check_occlusion(occlusion_region, workspace=None):
"""
if workspace is None:
workspace = get_current_workspace()
# Handle simplified side-based format
if isinstance(occlusion_region, tuple) and len(occlusion_region) == 2:
side, size = occlusion_region
if isinstance(side, str):
# Convert side-based format to coordinates
screen_width, screen_height = get_screen_dimensions()
if side.lower() == "bottom":
occlusion_region = (0, screen_height - size, screen_width, size)
elif side.lower() == "top":
@@ -88,7 +91,7 @@ def check_occlusion(occlusion_region, workspace=None):
occlusion_region = (0, 0, size, screen_height)
elif side.lower() == "right":
occlusion_region = (screen_width - size, 0, size, screen_height)
# Ensure occlusion_region is in the correct format (x, y, width, height)
if not isinstance(occlusion_region, tuple) or len(occlusion_region) != 4:
print(f"Invalid occlusion region format: {occlusion_region}")
@@ -96,9 +99,7 @@ def check_occlusion(occlusion_region, workspace=None):
try:
result = subprocess.run(
["hyprctl", "-j", "clients"],
capture_output=True,
text=True
["hyprctl", "-j", "clients"], capture_output=True, text=True
)
clients = json.loads(result.stdout)
except Exception as e:
@@ -131,7 +132,9 @@ def check_occlusion(occlusion_region, workspace=None):
win_x2, win_y2 = x + width, y + height
# Check for intersection between the window and occlusion region
if not (win_x2 <= occ_x or win_x1 >= occ_x2 or win_y2 <= occ_y or win_y1 >= occ_y2):
if not (
win_x2 <= occ_x or win_x1 >= occ_x2 or win_y2 <= occ_y or win_y1 >= occ_y2
):
return True # Occlusion region is occupied
return False # No window overlaps the occlusion region
+1 -1
View File
@@ -1,4 +1,3 @@
from gi.repository import Gdk, GObject, Gtk
import re
from collections.abc import Iterable
from enum import Enum
@@ -9,6 +8,7 @@ import gi
from fabric.core.service import Property
from fabric.utils.helpers import extract_css_values, get_enum_member
from fabric.widgets.window import Window
from gi.repository import Gdk, GObject, Gtk
from loguru import logger
gi.require_version("Gtk", "3.0")