diff options
| author | kj-sh604 | 2025-06-06 16:47:20 -0400 |
|---|---|---|
| committer | kj-sh604 | 2025-06-06 16:47:20 -0400 |
| commit | c8893a39af3bcd6689dbf9c796295a694042eca7 (patch) | |
| tree | 4da5074d761a32266857eca2d20299718e0bbe65 | |
| parent | e45e276dedee7ef402ef78af51e78af511c87db1 (diff) | |
refactor: make the application events-based
| -rwxr-xr-x | mic-icon.py | 62 |
1 files changed, 48 insertions, 14 deletions
diff --git a/mic-icon.py b/mic-icon.py index de95593..dfb38d8 100755 --- a/mic-icon.py +++ b/mic-icon.py @@ -1,15 +1,17 @@ #!/usr/bin/env python3 import sys +import threading +import subprocess +import signal + import pulsectl import gi gi.require_version('Gtk', '3.0') gi.require_version('AppIndicator3', '0.1') - from gi.repository import Gtk, GLib, AppIndicator3 -# ICON NAMES from the default Adwaita icon set: ICON_UNMUTED = "microphone" ICON_MUTED = "gtk-cancel" @@ -24,35 +26,67 @@ class MicIcon: self.ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) menu = Gtk.Menu() - - quit_item = Gtk.MenuItem(label='Quit') - quit_item.connect('activate', self.quit) + quit_item = Gtk.MenuItem(label="Quit") + quit_item.connect("activate", self.quit) menu.append(quit_item) menu.show_all() - self.ind.set_menu(menu) self.pulse = pulsectl.Pulse('mic-icon') - GLib.timeout_add_seconds(1, self.update_icon) + self.p = subprocess.Popen( + ["pactl", "subscribe"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, bufsize=1 + ) + + thr = threading.Thread( + target=self._pactl_subscribe_loop, + name="Pactl-Subscribe-Reader", + daemon=True + ) + thr.start() + + GLib.unix_signal_add( + GLib.PRIORITY_DEFAULT, + signal.SIGINT, + self.quit, + None + ) + + self._update_icon() + + def _pactl_subscribe_loop(self): + if not self.p.stdout: + return + + for line in self.p.stdout: + if " on source " in line: + GLib.idle_add(self._update_icon) + self.p.stdout.close() + self.p.wait() - def update_icon(self): + def _update_icon(self): try: default_name = self.pulse.server_info().default_source_name - source = self.pulse.get_source_by_name(default_name) - muted = source.mute - except Exception as e: + src = self.pulse.get_source_by_name(default_name) + muted = src.mute + except Exception: muted = False icon = ICON_MUTED if muted else ICON_UNMUTED self.ind.set_icon_full(icon, icon) - return True + return False - def quit(self, _): + def quit(self, *args): + if hasattr(self, 'p') and self.p.poll() is None: + self.p.terminate() Gtk.main_quit() - sys.exit(0) + return False if __name__ == "__main__": MicIcon() Gtk.main() + sys.exit(0) |
