#!/usr/bin/env python3 """FWS — panneau multimédia de la barre. Ouvert en cliquant la pochette ou le titre dans Waybar (ou avec SUPER+M), il montre la pochette, la piste, le temps écoulé et une barre de position déplaçable, avec les commandes de lecture. Tout passe par `playerctl` : n'importe quel lecteur MPRIS (Spotify, mpv, Firefox, VLC…) devient pilotable sans configuration, et l'interface ne sait rien d'autre des lecteurs que ce que MPRIS veut bien dire. Sans lecteur, le panneau reste ouvert et l'affiche au lieu de se fermer : on comprend que rien ne joue au lieu de croire à un bug. """ from __future__ import annotations import hashlib import os import subprocess import time import gi gi.require_version("Gtk", "4.0") gi.require_version("Pango", "1.0") from gi.repository import Gio, GLib, Gtk, Pango # noqa: E402 (après require_version) # Poll interval: fast enough that the slider follows the track smoothly, slow # enough to keep three `playerctl` calls per tick cheap. POLL_MS = 500 # Ignore the player position for a moment after a seek: the player reports the # old position for a few hundred milliseconds, which would make the slider jump # back under the cursor. SEEK_GRACE_S = 0.8 SEEK_STEP_S = 5 CSS = """ window { background: #29242e; border: 1px solid rgba(195, 182, 246, 0.35); border-radius: 14px; } .cover { border: 1px solid rgba(195, 182, 246, 0.35); border-radius: 12px; } .title { font-size: 15px; font-weight: bold; color: #fafafa; } .subtitle { font-size: 12px; color: #c3b6f6; } .album { font-size: 11px; color: #9a8cd8; } .time { font-size: 11px; color: #9a8cd8; } .hint { font-size: 10px; color: #6b6180; } .idle { font-size: 13px; color: #9a8cd8; } scale trough { background: #1f1a2e; border-radius: 6px; min-height: 6px; } scale trough highlight { background: #cba6f7; border-radius: 6px; } scale slider { background: #fafafa; border-radius: 8px; min-width: 14px; min-height: 14px; margin: -5px 0; } scale:hover slider { background: #c3b6f6; } button { background: #1f1a2e; color: #fafafa; border: none; border-radius: 10px; padding: 6px 14px; font-size: 15px; } button:hover { background: #3a3350; } button:disabled { color: #6b6180; } button.accent { background: #cba6f7; color: #29242e; font-weight: bold; } button.accent:hover { background: #c3b6f6; } button.close { padding: 2px 10px; color: #c3b6f6; } button.close:hover { background: #f569ca; color: #29242e; } """ def playerctl(*args: str) -> str | None: """Run a playerctl command, returning its output or None when it fails. Any failure (no player, key absent, playerctl gone) is a normal state for this panel, so it is reported as None rather than raising: the caller decides what to show. """ try: result = subprocess.run( ["playerctl", *args], capture_output=True, text=True, timeout=2 ) except (OSError, subprocess.SubprocessError): return None if result.returncode != 0: return None return result.stdout.strip() def metadata(key: str) -> str | None: value = playerctl("metadata", key) return value or None def position() -> float | None: value = playerctl("position") if value is None: return None try: return float(value) except ValueError: return None def length() -> float | None: """Track length in seconds (MPRIS exposes it in microseconds).""" value = metadata("mpris:length") if value is None: return None try: return int(value) / 1_000_000 except ValueError: return None def format_time(seconds: float) -> str: seconds = max(0, int(seconds)) minutes, secs = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) if hours: return f"{hours}:{minutes:02d}:{secs:02d}" return f"{minutes}:{secs:02d}" SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) CACHE_DIR = os.path.join( os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache")), "fws-media" ) # Repli quand la piste n'a pas de pochette : le logo FWS du thème, comme dans # la barre, plutôt qu'un carré vide. FALLBACK_ART = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, "icons", "logo.png")) def cache_path(url: str) -> str: """Cache file the bar's helper uses for a remote artwork URL. Same name on purpose (md5 of the URL): the panel only READS the cache the bar fills, so opening it never waits for a download. """ return os.path.join(CACHE_DIR, hashlib.md5(url.encode()).hexdigest()) def cover_for(url: str | None) -> tuple[str | None, bool]: """Local cover path for an artUrl, and whether it still has to be fetched. Remote artwork is never downloaded here: the answer is "not ready yet" and the caller shows the logo until the file shows up in the cache. """ if not url: return FALLBACK_ART, False if url.startswith("file://"): return url[len("file://"):], False if url.startswith("http"): cached = cache_path(url) return (cached, False) if os.path.exists(cached) else (None, True) return FALLBACK_ART, False def start_download() -> None: """Ask the bar's helper to fetch the artwork, in the background. Waybar runs it every couple of seconds anyway; running it too keeps the panel usable when the bar is not up. """ try: subprocess.Popen( [os.path.join(SCRIPT_DIR, "media-cover")], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, ) except OSError: pass class MediaPanel(Gtk.Application): def __init__(self) -> None: # L'identifiant d'application devient la CLASSE de la fenêtre pour le # compositeur : c'est lui qui applique les règles « float » et « size » # de hyprland.conf. Il doit être un nom D-Bus valide, d'où le point. super().__init__(application_id="fws.media") self.window: Gtk.ApplicationWindow | None = None self.dragging = False self.last_seek = 0.0 self.track_id: str | None = None self.pending_art: str | None = None self.css_loaded = False # ---------------------------------------------------------------- fenêtre def do_activate(self) -> None: # Une seule instance : recliquer sur la barre ferme le panneau déjà # ouvert au lieu d'en empiler un deuxième. if self.window is not None and self.window.get_visible(): self.window.close() return self.build_window() self.window.present() GLib.timeout_add(POLL_MS, self.refresh) def build_window(self) -> None: window = Gtk.ApplicationWindow(application=self) window.set_title("Lecture en cours") window.set_default_size(460, 214) window.set_decorated(False) window.set_resizable(False) if not self.css_loaded: provider = Gtk.CssProvider() provider.load_from_string(CSS) Gtk.StyleContext.add_provider_for_display( window.get_display(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION ) self.css_loaded = True outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8) outer.set_margin_top(10) outer.set_margin_bottom(12) outer.set_margin_start(16) outer.set_margin_end(16) window.set_child(outer) # La croix est en haut à droite, comme sur n'importe quelle fenêtre : # c'est le premier réflexe pour fermer, et sans elle un panneau sans # bordure (donc sans bouton du compositeur) semble impossible à fermer. header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0) outer.append(header) close_button = Gtk.Button(label="\U000f0156") close_button.add_css_class("close") close_button.set_tooltip_text("Fermer (Échap)") close_button.set_halign(Gtk.Align.END) close_button.set_hexpand(True) close_button.connect("clicked", lambda _button: window.close()) header.append(close_button) top = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=14) outer.append(top) self.cover = Gtk.Picture() self.cover.set_size_request(88, 88) self.cover.set_content_fit(Gtk.ContentFit.COVER) cover_frame = Gtk.Box() cover_frame.add_css_class("cover") # Le cadre arrondi doit rogner la pochette, sinon l'angle droit de # l'image déborde des coins de la bordure. cover_frame.set_overflow(Gtk.Overflow.HIDDEN) cover_frame.append(self.cover) top.append(cover_frame) info = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4) info.set_valign(Gtk.Align.CENTER) info.set_hexpand(True) top.append(info) self.title_label = Gtk.Label(xalign=0) self.title_label.add_css_class("title") self.title_label.set_ellipsize(Pango.EllipsizeMode.END) self.title_label.set_max_width_chars(34) info.append(self.title_label) self.artist_label = Gtk.Label(xalign=0) self.artist_label.add_css_class("subtitle") self.artist_label.set_ellipsize(Pango.EllipsizeMode.END) info.append(self.artist_label) self.album_label = Gtk.Label(xalign=0) self.album_label.add_css_class("album") self.album_label.set_ellipsize(Pango.EllipsizeMode.END) info.append(self.album_label) self.player_label = Gtk.Label(xalign=0) self.player_label.add_css_class("hint") self.player_label.set_ellipsize(Pango.EllipsizeMode.END) info.append(self.player_label) progress = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) outer.append(progress) self.elapsed_label = Gtk.Label(label="0:00") self.elapsed_label.add_css_class("time") progress.append(self.elapsed_label) self.scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, 0, 1, 1) self.scale.set_draw_value(False) self.scale.set_hexpand(True) self.scale.set_sensitive(False) progress.append(self.scale) self.total_label = Gtk.Label(label="0:00") self.total_label.add_css_class("time") progress.append(self.total_label) # Le glissement est suivi par un geste et non par la valeur du widget : # `change-value` se déclencherait à chaque pixel de déplacement, ce qui # enverrait des dizaines de seeks au lecteur. On déplace donc la barre # librement et on ne cherche la position qu'au relâchement. drag = Gtk.GestureDrag() drag.connect("drag-begin", self.on_drag_begin) drag.connect("drag-end", self.on_drag_end) self.scale.add_controller(drag) controls = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) controls.set_halign(Gtk.Align.CENTER) outer.append(controls) self.prev_button = self.control_button(controls, "󰒮", "Piste précédente", self.previous) self.restart_button = self.control_button(controls, "󰒉", "Revenir au début", self.restart) self.play_button = self.control_button(controls, "󰐊", "Lecture / pause", self.toggle, accent=True) self.next_button = self.control_button(controls, "󰒭", "Piste suivante", self.next) keys = Gtk.EventControllerKey() keys.connect("key-pressed", self.on_key) window.add_controller(keys) # Fermer automatiquement quand la fenêtre perd le focus serait tentant, # mais Hyprland est configuré ici en focus glissant (follow_mouse = 1) : # en ouvrant le panneau depuis la barre, le curseur reste hors de la # fenêtre, qui est dé-focalisée aussitôt et se fermerait avant d'avoir # été vue. On laisse donc fermer explicitement (croix, Échap, ou un # nouveau clic sur la barre, qui bascule). self.window = window def control_button(self, box: Gtk.Box, icon: str, tooltip: str, callback, accent: bool = False) -> Gtk.Button: button = Gtk.Button(label=icon) button.set_tooltip_text(tooltip) if accent: button.add_css_class("accent") button.connect("clicked", lambda _button: callback()) box.append(button) return button # ------------------------------------------------------------------ état def on_key(self, _controller, keyval, _code, _state) -> bool: if keyval == Gio.KEY_Escape: self.close() return True if keyval == Gio.KEY_space: self.toggle() return True if keyval == Gio.KEY_Left: playerctl("position", f"{SEEK_STEP_S}-") self.after_seek() return True if keyval == Gio.KEY_Right: playerctl("position", f"{SEEK_STEP_S}+") self.after_seek() return True return False def on_drag_begin(self, _gesture, _x, _y) -> None: self.dragging = True def on_drag_end(self, _gesture, _x, _y) -> None: self.dragging = False self.seek(self.scale.get_value()) def after_seek(self) -> None: self.last_seek = time.monotonic() def seek(self, seconds: float) -> None: playerctl("position", f"{max(0, seconds):.0f}") self.after_seek() def toggle(self) -> None: playerctl("play-pause") def next(self) -> None: playerctl("next") def previous(self) -> None: playerctl("previous") def restart(self) -> None: self.seek(0) def close(self) -> None: if self.window is not None: self.window.close() # ------------------------------------------------------------- rafraîchir def refresh(self) -> bool: status = playerctl("status") playing = status == "Playing" title = metadata("xesam:title") if title is None: self.show_idle() return GLib.SOURCE_CONTINUE self.title_label.set_text(title) self.artist_label.set_text(metadata("xesam:artist") or "Artiste inconnu") self.album_label.set_text(metadata("xesam:album") or "") self.player_label.set_text(status or "") self.play_button.set_label("󰏤" if playing else "󰐊") for widget in (self.prev_button, self.restart_button, self.play_button, self.next_button, self.scale): widget.set_sensitive(True) self.total_label.set_text(format_time(length() or 0)) self.scale.get_adjustment().set_upper(max(1.0, length() or 1.0)) track = metadata("mpris:trackid") if track != self.track_id: self.track_id = track self.update_cover() # Pochette distante pas encore en cache : le helper la télécharge, on # la pose dès qu'elle apparaît au lieu de bloquer l'interface. if self.pending_art is not None and os.path.exists(cache_path(self.pending_art)): self.set_cover(cache_path(self.pending_art)) self.pending_art = None current = position() if current is not None and not self.dragging: # Après un seek, le lecteur annonce encore l'ancienne position : # on garde la valeur demandée le temps qu'il se recale. if time.monotonic() - self.last_seek > SEEK_GRACE_S: self.scale.set_value(current) self.elapsed_label.set_text(format_time(current)) else: self.elapsed_label.set_text(format_time(self.scale.get_value())) return GLib.SOURCE_CONTINUE def show_idle(self) -> None: self.title_label.set_text("Aucun lecteur") self.artist_label.set_text("Lance une musique pour la piloter ici") self.album_label.set_text("") self.player_label.set_text("") self.total_label.set_text("0:00") self.elapsed_label.set_text("0:00") self.scale.set_value(0) self.track_id = None self.pending_art = None self.update_cover() for widget in (self.prev_button, self.restart_button, self.play_button, self.next_button, self.scale): widget.set_sensitive(False) def update_cover(self) -> None: url = metadata("mpris:artUrl") path, pending = cover_for(url) if not pending: self.pending_art = None elif url is not None and self.pending_art != url: self.pending_art = url start_download() self.set_cover(path) def set_cover(self, path: str | None) -> None: if path is None or not os.path.exists(path): self.cover.set_paintable(None) return try: self.cover.set_filename(path) except GLib.Error: self.cover.set_paintable(None) if __name__ == "__main__": raise SystemExit(MediaPanel().run([]))