2009/02/01

ミュートトグルアプリ若干改良

右クリックのメニューを少し拡張、コードの量は減少
あと少しかな

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import sys, subprocess, pygtk, gtk, threading

def get_controls():
amixer = subprocess.Popen(["/usr/bin/amixer", "scontrols"], stdout = subprocess.PIPE).communicate()[0]

controls = []
for control in amixer.rstrip().split("\n"):
controls.append(control.split(" ")[3])

return controls

def change_tray(tray, control):
amixer = subprocess.Popen(["/usr/bin/amixer", "sget", control], stdout = subprocess.PIPE)
grep = subprocess.Popen(["/bin/grep", "-e", "\[on\]$"], stdin = amixer.stdout, stdout = subprocess.PIPE).communicate()[0]

if grep == "":
msg = control + " is mute"
icon = gtk.STOCK_MEDIA_STOP
else:
msg = control + " is unmute"
icon = gtk.STOCK_MEDIA_PLAY

tray.set_from_stock(icon)
tray.set_tooltip(msg)

class PopupMenu(gtk.Menu):
def __init__(self, tray):
gtk.Menu.__init__(self)

self.tray = tray

# コントロール
controls = []
group = None
for i in get_controls():
controls.append(gtk.RadioMenuItem(group, i))
control = controls[-1]
control.connect("activate", self.activate_control, i)
group = control
self.append(control)
controls[0].set_active(True)

# 区切り線
self.append(gtk.SeparatorMenuItem())

# PulseAudio Volume Control
self.pavucontrol = gtk.ImageMenuItem("PulseAudio Volume Control")
self.pavucontrol.set_image(gtk.image_new_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU))
self.pavucontrol.connect("activate", self.activate_pavucontrol)
self.append(self.pavucontrol)

# 終了
self.exit = gtk.ImageMenuItem(stock_id = gtk.STOCK_QUIT)
self.exit.connect('activate', gtk.main_quit)
self.append(self.exit)

self.show_all()

def activate_pavucontrol(self, widget):
subprocess.Popen(["/usr/bin/pavucontrol"])

def activate_control(self, widget, control):
if widget.get_active() == True:
self.active_control = control
change_tray(self.tray, self.active_control)

class SystrayVolumeControl:
def __init__(self):
self.tray = gtk.StatusIcon()
self.menu = PopupMenu(self.tray)

self.tray.connect("activate", self.toggle_mute)
self.tray.connect("popup-menu", self.popup_menu)

def toggle_mute(self, widget):
subprocess.Popen(["/usr/bin/amixer", "sset", self.menu.active_control, "toggle"], stdout = subprocess.PIPE).communicate()[0]
change_tray(self.tray, self.menu.active_control)

def popup_menu(self, widget, button, time):
self.menu.popup(None, None, gtk.status_icon_position_menu, button, time, self.tray)

if __name__ == '__main__':
SystrayVolumeControl()
gtk.main()

0 件のコメント:

コメントを投稿