from Tkinter import *
from parttable import *
from listbox import *
from rhtkinter import *
from buttonbar import *
from rhutil import *
import os
import string

class KeyboardWin(RHFrame):

    def getKeymaps(self):
	os.chdir(self.root + "/usr/lib/kbd/keytables")
	(code, out, err) = rhrun(self.root + "/usr/bin/find",  \
		('.', '-name', '*map', '-type', 'f', '-print'), None)
	lines = string.splitfields(out, "\n")
	lines.sort()
	lines.reverse()   # to get the US timezones toward the top
	return lines

    def createWidgets(self, keyboards):
	self.message = Label(self, 
		{ 'text' : "What keyboard map do you need?" })
	self.message.pack()

	self.listframe = Frame(self)

	self.list = RHListbox(self.listframe, { 'height' : '20', 
				'width' : '40', 
				'relief' : 'sunken' } )
	self.list.bind('<Double-1>', self.done)
	for map in keyboards:
	    self.list.insert('end', map[2:])
	self.list.pack({ 'side' : 'left', 'expand' : '1' , 'fill' : 'both' })

	self.scrollbar = Scrollbar(self.listframe, 
		{ 'command' : self.list.yview } )
	self.scrollbar.pack({ 'side' : 'right', 'fill' : 'y'})
	self.list['yscrollcommand'] = self.scrollbar.set
	self.listframe.pack({ 'expand' : '1', 'fill' : 'both' })

	self.Buttons = ButtonBar(self)
	self.Buttons.addButton("Ok", self.done, 1)
	self.Buttons.pack({ 'fill' : 'x' })
	self.pack({ 'expand' : '1', 'fill' : 'both' })

    def done(self, e = None):
	selection = self.list.curselection()
	if (not len(selection)):
	    return
	map = self.list.get(selection)
	if (self.test):
	    print "Would set KEYTABLE=/usr/lib/kbd/keytables/" + map, \
		" in ", self.root + "/etc/sysconfig/keyboard"
	else:
	    f = open(self.root + "/etc/sysconfig/keyboard", "w")
	    f.write("KEYTABLE=/usr/lib/kbd/keytables/" + map + "\n")
	    f.close()
	self.quit()

    def __init__(self, test, root, Master = None):
	RHFrame.__init__(self, Master)
	self.test = test
	if (test):
	    self.root = "/"
	else:
	    self.root = root
	lines = self.getKeymaps()
	self.createWidgets(lines)
	if (Master):
	    Master.title("Keyboard Type")

def setupkbd(test, root = "/"):
    win = KeyboardWin(test, root, Toplevel())
    win.update()
    win.wait_window(win)

