#!/usr/bin/env python

import gtk,os,getpass,sys
from xml.dom import minidom, Node
exitx = False

class inputconf:
	if os.name == "nt":
		CFG_FILENAME = "./input.cfg"
		MOUSE_SETTING_FILE = "C:\\python24\\pdaxrom\\misc\\x11"
		MODMAP_FILE = "C:\\python24\\pdaxrom\\misc\\userdefined.xmodmap"
		KERNELMAP_FILE = "C:\\python24\\pdaxrom\\misc\\kernel.map"
		RC_XML = "C:\\python24\\pdaxrom\\misc\\rc.xml"
	else:
		CFG_FILENAME = os.environ['HOME'] + "/Choices/input.cfg"
		MOUSE_SETTING_FILE = "/etc/sysconfig/x11"
		MODMAP_FILE = "/etc/X11/kb/userdefined.xmodmap"
		KERNELMAP_FILE = "/etc/sysconfig/keyboard/kernel.map"
		RC_XML = "/etc/xdg/openbox/rc.xml"

	def __init__(self):

		if (getpass.getuser().lower() != "root" and os.name != "nt"):
			Warningdialog = gtk.MessageDialog(None,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"You need to be root in order to run this program.")
			Warningdialog.run()
			Warningdialog.destroy()
			sys.exit()
		self.window = gtk.Window()
		self.window.connect("delete_event", gtk.main_quit)
		self.window.connect("destroy", gtk.main_quit)
		self.window.set_title("Input settings")	
		self.window.set_border_width(10)
		self.window.set_resizable(gtk.FALSE)
		self.window.set_position(gtk.WIN_POS_CENTER)

		MainBox = gtk.VBox(gtk.FALSE, 5)
		self.window.add(MainBox)
		
		#Default values
		self.presshold = True
		self.rightmouse_mod = 129
		self.middlemouse_mod = 130
		self.ctrl_mod = 96
		self.alt_mod = 97
		self.scrollwheeldir = "updown"
		self.default_shortcuts = list()
		n = 0
		while n < 12:
			self.default_shortcuts.append("")
			n += 1
		self.load_prefs()

	# Right & middle mouse
		self.refilter = list()
		self.store = gtk.ListStore(str,int,bool)
		self.store.append(["Left Shift",35,True])
		self.store.append(["Fn",38,True])
		self.store.append(["Calendar",96,True])
		self.store.append(["Address",97,True])
		self.store.append(["Mail",98,True])
		self.store.append(["Home",48,True])
		self.store.append(["Kanji next to Fn button",129,True])
		self.store.append(['Kanji next to \"-\" button',130,True])
		self.store.append(["Right Shift",111,True])
		
		# rmbox and mmbox are mutually exclusive because they use the same ListStore!
		i = 0
		for strtxt in self.store:
			if (strtxt[1] == self.rightmouse_mod):
				break;
			i += 1
		self.rmbox,self.rmcombo = self.build_combobox(self.store,self.changed,"Right mouse : ",i,"RMB")

		i = 0
		for strtxt in self.store:
			if (strtxt[1] == self.middlemouse_mod):
				break;
			i += 1
		mmbox,mmcombo = self.build_combobox(self.store,self.changed,"Middle mouse: ",i,"MMB")
	
	# alt & ctrl mapping
		self.store1 = gtk.ListStore(str,int,bool)
		self.store1.append(["Left Shift",35,True])
		self.store1.append(["Fn",38,True])
		self.store1.append(["Calendar",96,True])
		self.store1.append(["Address",97,True])
		self.store1.append(["Mail",98,True])
		self.store1.append(["Home",48,True])
		self.store1.append(["Kanji next to Fn button",129,True])
		self.store1.append(['Kanji next to \"-\" button',130,True])
		self.store1.append(["Right Shift",111,True])

		# altbox and ctrlbox are mutually exclusive because they use the same ListStore,
		# but not mutually exclusive with regards to rmbox and mmbox as they use another ListStore!
		i = 0
		for strtxt in self.store1:
			if (strtxt[1] == self.alt_mod):
				break
			i += 1
		altbox,altcombo = self.build_combobox(self.store1,self.changed,"Alt key is mapped to : ",i,"ALT")
		
		i = 0
		for strtxt in self.store1:
			if (strtxt[1] == self.ctrl_mod):
				break
			i += 1
		ctrlbox,ctrlcombo = self.build_combobox(self.store1,self.changed,"Ctrl key is mapped to : ",i,"CTRL")

		vbox = gtk.VBox(homogeneous=gtk.TRUE, spacing=10)
		vbox.set_border_width(10)
		
	# press and hold on/off
		label = gtk.Label("Here you can configure how the right mouse and middle\nmouse button is triggered with the stylus.")
		vbox.pack_start(label, gtk.FALSE, gtk.TRUE)
		hbox = gtk.HBox(gtk.FALSE)
		vbox.pack_start(hbox, gtk.FALSE, gtk.TRUE)
	
		pressandhold_but = gtk.CheckButton("Use press & hold for right mouse click.") 
		pressandhold_but.set_active(gtk.FALSE)
		pressandhold_but.connect("toggled", self.toogle_presshold)
		#self.rmbox.set_sensitive(self.presshold)
		hbox.pack_start(pressandhold_but, gtk.FALSE, gtk.FALSE)

		# comboboxes adds
		vbox.pack_start(self.rmbox, gtk.FALSE, gtk.FALSE)
		vbox.pack_start(mmbox, gtk.FALSE, gtk.FALSE)

		hbox = gtk.HBox(gtk.FALSE)
		vbox.pack_start(hbox, gtk.FALSE, gtk.TRUE)
		self.clearcalib_but = gtk.CheckButton("Recalibrate stylus on next start of window manager.") 
		self.clearcalib_but.set_active(gtk.FALSE)
		hbox.pack_start(self.clearcalib_but, gtk.FALSE, gtk.FALSE)

		vbox2 = gtk.VBox(homogeneous=gtk.TRUE, spacing=10)
		vbox2.set_border_width(10)
		label = gtk.Label("Here you can configure which keys the control(ctrl)\nand alt buttons are mapped onto.")
		vbox2.pack_start(label, gtk.FALSE, gtk.TRUE)
		vbox2.pack_start(altbox, gtk.FALSE, gtk.FALSE)
		vbox2.pack_start(ctrlbox, gtk.FALSE, gtk.FALSE)

		vbox3 = gtk.VBox(homogeneous=gtk.TRUE, spacing=10)
		vbox3.set_border_width(10)
		label = gtk.Label("Here you can configure which programs are launched when\nthe \"shortcut\" keys are pressed.")
		vbox3.pack_start(label, gtk.FALSE, gtk.TRUE)
	
	# Shortcut keys
		self.shortcutoptions = gtk.ListStore(str,str,bool)
		self.shortcutoptions.append(["Select program","select",True])
		self.shortcutoptions.append(["Calendar(KO/pi)","kopi",True])
		self.shortcutoptions.append(["Address(KA/pi)","kapi",True])
		self.shortcutoptions.append(["Mail(Sylpheed)","sylpheed",True])
		self.shortcutoptions.append(["Mail(Thunderbird)","thunderbird",True])
		self.shortcutoptions.append(["Browser(Dillo)","dillo",True])
		self.shortcutoptions.append(["Browser(Firefox)","firefox",True])
		self.shortcutoptions.append(["Gaim","gaim",True])
		self.shortcutoptions.append(["XMMS","xmms",True])
		self.shortcutoptions.append(["ScITE","SciTE",True])
		self.shortcutoptions.append(["Abiword","abiword",True])
		self.shortcutoptions.append(["ATerm","aterm",True])
		self.shortcutoptions.append(["XTerm","xterm",True])
		self.shortcutoptions.append(["Clock","xclock",True])
		# self.shortcutoptions.append(["Suspend","xset dpms force off",True])

	# Shortcut buttons
		self.calendarkeybox,self.calendarkeyinput = self.build_shortcutbox("Calendar :",self.default_shortcuts[0],self.shortcutoptions,self.changed2)
		vbox3.pack_start(self.calendarkeybox, gtk.FALSE, gtk.FALSE)

		self.addresskeybox,self.addresskeyinput = self.build_shortcutbox("Address :",self.default_shortcuts[1],self.shortcutoptions,self.changed2)
		vbox3.pack_start(self.addresskeybox, gtk.FALSE, gtk.FALSE)

		self.mailkeybox,self.mailkeyinput = self.build_shortcutbox("Mail :",self.default_shortcuts[2],self.shortcutoptions,self.changed2)
		vbox3.pack_start(self.mailkeybox, gtk.FALSE, gtk.FALSE)

		self.homekeybox,self.homekeyinput = self.build_shortcutbox("Home :",self.default_shortcuts[3],self.shortcutoptions,self.changed2)
		vbox3.pack_start(self.homekeybox, gtk.FALSE, gtk.FALSE)

	# Silkscreen buttons
		vbox4 = gtk.VBox(homogeneous=gtk.TRUE, spacing=10)

		label = gtk.Label("Here you can configure which programs are launched when\nthe \"silkscreen\" buttons are pressed.")
		vbox4.pack_start(label, gtk.FALSE, gtk.TRUE)

		self.silk_homebox,self.silk_homeinput = self.build_shortcutbox("Home :",self.default_shortcuts[4],self.shortcutoptions,self.changed2)
		vbox4.pack_start(self.silk_homebox, gtk.FALSE, gtk.FALSE)

		self.silk_mailbox,self.silk_mailinput = self.build_shortcutbox("Mail :",self.default_shortcuts[5],self.shortcutoptions,self.changed2)
		vbox4.pack_start(self.silk_mailbox, gtk.FALSE, gtk.FALSE)

		self.silk_addressbox,self.silk_addressinput = self.build_shortcutbox("Address :",self.default_shortcuts[6],self.shortcutoptions,self.changed2)
		vbox4.pack_start(self.silk_addressbox, gtk.FALSE, gtk.FALSE)

		self.silk_calendar,self.silk_calendarinput = self.build_shortcutbox("Calendar :",self.default_shortcuts[7],self.shortcutoptions,self.changed2)
		vbox4.pack_start(self.silk_calendar, gtk.FALSE, gtk.FALSE)

		self.silk_starbox,self.silk_starinput = self.build_shortcutbox('\"*\" :',self.default_shortcuts[8],self.shortcutoptions,self.changed2)
		vbox4.pack_start(self.silk_starbox, gtk.FALSE, gtk.FALSE)
		
		vbox4.set_border_width(10)


	# Jog wheel on side
		vbox5 = gtk.VBox(homogeneous=gtk.TRUE, spacing=10)

		label = gtk.Label("Here you can configure the way the jogwheel operates.")
		vbox5.pack_start(label, gtk.FALSE, gtk.TRUE)

		self.scrollwheeldirbox = gtk.combo_box_new_text()
	      	self.scrollwheeldirbox.append_text("Arrow key up and down")
	      	self.scrollwheeldirbox.append_text("Arrow key left and right")
	      	self.scrollwheeldirbox.set_size_request(250,30)
	      	if (self.scrollwheeldir == "updown"):
	      		self.scrollwheeldirbox.set_active(0)
	      	else:
	      		self.scrollwheeldirbox.set_active(1)

		hbox = gtk.HBox(homogeneous=gtk.FALSE, spacing=10)
		label = gtk.Label("The jogwheel should work as:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 10)
		hbox.pack_end(self.scrollwheeldirbox, gtk.FALSE, gtk.FALSE, 10)

		vbox5.pack_start(hbox, gtk.FALSE, gtk.FALSE)
		
		notebook = gtk.Notebook()
		notebook.set_tab_pos(gtk.POS_TOP)
		notebook.show()

		notebook.append_page(vbox, gtk.Label("Stylus/Mouse settings"))
		notebook.append_page(vbox2, gtk.Label("Ctrl/Alt settings"))
		notebook.append_page(vbox3, gtk.Label("Shortcut keys"))
		notebook.append_page(vbox4, gtk.Label("Silkscreen"))
		notebook.append_page(vbox5, gtk.Label("Jog wheel"))
		notebook.connect("switch-page",self.lock_others_check)
		MainBox.pack_start(notebook, gtk.TRUE, gtk.TRUE, 5)

		if (self.presshold):
			self.presshold = False
			pressandhold_but.set_active(gtk.TRUE)

	# 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()
		
		self.lock_others()
		self.window.show_all()
		return

	def build_combobox(self,store,change,txt,default,varname):
		modelfilter = store.filter_new()
		combobox = gtk.combo_box_new_text()
		combobox.set_data("name",varname)
		modelfilter.set_visible_func(self.filterfunc, combobox)
		combobox.set_model(modelfilter)
		combobox.set_data("iter",store.get_iter(str(default)))
		combobox.connect('changed',change)
		combobox.set_active(int(modelfilter.get_string_from_iter(modelfilter.convert_child_iter_to_iter(store.get_iter(default)))))
		combobox.set_size_request(250,35)
		hbox = gtk.HBox(homogeneous=gtk.FALSE, spacing=10)
		label = gtk.Label(txt)
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 10)
		hbox.pack_end(combobox, gtk.FALSE, gtk.FALSE, 10)
		self.refilter.append(modelfilter)
		return hbox,combobox

	def build_shortcutbox(self,title,default,store,change):
		hbox = gtk.HBox(homogeneous=gtk.FALSE, spacing=10)
		modelfilter = store.filter_new()
		combobox = gtk.combo_box_entry_new_text()
		modelfilter.set_visible_func(self.filterfunc, combobox)
		combobox.set_model(modelfilter)
		combobox.set_data("iter",store.get_iter(0))
		combobox.set_size_request(250,30)
		combobox.child.set_text(str(default))
		combobox.connect('changed',change)
		label = gtk.Label(title)
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 10)
		hbox.pack_end(combobox, gtk.FALSE, gtk.FALSE, 10)
		return hbox,combobox

	def changed(self, combobox):
		model =	combobox.get_model()
		store = model.get_model()
		index =	combobox.get_active()
		iter = model.convert_iter_to_child_iter(model.get_iter(index))
		
		store[combobox.get_data("iter")][2] = True					# Enable previous selection again!
		combobox.set_data("iter", iter)
		store[iter][2] = False								# Disable current selection!
		for upd in self.refilter:							# Update all comboboxes
			upd.refilter()								# We actually don't need to update own(this) combobox but w.t.h.
		
		store.set_data(combobox.get_data("name"),model[index][1])
		return

	def changed2(self, combobox):
		model =	combobox.get_model()
		index =	combobox.get_active()
		if (index == 0):
			dialog = gtk.FileChooserDialog("Select a program to run when key is pressed!",self.window,gtk.FILE_CHOOSER_ACTION_OPEN,(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN, gtk.RESPONSE_OK))
			dialog.set_default_response(gtk.RESPONSE_OK)
			response = dialog.run()
			if response == gtk.RESPONSE_OK:
				combobox.child.set_text(dialog.get_filename())
			dialog.destroy()
		elif (index != -1):
			combobox.child.set_text(model[index][1])
		return

	def lock_others_check(self,notebook, page, page_num):
		if (page_num == 2 or page_num == 3):
			self.lock_others()
		return

	def lock_others(self):
		# hardcoded check of buttons selected which locks them from assignment
		if ((not self.store[2][2] or not self.store1[2][2])):
			self.calendarkeybox.set_sensitive(0)
		else:
			self.calendarkeybox.set_sensitive(1)

		if (not self.store[3][2] or not self.store1[3][2]):
			self.addresskeybox.set_sensitive(0)
		else:
			self.addresskeybox.set_sensitive(1)

		if (not self.store[4][2] or not self.store1[4][2]):
			self.mailkeybox.set_sensitive(0)
		else:
			self.mailkeybox.set_sensitive(1)
			
		if (not self.store[5][2] or not self.store1[5][2]):
			self.homekeybox.set_sensitive(0)
		else:
			self.homekeybox.set_sensitive(1)
		return

	def filterfunc(self, model, iter, combobox):						# combobox is actually user_data passed from "store.set_visible_func(self.filterfunc, combobox)"
		if(model[iter][2] or model[iter][0] == model[combobox.get_data("iter")][0]):
			return True
		return False

	def toogle_presshold(self,widget):
		self.presshold = not self.presshold
		self.rmbox.set_sensitive(not self.presshold)
		if(self.presshold == False):
			if( not self.store[self.rmcombo.get_data("iter")][2] ):	# did someone else steal my selection
				num = 0
				for free in self.store:
					if(free[2] == True):
						self.rmcombo.set_data("iter",self.store.get_iter(num))
						self.rmcombo.set_active(num)
						break
					num += 1
			else:
				self.changed(self.rmcombo)
		else:
			self.store[self.rmcombo.get_data("iter")][2] = True
		return

	def load_prefs(self):
		if os.path.isfile(self.CFG_FILENAME):
			try:
				xmldoc = minidom.parse(self.CFG_FILENAME)
			except:
				return False
			else:
				tags = xmldoc.getElementsByTagName("INPUTSETTINGS")
				for tag in tags:
					Mods = tag.getElementsByTagName("Mods")
					for ModsTag in Mods:
						if (ModsTag.getAttribute("MIDDLEMOUSEMOD") != "" and ModsTag.getAttribute("MIDDLEMOUSEMOD").isdigit()):
							self.rightmouse_mod = int(ModsTag.getAttribute("RIGHTMOUSEMOD"))
						if (ModsTag.getAttribute("MIDDLEMOUSEMOD") != "" and ModsTag.getAttribute("MIDDLEMOUSEMOD").isdigit()):
							self.middlemouse_mod = int(ModsTag.getAttribute("MIDDLEMOUSEMOD"))
						if (ModsTag.getAttribute("CTRLMOD") != "" and ModsTag.getAttribute("CTRLMOD").isdigit()):
							self.ctrl_mod = int(ModsTag.getAttribute("CTRLMOD"))
						if (ModsTag.getAttribute("ALTMOD") != "" and ModsTag.getAttribute("ALTMOD").isdigit()):
							self.alt_mod = int(ModsTag.getAttribute("ALTMOD"))
						if (ModsTag.getAttribute("PRESSANDHOLD") != ""):
							self.presshold = (ModsTag.getAttribute("PRESSANDHOLD").lower() == "true")
						if (ModsTag.getAttribute("SCROLLWHEELDIR") != ""):
							self.scrollwheeldir = ModsTag.getAttribute("SCROLLWHEELDIR").lower()

					Mods = tag.getElementsByTagName("Shortcuts")
					for ModsTag in Mods:
						self.default_shortcuts[int(ModsTag.getAttribute("ID"))] = ModsTag.getAttribute("Program")
				return True
		else:
			return False

	def save_prefs(self,widget=None):
		conf_tree = minidom.Document()
		conf_tree.appendChild(conf_tree.createComment("pdaXrom settings file"))
		root_node = conf_tree.createElement("INPUTSETTINGS")
		input_node = conf_tree.createElement("Mods")
		input_node.setAttribute("RIGHTMOUSEMOD", str(bcb.store.get_data("RMB")))
		input_node.setAttribute("MIDDLEMOUSEMOD", str(bcb.store.get_data("MMB")))
		input_node.setAttribute("CTRLMOD", str(bcb.store1.get_data("CTRL")))
		input_node.setAttribute("ALTMOD", str(bcb.store1.get_data("ALT")))
		input_node.setAttribute("PRESSANDHOLD", str(self.presshold))

		model = self.scrollwheeldirbox.get_model()
		active = self.scrollwheeldirbox.get_active()
		if (model[active][0].lower() == "arrow key up and down"):
			input_node.setAttribute("SCROLLWHEELDIR", "updown")
			self.scrollwheeldir = "updown"
		else:
			input_node.setAttribute("SCROLLWHEELDIR", "leftright")
			self.scrollwheeldir = "leftright"
		
		root_node.appendChild(input_node)	

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "0")
		input_node.setAttribute("Program", str(self.calendarkeyinput.child.get_text()))
		root_node.appendChild(input_node)	

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "1")
		input_node.setAttribute("Program", str(self.addresskeyinput.child.get_text()))
		root_node.appendChild(input_node)	

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "2")
		input_node.setAttribute("Program", str(self.mailkeyinput.child.get_text()))
		root_node.appendChild(input_node)	

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "3")
		input_node.setAttribute("Program", str(self.homekeyinput.child.get_text()))
		root_node.appendChild(input_node)

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "4")
		input_node.setAttribute("Program", str(self.silk_homeinput.child.get_text()))
		root_node.appendChild(input_node)

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "5")
		input_node.setAttribute("Program", str(self.silk_mailinput.child.get_text()))
		root_node.appendChild(input_node)

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "6")
		input_node.setAttribute("Program", str(self.silk_addressinput.child.get_text()))
		root_node.appendChild(input_node)

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID","7")
		input_node.setAttribute("Program", str(self.silk_calendarinput.child.get_text()))
		root_node.appendChild(input_node)

		input_node = conf_tree.createElement("Shortcuts")
		input_node.setAttribute("ID", "8")
		input_node.setAttribute("Program", str(self.silk_starinput.child.get_text()))
		root_node.appendChild(input_node)

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

	def close_and_update(self,widget):
		global exitx
		self.lock_others()
		self.save_prefs()
	
	# Create X mouse mapping
		output = ""
		if (self.presshold):
			output += "X11_RIGHT_MOUSE_BUTTON=hold\n"
		else:
			output += "X11_RIGHT_MOUSE_BUTTON=\"\"\n"
			output += "X11_RIGHT_MOUSE_BUTTON_MOD=" + str(int(bcb.store.get_data("RMB"))-8) + "\n"
		
		output += "X11_MIDDLE_MOUSE_BUTTON_MOD=" + str(int(bcb.store.get_data("MMB"))-8)
		f=open(self.MOUSE_SETTING_FILE, "w")
		f.write(output)
		f.close()
		
		output = "! ------------ User defined keys ------------ \n\n"
		
		if (self.scrollwheeldir == "updown"):
			output += "keycode 133 = Up\n"
			output += "keycode 134 = Down\n\n"
		else:
			output += "keycode 133 = Right\n"
			output += "keycode 134 = Left\n\n"
		
		
	# Save RC.xml file
		try:
			xmldoc = minidom.parse(self.RC_XML)
		except:
			print "WARNING DIALOG GOES HERE!!"
		else:
			tags = xmldoc.getElementsByTagName("keybind")
			for tag in tags:

				if (tag.getAttribute("key") == "XF86LaunchA"):
					if (self.calendarkeybox.get_property("sensitive")):
						output += "keycode 96 = XF86LaunchA\n"
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = self.calendarkeyinput.child.get_text()
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.calendarkeyinput.child.get_text()))
					else:
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = ""
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(""))
			

				if (tag.getAttribute("key") == "XF86LaunchB"):
					if (self.addresskeybox.get_property("sensitive")):
						output += "keycode 97 = XF86LaunchB\n"
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = self.addresskeyinput.child.get_text()
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.addresskeyinput.child.get_text()))
					else:
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = ""
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(""))


				if (tag.getAttribute("key") == "XF86LaunchC"):
					if (self.mailkeybox.get_property("sensitive")):
						output += "keycode 98 = XF86LaunchC\n"
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = self.mailkeyinput.child.get_text()
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.mailkeyinput.child.get_text()))
					else:
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = ""
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(""))


				if (tag.getAttribute("key") == "XF86LaunchD"):
					if (self.homekeybox.get_property("sensitive")):
						output += "keycode 48 = XF86LaunchD\n"
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = self.homekeyinput.child.get_text()
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.homekeyinput.child.get_text()))
					else:
						if (tag.getElementsByTagName("execute")[0].firstChild != None):
							tag.getElementsByTagName("execute")[0].firstChild.data = ""
						else:
							tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(""))

				if (tag.getAttribute("key") == "XF86Launch0"):
					if (tag.getElementsByTagName("execute")[0].firstChild != None):
						tag.getElementsByTagName("execute")[0].firstChild.data = self.silk_homeinput.child.get_text()
					else:
						tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.silk_homeinput.child.get_text()))

				if (tag.getAttribute("key") == "XF86Launch1"):
					if (tag.getElementsByTagName("execute")[0].firstChild != None):
						tag.getElementsByTagName("execute")[0].firstChild.data = self.silk_mailinput.child.get_text()
					else:
						tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.silk_mailinput.child.get_text()))		

				if (tag.getAttribute("key") == "XF86Launch2"):
					if (tag.getElementsByTagName("execute")[0].firstChild != None):
						tag.getElementsByTagName("execute")[0].firstChild.data = self.silk_addressinput.child.get_text()
					else:
						tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.silk_addressinput.child.get_text()))

				if (tag.getAttribute("key") == "XF86Launch3"):
					if (tag.getElementsByTagName("execute")[0].firstChild != None):
						tag.getElementsByTagName("execute")[0].firstChild.data = self.silk_calendarinput.child.get_text()
					else:
						tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.silk_calendarinput.child.get_text()))

				if (tag.getAttribute("key") == "XF86Launch4"):
					if (tag.getElementsByTagName("execute")[0].firstChild != None):
						tag.getElementsByTagName("execute")[0].firstChild.data = self.silk_starinput.child.get_text()
					else:
						tag.getElementsByTagName("execute")[0].appendChild(xmldoc.createTextNode(self.silk_starinput.child.get_text()))

			FD = open(self.RC_XML, "w")
			FD.write(xmldoc.toprettyxml("",""))
			FD.close()
			xmldoc.unlink()

	# Create xmodmap file for keys
		f=open(self.MODMAP_FILE, "w")
		
		output += "keycode " + str(bcb.store1.get_data("CTRL")) + " = Control_L\n"	
		output += "keycode " + str(bcb.store1.get_data("ALT")) + " = Alt_L"
		f.write(output)
		f.close()

	# Create kernel keymap file for keys
		output = """keycode 65 = Tab\n\talt\tkeycode 65 = Caps_Lock\n\tshift\tkeycode 65 = Caps_Lock\n\tcontrol\tkeycode 65 = Caps_Lock\n"""
		for strtxt in self.store1:
			if ((strtxt[1]-8) == int(bcb.store1.get_data("ALT"))-8):
				output += "keycode " + str(int(bcb.store1.get_data("ALT"))-8) + " = Alt \n"
			elif ((strtxt[1]-8) == int(bcb.store1.get_data("CTRL"))-8):
				output += "keycode " + str(int(bcb.store1.get_data("CTRL"))-8) + " = Control \n"
			else:
				if ((strtxt[1]-8) == 27):
					output += "keycode 27 = Shift\n"
				elif ((strtxt[1]-8) == 30):
					output += "keycode 30 = Alt\n"
				elif ((strtxt[1]-8) == 103):
					output += "keycode 103 = Shift\n"
				else:
					output += "keycode " + str(strtxt[1]-8) + " = nul\n"
		f=open(self.KERNELMAP_FILE, "w")
		f.write(output)
		f.close()
		
		if (self.clearcalib_but.get_active()):
			os.system("rm /etc/pointercal")
		
		os.system("xmodmap " + self.MODMAP_FILE)
		Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"You have to exit and start the window manager again (with startx) in order to get new mouse key mappings to work.")
		Warningdialog.run()
		Warningdialog.destroy()
		
		exitx = True
		self.window.destroy()
		gtk.main_quit()

def main():
	gtk.main()
	return

if __name__	== "__main__":
	bcb	= inputconf()	
	main()
	if (exitx):
		os.system("eXit")