#! /usr/bin/python2

import sys
import os
import os.path
import gtk
import gobject
from subprocess import CalledProcessError, check_output, call, check_call

pygtklibdir = os.path.join("/usr/lib", "pygtk", "2.0")
sys.path.insert(0, pygtklibdir)
# found on <http://files.majorsilence.com/rubbish/pygtk-book/pygtk-notebook-html/pygtk-notebook-latest.html#SECTION00430000000000000000>
# simple example of a tray icon application using PyGTK
 
def close_app(data=None):
  gtk.main_quit()
 
def make_menu(event_button, event_time, data=None):
  menu = gtk.Menu()
  if comptonisrunning():
    toggle_item = gtk.MenuItem("Stop Compton")
  else:
    toggle_item = gtk.MenuItem("Start Compton")
  close_item = gtk.MenuItem("Quit")
  
  #Append the menu items
  menu.append(toggle_item)
  #Check if compton-config is installed
  if isinstalled():
     preference_item = gtk.MenuItem("Compton Config")
     menu.append(preference_item)
     preference_item.connect_object("activate", openconfig, "Compton Config")
     preference_item.show()
  menu.append(close_item)
  #add callbacks
  toggle_item.connect_object("activate", togglecompton, "Toggle")
  close_item.connect_object("activate", close_app, "Quit")
  #Show the menu items
  toggle_item.show()
  close_item.show()
  
  #Popup the menu
  menu.popup(None, None, None, event_button, event_time)
 
def on_right_click(data, event_button, event_time):
  make_menu(event_button, event_time)
 
def on_left_click(event):
  togglecompton()

def openconfig(data=None):
	call(["compton-conf"])
  
def comptonisrunning():
        try:
                output = check_output(["pgrep", "compton"])
        except CalledProcessError as e:
                output=False
        if output:
                curstatus=True
        else:
                curstatus=False
        return curstatus
        
def isinstalled(name="compton-conf"):
        try:
                output = check_output(["which", name])
        except CalledProcessError as e:
                output=False
        if output:
                installed=True
        else:
                installed=False
        return installed

def togglecompton(data=None):
    if comptonisrunning():
        call(["pkill", "compton"])
    else:
        call(["compton", "-b"])
	
def check_for_update():		
    if comptonisrunning():
        iconname=gtk.STOCK_YES
    else:
        iconname=gtk.STOCK_NO
    return iconname

def update_icon():
    if tray.get_stock() == check_for_update():
      return True
    else:
      tray.set_from_stock(check_for_update())
      return True

#Continuesly check for status update
gobject.timeout_add(1000, update_icon)

if __name__ == '__main__':
  tray = gtk.StatusIcon()
  tray.set_from_stock(check_for_update())
  tray.set_tooltip(('Comptray'))
  tray.connect('popup-menu', on_right_click)
  tray.connect('activate', on_left_click)
  gtk.main()
