#!/usr/bin/python3
import gi, os, time
from shutil import which
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

# JWM Kit - A set of Graphical Apps to simplify use of JWM (Joe's Window Manager) <https://codeberg.org/JWMKit/JWM_Kit>
# Copyright © 2020-2022 Calvin Kent McNabb <apps.jwmkit@gmail.com>
#
# This file is part of JWM Kit.
#
# JWM Kit is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# JWM Kit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with JWM Kit.  If not, see <https://www.gnu.org/licenses/>.


class Mixer(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="JWM Kit Mixer")
        self.set_position(Gtk.WindowPosition.MOUSE)
        self.set_decorated(False)
        main_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        self.add(main_box)
        self.set_default_size(32, 20)
        image = Gtk.Image()
        main_box.pack_start(image, True, True, 0)
        # use the default ALSA's amixer
        if which('amixer') is not None:
            data_cmd = "amixer sget Master | tail -n1 | sed -n -e 's/.*\[//p' | sed -n -e 's/\]//p'"
        else:
            data_cmd = "sndioctl | sed -n -e 's/output.level=//p'"

        wait = time.time() + 1
        while time.time() < wait:
            data = os.popen(data_cmd).read().strip()
            data = data
            if data in ('off', '0.000'):
                icon = Gtk.IconTheme.get_default().load_icon('audio-volume-muted', 24, 0)
            else:
                icon = Gtk.IconTheme.get_default().load_icon('audio-volume-high', 24, 0)
            image.set_from_pixbuf(icon)
            self.show_all()
            while Gtk.events_pending():
                Gtk.main_iteration()
            time.sleep(.12)
        self.destroy()


if __name__ == "__main__":
    win = Mixer()
