#!/usr/bin/python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program 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 this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

from popen2 import popen3
import gnome.applet
from gnome.ui import *
import gnome.util
from gtk import *


CONTROLLER = "armada-backlight"


def run( command ):
    p_stdout, p_stdin, p_stderr = popen3( command )
    
    p_stdin.close()
    result = p_stdout.read()
    if result == "":
        error = p_stderr.read()
        if error == "":
            return result
        else:
            raise error
    else:
        return result

def backlight_set_brightness( brightness ):
    run( CONTROLLER + " " + str(brightness) )

def backlight_get_brightness():
    return int( run( CONTROLLER ) )

def on_value_changed( adj ):
    new_brightness = adjustment_to_brightness( adj )
    backlight_set_brightness( new_brightness )
    level.set_text( str(new_brightness ) )

def adjustment_to_brightness( adj ):
    return 8 - int(adj.value)

# The signals of the adjustment will propagate the value to the label
def update_brightness_display():
    global adj
    adj.set_value( 8 - backlight_get_brightness() )

def poll_brightness():
    update_brightness_display()
    timeout_add( 1000, poll_brightness )

applet = gnome.applet.AppletWidget("armada-backlight-applet")
applet.set_tooltip("Set the brightness of the LCD backlight")

adj = GtkAdjustment( 0, 0, 9, 1, 1, 1 )
adj.connect( "value-changed", on_value_changed )

slider = GtkVScrollbar( adj )

panel_size = applet.get_panel_pixel_size()
icon = GnomePixmap( gnome.util.datadir_file("pixmaps/armada-backlight.png"),
                    panel_size/2, panel_size/2 )

level = GtkLabel( str(adjustment_to_brightness(adj)) )

table = GtkTable(2,2)
table.attach( slider, 1, 2, 0, 2 )
table.attach( icon, 0, 1, 0, 1 )
table.attach( level, 0, 1, 1, 2 )

applet.add( table )

poll_brightness()
applet.show_all()
mainloop()
