🔧 refactor(config, notification_utils): remove music_player visibility management

This commit is contained in:
sankalp committed 2025-06-29 12:23:14 +05:45
1 parent 02c148a12a
commit 3ec4c6229d
14 files changed
+450 -1533

No files matched your search

-342
View File
@@ -1,342 +0,0 @@
import configparser
import ctypes
import os
import re
import signal
import struct
import subprocess
from math import pi
from fabric.utils.helpers import get_relative_path
from fabric.widgets.overlay import Overlay
from gi.repository import Gdk, GLib, Gtk
from loguru import logger
import config.data as data
def get_bars(file_path):
config = configparser.ConfigParser()
config.read(file_path)
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
process is killed, the child (cava) is automatically terminated.
"""
libc = ctypes.CDLL("libc.so.6")
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
CLOSING = 3
def __init__(self, mainapp):
self.bars = bars
self.path = "/tmp/cava.fifo"
self.cava_config_file = CAVA_CONFIG
self.data_handler = mainapp.draw.update
self.command = ["cava", "-p", self.cava_config_file]
self.state = self.NONE
self.env = dict(os.environ)
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)
)
if not os.path.exists(self.path):
os.mkfifo(self.path)
self.fifo_fd = None
self.fifo_dummy_fd = None
self.io_watch_id = None
def _run_process(self):
logger.debug("Launching cava process...")
try:
self.process = subprocess.Popen(
self.command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=self.env,
# Ensure cava gets killed when the parent dies.
preexec_fn=set_death_signal,
)
logger.debug("cava successfully launched!")
self.state = self.RUNNING
except Exception:
logger.exception("Fail to launch cava")
def _start_io_reader(self):
logger.debug("Activating GLib IO watch for cava stream handler")
# Open FIFO in non-blocking mode for reading
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
)
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:
# logger.error("Error reading FIFO: {}".format(e))
return False
# When no data is read, do not remove the IO watch immediately.
if len(data) < chunk:
# Instead of closing the FIFO, we log a warning and continue.
# logger.warning("Incomplete data packet received (expected {} bytes, got {}). Waiting for more data...".format(chunk, len(data)))
# Returning True keeps the IO watch active. A real EOF will only occur when the writer closes.
return True
fmt = self.byte_type * self.bars # format string for struct.unpack
sample = [i / self.byte_norm for i in struct.unpack(fmt, data)]
GLib.idle_add(self.data_handler, sample)
return True
def _on_stop(self):
logger.debug("Cava stream handler deactivated")
if self.state == self.RESTARTING:
self.start()
elif self.state == self.RUNNING:
self.state = self.NONE
logger.error("Cava process was unexpectedly terminated.")
# self.restart() # May cause infinity loop, need more check
def start(self):
"""Launch cava"""
self._start_io_reader()
self._run_process()
def restart(self):
"""Restart cava process"""
if self.state == self.RUNNING:
logger.debug("Restarting cava process (normal mode) ...")
self.state = self.RESTARTING
if self.process.poll() is None:
self.process.kill()
elif self.state == self.NONE:
logger.warning("Restarting cava process (after crash) ...")
self.start()
def close(self):
"""Stop cava process"""
self.state = self.CLOSING
if self.process.poll() is None:
self.process.kill()
if self.io_watch_id:
GLib.source_remove(self.io_watch_id)
if self.fifo_fd:
os.close(self.fifo_fd)
if self.fifo_dummy_fd:
os.close(self.fifo_dummy_fd)
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 = []
self.color = None
self.area = Gtk.DrawingArea()
self.area.connect("draw", self.redraw)
self.area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.sizes = AttributeDict()
self.sizes.area = AttributeDict()
self.sizes.bar = AttributeDict()
self.silence = 10
self.max_height = 12
self.area.connect("configure-event", self.size_update)
self.color_update()
def is_silence(self, value):
"""Check if volume level critically low during last iterations"""
self.silence_value = 0 if value > 0 else self.silence_value + 1
return self.silence_value > self.silence
def update(self, data):
"""Audio data processing"""
self.color_update()
self.audio_sample = data
if not self.is_silence(self.audio_sample[0]):
self.area.queue_draw()
elif self.silence_value == (self.silence + 1):
self.audio_sample = [0] * self.sizes.number
self.area.queue_draw()
def redraw(self, widget, cr):
"""Draw spectrum graph"""
cr.set_source_rgba(*self.color)
if data.VERTICAL:
# Vertical mode: draw bars horizontally (rotated 90 degrees)
dy = 3
center_x = self.sizes.area.width / 2 # center horizontal of the drawing area
for i, value in enumerate(self.audio_sample):
height = self.sizes.area.height / self.sizes.number - self.sizes.padding
radius = height / 2
width = max(self.sizes.bar.width * min(value, 1), self.sizes.zero) / 2
if width == self.sizes.zero / 2 + 1:
width *= 0.5
width = min(width, self.max_height)
# Draw rectangle and arcs for rounded ends (horizontal bars)
cr.rectangle(center_x - width, dy, width * 2, height)
cr.arc(center_x - width, dy + radius, radius, 0, 2 * pi)
cr.arc(center_x + width, dy + radius, radius, 0, 2 * pi)
cr.close_path()
dy += height + self.sizes.padding
else:
# Horizontal mode: draw bars vertically (original behavior)
dx = 3
center_y = self.sizes.area.height / 2 # center vertical of the drawing area
for i, value in enumerate(self.audio_sample):
width = self.sizes.area.width / self.sizes.number - self.sizes.padding
radius = width / 2
height = max(self.sizes.bar.height * min(value, 1), self.sizes.zero) / 2
if height == self.sizes.zero / 2 + 1:
height *= 0.5
height = min(height, self.max_height)
# Draw rectangle and arcs for rounded ends (vertical bars)
cr.rectangle(dx, center_y - height, width, height * 2)
cr.arc(dx + radius, center_y - height, radius, 0, 2 * pi)
cr.arc(dx + radius, center_y + height, radius, 0, 2 * pi)
cr.close_path()
dx += width + self.sizes.padding
cr.fill()
def size_update(self, *args):
"""Update drawing geometry"""
self.sizes.number = bars
self.sizes.padding = 100 / bars
self.sizes.zero = 0
self.sizes.area.width = self.area.get_allocated_width()
self.sizes.area.height = self.area.get_allocated_height() - 2
tw = self.sizes.area.width - self.sizes.padding * (self.sizes.number - 1)
self.sizes.bar.width = max(int(tw / self.sizes.number), 1)
self.sizes.bar.height = self.sizes.area.height
def color_update(self):
"""Set drawing color according to current settings by reading primary color from CSS"""
color = "#a5c8ff" # default value
try:
with open(get_relative_path("../styles/colors.css"), "r") as f:
content = f.read()
m = re.search(r"--primary:\s*(#[0-9a-fA-F]{6})", content)
if m:
color = m.group(1)
except Exception as e:
logger.error("Failed to read primary color: {}".format(e))
red = int(color[1:3], 16) / 255
green = int(color[3:5], 16) / 255
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
self.draw = Spectrum()
self.cava = Cava(self)
self.cava.start()
def get_spectrum_box(self):
# Get the spectrum box
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
return box
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)
self.width = width
self.height = height
self.bars = bars
self.is_playing = False
# Create spectrum renderer
self.spectrum_render = SpectrumRender()
self.spectrum_box = self.spectrum_render.get_spectrum_box()
# Set size
self.spectrum_box.set_size_request(width, height)
# Add to overlay
self.add_overlay(self.spectrum_box)
# Set alignment
self.set_halign(Gtk.Align.CENTER)
self.set_valign(Gtk.Align.CENTER)
def set_visible(self, visible):
"""Override set_visible to control spectrum rendering"""
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
self.spectrum_render.cava.start()
elif not visible:
# Optionally pause spectrum when not visible to save resources
pass
+382
View File
@@ -0,0 +1,382 @@
"""
Common notification utilities and shared functionality
"""
import json
import locale
import os
import uuid
from datetime import datetime, timedelta
from fabric.utils.helpers import get_relative_path
from fabric.widgets.box import Box
from gi.repository import GdkPixbuf, GLib, GObject
from loguru import logger
import config.data as data
# Constants
PERSISTENT_DIR = f"/tmp/{data.APP_NAME}/notifications"
PERSISTENT_HISTORY_FILE = os.path.join(PERSISTENT_DIR, "notification_history.json")
CONFIG_FILE = get_relative_path("../config/assets/config.json")
NOTIFICATION_IMAGE_PREFIX = "notification_"
NOTIFICATION_IMAGE_SUFFIX = ".png"
DEFAULT_NOTIFICATION_IMAGE_SIZE = 48
MAX_PERSISTENT_NOTIFICATIONS = 100
LIMITED_APPS = ["Spotify"]
# Global shared notification history instance
_shared_notification_history = None
class HistoricalNotification:
"""Data structure for historical notification data"""
def __init__(self, id, app_icon, summary, body, app_name, timestamp, cached_image_path=None):
self.id = id
self.app_icon = app_icon
self.summary = summary
self.body = body
self.app_name = app_name
self.timestamp = timestamp
self.cached_image_path = cached_image_path
self.image_pixbuf = None
self.actions = []
self.cached_scaled_pixbuf = None
# Image handling functions
def cache_notification_pixbuf(notification_box):
"""Cache notification image to disk and return cache file path"""
notification = notification_box.notification
if notification.image_pixbuf:
os.makedirs(PERSISTENT_DIR, exist_ok=True)
cache_file = os.path.join(
PERSISTENT_DIR, f"{NOTIFICATION_IMAGE_PREFIX}{notification_box.uuid}{NOTIFICATION_IMAGE_SUFFIX}"
)
try:
scaled = notification.image_pixbuf.scale_simple(
DEFAULT_NOTIFICATION_IMAGE_SIZE, DEFAULT_NOTIFICATION_IMAGE_SIZE, GdkPixbuf.InterpType.BILINEAR
)
scaled.savev(cache_file, "png", [], [])
return cache_file
except Exception as e:
logger.error(f"Error caching image for notification {notification.id}: {e}")
return None
else:
logger.debug(f"Notification {notification.id} has no image_pixbuf to cache.")
return None
def load_scaled_pixbuf(notification_box, width, height):
"""Load and scale pixbuf from notification box"""
notification = notification_box.notification
if not hasattr(notification_box, "notification") or notification is None:
return None
pixbuf = None
# Try to load from cached image first
if (
hasattr(notification_box, "cached_image_path")
and notification_box.cached_image_path
and os.path.exists(notification_box.cached_image_path)
):
try:
logger.debug(
f"Attempting to load cached image from: {notification_box.cached_image_path} "
f"for notification {notification.id}"
)
pixbuf = GdkPixbuf.Pixbuf.new_from_file(notification_box.cached_image_path)
if pixbuf:
pixbuf = pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
return pixbuf
except Exception as e:
logger.error(
f"Error loading cached image from {notification_box.cached_image_path} "
f"for notification {notification.id}: {e}"
)
logger.warning(f"Falling back to notification.image_pixbuf for notification {notification.id}")
# Fall back to notification image_pixbuf
if notification.image_pixbuf:
pixbuf = notification.image_pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
return pixbuf
# Fall back to app icon
return get_app_icon_pixbuf(notification.app_icon, width, height)
def get_app_icon_pixbuf(icon_path, width, height):
"""Load and scale app icon pixbuf"""
if not icon_path:
return None
if icon_path.startswith("file://"):
icon_path = icon_path[7:]
if not os.path.exists(icon_path):
logger.warning(f"Icon path does not exist: {icon_path}")
return None
try:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon_path)
return pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
except Exception as e:
logger.error(f"Failed to load or scale icon: {e}")
return None
def cleanup_orphan_cached_images(persistent_notifications):
"""Clean up cached images that no longer have corresponding notifications"""
if not os.path.exists(PERSISTENT_DIR):
return
cached_files = [
f for f in os.listdir(PERSISTENT_DIR)
if f.startswith(NOTIFICATION_IMAGE_PREFIX) and f.endswith(NOTIFICATION_IMAGE_SUFFIX)
]
if not cached_files:
return
history_uuids = {
note.get("id") for note in persistent_notifications if note.get("id")
}
for cached_file in cached_files:
try:
uuid_from_filename = cached_file[len(NOTIFICATION_IMAGE_PREFIX):-len(NOTIFICATION_IMAGE_SUFFIX)]
if uuid_from_filename not in history_uuids:
cache_file_path = os.path.join(PERSISTENT_DIR, cached_file)
os.remove(cache_file_path)
except Exception as e:
print(f"Error processing cached file {cached_file} during cleanup: {e}")
def delete_cached_image(cached_image_path):
"""Delete a specific cached image file"""
if cached_image_path and os.path.exists(cached_image_path):
try:
os.remove(cached_image_path)
logger.info(f"Deleted cached image: {cached_image_path}")
except Exception as e:
logger.error(f"Error deleting cached image {cached_image_path}: {e}")
# Time and date utilities
def get_ordinal(n):
"""Get ordinal suffix for a number (1st, 2nd, 3rd, etc.)"""
if 11 <= (n % 100) <= 13:
return "th"
else:
return {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
def get_date_header(dt):
"""Get human-readable date header for a datetime"""
now = datetime.now()
today = now.date()
date = dt.date()
if date == today:
return "Today"
elif date == today - timedelta(days=1):
return "Yesterday"
else:
original_locale = locale.getlocale(locale.LC_TIME)
try:
locale.setlocale(locale.LC_TIME, ("en_US", "UTF-8"))
except locale.Error:
locale.setlocale(locale.LC_TIME, "C")
try:
day = dt.day
ordinal = get_ordinal(day)
month = dt.strftime("%B")
if dt.year == now.year:
result = f"{month} {day}{ordinal}"
else:
result = f"{month} {day}{ordinal}, {dt.year}"
finally:
locale.setlocale(locale.LC_TIME, original_locale)
return result
def schedule_midnight_update(callback):
"""Schedule a callback to run at midnight"""
now = datetime.now()
next_midnight = datetime.combine(
now.date() + timedelta(days=1), datetime.min.time()
)
delta_seconds = (next_midnight - now).total_seconds()
return GLib.timeout_add_seconds(int(delta_seconds), callback)
def compute_time_label(arrival_time):
"""Compute time label for notification timestamp"""
return arrival_time.strftime("%H:%M")
# Data creation utilities
def create_notification_data(notification_box):
"""Create notification data dictionary from notification box"""
notification = notification_box.notification
return {
"id": notification_box.uuid,
"app_icon": getattr(notification, "app_icon", "dialog-information-symbolic"),
"summary": getattr(notification, "summary", "No summary"),
"body": getattr(notification, "body", ""),
"app_name": getattr(notification, "app_name", "Unknown"),
"timestamp": datetime.now().isoformat(),
"cached_image_path": getattr(notification_box, "cached_image_path", None),
}
def create_historical_notification_from_data(note_data):
"""Create HistoricalNotification object from data dictionary"""
return HistoricalNotification(
id=note_data.get("id"),
app_icon=note_data.get("app_icon"),
summary=note_data.get("summary"),
body=note_data.get("body"),
app_name=note_data.get("app_name"),
timestamp=note_data.get("timestamp"),
cached_image_path=note_data.get("cached_image_path"),
)
# Storage utilities
def ensure_persistent_dir():
"""Ensure the persistent directory exists"""
if not os.path.exists(PERSISTENT_DIR):
os.makedirs(PERSISTENT_DIR, exist_ok=True)
def load_persistent_history():
"""Load notification history from persistent storage"""
ensure_persistent_dir()
if os.path.exists(PERSISTENT_HISTORY_FILE):
try:
with open(PERSISTENT_HISTORY_FILE, "r") as f:
notifications = json.load(f)
logger.info(f"Loaded {len(notifications)} notifications from persistent history")
return notifications
except Exception as e:
logger.error(f"Error loading persistent history: {e}")
return []
else:
return []
def save_persistent_history(notifications):
"""Save notification history to persistent storage"""
try:
ensure_persistent_dir()
with open(PERSISTENT_HISTORY_FILE, "w") as f:
json.dump(notifications, f, indent=2)
logger.info(f"Saved {len(notifications)} notifications to persistent history")
except Exception as e:
logger.error(f"Error saving persistent history: {e}")
def load_dnd_state():
"""Load Do Not Disturb state from config"""
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r") as f:
config_data = json.load(f)
dnd_enabled = config_data.get("dnd_enabled", False)
logger.info(f"Loaded DND state: {dnd_enabled}")
return dnd_enabled
except Exception as e:
logger.error(f"Error loading DND state: {e}")
return False
def save_dnd_state(dnd_enabled):
"""Save Do Not Disturb state to config"""
try:
config_data = {}
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r") as f:
config_data = json.load(f)
config_data["dnd_enabled"] = dnd_enabled
with open(CONFIG_FILE, "w") as f:
json.dump(config_data, f, indent=4)
logger.debug(f"Saved DND state: {dnd_enabled}")
except Exception as e:
logger.error(f"Error saving DND state: {e}")
# Shared notification history class
class NotificationHistory(Box):
"""Shared notification history with DND state management"""
__gsignals__ = {
"dnd-state-changed": (GObject.SignalFlags.RUN_FIRST, None, (bool,)),
"notification-added": (GObject.SignalFlags.RUN_FIRST, None, ()),
}
def __init__(self, **kwargs):
super().__init__(name="notification-history", orientation="v", **kwargs)
self.do_not_disturb_enabled = False
self.persistent_notifications = []
self._load_persistent_history()
self._load_dnd_state()
def set_do_not_disturb_enabled(self, enabled):
"""Set DND state and emit signal if changed"""
if self.do_not_disturb_enabled != enabled:
self.do_not_disturb_enabled = enabled
save_dnd_state(enabled)
self.emit("dnd-state-changed", enabled)
def _load_persistent_history(self):
"""Load persistent notification history"""
self.persistent_notifications = load_persistent_history()
def _load_dnd_state(self):
"""Load DND state from config"""
self.do_not_disturb_enabled = load_dnd_state()
def _save_persistent_history(self):
"""Save persistent notification history"""
save_persistent_history(self.persistent_notifications)
def add_notification(self, notification_box):
"""Add notification to history"""
try:
hist_data = create_notification_data(notification_box)
self.persistent_notifications.append(hist_data)
# Remove old notifications if we exceed the limit
if len(self.persistent_notifications) > MAX_PERSISTENT_NOTIFICATIONS:
self.persistent_notifications.pop(0)
self._save_persistent_history()
self.emit("notification-added")
except Exception as e:
print(f"Error adding notification to history: {e}")
def clear_history_for_app(self, app_name):
"""Clear history for specific app"""
try:
original_count = len(self.persistent_notifications)
self.persistent_notifications = [
notif for notif in self.persistent_notifications
if notif.get("app_name") != app_name
]
removed_count = original_count - len(self.persistent_notifications)
if removed_count > 0:
self._save_persistent_history()
logger.info(f"Cleared {removed_count} notifications for app: {app_name}")
except Exception as e:
print(f"Error clearing history for app {app_name}: {e}")
def get_shared_notification_history():
"""Get or create the shared notification history instance"""
global _shared_notification_history
if _shared_notification_history is None:
_shared_notification_history = NotificationHistory()
return _shared_notification_history