#!/usr/bin/python
import re
import subprocess
import os

#get the current layout
cur_layout_cmd = ['setxkbmap', '-v']
cur_l = subprocess.Popen(cur_layout_cmd, stdout=subprocess.PIPE)
cur_l = cur_l.communicate()[0]
cur_l = cur_l.split('\n')
for l in cur_l:
	if l.startswith("symbols:"):
		cur_l = l.split()[1]
		break;
current_layout = cur_l.split('+')[1].strip()

# get the list of all xkb layouts
xkb_rules_base = "/usr/share/X11/xkb/rules/base.lst"

layouts = []
xkb_rules = open( xkb_rules_base)

l = xkb_rules.readline()
while not (l.startswith("!") and l.startswith("! layout")):
	l = xkb_rules.readline()

#layouts section starts

l = xkb_rules.readline().strip()
while l.strip() != "":
	pair = re.split("\s+", l, maxsplit=1)
	layouts.append(pair)
	l = xkb_rules.readline().strip()

xkb_rules.close()

# create  list dialog
zenity_cmd = ['zenity', '--list', '--text', "Choose desired keyboard layout.", '--radiolist']
zenity_cmd.append( "--title='Keyboard Layout'")
zenity_cmd.append("--height=500")
zenity_cmd.append("--width=350")
zenity_cmd.append('--column')
zenity_cmd.append("")
zenity_cmd.append('--column')
zenity_cmd.append("Code")
zenity_cmd.append('--column')
zenity_cmd.append("Full name")


for l in layouts:
	if l[0] == current_layout:
		zenity_cmd.append("TRUE")
	else:
		zenity_cmd.append("FALSE")
	zenity_cmd.append(l[0])
	zenity_cmd.append(l[1])
	
p = subprocess.Popen(zenity_cmd, stdout=subprocess.PIPE)
choice = p.communicate()[0]
choice = choice.strip()

#apply the choice

vm_layout = "%s/.config/qubes-keyboard-layout.rc" % os.getenv("HOME")
if choice != "":
    subprocess.check_call(['setxkbmap', choice])
    try:
        subprocess.check_call(['gsettings', 'set', 'org.gnome.libgnomekbd.keyboard', 'layouts', "['%s']" % choice])
    except:
        # fallback to config file
        file = open(vm_layout, 'w+')
        file.write(choice)
        file.close()

