#!/usr/bin/env python
import os,sys
from xml.dom import minidom, Node

class powersettings:
	DEF_PAD = 5
	SET_ONLY_LIGHT = False
	if os.name == "nt":
		CFG_FILENAME = ".\\lightnpower.cfg"
	else:
		CFG_FILENAME = os.environ['HOME'] + "/Choices/lightnpower.cfg"
	
	Zaurus_Charging = False
	ac_suspend = 10
	ac_screenoff = 10
	ac_backlight = 4

	bat_suspend = 10
	bat_screenoff = 10
	bat_backlight = 4

	def __init__(self):
		exitnow = False
		savesettingsonexit = False
		self.load_settings()
		Zaurus_Charging = self.is_the_zaurus_charging()
	    	if len(sys.argv) > 0:
	    		i = 0
	    		while i < len(sys.argv):
	    			if sys.argv[i] == "--loadandquit":
	    				exitnow = True
			    	if sys.argv[i] == "--setbackonly":
			    		self.SET_ONLY_LIGHT = True
			    		exitnow = True
				if sys.argv[i] == "--lightup":
					if Zaurus_Charging:
						if int(self.ac_backlight) < 6: 
							self.ac_backlight = int(self.ac_backlight)+1
					else:
						if int(self.bat_backlight) < 6: 
							self.bat_backlight = int(self.bat_backlight)+1
					self.SET_ONLY_LIGHT = True
					exitnow = True
					savesettingsonexit = True
				if sys.argv[i] == "--lightdown":
					if Zaurus_Charging:
						if int(self.ac_backlight) > 0: 
							self.ac_backlight = int(self.ac_backlight)-1
					else:
						if int(self.bat_backlight) > 0: 
							self.bat_backlight = int(self.bat_backlight)-1
					self.SET_ONLY_LIGHT = True
					exitnow = True
					savesettingsonexit = True
			    	i = i + 1

		if Zaurus_Charging:
			self.setvalues(float(self.ac_screenoff)*60,float(self.ac_suspend)*60,self.ac_backlight)
		else:
			self.setvalues(float(self.bat_screenoff)*60,float(self.bat_suspend)*60,self.bat_backlight)

		if (exitnow):
			if (savesettingsonexit):
				self.save_config()	
			sys.exit()
		else:
			global gtk
			import gtk
	        # create a new window
	        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	        self.window.set_title("Light & power settings")
	        self.window.set_border_width(10)
	        self.window.set_position(gtk.WIN_POS_CENTER)
	        self.window.set_resizable(gtk.FALSE)
	        self.window.connect("delete_event", gtk.main_quit)
	        self.window.connect("destroy", gtk.main_quit)
	
	        MainBox = gtk.VBox(gtk.FALSE, self.DEF_PAD)
	        self.window.add(MainBox)
	
		notebook = gtk.Notebook()
		notebook.set_tab_pos(gtk.POS_TOP)
		notebook.show()
		MainBox.pack_start(notebook, gtk.TRUE, gtk.TRUE, self.DEF_PAD)
	
		# Tabbed interface
		batteryframe = gtk.Frame()
		batteryframe.show()
		
		label = gtk.Label("Battery")
		notebook.append_page(batteryframe, label)
	     	batterybox = gtk.VBox(gtk.FALSE, self.DEF_PAD)
		batteryframe.add(batterybox)

		acframe = gtk.Frame()
		acframe.show()
		
		label = gtk.Label("AC Power")
		notebook.append_page(acframe, label)
	     	acbox = gtk.VBox(gtk.FALSE, self.DEF_PAD)
		acframe.add(acbox)
		
	# Battery content start
		
		# Suspend
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		batterybox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
		
		label = gtk.Label("Suspend after (min):")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
	        adj = gtk.Adjustment(float(self.bat_suspend), 0, 360, 1, 0.5, 0)
	        self.bat_suspend_input = gtk.SpinButton(adj, 1, 1)
	        self.bat_suspend_input.set_wrap(gtk.TRUE)
	        self.bat_suspend_input.connect("value-changed", self.check_battery_diff)
		box1.pack_end(self.bat_suspend_input, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		# Screen off
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		batterybox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
		
		label = gtk.Label("Screen off after (min):")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
	        adj = gtk.Adjustment(float(self.bat_screenoff), 0, 360, 1, 0.5, 0)
	        self.bat_screenoff_input = gtk.SpinButton(adj, 1, 1)
	        self.bat_screenoff_input.set_wrap(gtk.TRUE)
	        self.bat_screenoff_input.connect("value-changed", self.check_battery_diff)
		box1.pack_end(self.bat_screenoff_input, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
		
		label = gtk.Label(" 0 min. equals no suspend/standby ")
		batterybox.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		# Backlighting
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		batterybox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		label = gtk.Label("Backlighting:")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		self.adj_bat_backlight = gtk.Adjustment(float(self.bat_backlight), 1, 7, 1, 0.5, 1)
		self.adj_bat_backlight.connect("value_changed", self.set_backlighting)
		self.bat_backlight_input = gtk.HScale(self.adj_bat_backlight)
		self.bat_backlight_input.set_size_request(100, 20)
		self.bat_backlight_input.set_update_policy(gtk.UPDATE_CONTINUOUS)
		self.bat_backlight_input.set_digits(0)
		self.bat_backlight_input.set_value_pos(gtk.POS_LEFT)
		self.bat_backlight_input.set_draw_value(gtk.TRUE)
		box1.pack_end(self.bat_backlight_input, gtk.TRUE, gtk.TRUE,  self.DEF_PAD)
		self.bat_backlight_input.show()


	# Battery content end 
	
	# AC content start
		# Suspend
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		acbox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
		
		label = gtk.Label("Suspend after (min):")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
	        adj = gtk.Adjustment(float(self.ac_suspend), 0, 360, 1, 0.5, 0)
	        self.ac_suspend_input = gtk.SpinButton(adj, 1, 1)
	        self.ac_suspend_input.set_wrap(gtk.TRUE)
	        self.ac_suspend_input.connect("value-changed", self.check_ac_diff)
		box1.pack_end(self.ac_suspend_input, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		# Screen off
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		acbox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
		
		label = gtk.Label("Screen off after (min):")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
	        adj = gtk.Adjustment(float(self.ac_screenoff), 0, 360, 1, 1, 0)
	        self.ac_screenoff_input = gtk.SpinButton(adj, 1, 1)
	        self.ac_screenoff_input.set_wrap(gtk.TRUE)
	        self.ac_screenoff_input.connect("value-changed", self.check_ac_diff)
		box1.pack_end(self.ac_screenoff_input, gtk.FALSE, gtk.FALSE, self.DEF_PAD)

		label = gtk.Label(" 0 min. equals no suspend/standby ")
		acbox.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)

		# Backlighting
	     	box1 = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		acbox.pack_start(box1, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		label = gtk.Label("Backlighting:")
		box1.pack_start(label, gtk.FALSE, gtk.FALSE, self.DEF_PAD)
	
		self.adj_ac_backlight = gtk.Adjustment(float(self.ac_backlight), 1, 7, 1, 1, 1)
		self.adj_ac_backlight.connect("value_changed", self.set_backlighting)
		self.ac_backlight_input = gtk.HScale(self.adj_ac_backlight)
		self.ac_backlight_input.set_size_request(100, 20)
		self.ac_backlight_input.set_update_policy(gtk.UPDATE_CONTINUOUS)
		self.ac_backlight_input.set_digits(0)
		self.ac_backlight_input.set_value_pos(gtk.POS_LEFT)
		self.ac_backlight_input.set_draw_value(gtk.TRUE)
		box1.pack_end(self.ac_backlight_input, gtk.TRUE, gtk.TRUE,  self.DEF_PAD)
		self.ac_backlight_input.show()
	
	# AC content end 
		
	# Ok and Cancel buttons
	        bbox = gtk.HButtonBox()
		MainBox.pack_start(bbox, gtk.FALSE, gtk.FALSE, 0)
	        bbox.set_layout(gtk.BUTTONBOX_END)
	   	
	        cancel_button = gtk.Button("Cancel",gtk.STOCK_CANCEL)
	        cancel_button.connect("clicked", gtk.main_quit)
	        bbox.add(cancel_button)

	        okbutton = gtk.Button("Ok",gtk.STOCK_OK)
	        okbutton.connect("clicked", self.close_and_update)
	        bbox.add(okbutton)
	        okbutton.set_flags(gtk.CAN_DEFAULT)
	        okbutton.grab_default()

		if Zaurus_Charging:
			notebook.set_current_page(1)
	
	        self.window.show_all()

	def load_settings(self):
		if os.path.isfile(self.CFG_FILENAME):
			try:
				xmldoc = minidom.parse(self.CFG_FILENAME)
			except:
				return False
			else:
				tags = xmldoc.getElementsByTagName("POWERSETTINGS");
				for tag in tags:
					powertypes = tag.getElementsByTagName("Powersetting")
					for powertype in powertypes:
						mode = powertype.getAttribute("type")
						if mode == "AC":
							self.ac_suspend = powertype.getAttribute("suspend")
							self.ac_screenoff = powertype.getAttribute("screenoff")
							self.ac_backlight = powertype.getAttribute("backlight")
						if mode == "BATTERY":
							self.bat_suspend = powertype.getAttribute("suspend")
							self.bat_screenoff = powertype.getAttribute("screenoff")
							self.bat_backlight = powertype.getAttribute("backlight")
				return True
		else:
			return False

	def save_config(self):
		conf_tree = minidom.Document()
		conf_tree.appendChild(conf_tree.createComment("pdaXrom settings file"))
		root_node = conf_tree.createElement("POWERSETTINGS")

		power_node = conf_tree.createElement("Powersetting")
		power_node.setAttribute("type", "AC")
		power_node.setAttribute("suspend", str(self.ac_suspend))
		power_node.setAttribute("screenoff", str(self.ac_screenoff))
		power_node.setAttribute("backlight", str(self.ac_backlight))
		root_node.appendChild(power_node)

		power_node = conf_tree.createElement("Powersetting")
		power_node.setAttribute("type", "BATTERY")
		power_node.setAttribute("suspend", str(self.bat_suspend))
		power_node.setAttribute("screenoff", str(self.bat_screenoff))
		power_node.setAttribute("backlight", str(self.bat_backlight))
		root_node.appendChild(power_node)

		conf_tree.appendChild(root_node)
		FD = open(self.CFG_FILENAME, "w")
		FD.write(conf_tree.toprettyxml())
		FD.close()

	def is_the_zaurus_charging(self):
		program = os.popen("apm", "r")   
		for line in program.readlines():
			line = line.lower()
	        	if line.find("on-line") != -1:
	        		return True
	        		break
	        return False

	def is_the_screen_on(self):
		program = os.popen("/usr/X11R6/bin/xset q >/dev/null 2>/dev/null", "r")   
		for line in program.readlines():
			line = line.lower()
	        	if line.find("monitor is in standby") != -1:
	        		return False
	        		break
	        return True


	def set_backlighting(self,widget):
		Zaurus_Charging = self.is_the_zaurus_charging()
		self.ac_backlight = int(self.adj_ac_backlight.get_value())
		self.bat_backlight = int(self.adj_bat_backlight.get_value())
		if Zaurus_Charging == True:
	        	setfl = "/sbin/setfl %s" %self.ac_backlight
			os.system(setfl)
		else:
	        	setfl = "/sbin/setfl %s" %self.bat_backlight
			os.system(setfl)
    
	def check_battery_diff(self,widget):
	    	if self.bat_screenoff_input.get_value() > self.bat_suspend_input.get_value() and self.bat_suspend_input.get_value() != 0:
	    		self.bat_screenoff_input.set_value(self.bat_suspend_input.get_value())
		self.bat_suspend = self.bat_suspend_input.get_value()
		self.bat_screenoff = self.bat_screenoff_input.get_value()

	def check_ac_diff(self,widget):
    		if self.ac_screenoff_input.get_value() > self.ac_suspend_input.get_value() and self.ac_suspend_input.get_value() != 0:
    			self.ac_screenoff_input.set_value(self.ac_suspend_input.get_value())
		self.ac_suspend = self.ac_suspend_input.get_value()
		self.ac_screenoff = self.ac_screenoff_input.get_value()

	def setvalues(self,screenoff,suspend,brightness):
		if (self.is_the_screen_on()):
		    setfl = "/sbin/setfl %s" %brightness
		    os.system(setfl)
        	if (self.SET_ONLY_LIGHT == False):
	        	if suspend == 0:
	        		xset = "/usr/X11R6/bin/xset dpms %s 0 %s >/dev/null 2>/dev/null" %(int(screenoff),int(suspend))
	        		os.system(xset)
	        		xset = "/usr/X11R6/bin/xset -dpms >/dev/null 2>/dev/null"
	        		os.system(xset)
	        	else:
	        		xset = "/usr/X11R6/bin/xset +dpms >/dev/null 2>/dev/null"
	        		os.system(xset)
				xset = "/usr/X11R6/bin/xset dpms %s 0 %s >/dev/null 2>/dev/null" %(int(screenoff),int(suspend))
				os.system(xset)

	def close_and_update(self,widget):
    		Zaurus_Charging = self.is_the_zaurus_charging()
		if Zaurus_Charging:
			self.setvalues(float(self.ac_screenoff)*60,float(self.ac_suspend)*60,self.ac_backlight)
		else:
			self.setvalues(float(self.bat_screenoff)*60,float(self.bat_suspend)*60,self.bat_backlight)
		self.save_config()
		gtk.main_quit()

	def main(self):
        	gtk.main()

if __name__ == "__main__":
	powersettings = powersettings()
	powersettings.main()


