#!/usr/bin/env python3
#
# by Kendall Weaver <kendall@peppermintos.com>
# for Peppermint OS <http://peppermintos.com>
#
# Peppermint Control Center is a Python/GTK+3 GUI wrapper to handle a
# number of desktop configuration options from a number of different
# applications/scripts and put them all in one place.
#
#############
### To Do ###
#############
#
# 1. Improve keyboard shortcut support.
#
# 2. Add gettext support and begin working on translations.
#
# 3. Push to github.
#

import os
import sys
import subprocess
from gi.repository import Gtk
import xml.etree.ElementTree as ET


if not os.path.exists(os.path.expanduser("~/.config/peppermint-control-center/")):
    try:
        os.system("mkdir -p ~/.config/peppermint-control-center")
    except:
        print("ERROR: Configuration directory does not exist and could not be created.")
        sys.exit(1)

if not os.path.exists(os.path.expanduser("~/.config/peppermint-control-center/pointer")):
    try:
        os.system("echo '#!/bin/bash\n#Autogenerated script - Do not edit\nxset m 2 2\nxmodmap -e \"pointer = 1 2 3\"\nsynclient TouchPadOff=0\nsynclient VertEdgeScroll=0\nsynclient HorizEdgeScroll=0\nsynclient TapButton1=1\nsynclient VertTwoFingerScroll=1\nsynclient HorizTwoFingerScroll=0' >> ~/.config/peppermint-control-center/pointer")
        os.system("chmod +x ~/.config/peppermint-control-center/pointer")
    except:
        print("ERROR: pointer file does not exist and could not be generated.")
        sys.exit(1)

if not os.path.exists(os.path.expanduser("~/.config/peppermint-control-center/keyboard")):
    try:
        os.system("echo '#!/bin/bash\n#Autogenerated script - Do not edit\nxset r rate 500 20' >> ~/.config/peppermint-control-center/keyboard")
        os.system("chmod +x ~/.config/peppermint-control-center/keyboard")
    except:
        print("ERROR: keyboard file does not exist and could not be generated.")
        sys.exit(1)

if not os.path.exists(os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml")):
    try:
        os.system("cp /usr/share/peppermint/peppermint-control-center/xfce4-keyboard-shortcuts.xml ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml")
    except:
        print("ERROR: xfce4-keyboard-shortcuts.xml does not exist and could not be generated.")
        sys.exit(1)

if not os.path.exists(os.path.expanduser("~/.config/peppermint-control-center/xbindkeys.conf")):
    try:
        os.system("cp /usr/share/peppermint/peppermint-control-center/xbindkeys.conf ~/.config/peppermint-control-center/xbindkeys.conf")
    except:
        print("ERROR: xbindkeys.conf does not exist and could not be generated.")
        sys.exit(1)

if not os.path.exists(os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml")):
    try:
        os.system("cp /usr/share/peppermint/peppermint-control-center/xfwm4.xml ~/.config/xfce4/xfce-perchannel-xml/xfwm4.xml")
    except:
        print("ERROR: xfwm4.xml does not exist and could not be generated.")
        sys.exit(1)

# Open, read, and close the configuration files.
try:
    pntr_file = open(os.path.expanduser("~/.config/peppermint-control-center/pointer"), 'r')
    keys_file = open(os.path.expanduser("~/.config/peppermint-control-center/keyboard"), 'r')
    xfks_file = open(os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml"), 'r')
    bind_file = open(os.path.expanduser("~/.config/peppermint-control-center/xbindkeys.conf"), 'r')
    xfwm_file = open(os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml"), 'r')
except:
    print("ERROR: Could not open the necessary configuration files.")
    sys.exit(1)

try:
    pntr_data = pntr_file.readlines()
    keys_data = keys_file.readlines()
    xfks_data = xfks_file.readlines()
    bind_data = bind_file.readlines()
    xfwm_data = xfwm_file.readlines()
except:
    print("ERROR: One or more configuration files is corrupt.")
    sys.exit(1)

pntr_file.close()
keys_file.close()
xfks_file.close()
bind_file.close()
xfwm_file.close()

###########################################################
### Generic methods for getting/setting boolean values. ###
###########################################################


def value_from_xml(a):
    for line in xfwm_data:
        if a in line:
            b = line.split()
            c = b[3]
            d = c.replace(" ", "_")
            e = d.replace('"', ' ')
            f = e.split()
            return f[1]


def get_generic(a):
    if value_from_xml('name="{0}"'.format(a)) == "true":
        return True
    return False


def set_generic(widget, prop):
    if widget.get_active():
        os.system("xfconf-query -c xfwm4 -p /general/{0} -s true".format(prop))
    else:
        os.system("xfconf-query -c xfwm4 -p /general/{0} -s false".format(prop))

##########################################
### Methods for 'Window Manager' page. ###
##########################################


# xfwm4 theme methods.
def get_theme():
    return value_from_xml('name="theme"')


def theme_list():
    themelist = []

    syslist = os.listdir("/usr/share/themes")
    for item in syslist:
        if os.path.exists("/usr/share/themes/{0}/xfwm4/themerc".format(item)):
            themelist.append(item)

    if os.path.exists(os.path.expanduser("~/.themes/")):
        usrlist = os.listdir(os.path.expanduser("~/.themes"))
        for item in usrlist:
            if os.path.exists(os.path.expanduser("~/.themes/{0}/xfwm4/themerc".format(item))):
                themelist.append(item)

    if os.path.exists(os.path.expanduser("/usr/local/share/themes/")):
        usrlist = os.listdir(os.path.expanduser("/usr/local/share/themes"))
        for item in usrlist:
            if os.path.exists(os.path.expanduser("/usr/local/share/themes/{0}/xfwm4/themerc".format(item))):
                themelist.append(item)

    return sorted(themelist)


def theme_index():
    try:
        return theme_list().index(get_theme())
    except ValueError as e:
        print("DEBUG: Caught exception '{0}', using 'Xfwm4_Fallback' as default.".format(e))
        return theme_list().index('Xfwm4_Fallback')


def set_theme(widget):
    os.system("xfconf-query -c xfwm4 -p /general/theme -s {0}".format(theme_box.get_active_text()))


# Title font methods.
def get_title_font():
    for line in xfwm_data:
        if 'name="title_font"' in line:
            a = line.replace('    <property name="title_font" type="string" value="', '')
            b = a.replace('"/>', '')
            return b.replace("\n", "")


def set_title_font(widget):
    font_name = widget.get_font_name()
    os.system('xfconf-query -c xfwm4 -p /general/title_font -s "{0}"'.format(font_name))
    widget.set_title(font_name)


# Title alignment methods.
def get_title_alignment():
    return value_from_xml('name="title_alignment"')


def alignment_index():
    indices = {
        'left': 0,
        'center': 1,
        'right': 2
    }
    a = get_title_alignment()
    try:
        return indices[a]
    except KeyError:
        print("ERROR: Alignment index out of range.")
        sys.exit(1)


def set_title_alignment(widget):
    indices = ['left', 'center', 'right']
    a = alignment_box.get_active_text()
    if a.lower() in indices:
        os.system("xfconf-query -c xfwm4 -p /general/title_alignment -s {0}".format(a.lower()))
    else:
        print("ERROR: Alignment index out of range.")
        sys.exit(1)


# Workspace count methods:

def get_workspace_count():
    return int(value_from_xml('name="workspace_count"'))


def set_workspace_count(button):
    os.system("xfconf-query -c xfwm4 -p /general/workspace_count -s {0}".format(str(int(button.get_value()))))


# Click to focus methods.
def get_click_to_focus():
    return value_from_xml('name="click_to_focus"')


def set_click_to_focus(button, value):
    if button.get_active():
        os.system("xfconf-query -c xfwm4 -p /general/click_to_focus -s {0}".format(value))
    if value == "false":
        focus_delay_box.set_sensitive(True)
    if value == "true":
        focus_delay_box.set_sensitive(False)


# Focus Delay methods.
def get_focus_delay():
    return int(value_from_xml('name="focus_delay"'))


def set_focus_delay(widget):
    os.system("xfconf-query -c xfwm4 -p /general/focus_delay -s {0}".format(str(int(focus_delay.get_value()))))


# New window focus methods.
def get_focus_new():
    return get_generic("focus_new")


def set_focus_new(widget):
    set_generic(widget, "focus_new")


# Raise on focus methods.
def get_raise_on_focus():
    return get_generic("raise_on_focus")


def set_raise_on_focus(widget):
    set_generic(widget, "raise_on_focus")


# Methods for focus raise delay.
def get_raise_delay():
    return int(value_from_xml('name="raise_delay"'))


def set_raise_delay(widget):
    os.system("xfconf-query -c xfwm4 -p /general/raise_delay -s {0}".format(str(int(raise_delay.get_value()))))


# Raise on click methods.
def get_raise_on_click():
    return get_generic("raise_on_click")


def set_raise_on_click(widget):
    set_generic(widget, "raise_on_click")


# Window snapping methods.
def get_snap_to_border():
    return get_generic("snap_to_border")


def set_snap_to_border(widget):
    set_generic(widget, "snap_to_border")


def get_snap_to_windows():
    return get_generic("snap_to_windows")


def set_snap_to_windows(widget):
    set_generic(widget, "snap_to_windows")


def get_snap_width():
    return int(value_from_xml('name="snap_width"'))


def set_snap_width(widget):
    os.system("xfconf-query -c xfwm4 -p /general/snap_width -s {0}".format(str(int(snap_width.get_value()))))


# Workspace wrapping methods.
def get_wrap_workspaces():
    return get_generic("wrap_workspaces")


def set_wrap_workspaces(widget):
    set_generic(widget, "wrap_workspaces")


def get_wrap_windows():
    return get_generic("wrap_windows")


def set_wrap_windows(widget):
    set_generic(widget, "wrap_windows")


def get_wrap_resistance():
    return int(value_from_xml('name="wrap_resistance"'))


def set_wrap_resistance(widget):
    os.system("xfconf-query -c xfwm4 -p /general/wrap_resistance -s {0}".format(str(int(wrap_resistance.get_value()))))


# Methods for hiding window content during transformations.
def get_box_move():
    return get_generic("box_move")


def set_box_move(widget):
    set_generic(widget, "box_move")


def get_box_resize():
    return get_generic("box_resize")


def set_box_resize(widget):
    set_generic(widget, "box_resize")


# Title bar double click methods.
def get_double_click_action():
    return value_from_xml('name="double_click_action"')


def set_double_click_action(button):
    a = double_click_action.get_active_text()
    if a == "Shade window":
        b = "shade"
    elif a == "Hide window":
        b = "hide"
    elif a == "Maximize window":
        b = "maximize"
    elif a == "Fill window":
        b = "fill"
    elif a == "Nothing":
        b = "none"
    else:
        print("ERROR: Double click action index out of range.")
        sys.exit(1)
    os.system("xfconf-query -c xfwm4 -p /general/double_click_action -s {0}".format(b))


def double_click_action_index():
    indices = {
        'shade': 0,
        'hide': 1,
        'maximize': 2,
        'fill': 3,
        'none': 4
    }
    a = get_double_click_action()
    try:
        return indices[a]
    except KeyError:
        print("ERROR: Double click action index out of range.")
        sys.exit(1)

###########################################
### Methods for 'Pointer Options' page. ###
###########################################


def get_acceleration():
    return int(pntr_data[2].split()[2])


def get_threshold():
    return int(pntr_data[2].split()[3])


def get_lefthanded():
    return pntr_data[3][22] == "3"


def get_touchenable():
    return pntr_data[4][22] == "0"


def get_taptoclick():
    return pntr_data[7][21] == "1"


def get_vertedge():
    return pntr_data[5][25] == "1"


def get_horizedge():
    return pntr_data[6][26] == "1"


def get_vtwofinger():
    return pntr_data[8][30] == "1"


def get_htwofinger():
    return pntr_data[9][31] == "1"


# 'Apply Pointer Options' button.
def pntr_apply(widget):
    acceleration_value = str(int(acceleration.get_value()))
    threshold_value = str(int(threshold.get_value()))

    if lefthanded.get_active():
        lefthanded_value = "3 2 1"
    else:
        lefthanded_value = "1 2 3"

    if touchenable.get_active():
        touchenable_value = "0"
    else:
        touchenable_value = "1"

    if taptoclick.get_active():
        taptoclick_value = "1"
    else:
        taptoclick_value = "0"

    if vertedge.get_active():
        vertedge_value = "1"
    else:
        vertedge_value = "0"

    if horizedge.get_active():
        horizedge_value = "1"
    else:
        horizedge_value = "0"

    if vtwofinger.get_active():
        vtwofinger_value = "1"
    else:
        vtwofinger_value = "0"

    if htwofinger.get_active():
        htwofinger_value = "1"
    else:
        htwofinger_value = "0"

    try:
        with open(os.path.expanduser("~/.config/peppermint-control-center/pointer"), 'w') as conf:
            conf.truncate()
            conf.write("#!/bin/bash\n")
            conf.write("#Autogenerated script - Do not edit\n")
            conf.write("xset m {0} {1}\n".format(acceleration_value, threshold_value))
            conf.write('xmodmap -e "pointer = {0}"\n'.format(lefthanded_value))
            conf.write("synclient TouchPadOff={0}\n".format(touchenable_value))
            conf.write("synclient VertEdgeScroll={0}\n".format(vertedge_value))
            conf.write("synclient HorizEdgeScroll={0}\n".format(horizedge_value))
            conf.write("synclient TapButton1={0}\n".format(taptoclick_value))
            conf.write("synclient VertTwoFingerScroll={0}\n".format(vtwofinger_value))
            conf.write("synclient HorizTwoFingerScroll={0}\n".format(htwofinger_value))
    except:
        print("ERROR: Could not save new configuration.")
        sys.exit(1)

    try:
        os.system("ppmcc-load")
    except:
        print("ERROR: Could not load new configuration.")
        sys.exit(1)


def get_delay():
    return int(keys_data[2].split()[3])


def get_interval():
    return int(keys_data[2].split()[4])


def lxkeymap(widget):
    os.system("lxkeymap &")


def layoutsetter(widget):
    win = SetLayout()
    win.show_all()


def keys_apply(widget):
    delay_value = str(int(delay.get_value()))
    interval_value = str(int(interval.get_value()))

    try:
        with open(os.path.expanduser("~/.config/peppermint-control-center/keyboard"), 'w') as conf:
            conf.truncate()
            conf.write("#!/bin/bash\n")
            conf.write("#Autogenerated script - Do not edit\n")
            conf.write("xset r rate {0} {1}\n".format(delay_value, interval_value))
    except:
        print("ERROR: Could not save new configuration.")
        sys.exit(1)

    try:
        os.system("ppmcc-load")
    except:
        print("ERROR: Could not load new configuration.")
        sys.exit(1)

##############################################
### Methods for 'Keyboard Shortcuts' page. ###
##############################################


# Swap out encoded strings for human readable characters.
def encodereplace(a):
    b = a.replace("&lt;", "<")
    c = b.replace("&gt;", ">")
    return c


# Swap out human readable characters for encoded strings.
def unencodereplace(a):
    b = a.replace("<", "&lt;")
    c = b.replace(">", "&gt;")
    return c


# Format the xml data into a more human readable form.
def xmlformat(a):
    spl = a.split()
    name = spl[3].replace('"', ' ').split()
    keys = spl[1].replace('"', ' ').split()
    disp = "{0} {1}".format(name[1], keys[1])
    kpad = disp.replace("KP_", "")
    return encodereplace(kpad).replace("Primary", "Control")


# Match the xbindkeys format to the xfce4 format.
def bindformat(a):
    b = a.replace("Alt", "<Alt>")
    c = b.replace("Mod4", "<Super>")
    d = c.replace("Control", "<Control>")
    e = d.replace("Shift", "<Shift>")
    return e.replace("+", "")


# Return the xfce4 format to native xbindkeys format.
def unbindformat(a):
    b = a.replace("<Alt>", "Alt + ")
    c = b.replace("<Super>", "Mod4 + ")
    d = c.replace("<Control>", "Control + ")
    e = d.replace("<Shift>", "Shift + ")
    return e


# Return a list of all valid shortcuts in xfce4-keyboard-shortcuts.xml.
def get_xfce_shortcuts():

    xfceline = []

    for line in xfks_data:
        if 'type="string"' in line:
            try:
                xfceline.append(xmlformat(line))
            except:
                continue

    return xfceline


# This works as long as xbindkeys-config is not used and the user does
# not edit the config file. We should launch xbindkeys in Peppermint
# using a custom config file and this package should probably provide
# xbindkeys-config in the debian/control file in order to prevent any
# conflicts.
def get_xbindkeys():

    bindlist = []
    bindtemp = ""
    bindline = []

    for line in bind_data:
        if line[0] == "#" or line[0] == "\n":
            continue
        else:
            bindlist.append(line.replace("\n", ""))

    for line in bindlist:
        if line[0] == '"':
            bindtemp = line.replace('"', '')
        elif line[0] == " ":
            a = line.replace(" ", "")
            bindline.append(bindtemp + "\n" + bindformat(a))
        else:
            continue

    return bindline


def edit_xfce_shortcut(selection, path, column):
    global workspace
    workspace = "xfce"
    store = selection.get_model()
    global command
    command = store[path][0]
    global oldcommand
    oldcommand = store[path][1]
    treeiter = store.get_iter(path)
    shortcut = KeyboardShortcut(store, treeiter)
    shortcut.show_all()


def edit_bind_shortcut(selection, path, column):
    global workspace
    workspace = "bind"
    store = selection.get_model()
    global command
    command = store[path][0]
    global oldcommand
    oldcommand = store[path][1]
    treeiter = store.get_iter(path)
    shortcut = KeyboardShortcut(store, treeiter)
    shortcut.show_all()


def set_xfce_shortcut(command, shortcut):
    new0 = shortcut.replace("Control", "Primary")
    new1 = new0.replace("Space", "space")
    os.system('xfconf-query -c xfce4-keyboard-shortcuts -p "/xfwm4/custom/{0}" -r'.format(oldcommand))
    os.system('xfconf-query -c xfce4-keyboard-shortcuts -p "/xfwm4/custom/{0}" -n -t string -s {1}'.format(
        new1, command))


################################################################################################
### To Do: This will require more formatting as it has a bazillion possible breaking points. ###
################################################################################################
def set_bind_shortcut(command, shortcut, store):
    bindlist = []
    for item in store:
        if command in item[0] and oldcommand in item[1]:
            bindlist.append([item[0], shortcut])
            continue
        bindlist.append([item[0], item[1]])

    with open(os.path.expanduser("~/.config/peppermint-control-center/xbindkeys.conf"), 'w') as conf:
        conf.truncate()
        for line in bindlist:
            new0 = line[1]
            new1 = new0.replace("<Control>", "Control+")
            new2 = new1.replace("<Alt>", "Alt+")
            new3 = new2.replace("<Super>", "Mod4+")
            new4 = new3.replace("<Shift>", "Shift+")
            conf.write('"{0}"\n    {1}\n\n'.format(line[0], new4))

    os.system("killall xbindkeys")
    os.system("xbindkeys -f ~/.config/peppermint-control-center/xbindkeys.conf")


def refresh_bind_shortcuts():
    bindlist = []
    for item in bindstore:
        bindlist.append([item[0], item[1]])

    with open(os.path.expanduser("~/.config/peppermint-control-center/xbindkeys.conf"), 'w') as conf:
        conf.truncate()
        for line in bindlist:
            new0 = line[1]
            new1 = new0.replace("<Control>", "Control+")
            new2 = new1.replace("<Alt>", "Alt+")
            new3 = new2.replace("<Super>", "Mod4+")
            new4 = new3.replace("<Shift>", "Shift+")
            conf.write('"{0}"\n    {1}\n\n'.format(line[0], new4))

    os.system("killall xbindkeys")
    os.system("xbindkeys -f ~/.config/peppermint-control-center/xbindkeys.conf")


def action_bind_new(widget, liststore):
    new = NewShortcut(liststore)
    new.show_all()


def action_bind_restore(widget):
    action = "bind-restore"
    command = "cp -f /usr/share/peppermint/peppermint-control-center/xbindkeys.conf ~/.config/peppermint-control-center/xbindkeys.conf"
    confirm = AreYouSure(action, command)
    confirm.show_all()


def action_xfce_restore(widget):
    action = "xfce-restore"
    command = ""
    confirm = AreYouSure(action, command)
    confirm.show_all()

###########################################
### Methods for 'Desktop Effects' page. ###
###########################################


def get_use_compositing():
    return get_generic("use_compositing")


def set_use_compositing(widget):
    set_generic(widget, "use_compositing")
    if widget.get_active() == True:
        effects_box.set_sensitive(True)
    elif widget.get_active() == False:
        effects_box.set_sensitive(False)


# CheckButtons
def get_unredirect_overlays():
    return get_generic("unredirect_overlays")


def set_unredirect_overlays(widget):
    set_generic(widget, "unredirect_overlays")


def get_sync_to_vblank():
    return get_generic("sync_to_vblank")


def set_sync_to_vblank(widget):
    set_generic(widget, "sync_to_vblank")


def get_show_popup_shadow():
    return get_generic("show_popup_shadow")


def set_show_popup_shadow(widget):
    set_generic(widget, "show_popup_shadow")


def get_show_dock_shadow():
    return get_generic("show_dock_shadow")


def set_show_dock_shadow(widget):
    set_generic(widget, "show_dock_shadow")


def get_show_frame_shadow():
    return get_generic("show_frame_shadow")


def set_show_frame_shadow(widget):
    set_generic(widget, "show_frame_shadow")


# HScales
def get_frame_opacity():
    return int(value_from_xml('name="frame_opacity"'))


def set_frame_opacity(widget):
    os.system("xfconf-query -c xfwm4 -p /general/frame_opacity -s {0}".format(str(int(widget.get_value()))))


def get_inactive_opacity():
    return int(value_from_xml('name="inactive_opacity"'))


def set_inactive_opacity(widget):
    os.system("xfconf-query -c xfwm4 -p /general/inactive_opacity -s {0}".format(str(int(widget.get_value()))))


def get_move_opacity():
    return int(value_from_xml('name="move_opacity"'))


def set_move_opacity(widget):
    os.system("xfconf-query -c xfwm4 -p /general/move_opacity -s {0}".format(str(int(widget.get_value()))))


def get_resize_opacity():
    return int(value_from_xml('name="resize_opacity"'))


def set_resize_opacity(widget):
    os.system("xfconf-query -c xfwm4 -p /general/resize_opacity -s {0}".format(str(int(widget.get_value()))))


def get_popup_opacity():
    return int(value_from_xml('name="popup_opacity"'))


def set_popup_opacity(widget):
    os.system("xfconf-query -c xfwm4 -p /general/popup_opacity -s {0}".format(str(int(widget.get_value()))))

####################################
### Methods for 'Advanced' page. ###
####################################


# Window cycling
def get_cycle_minimum():
    return get_generic("cycle_minimum")


def set_cycle_minimum(widget):
    set_generic(widget, "cycle_minimum")


def get_cycle_hidden():
    return get_generic("cycle_hidden")


def set_cycle_hidden(widget):
    set_generic(widget, "cycle_hidden")


def get_cycle_workspaces():
    return get_generic("cycle_workspaces")


def set_cycle_workspaces(widget):
    set_generic(widget, "cycle_workspaces")


def get_cycle_draw_frame():
    return get_generic("cycle_draw_frame")


def set_cycle_draw_frame(widget):
    set_generic(widget, "cycle_draw_frame")


# Window focus
def get_prevent_focus_stealing():
    return get_generic("prevent_focus_stealing")


def set_prevent_focus_stealing(widget):
    set_generic(widget, "prevent_focus_stealing")


def get_focus_hint():
    return get_generic("focus_hint")


def set_focus_hint(widget):
    set_generic(widget, "focus_hint")


def get_activate_action():
    return value_from_xml('name="activate_action"')


def set_activate_action(button, value):
    if button.get_active():
        os.system("xfconf-query -c xfwm4 -p /general/activate_action -s {0}".format(value))


# Accessibility
def get_raise_with_any_button():
    return get_generic("raise_with_any_button")


def set_raise_with_any_button(widget):
    set_generic(widget, "raise_with_any_button")


def get_borderless_maximize():
    return get_generic("borderless_maximize")


def set_borderless_maximize(widget):
    set_generic(widget, "borderless_maximize")


def get_restore_on_move():
    return get_generic("restore_on_move")


def set_restore_on_move(widget):
    set_generic(widget, "restore_on_move")
    if widget.get_active() == True:
        tile_on_move.set_sensitive(True)
    elif widget.get_active() == False:
        tile_on_move.set_sensitive(False)


def get_tile_on_move():
    return get_generic("tile_on_move")


def set_tile_on_move(widget):
    set_generic(widget, "tile_on_move")


def get_snap_resist():
    return get_generic("snap_resist")


def set_snap_resist(widget):
    set_generic(widget, "snap_resist")


def get_urgent_blink():
    return get_generic("urgent_blink")


def set_urgent_blink(widget):
    set_generic(widget, "urgent_blink")
    if widget.get_active() == True:
        repeat_urgent_blink.set_sensitive(True)
    else:
        repeat_urgent_blink.set_sensitive(False)
        repeat_urgent_blink.set_active(False)
        set_repeat_urgent_blink_off()


def get_repeat_urgent_blink():
    return get_generic("repeat_urgent_blink")


def set_repeat_urgent_blink(widget):
    set_generic(widget, "repeat_urgent_blink")


def set_repeat_urgent_blink_off():
    os.system("xfconf-query -c xfwm4 -p /general/repeat_urgent_blink -s false")


def get_mousewheel_rollup():
    return get_generic("mousewheel_rollup")


def set_mousewheel_rollup(widget):
    set_generic(widget, "mousewheel_rollup")


# Workspaces
def get_scroll_workspaces():
    return get_generic("scroll_workspaces")


def set_scroll_workspaces(widget):
    set_generic(widget, "scroll_workspaces")


def get_wrap_layout():
    return get_generic("wrap_layout")


def set_wrap_layout(widget):
    set_generic(widget, "wrap_layout")


# Window placement
def get_placement_ratio():
    return int(value_from_xml("placement_ratio"))


def set_placement_ratio(widget):
    os.system("xfconf-query -c xfwm4 -p /general/placement_ratio -s {0}".format(str(int(widget.get_value()))))


def get_placement_mode():
    return value_from_xml("placement_mode")


def set_placement_mode(button, value):
    if button.get_active():
        os.system("xfconf-query -c xfwm4 -p /general/placement_mode -s {0}".format(value))


# 'Are you sure?' window.
class AreYouSure(Gtk.Window):

    def close_it(self, widget):
        self.close()

    def confirm(self, widget, action, command):
        if action == "bind-restore":
            os.system(command)
            os.system("killall xbindkeys")
            os.system("xbindkeys -f ~/.config/peppermint-control-center/xbindkeys.conf")

            bindview.set_model(None)
            bindstore.clear()
            get_bind = get_xbindkeys()
            for line in get_bind:
                a = line.split("\n")
                bindstore.append([a[0], a[1]])

            bindview.set_model(bindstore)

            self.close()
        elif action == "xfce-restore":
            os.system('zenity --error --text "This feature has not yet been implemented."')
        elif action == "delete":
            bindstore.remove(command)
            refresh_bind_shortcuts()
            self.close()

    def __init__(self, action, command):
        Gtk.Window.__init__(self, title="Confirm")
        self.set_size_request(250, 120)
        self.set_icon_from_file("/usr/share/pixmaps/peppermint-control-center.png")

        label = Gtk.Label()
        label.set_markup("<b>Are you sure you want to perform this action?</b>")

        buttons = Gtk.HBox()
        void = Gtk.Label()
        no = Gtk.Button.new_from_stock(Gtk.STOCK_NO)
        no.connect("clicked", self.close_it)
        yes = Gtk.Button.new_from_stock(Gtk.STOCK_YES)
        yes.connect("clicked", self.confirm, action, command)
        buttons.pack_start(void, True, True, 0)
        buttons.pack_start(no, False, False, 10)
        buttons.pack_start(yes, False, False, 0)

        vbox = Gtk.VBox()
        vbox.pack_start(label, True, True, 0)
        vbox.pack_start(buttons, False, False, 10)
        hbox = Gtk.HBox()
        hbox.pack_start(vbox, True, True, 10)
        self.add(hbox)


class SetLayout(Gtk.Window):

    def close_it(self, widget):
        self.close()

    def revert_it(self, widget, command):
        execute = "setxkbmap " + command
        os.system(execute)
        os.system('touch ~/.config/peppermint-control-center/keyboard_layout')
        os.system('chmod +x ~/.config/peppermint-control-center/keyboard_layout')
        os.system('echo "#!/bin/sh\n{0}" > ~/.config/peppermint-control-center/keyboard_layout'.format(execute))

    def getlist(self):
        layoutfile = ET.parse("/usr/share/X11/xkb/rules/base.xml")
        root = layoutfile.getroot()

        layoutlist = []

        for child in root.iter('layout'):
            name = ""
            sublist = []

            for item in child.findall('configItem'):
                name = item.find('name').text
                command = name
                desc = item.find('description').text
                sublist.append([command, desc])

            for variantList in child.findall('variantList'):
                for variant in variantList.findall('variant'):
                    for item in variant.findall('configItem'):
                        varname = item.find('name').text
                        command = name + " " + varname
                        vardesc = item.find('description').text
                        sublist.append([command, vardesc])

            layoutlist.append([name, sublist])

        return sorted(layoutlist)

    def fill_variants(self, widget):
        variantstore.clear()
        layouts = self.getlist()
        select = layoutview.get_selection()
        model, treeiter = select.get_selected()
        for layout in layouts:
            if layout[0] == model[treeiter][0]:
                for variant in layout[1]:
                    variantstore.append([variant[0], variant[1]])

        x = 0
        for obj in variantstore:
            if str(obj[0]) == cm:
                variantview.set_cursor(x)
                variantview.scroll_to_cell(x)
            x += 1

    def set_layout(self, widget, var):
        try:
            select = variantview.get_selection()
            model, treeiter = select.get_selected()
            execute = "setxkbmap {0}".format(model[treeiter][0])
            os.system(execute)
            os.system('touch ~/.config/peppermint-control-center/keyboard_layout')
            os.system('chmod +x ~/.config/peppermint-control-center/keyboard_layout')
            os.system('echo "#!/bin/sh\n{0}" > ~/.config/peppermint-control-center/keyboard_layout'.format(execute))
        except:
            pass

    def get_current(self):
        command = ""
        cl = subprocess.Popen('setxkbmap -query | grep layout', shell=True, stdout=subprocess.PIPE)
        curlay = str(cl.stdout.read())
        if "layout:" in curlay:
            cl1 = curlay.split()
            current_layout = cl1[1].replace("\\n'", "")
            command = command + current_layout

        cv = subprocess.Popen('setxkbmap -query | grep variant', shell=True, stdout=subprocess.PIPE)
        curvar = str(cv.stdout.read())
        if "variant:" in curvar:
            cv1 = curvar.split()
            current_variant = cv1[1].replace("\\n'", "")
            command = "{0} {1}".format(command, current_variant)

        return current_layout, command

    def __init__(self):
        Gtk.Window.__init__(self, title="Select Keyboard Layout")
        self.set_size_request(600, 480)
        self.set_icon_from_file("/usr/share/pixmaps/peppermint-control-center.png")

        global cl, cm
        cl, cm = self.get_current()
        oldcommand = cm

        global layoutstore
        layoutstore = Gtk.ListStore(str)
        global variantstore
        variantstore = Gtk.ListStore(str, str)

        global layoutview
        layoutview = Gtk.TreeView(layoutstore)
        layout = Gtk.CellRendererText()
        layoutcolumn = Gtk.TreeViewColumn("Layout", layout, text=0)
        layoutview.append_column(layoutcolumn)

        global variantview
        variantview = Gtk.TreeView(variantstore)
        variant = Gtk.CellRendererText()
        description = Gtk.CellRendererText()
        variantcolumn = Gtk.TreeViewColumn("Variant")
        variantcolumn.pack_start(variant, True)
        variantcolumn.pack_start(description, True)
        variantcolumn.add_attribute(variant, "text", 0)
        variantcolumn.add_attribute(description, "text", 1)
        variantview.append_column(variantcolumn)

        layouts = self.getlist()
        for layout in layouts:
            layoutstore.append([layout[0]])

        select = layoutview.get_selection()
        select.connect("changed", self.fill_variants)

        x = 0
        for obj in layoutstore:
            if str(obj[0]) == cl:
                layoutview.set_cursor(x)
                layoutview.scroll_to_cell(x)
            x += 1

        layoutbox = Gtk.HBox()
        layoutscroll = Gtk.ScrolledWindow()
        variantscroll = Gtk.ScrolledWindow()
        layoutscroll.add(layoutview)
        variantscroll.add(variantview)
        layoutbox.pack_start(layoutscroll, True, True, 0)
        layoutbox.pack_start(variantscroll, True, True, 5)

        entryt = Gtk.Entry()
        entryt.set_width_chars(35)
        entryt.set_placeholder_text("Type here to test the layout.")
        void = Gtk.Label()
        applyb = Gtk.Button.new_from_stock(Gtk.STOCK_APPLY)
        applyb.connect("clicked", self.set_layout, "us")
        revert = Gtk.Button.new_from_stock(Gtk.STOCK_REVERT_TO_SAVED)
        revert.connect("clicked", self.revert_it, oldcommand)
        cancel = Gtk.Button.new_from_stock(Gtk.STOCK_CLOSE)
        cancel.connect("clicked", self.close_it)
        buttons = Gtk.HBox()
        buttons.pack_start(entryt, False, False, 0)
        buttons.pack_start(void, True, True, 0)
        buttons.pack_start(applyb, False, False, 0)
        buttons.pack_start(revert, False, False, 10)
        buttons.pack_start(cancel, False, False, 0)

        vbox = Gtk.VBox()
        vbox.pack_start(layoutbox, True, True, 0)
        vbox.pack_start(buttons, False, False, 10)
        hbox = Gtk.HBox()
        hbox.pack_start(vbox, True, True, 10)
        self.add(hbox)


# Add new shortcut window.
class NewShortcut(Gtk.Window):

    def close_it(self, widget):
        self.close()

    def add_shortcut(self, widget, liststore):
        global oldcommand
        oldcommand = ""
        global command
        command = newcommand.get_text()
        global workspace
        workspace = "bind"
        liststore.prepend([newcommand.get_text(), ""])
        treeiter = liststore.get_iter(0)
        print(treeiter)
        print(newcommand.get_text())
        print(liststore[0][0])
        self.close()
        a = KeyboardShortcut(liststore, treeiter)
        a.show_all()

    def __init__(self, liststore):
        Gtk.Window.__init__(self, title="Add New Shortcut")
        self.set_size_request(250, 120)
        self.set_icon_from_file("/usr/share/pixmaps/peppermint-control-center.png")

        label = Gtk.Label("Enter the command to execute:")

        global newcommand
        newcommand = Gtk.Entry()

        buttons = Gtk.HBox()
        button_void = Gtk.Label()
        button_okay = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
        button_okay.connect("clicked", self.add_shortcut, liststore)
        button_cancel = Gtk.Button.new_from_stock(Gtk.STOCK_CANCEL)
        button_cancel.connect("clicked", self.close_it)
        buttons.pack_start(button_void, True, True, 0)
        buttons.pack_start(button_cancel, False, False, 10)
        buttons.pack_start(button_okay, False, False, 0)

        vbox = Gtk.VBox()
        vbox.pack_start(label, True, True, 10)
        vbox.pack_start(newcommand, False, False, 0)
        vbox.pack_start(buttons, False, False, 10)
        hbox = Gtk.HBox()
        hbox.pack_start(vbox, True, True, 10)
        self.add(hbox)


# Keyboard Shortcut selection window.
class KeyboardShortcut(Gtk.Window):

    def close_it(self, widget):
        self.close()

    def action_bind_del(self, widget, store, treeiter):
        action = "delete"
        command = treeiter
        self.close()
        confirm = AreYouSure(action, command)
        confirm.show_all()

    def set_shortcut(self, widget, store, treeiter):

        newkey = keybox_entry.get_text()
        array = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F12", "`", "1", "2", "3", "4", "5", "6",
                 "7", "8", "9", "0", "-", "=", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s",
                 "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/", "\\",
                 "Space", "Tab", "Up", "Down", "Left", "Right"]
        newshortcut = ""
        if newkey == " ":
            newkey = "Space"

        if newkey in array:
            if _shift.get_active():
                newshortcut = newshortcut + "<Shift>"
            if _control.get_active():
                newshortcut = newshortcut + "<Control>"
            if _super.get_active():
                newshortcut = newshortcut + "<Super>"
            if _alt.get_active():
                newshortcut = newshortcut + "<Alt>"

            if _shift.get_active() == False and _control.get_active() == False and _super.get_active() == False and \
                    _alt.get_active() == False:
                assign_void.set_markup("<b>Specify modifier(s)</b>")
            else:
                newshortcut = newshortcut + newkey
                print(newshortcut)
                store.set_value(treeiter, 1, newshortcut)

                if workspace == "xfce":
                    set_xfce_shortcut(command, newshortcut)
                elif workspace == "bind":
                    set_bind_shortcut(command, newshortcut, store)
                else:
                    print("ERROR: Unknown workspace type.")
                    sys.exit(1)
                self.close()
        else:
            assign_void.set_markup("<b>Invalid character</b>")

    def __init__(self, store, treeiter):
        Gtk.Window.__init__(self, title="Assign New Shortcut")
        self.set_size_request(250, 120)
        self.set_icon_from_file("/usr/share/pixmaps/peppermint-control-center.png")

        buttons = Gtk.HBox()
        global _shift
        _shift = Gtk.ToggleButton("Shift")
        global _control
        _control = Gtk.ToggleButton("Control")
        global _super
        _super = Gtk.ToggleButton("Super")
        global _alt
        _alt = Gtk.ToggleButton("Alt")
        buttons.pack_start(_shift, True, True, 5)
        buttons.pack_start(_control, True, True, 5)
        buttons.pack_start(_super, True, True, 5)
        buttons.pack_start(_alt, True, True, 5)

        keybox = Gtk.HBox()
        keybox_label = Gtk.Label("Enter a valid character:")
        keybox_space = Gtk.Label(" ")
        global keybox_entry
        keybox_entry = Gtk.Entry()
        keybox.pack_start(keybox_label, False, False, 0)
        keybox.pack_start(keybox_space, False, False, 5)
        keybox.pack_start(keybox_entry, True, True, 0)

        assign = Gtk.HBox()
        global assign_void
        assign_void = Gtk.Label()
        bind_delete = Gtk.Button.new_from_stock(Gtk.STOCK_DELETE)
        bind_delete.connect("clicked", self.action_bind_del, store, treeiter)
        assign_cancel = Gtk.Button.new_from_stock(Gtk.STOCK_CANCEL)
        assign_cancel.connect("clicked", self.close_it)
        assign_apply = Gtk.Button.new_from_stock(Gtk.STOCK_APPLY)
        assign_apply.connect("clicked", self.set_shortcut, store, treeiter)
        assign.pack_start(assign_void, True, True, 0)
        assign.pack_start(bind_delete, False, False, 0)
        assign.pack_start(assign_cancel, False, False, 5)
        assign.pack_start(assign_apply, False, False, 0)

        shortvbox = Gtk.VBox()
        shortvbox.pack_start(buttons, True, False, 5)
        shortvbox.pack_start(keybox, True, False, 5)
        shortvbox.pack_start(assign, True, False, 5)
        shorthbox = Gtk.HBox()
        shorthbox.pack_start(shortvbox, True, True, 10)

        self.add(shorthbox)


# Window and window layout.
class ControlCenter(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Peppermint Control Center")
        self.set_size_request(600, 500)
        self.set_icon_from_file("/usr/share/pixmaps/peppermint-control-center.png")

        ##############################
        ### 'Window Manager' page. ###
        ##############################
        page_wman_lab = Gtk.Label("Window Manager")
        page_wman = Gtk.VBox()
        page_wman_hbox = Gtk.HBox()
        page_wman_hbox.pack_start(page_wman, True, True, 10)
        scroll_wman = Gtk.ScrolledWindow()
        scroll_wman.add(page_wman_hbox)

        theme_label = Gtk.Label()
        theme_label.set_markup("<b>Theme</b>")
        theme_void = Gtk.Label(" ")
        theme_label_wrapper = Gtk.HBox()
        theme_label_wrapper.pack_start(theme_label, False, False, 10)
        theme_label_wrapper.pack_start(theme_void, True, True, 0)
        global theme_box
        theme_box = Gtk.ComboBoxText()
        theme_box.connect("changed", set_theme)

        for theme in theme_list():
            theme_box.append_text(theme)

        theme_box.set_active(theme_index())
        theme_box_wrapper = Gtk.HBox()
        theme_box_wrapper.pack_start(theme_box, True, True, 20)

        title_font_label = Gtk.Label()
        title_font_label.set_markup("<b>Title font</b>")
        title_font_void = Gtk.Label(" ")
        title_font_label_wrapper = Gtk.HBox()
        title_font_label_wrapper.pack_start(title_font_label, False, False, 10)
        title_font_label_wrapper.pack_start(title_font_void, True, True, 0)
        global title_font
        title_font = Gtk.FontButton()
        title_font.set_font_name(get_title_font())
        title_font.connect("font-set", set_title_font)
        title_font_wrapper = Gtk.HBox()
        title_font_wrapper.pack_start(title_font, True, True, 20)

        title_alignment_label = Gtk.Label()
        title_alignment_label.set_markup("<b>Title alignment</b>")
        title_alignment_void = Gtk.Label(" ")
        title_alignment_label_wrapper = Gtk.HBox()
        title_alignment_label_wrapper.pack_start(title_alignment_label, False, False, 10)
        title_alignment_label_wrapper.pack_start(title_alignment_void, True, True, 0)
        global alignment_box
        alignment_box = Gtk.ComboBoxText()
        alignment_box.connect("changed", set_title_alignment)
        alignment_box.append_text("Left")
        alignment_box.append_text("Center")
        alignment_box.append_text("Right")
        alignment_box.set_active(alignment_index())
        alignment_box_wrapper = Gtk.HBox()
        alignment_box_wrapper.pack_start(alignment_box, True, True, 20)

        workspace_count_label = Gtk.Label()
        workspace_count_label.set_markup("<b>Number of workspaces:</b>")
        workspace_count_adj = Gtk.Adjustment(0, 1, 100, 1, 10, 0)
        global workspace_count
        workspace_count = Gtk.SpinButton()
        workspace_count.set_adjustment(workspace_count_adj)
        workspace_count.set_value(get_workspace_count())
        workspace_count.set_numeric(True)
        workspace_count.connect("changed", set_workspace_count)
        workspace_count_box = Gtk.HBox()
        workspace_count_box.pack_start(workspace_count_label, False, False, 10)
        workspace_count_box.pack_start(workspace_count, False, False, 10)

        global focus_delay_box
        focus_delay_box = Gtk.HBox()
        focus_delay_wrapper = Gtk.HBox()
        focus_delay_wrapper.pack_start(focus_delay_box, True, True, 50)

        click_to_focus_label_box = Gtk.HBox()
        click_to_focus_label = Gtk.Label()
        click_to_focus_label.set_markup("<b>Focus model</b>")
        click_to_focus_void = Gtk.Label(" ")
        click_to_focus_label_box.pack_start(click_to_focus_label, False, False, 10)
        click_to_focus_label_box.pack_start(click_to_focus_void, True, True, 0)
        ctf_button1 = Gtk.RadioButton.new_with_label_from_widget(None, "Click to focus")
        ctf_button1.connect("toggled", set_click_to_focus, "true")

        if get_click_to_focus() == "true":
            ctf_button1.set_active(True)

        ctf_button2 = Gtk.RadioButton.new_from_widget(ctf_button1)
        ctf_button2.set_label("Focus follows mouse")
        ctf_button2.connect("toggled", set_click_to_focus, "false")

        if get_click_to_focus() == "false":
            ctf_button2.set_active(True)

        click_to_focus = Gtk.HBox()
        click_to_focus.pack_start(ctf_button1, True, True, 30)
        click_to_focus.pack_start(ctf_button2, True, True, 30)

        focus_delay_label_box = Gtk.HBox()
        focus_delay_label = Gtk.Label("Delay before window receives focus:")
        focus_delay_void = Gtk.Label(" ")
        focus_delay_label_box.pack_start(focus_delay_label, False, False, 30)
        focus_delay_label_box.pack_start(focus_delay_void, True, True, 0)
        focus_delay_short = Gtk.Label()
        focus_delay_short.set_markup("<i>Short</i>")
        focus_delay_long = Gtk.Label()
        focus_delay_long.set_markup("<i>Long</i>")
        global focus_delay
        focus_delay = Gtk.HScale()
        focus_delay.set_range(5, 2000)
        focus_delay.set_increments(1, 1)
        focus_delay.set_digits(0)
        focus_delay.set_value(get_focus_delay())
        focus_delay.connect("value-changed", set_focus_delay)
        focus_delay_box.pack_start(focus_delay_short, False, False, 0)
        focus_delay_box.pack_start(focus_delay, True, True, 10)
        focus_delay_box.pack_start(focus_delay_long, False, False, 0)

        if ctf_button1.get_active():
            focus_delay_box.set_sensitive(False)

        focus_new_label_box = Gtk.HBox()
        focus_new_label = Gtk.Label()
        focus_new_label.set_markup("<b>New window focus</b>")
        focus_new_void = Gtk.Label(" ")
        focus_new_label_box.pack_start(focus_new_label, False, False, 10)
        focus_new_label_box.pack_start(focus_new_void, True, True, 0)
        global focus_new
        focus_new = Gtk.CheckButton("Automatically give focus to newly created windows")
        focus_new.set_active(get_focus_new())
        focus_new.connect("toggled", set_focus_new)
        focus_new_wrapper = Gtk.HBox()
        focus_new_wrapper.pack_start(focus_new, True, True, 30)

        global raise_delay_box
        raise_delay_box = Gtk.HBox()
        raise_delay_wrapper = Gtk.HBox()
        raise_delay_wrapper.pack_start(raise_delay_box, True, True, 50)

        raise_on_focus_label_box = Gtk.HBox()
        raise_on_focus_label = Gtk.Label()
        raise_on_focus_label.set_markup("<b>Raise on focus</b>")
        raise_on_focus_void = Gtk.Label(" ")
        raise_on_focus_label_box.pack_start(raise_on_focus_label, False, False, 10)
        raise_on_focus_label_box.pack_start(raise_on_focus_void, True, True, 0)
        global raise_on_focus
        raise_on_focus = Gtk.CheckButton("Automatically raise windows when they receive focus")
        raise_on_focus.set_active(get_raise_on_focus())
        raise_on_focus.connect("toggled", set_raise_on_focus)
        raise_on_focus_wrapper = Gtk.HBox()
        raise_on_focus_wrapper.pack_start(raise_on_focus, True, True, 30)

        raise_delay_label_box = Gtk.HBox()
        raise_delay_label_wrapper = Gtk.HBox()
        raise_delay_label_wrapper.pack_start(raise_delay_label_box, True, True, 30)
        raise_delay_label = Gtk.Label("Delay before raising focused window:")
        raise_delay_void = Gtk.Label(" ")
        raise_delay_label_box.pack_start(raise_delay_label, False, False, 0)
        raise_delay_label_box.pack_start(raise_delay_void, True, True, 0)
        raise_delay_short = Gtk.Label()
        raise_delay_short.set_markup("<i>Short</i>")
        raise_delay_long = Gtk.Label()
        raise_delay_long.set_markup("<i>Long</i>")
        global raise_delay
        raise_delay = Gtk.HScale()
        raise_delay.set_range(5, 2000)
        raise_delay.set_increments(1, 1)
        raise_delay.set_digits(0)
        raise_delay.set_value(get_raise_delay())
        raise_delay.connect("value-changed", set_raise_delay)
        raise_delay_box.pack_start(raise_delay_short, False, False, 0)
        raise_delay_box.pack_start(raise_delay, True, True, 10)
        raise_delay_box.pack_start(raise_delay_long, False, False, 0)

        raise_on_click_label_box = Gtk.HBox()
        raise_on_click_label = Gtk.Label()
        raise_on_click_label.set_markup("<b>Raise on click</b>")
        raise_on_click_void = Gtk.Label(" ")
        raise_on_click_label_box.pack_start(raise_on_click_label, False, False, 10)
        raise_on_click_label_box.pack_start(raise_on_click_void, True, True, 0)
        global raise_on_click
        raise_on_click = Gtk.CheckButton("Raise window when clicking inside an application window")
        raise_on_click.set_active(get_raise_on_click())
        raise_on_click.connect("toggled", set_raise_on_click)
        raise_on_click_wrapper = Gtk.HBox()
        raise_on_click_wrapper.pack_start(raise_on_click, True, True, 30)

        snap_label_box = Gtk.HBox()
        snap_label = Gtk.Label()
        snap_label.set_markup("<b>Window Snapping</b>")
        snap_void = Gtk.Label(" ")
        snap_label_box.pack_start(snap_label, False, False, 10)
        snap_label_box.pack_start(snap_void, True, True, 0)
        global snap_to_border
        snap_to_border = Gtk.CheckButton("To screen borders")
        snap_to_border.set_active(get_snap_to_border())
        snap_to_border.connect("toggled", set_snap_to_border)
        global snap_to_windows
        snap_to_windows = Gtk.CheckButton("To other windows")
        snap_to_windows.set_active(get_snap_to_windows())
        snap_to_windows.connect("toggled", set_snap_to_windows)
        snap_to_wrapper = Gtk.HBox()
        snap_to_wrapper.pack_start(snap_to_border, True, True, 30)
        snap_to_wrapper.pack_start(snap_to_windows, True, True, 30)

        global snap_width_box
        snap_width_box = Gtk.HBox()
        snap_width_wrapper = Gtk.HBox()
        snap_width_wrapper.pack_start(snap_width_box, True, True, 50)

        snap_width_label = Gtk.Label("Distance:")
        snap_width_void = Gtk.Label(" ")
        snap_width_label_wrapper = Gtk.HBox()
        snap_width_label_wrapper.pack_start(snap_width_label, False, False, 30)
        snap_width_label_wrapper.pack_start(snap_width_void, True, True, 0)
        snap_width_small = Gtk.Label()
        snap_width_small.set_markup("<i>Small</i>")
        snap_width_wide = Gtk.Label()
        snap_width_wide.set_markup("<i>Wide</i>")
        global snap_width
        snap_width = Gtk.HScale()
        snap_width.set_range(5, 100)
        snap_width.set_increments(1, 1)
        snap_width.set_digits(0)
        snap_width.set_value(get_snap_width())
        snap_width.connect("value-changed", set_snap_width)
        snap_width_box.pack_start(snap_width_small, False, False, 0)
        snap_width_box.pack_start(snap_width, True, True, 10)
        snap_width_box.pack_start(snap_width_wide, False, False, 0)

        wrap_label_box = Gtk.HBox()
        wrap_label = Gtk.Label()
        wrap_label.set_markup("<b>Wrap workspaces when reaching the screen edge</b>")
        wrap_void = Gtk.Label(" ")
        wrap_label_box.pack_start(wrap_label, False, False, 10)
        wrap_label_box.pack_start(wrap_void, True, True, 0)
        global wrap_workspaces
        wrap_workspaces = Gtk.CheckButton("With the mouse pointer")
        wrap_workspaces.set_active(get_wrap_workspaces())
        wrap_workspaces.connect("toggled", set_wrap_workspaces)
        global wrap_windows
        wrap_windows = Gtk.CheckButton("To other windows")
        wrap_windows.set_active(get_wrap_windows())
        wrap_windows.connect("toggled", set_wrap_windows)
        wrap_type_wrapper = Gtk.HBox()
        wrap_type_wrapper.pack_start(wrap_workspaces, True, True, 30)
        wrap_type_wrapper.pack_start(wrap_windows, True, True, 30)

        global wrap_resistance_box
        wrap_resistance_box = Gtk.HBox()
        wrap_resistance_wrapper = Gtk.HBox()
        wrap_resistance_wrapper.pack_start(wrap_resistance_box, True, True, 50)

        wrap_resistance_label = Gtk.Label("Edge Resistance:")
        wrap_resistance_void = Gtk.Label(" ")
        wrap_resistance_label_wrapper = Gtk.HBox()
        wrap_resistance_label_wrapper.pack_start(wrap_resistance_label, False, False, 30)
        wrap_resistance_label_wrapper.pack_start(wrap_resistance_void, True, True, 0)
        wrap_resistance_small = Gtk.Label()
        wrap_resistance_small.set_markup("<i>Small</i>")
        wrap_resistance_wide = Gtk.Label()
        wrap_resistance_wide.set_markup("<i>Wide</i>")
        global wrap_resistance
        wrap_resistance = Gtk.HScale()
        wrap_resistance.set_range(5, 100)
        wrap_resistance.set_increments(1, 1)
        wrap_resistance.set_digits(0)
        wrap_resistance.set_value(get_wrap_resistance())
        wrap_resistance.connect("value-changed", set_wrap_resistance)
        wrap_resistance_box.pack_start(wrap_resistance_small, False, False, 0)
        wrap_resistance_box.pack_start(wrap_resistance, True, True, 10)
        wrap_resistance_box.pack_start(wrap_resistance_wide, False, False, 0)

        box_label_box = Gtk.HBox()
        box_label = Gtk.Label()
        box_label.set_markup("<b>Hide content of windows</b>")
        box_void = Gtk.Label(" ")
        box_label_box.pack_start(box_label, False, False, 10)
        box_label_box.pack_start(box_void, True, True, 0)
        global box_move
        box_move = Gtk.CheckButton("When moving")
        box_move.set_active(get_box_move())
        box_move.connect("toggled", set_box_move)
        global box_resize
        box_resize = Gtk.CheckButton("When resizing")
        box_resize.set_active(get_box_resize())
        box_resize.connect("toggled", set_box_resize)
        box_type_wrapper = Gtk.HBox()
        box_type_wrapper.pack_start(box_move, True, True, 30)
        box_type_wrapper.pack_start(box_resize, True, True, 30)

        double_click_label_box = Gtk.HBox()
        double_click_label = Gtk.Label()
        double_click_label.set_markup("<b>Title bar double click action</b>")
        double_click_void = Gtk.Label(" ")
        double_click_label_box.pack_start(double_click_label, False, False, 10)
        double_click_label_box.pack_start(double_click_void, True, True, 0)

        global double_click_action
        double_click_action = Gtk.ComboBoxText()
        double_click_action.connect("changed", set_double_click_action)
        double_click_action.append_text("Shade window")
        double_click_action.append_text("Hide window")
        double_click_action.append_text("Maximize window")
        double_click_action.append_text("Fill window")
        double_click_action.append_text("Nothing")
        double_click_action.set_active(double_click_action_index())
        double_click_box = Gtk.HBox()
        double_click_box.pack_start(double_click_action, True, True, 30)

        wmimage = Gtk.Image()
        wmimage.set_from_file("/usr/lib/peppermint/peppermint-control-center/images/wm.png")  # temporary
        wmimage_label = Gtk.Label("Configure window manager\nbehavior and options")
        wmimage_label.set_justify(Gtk.Justification.CENTER)

        box_wmimage = Gtk.VBox()
        box_wmimage.pack_start(wmimage, True, True, 10)
        box_wmimage.pack_start(wmimage_label, True, True, 0)

        box_theme = Gtk.VBox()
        box_theme.pack_start(theme_label_wrapper, False, False, 4)
        box_theme.pack_start(theme_box_wrapper, False, False, 4)
        box_theme.pack_start(title_font_label_wrapper, False, False, 4)
        box_theme.pack_start(title_font_wrapper, False, False, 4)
        box_theme.pack_start(title_alignment_label_wrapper, False, False, 4)
        box_theme.pack_start(alignment_box_wrapper, False, False, 4)
        box_theme.pack_start(workspace_count_box, False, False, 10)

        box_top = Gtk.HBox()
        box_top.pack_start(box_wmimage, False, False, 30)
        box_top.pack_start(box_theme, True, True, 0)

        box_focus = Gtk.VBox()
        box_focus.pack_start(click_to_focus_label_box, False, False, 4)
        box_focus.pack_start(click_to_focus, False, False, 4)
        box_focus.pack_start(focus_delay_label_box, False, False, 4)
        box_focus.pack_start(focus_delay_wrapper, False, False, 4)

        box_focus_new = Gtk.VBox()
        box_focus_new.pack_start(focus_new_label_box, False, False, 4)
        box_focus_new.pack_start(focus_new_wrapper, False, False, 4)

        box_raise = Gtk.VBox()
        box_raise.pack_start(raise_on_focus_label_box, False, False, 4)
        box_raise.pack_start(raise_on_focus_wrapper, False, False, 4)
        box_raise.pack_start(raise_delay_label_wrapper, False, False, 4)
        box_raise.pack_start(raise_delay_wrapper, False, False, 4)

        box_click = Gtk.VBox()
        box_click.pack_start(raise_on_click_label_box, False, False, 4)
        box_click.pack_start(raise_on_click_wrapper, False, False, 4)

        box_snap = Gtk.VBox()
        box_snap.pack_start(snap_label_box, False, False, 4)
        box_snap.pack_start(snap_to_wrapper, False, False, 4)
        box_snap.pack_start(snap_width_label_wrapper, False, False, 4)
        box_snap.pack_start(snap_width_wrapper, False, False, 4)

        box_wrap = Gtk.VBox()
        box_wrap.pack_start(wrap_label_box, False, False, 4)
        box_wrap.pack_start(wrap_type_wrapper, False, False, 4)
        box_wrap.pack_start(wrap_resistance_label_wrapper, False, False, 4)
        box_wrap.pack_start(wrap_resistance_wrapper, False, False, 4)

        box_box = Gtk.VBox()
        box_box.pack_start(box_label_box, False, False, 4)
        box_box.pack_start(box_type_wrapper, False, False, 4)

        box_dclick = Gtk.VBox()
        box_dclick.pack_start(double_click_label_box, False, False, 4)
        box_dclick.pack_start(double_click_box, False, False, 4)

        page_wman.pack_start(box_top, True, True, 6)
        page_wman.pack_start(box_focus, True, True, 4)
        page_wman.pack_start(box_focus_new, True, True, 4)
        page_wman.pack_start(box_raise, True, True, 4)
        page_wman.pack_start(box_click, True, True, 4)
        page_wman.pack_start(box_snap, True, True, 4)
        page_wman.pack_start(box_wrap, True, True, 4)
        page_wman.pack_start(box_box, True, True, 4)
        page_wman.pack_start(box_dclick, True, True, 4)

        ###############################
        ### 'Pointer Options' page. ###
        ###############################
        page_point_lab = Gtk.Label("Keyboard & Pointer")
        page_point = Gtk.VBox()
        scroll_point = Gtk.ScrolledWindow()
        scroll_point.add(page_point)

        keyopt_label = Gtk.Label()
        keyopt_label.set_markup("<b>Keyboard options</b>")
        keyopt_void = Gtk.Label(" ")
        keyopt_label_box = Gtk.HBox()
        keyopt_label_box.pack_start(keyopt_label, False, False, 10)
        keyopt_label_box.pack_start(keyopt_void, True, True, 0)

        delay_label = Gtk.Label("Delay:")
        global delay
        delay = Gtk.HScale()
        delay.set_range(10, 1000)
        delay.set_increments(1, 1)
        delay.set_digits(0)

        try:
            delay.set_value(get_delay())
        except:
            delay.set_value(500)

        delay.connect("value-changed", keys_apply)
        delay_label_box = Gtk.HBox()
        delay_label_box.pack_start(delay_label, False, False, 20)
        delay_label_box.pack_start(delay, True, True, 0)

        interval_label = Gtk.Label("Interval:")
        global interval
        interval = Gtk.HScale()
        interval.set_range(1, 50)
        interval.set_increments(1, 1)
        interval.set_digits(0)

        try:
            interval.set_value(get_interval())
        except:
            interval.set_value(20)

        interval.connect("value-changed", keys_apply)
        interval_label_box = Gtk.HBox()
        interval_label_box.pack_start(interval_label, False, False, 20)
        interval_label_box.pack_start(interval, True, True, 0)

        kbimage = Gtk.Image()
        kbimage.set_from_file("/usr/lib/peppermint/peppermint-control-center/images/keyboard.png")

        layout_button = Gtk.Button("Select Keyboard Layout")
        layout_button.connect("clicked", layoutsetter)
        layout_button_left = Gtk.Label(" ")
        layout_button_right = Gtk.Label(" ")
        layout_button_box = Gtk.HBox()
        layout_button_box.pack_start(layout_button_left, True, True, 30)
        layout_button_box.pack_start(layout_button, True, True, 0)
        layout_button_box.pack_start(layout_button_right, True, True, 30)

        pntopt_label = Gtk.Label()
        pntopt_label.set_markup("<b>Pointer options</b>")
        pntopt_void = Gtk.Label(" ")
        pntopt_label_box = Gtk.HBox()
        pntopt_label_box.pack_start(pntopt_label, False, False, 10)
        pntopt_label_box.pack_start(pntopt_void, True, True, 0)

        acceleration_label = Gtk.Label("Acceleration:")
        global acceleration
        acceleration = Gtk.HScale()
        acceleration.set_range(0, 10)
        acceleration.set_increments(1, 1)
        acceleration.set_digits(0)

        try:
            acceleration.set_value(get_acceleration())
        except:
            acceleration.set_value(2)

        acceleration.connect("value-changed", pntr_apply)
        acceleration_label_box = Gtk.HBox()
        acceleration_label_box.pack_start(acceleration_label, False, False, 20)
        acceleration_label_box.pack_start(acceleration, True, True, 0)

        threshold_label = Gtk.Label("Threshold")
        global threshold
        threshold = Gtk.HScale()
        threshold.set_range(0, 10)
        threshold.set_increments(1, 1)
        threshold.set_digits(0)

        try:
            threshold.set_value(get_threshold())
        except:
            threshold.set_value(2)

        threshold.connect("value-changed", pntr_apply)
        threshold_label_box = Gtk.HBox()
        threshold_label_box.pack_start(threshold_label, False, False, 20)
        threshold_label_box.pack_start(threshold, True, True, 0)

        pntimage = Gtk.Image()
        pntimage.set_from_file("/usr/lib/peppermint/peppermint-control-center/images/mouse.png")

        global lefthanded
        lefthanded = Gtk.CheckButton("Left handed button layout")
        lefthanded.set_active(get_lefthanded())
        lefthanded.connect("toggled", pntr_apply)
        lefthanded_left = Gtk.Label(" ")
        lefthanded_right = Gtk.Label(" ")
        lefthanded_box = Gtk.HBox()
        lefthanded_box.pack_start(lefthanded_left, True, True, 0)
        lefthanded_box.pack_start(lefthanded, False, False, 0)
        lefthanded_box.pack_start(lefthanded_right, True, True, 0)

        touch_label = Gtk.Label()
        touch_label.set_markup("<b>Touchpad options</b>")
        touch_void = Gtk.Label(" ")
        touch_label_box = Gtk.HBox()
        touch_label_box.pack_start(touch_label, False, False, 30)
        touch_label_box.pack_start(touch_void, True, True, 0)

        global touchenable
        touchenable = Gtk.CheckButton("Touchpad Enabled")
        touchenable.set_active(get_touchenable())
        touchenable.connect("toggled", pntr_apply)

        global taptoclick
        taptoclick = Gtk.CheckButton("Tap-to-Click Enabled")
        taptoclick.set_active(get_taptoclick())
        taptoclick.connect("toggled", pntr_apply)

        global vertedge
        vertedge = Gtk.CheckButton("Vertical Edge Scrolling")
        vertedge.set_active(get_vertedge())
        vertedge.connect("toggled", pntr_apply)

        global horizedge
        horizedge = Gtk.CheckButton("Horizontal Edge Scrolling")
        horizedge.set_active(get_horizedge())
        horizedge.connect("toggled", pntr_apply)

        global vtwofinger
        vtwofinger = Gtk.CheckButton("Two Finger Vertical Scrolling")
        vtwofinger.set_active(get_vtwofinger())
        vtwofinger.connect("toggled", pntr_apply)

        global htwofinger
        htwofinger = Gtk.CheckButton("Two Finger Horizontal Scrolling")
        htwofinger.set_active(get_htwofinger())
        htwofinger.connect("toggled", pntr_apply)

        kbimage_box = Gtk.VBox()
        kbimage_box.pack_start(kbimage, True, True, 20)

        kboptions_box = Gtk.VBox()
        kboptions_box.pack_start(keyopt_label_box, False, False, 4)
        kboptions_box.pack_start(delay_label_box, False, False, 4)
        kboptions_box.pack_start(interval_label_box, False, False, 4)
        kboptions_box.pack_start(layout_button_box, False, False, 8)

        kb_box = Gtk.HBox()
        kb_box.pack_start(kbimage_box, False, False, 40)
        kb_box.pack_start(kboptions_box, True, True, 20)

        pntimage_box = Gtk.VBox()
        pntimage_box.pack_start(pntimage, True, True, 20)

        pntoptions_box = Gtk.VBox()
        pntoptions_box.pack_start(pntopt_label_box, False, False, 4)
        pntoptions_box.pack_start(acceleration_label_box, False, False, 4)
        pntoptions_box.pack_start(threshold_label_box, False, False, 4)
        pntoptions_box.pack_start(lefthanded_box, False, False, 4)

        pnt_box = Gtk.HBox()
        pnt_box.pack_start(pntoptions_box, True, True, 20)
        pnt_box.pack_start(pntimage_box, False, False, 40)

        touchleft_box = Gtk.VBox()
        touchleft_box.pack_start(touchenable, False, False, 0)
        touchleft_box.pack_start(vertedge, False, False, 0)
        touchleft_box.pack_start(horizedge, False, False, 0)

        touchright_box = Gtk.VBox()
        touchright_box.pack_start(taptoclick, False, False, 0)
        touchright_box.pack_start(vtwofinger, False, False, 0)
        touchright_box.pack_start(htwofinger, False, False, 0)

        touch_box = Gtk.HBox()
        touch_box.pack_start(touchleft_box, False, False, 40)
        touch_box.pack_start(touchright_box, False, False, 0)

        page_point.pack_start(kb_box, False, False, 10)
        page_point.pack_start(pnt_box, False, False, 0)
        page_point.pack_start(touch_label_box, False, False, 10)
        page_point.pack_start(touch_box, False, False, 10)

        ##################################
        ### 'Keyboard Shortcuts' page. ###
        ##################################
        page_short_lab = Gtk.Label("Keyboard Shortcuts")
        page_short = Gtk.VBox()
        scroll_short = Gtk.ScrolledWindow()
        scroll_short.add(page_short)

        xfce_label = Gtk.Label()
        xfce_label.set_markup("<b>Window Manager Shortcuts</b>")
        xfce_void = Gtk.Label(" ")
        xfce_restore = Gtk.Button("Restore Defaults")
        xfce_restore.connect("clicked", action_xfce_restore)
        xfce_label_box = Gtk.HBox()
        xfce_label_box.pack_start(xfce_label, False, False, 10)
        xfce_label_box.pack_start(xfce_void, True, True, 0)
        xfce_label_box.pack_start(xfce_restore, False, False, 10)

        xfcestore = Gtk.ListStore(str, str)
        get_xfce = get_xfce_shortcuts()
        move_directions = ['move_window_workspace', 'move_window_right_key', 'move_window_left_key',
                           'move_window_up_key', 'up_workspace_key', 'down_workspace_key', 'switch_window_key',
                           'raise_window_key']
        for line in get_xfce:
            a = line.split()
            for direction in move_directions:
                if direction in a[0]:
                    continue

            xfcestore.append([a[0], a[1]])

        xfceview = Gtk.TreeView(model=xfcestore)

        xfce_renderer_action = Gtk.CellRendererText()
        xfce_column_action = Gtk.TreeViewColumn("Action", xfce_renderer_action, text=0)
        xfceview.append_column(xfce_column_action)

        xfce_renderer_shortcut = Gtk.CellRendererText()
        xfce_column_shortcut = Gtk.TreeViewColumn("Shortcut", xfce_renderer_shortcut, text=1)
        xfceview.append_column(xfce_column_shortcut)

        xfceview.connect("row-activated", edit_xfce_shortcut)

        global bindstore
        bindstore = Gtk.ListStore(str, str)
        get_bind = get_xbindkeys()

        for line in get_bind:
            a = line.split("\n")
            bindstore.append([a[0], a[1]])

        bind_label = Gtk.Label()
        bind_label.set_markup("<b>System Shortcuts</b>")
        bind_void = Gtk.Label(" ")
        bind_new = Gtk.Button("Add New")
        bind_new.connect("clicked", action_bind_new, bindstore)
        bind_restore = Gtk.Button("Restore Defaults")
        bind_restore.connect("clicked", action_bind_restore)
        bind_label_box = Gtk.HBox()
        bind_label_box.pack_start(bind_label, False, False, 10)
        bind_label_box.pack_start(bind_void, True, True, 0)
        bind_label_box.pack_start(bind_new, False, False, 0)
        bind_label_box.pack_start(bind_restore, False, False, 10)

        global bindview
        bindview = Gtk.TreeView(model=bindstore)

        bind_renderer_action = Gtk.CellRendererText()
        bind_column_action = Gtk.TreeViewColumn("Action", bind_renderer_action, text=0)
        bindview.append_column(bind_column_action)

        bind_renderer_shortcut = Gtk.CellRendererText()
        bind_column_shortcut = Gtk.TreeViewColumn("Shortcut", bind_renderer_shortcut, text=1)
        bindview.append_column(bind_column_shortcut)

        bindview.connect("row-activated", edit_bind_shortcut)

        page_short.pack_start(bind_label_box, False, False, 10)
        page_short.pack_start(bindview, True, True, 0)
        page_short.pack_start(xfce_label_box, False, False, 10)
        page_short.pack_start(xfceview, True, True, 0)

        ###############################
        ### 'Desktop Effects' page. ###
        ###############################

        page_effect_lab = Gtk.Label("Desktop Effects")
        page_effect = Gtk.VBox()
        scroll_effect = Gtk.ScrolledWindow()
        scroll_effect.add(page_effect)

        use_compositing = Gtk.CheckButton()
        use_compositing.set_active(get_use_compositing())
        use_compositing.connect("toggled", set_use_compositing)
        use_compositing_label = Gtk.Label()
        use_compositing_label.set_markup("<b>Enable desktop effects</b>")
        use_compositing_void = Gtk.Label(" ")
        use_compositing_box = Gtk.HBox()
        use_compositing_box.pack_start(use_compositing, False, False, 10)
        use_compositing_box.pack_start(use_compositing_label, False, False, 0)
        use_compositing_box.pack_start(use_compositing_void, True, True, 0)

        unredirect_overlays = Gtk.CheckButton("Display fullscreen overlay windows directly")
        unredirect_overlays.set_active(get_unredirect_overlays())
        unredirect_overlays.connect("toggled", set_unredirect_overlays)

        sync_to_vblank = Gtk.CheckButton("Synchronize drawing to the vertical blank")
        sync_to_vblank.set_active(get_sync_to_vblank())
        sync_to_vblank.connect("toggled", set_sync_to_vblank)

        show_popup_shadow = Gtk.CheckButton("Show shadows under popup windows")
        show_popup_shadow.set_active(get_show_popup_shadow())
        show_popup_shadow.connect("toggled", set_show_popup_shadow)

        show_dock_shadow = Gtk.CheckButton("Show shadows under dock windows")
        show_dock_shadow.set_active(get_show_dock_shadow())
        show_dock_shadow.connect("toggled", set_show_dock_shadow)

        show_frame_shadow = Gtk.CheckButton("Show shadows under regular windows")
        show_frame_shadow.set_active(get_show_frame_shadow())
        show_frame_shadow.connect("toggled", set_show_frame_shadow)

        frame_opacity_label = Gtk.Label("Opacity of window decorations:")
        frame_opacity_void = Gtk.Label(" ")
        frame_opacity_label_box = Gtk.HBox()
        frame_opacity_label_box.pack_start(frame_opacity_label, False, False, 0)
        frame_opacity_label_box.pack_start(frame_opacity_void, True, True, 0)
        frame_opacity_left = Gtk.Label()
        frame_opacity_left.set_markup("<i>Transparent</i>")
        frame_opacity_right = Gtk.Label()
        frame_opacity_right.set_markup("<i>Opaque</i>")
        frame_opacity = Gtk.HScale()
        frame_opacity.set_range(0, 100)
        frame_opacity.set_increments(1, 1)
        frame_opacity.set_digits(0)

        try:
            frame_opacity.set_value(get_frame_opacity())
        except:
            frame_opacity.set_value(100)

        frame_opacity.connect("value-changed", set_frame_opacity)
        frame_opacity_box = Gtk.HBox()
        frame_opacity_box.pack_start(frame_opacity_left, False, False, 15)
        frame_opacity_box.pack_start(frame_opacity, True, True, 0)
        frame_opacity_box.pack_start(frame_opacity_right, False, False, 15)

        inactive_opacity_label = Gtk.Label("Opacity of inactive windows:")
        inactive_opacity_void = Gtk.Label(" ")
        inactive_opacity_label_box = Gtk.HBox()
        inactive_opacity_label_box.pack_start(inactive_opacity_label, False, False, 0)
        inactive_opacity_label_box.pack_start(inactive_opacity_void, True, True, 0)
        inactive_opacity_left = Gtk.Label()
        inactive_opacity_left.set_markup("<i>Transparent</i>")
        inactive_opacity_right = Gtk.Label()
        inactive_opacity_right.set_markup("<i>Opaque</i>")
        inactive_opacity = Gtk.HScale()
        inactive_opacity.set_range(0, 100)
        inactive_opacity.set_increments(1, 1)
        inactive_opacity.set_digits(0)

        try:
            inactive_opacity.set_value(get_inactive_opacity())
        except:
            inactive_opacity.set_value(100)

        inactive_opacity.connect("value-changed", set_inactive_opacity)
        inactive_opacity_box = Gtk.HBox()
        inactive_opacity_box.pack_start(inactive_opacity_left, False, False, 15)
        inactive_opacity_box.pack_start(inactive_opacity, True, True, 0)
        inactive_opacity_box.pack_start(inactive_opacity_right, False, False, 15)

        move_opacity_label = Gtk.Label("Opacity of windows during move:")
        move_opacity_void = Gtk.Label(" ")
        move_opacity_label_box = Gtk.HBox()
        move_opacity_label_box.pack_start(move_opacity_label, False, False, 0)
        move_opacity_label_box.pack_start(move_opacity_void, True, True, 0)
        move_opacity_left = Gtk.Label()
        move_opacity_left.set_markup("<i>Transparent</i>")
        move_opacity_right = Gtk.Label()
        move_opacity_right.set_markup("<i>Opaque</i>")
        move_opacity = Gtk.HScale()
        move_opacity.set_range(0, 100)
        move_opacity.set_increments(1, 1)
        move_opacity.set_digits(0)

        try:
            move_opacity.set_value(get_move_opacity())
        except:
            move_opacity.set_value(100)

        move_opacity.connect("value-changed", set_move_opacity)
        move_opacity_box = Gtk.HBox()
        move_opacity_box.pack_start(move_opacity_left, False, False, 15)
        move_opacity_box.pack_start(move_opacity, True, True, 0)
        move_opacity_box.pack_start(move_opacity_right, False, False, 15)

        resize_opacity_label = Gtk.Label("Opacity of windows during resize:")
        resize_opacity_void = Gtk.Label(" ")
        resize_opacity_label_box = Gtk.HBox()
        resize_opacity_label_box.pack_start(resize_opacity_label, False, False, 0)
        resize_opacity_label_box.pack_start(resize_opacity_void, True, True, 0)
        resize_opacity_left = Gtk.Label()
        resize_opacity_left.set_markup("<i>Transparent</i>")
        resize_opacity_right = Gtk.Label()
        resize_opacity_right.set_markup("<i>Opaque</i>")
        resize_opacity = Gtk.HScale()
        resize_opacity.set_range(0, 100)
        resize_opacity.set_increments(1, 1)
        resize_opacity.set_digits(0)

        try:
            resize_opacity.set_value(get_resize_opacity())
        except:
            resize_opacity.set_value(100)

        resize_opacity.connect("value-changed", set_resize_opacity)
        resize_opacity_box = Gtk.HBox()
        resize_opacity_box.pack_start(resize_opacity_left, False, False, 15)
        resize_opacity_box.pack_start(resize_opacity, True, True, 0)
        resize_opacity_box.pack_start(resize_opacity_right, False, False, 15)

        popup_opacity_label = Gtk.Label("Opacity of popup windows:")
        popup_opacity_void = Gtk.Label(" ")
        popup_opacity_label_box = Gtk.HBox()
        popup_opacity_label_box.pack_start(popup_opacity_label, False, False, 0)
        popup_opacity_label_box.pack_start(popup_opacity_void, True, True, 0)
        popup_opacity_left = Gtk.Label()
        popup_opacity_left.set_markup("<i>Transparent</i>")
        popup_opacity_right = Gtk.Label()
        popup_opacity_right.set_markup("<i>Opaque</i>")
        popup_opacity = Gtk.HScale()
        popup_opacity.set_range(0, 100)
        popup_opacity.set_increments(1, 1)
        popup_opacity.set_digits(0)

        try:
            popup_opacity.set_value(get_popup_opacity())
        except:
            popup_opacity.set_value(100)

        popup_opacity.connect("value-changed", set_popup_opacity)
        popup_opacity_box = Gtk.HBox()
        popup_opacity_box.pack_start(popup_opacity_left, False, False, 15)
        popup_opacity_box.pack_start(popup_opacity, True, True, 0)
        popup_opacity_box.pack_start(popup_opacity_right, False, False, 15)

        deimage = Gtk.Image()
        deimage.set_from_file("/usr/lib/peppermint/peppermint-control-center/images/de.png")
        deimage_box = Gtk.HBox()
        deimage_box.pack_start(deimage, True, True, 0)

        effects_left = Gtk.VBox()
        effects_left.pack_start(unredirect_overlays, False, False, 0)
        effects_left.pack_start(sync_to_vblank, False, False, 0)
        effects_left.pack_start(show_popup_shadow, False, False, 0)
        effects_left.pack_start(show_dock_shadow, False, False, 0)
        effects_left.pack_start(show_frame_shadow, False, False, 0)

        effects_top = Gtk.HBox()
        effects_top.pack_start(effects_left, False, False, 0)
        effects_top.pack_start(deimage_box, True, True, 0)

        global effects_box
        effects_box = Gtk.VBox()

        if get_use_compositing() == False:
            effects_box.set_sensitive(False)

        effects_box.pack_start(effects_top, False, False, 10)
        effects_box.pack_start(frame_opacity_label_box, False, False, 0)
        effects_box.pack_start(frame_opacity_box, False, False, 0)
        effects_box.pack_start(inactive_opacity_label_box, False, False, 0)
        effects_box.pack_start(inactive_opacity_box, False, False, 0)
        effects_box.pack_start(move_opacity_label_box, False, False, 0)
        effects_box.pack_start(move_opacity_box, False, False, 0)
        effects_box.pack_start(resize_opacity_label_box, False, False, 0)
        effects_box.pack_start(resize_opacity_box, False, False, 0)
        effects_box.pack_start(popup_opacity_label_box, False, False, 0)
        effects_box.pack_start(popup_opacity_box, False, False, 0)
        effects_wrapper = Gtk.HBox()
        effects_wrapper.pack_start(effects_box, True, True, 30)

        page_effect.pack_start(use_compositing_box, False, False, 10)
        page_effect.pack_start(effects_wrapper, True, True, 0)

        ########################
        ### 'Advanced' page. ###
        ########################

        page_adv_lab = Gtk.Label("Advanced")
        page_adv = Gtk.VBox()
        scroll_adv = Gtk.ScrolledWindow()
        scroll_adv.add(page_adv)

        cycling_label = Gtk.Label()
        cycling_label.set_markup("<b>Window cycling</b>")
        cycling_void = Gtk.Label(" ")
        cycling_label_box = Gtk.HBox()
        cycling_label_box.pack_start(cycling_label, False, False, 10)
        cycling_label_box.pack_start(cycling_void, True, True, 0)

        cycle_minimum = Gtk.CheckButton("Skip windows specified to skip the pager/taskbar")
        cycle_minimum.set_active(get_cycle_minimum())
        cycle_minimum.connect("toggled", set_cycle_minimum)

        cycle_hidden = Gtk.CheckButton("Include hidden/iconified windows")
        cycle_hidden.set_active(get_cycle_hidden())
        cycle_hidden.connect("toggled", set_cycle_minimum)

        cycle_workspaces = Gtk.CheckButton("Cycle through windows on all workspaces")
        cycle_workspaces.set_active(get_cycle_workspaces())
        cycle_workspaces.connect("toggled", set_cycle_workspaces)

        cycle_draw_frame = Gtk.CheckButton("Draw frame around selected windows while cycling")
        cycle_draw_frame.set_active(get_cycle_draw_frame())
        cycle_draw_frame.connect("toggled", set_cycle_draw_frame)

        cycling_section = Gtk.VBox()
        cycling_section.pack_start(cycle_minimum, False, False, 0)
        cycling_section.pack_start(cycle_hidden, False, False, 0)
        cycling_section.pack_start(cycle_workspaces, False, False, 0)
        cycling_section.pack_start(cycle_draw_frame, False, False, 0)
        cycling_section_box = Gtk.HBox()
        cycling_section_box.pack_start(cycling_section, False, False, 30)

        cycling_box = Gtk.VBox()
        cycling_box.pack_start(cycling_label_box, False, False, 4)
        cycling_box.pack_start(cycling_section_box, False, False, 4)

        focus_label = Gtk.Label()
        focus_label.set_markup("<b>Window focus</b>")
        focus_void = Gtk.Label(" ")
        focus_label_box = Gtk.HBox()
        focus_label_box.pack_start(focus_label, False, False, 10)
        focus_label_box.pack_start(focus_void, True, True, 0)

        prevent_focus_stealing = Gtk.CheckButton("Activate focus stealing prevention")
        prevent_focus_stealing.set_active(get_prevent_focus_stealing())
        prevent_focus_stealing.connect("toggled", set_prevent_focus_stealing)

        focus_hint = Gtk.CheckButton("Honor standard ICCCM focus hint")
        focus_hint.set_active(get_focus_hint())
        focus_hint.connect("toggled", set_focus_hint)

        window_raise_label = Gtk.Label()
        window_raise_label.set_markup("<i>When a window raises itself:</i>")
        window_raise_void = Gtk.Label(" ")
        window_raise_label_box = Gtk.HBox()
        window_raise_label_box.pack_start(window_raise_label, False, False, 30)
        window_raise_label_box.pack_start(window_raise_void, True, True, 0)

        activate_action_box = Gtk.VBox()
        activate_action_bring = Gtk.RadioButton.new_with_label_from_widget(None, "Bring window on current workspace")
        activate_action_bring.connect("toggled", set_activate_action, "bring")

        if get_activate_action() == "bring":
            activate_action_bring.set_active(True)

        activate_action_switch = Gtk.RadioButton.new_from_widget(activate_action_bring)
        activate_action_switch.set_label("Switch to window's workspace")
        activate_action_switch.connect("toggled", set_activate_action, "switch")

        if get_activate_action() == "switch":
            activate_action_switch.set_active(True)

        activate_action_none = Gtk.RadioButton.new_from_widget(activate_action_bring)
        activate_action_none.set_label("Do nothing")
        activate_action_none.connect("toggled", set_activate_action, "none")

        if get_activate_action() == "none":
            activate_action_none.set_active(True)

        activate_action_box.pack_start(activate_action_bring, False, False, 0)
        activate_action_box.pack_start(activate_action_switch, False, False, 0)
        activate_action_box.pack_start(activate_action_none, False, False, 0)
        activate_action_wrapper = Gtk.HBox()
        activate_action_wrapper.pack_start(activate_action_box, False, False, 50)

        focus_section = Gtk.VBox()
        focus_section.pack_start(prevent_focus_stealing, False, False, 0)
        focus_section.pack_start(focus_hint, False, False, 0)
        focus_section.pack_start(window_raise_label_box, False, False, 10)
        focus_section.pack_start(activate_action_wrapper, False, False, 0)
        focus_section_box = Gtk.HBox()
        focus_section_box.pack_start(focus_section, False, False, 30)

        focus_box = Gtk.VBox()
        focus_box.pack_start(focus_label_box, False, False, 4)
        focus_box.pack_start(focus_section_box, False, False, 4)

        accessibility_label = Gtk.Label()
        accessibility_label.set_markup("<b>Accessibility</b>")
        accessibility_void = Gtk.Label(" ")
        accessibility_label_box = Gtk.HBox()
        accessibility_label_box.pack_start(accessibility_label, False, False, 10)
        accessibility_label_box.pack_start(accessibility_void, True, True, 0)

        raise_with_any_button = Gtk.CheckButton("Raise windows when any pointer button is pressed")
        raise_with_any_button.set_active(get_raise_with_any_button())
        raise_with_any_button.connect("toggled", set_raise_with_any_button)

        borderless_maximize = Gtk.CheckButton("Hide frames of maximized windows")
        borderless_maximize.set_active(get_borderless_maximize())
        borderless_maximize.connect("toggled", set_borderless_maximize)

        global restore_on_move
        restore_on_move = Gtk.CheckButton("Restore original size of maximized windows when moving")
        restore_on_move.set_active(get_restore_on_move())
        restore_on_move.connect("toggled", set_restore_on_move)

        # Depends on restore_on_move
        global tile_on_move
        tile_on_move = Gtk.CheckButton("Automatically tile windows when moving toward the screen edge")
        tile_on_move.set_active(get_tile_on_move())
        tile_on_move.connect("toggled", set_tile_on_move)

        if get_restore_on_move() == True:
            tile_on_move.set_sensitive(True)
        else:
            tile_on_move.set_sensitive(False)

        snap_resist = Gtk.CheckButton("Use edge resistance instead of window snapping")
        snap_resist.set_active(get_snap_resist())
        snap_resist.connect("toggled", set_snap_resist)

        # Also disable repeat_urgent_blink
        global urgent_blink
        urgent_blink = Gtk.CheckButton("Notify of urgency with blinking window decorations")
        urgent_blink.set_active(get_urgent_blink())
        urgent_blink.connect("toggled", set_urgent_blink)

        # Depends on urgent_blink
        global repeat_urgent_blink
        repeat_urgent_blink = Gtk.CheckButton("Keep urgent windows blinking repeatedly")
        repeat_urgent_blink.set_active(get_repeat_urgent_blink())
        repeat_urgent_blink.connect("toggled", set_repeat_urgent_blink)

        if get_urgent_blink() == True:
            repeat_urgent_blink.set_sensitive(True)
        else:
            repeat_urgent_blink.set_active(False)
            repeat_urgent_blink.set_sensitive(False)
            set_repeat_urgent_blink_off()

        mousewheel_rollup = Gtk.CheckButton("Scroll on title bar to roll up the window")
        mousewheel_rollup.set_active(get_mousewheel_rollup())
        mousewheel_rollup.connect("toggled", set_mousewheel_rollup)

        accessibility_section = Gtk.VBox()
        accessibility_section.pack_start(raise_with_any_button, False, False, 0)
        accessibility_section.pack_start(borderless_maximize, False, False, 0)
        accessibility_section.pack_start(restore_on_move, False, False, 0)
        accessibility_section.pack_start(tile_on_move, False, False, 0)
        accessibility_section.pack_start(snap_resist, False, False, 0)
        accessibility_section.pack_start(urgent_blink, False, False, 0)
        accessibility_section.pack_start(repeat_urgent_blink, False, False, 0)
        accessibility_section.pack_start(mousewheel_rollup, False, False, 0)
        accessibility_section_box = Gtk.HBox()
        accessibility_section_box.pack_start(accessibility_section, False, False, 30)

        accessibility_box = Gtk.VBox()
        accessibility_box.pack_start(accessibility_label_box, False, False, 4)
        accessibility_box.pack_start(accessibility_section_box, False, False, 4)

        workspaces_label = Gtk.Label()
        workspaces_label.set_markup("<b>Workspaces</b>")
        workspaces_void = Gtk.Label(" ")
        workspaces_label_box = Gtk.HBox()
        workspaces_label_box.pack_start(workspaces_label, False, False, 10)
        workspaces_label_box.pack_start(workspaces_void, True, True, 0)

        scroll_workspaces = Gtk.CheckButton("Scroll on desktop to change workspaces")
        scroll_workspaces.set_active(get_scroll_workspaces())
        scroll_workspaces.connect("toggled", set_scroll_workspaces)

        wrap_layout = Gtk.CheckButton("Wrap workspaces")
        wrap_layout.set_active(get_wrap_layout())
        wrap_layout.connect("toggled", set_wrap_layout)

        workspaces_section = Gtk.VBox()
        workspaces_section.pack_start(scroll_workspaces, False, False, 0)
        workspaces_section.pack_start(wrap_layout, False, False, 0)
        workspaces_section_box = Gtk.HBox()
        workspaces_section_box.pack_start(workspaces_section, False, False, 30)

        workspaces_box = Gtk.VBox()
        workspaces_box.pack_start(workspaces_label_box, False, False, 4)
        workspaces_box.pack_start(workspaces_section_box, False, False, 4)

        placement_label = Gtk.Label()
        placement_label.set_markup("<b>Window placement</b>")
        placement_void = Gtk.Label(" ")
        placement_label_box = Gtk.HBox()
        placement_label_box.pack_start(placement_label, False, False, 10)
        placement_label_box.pack_start(placement_void, True, True, 0)

        placement_ratio_label = Gtk.Label("Minimum window size to trigger smart placement:")
        placement_ratio_void = Gtk.Label(" ")
        placement_ratio_label_box = Gtk.HBox()
        placement_ratio_label_box.pack_start(placement_ratio_label, False, False, 0)
        placement_ratio_label_box.pack_start(placement_ratio_void, True, True, 0)
        placement_ratio_small = Gtk.Label()
        placement_ratio_small.set_markup("<i>Small</i>")
        placement_ratio_large = Gtk.Label()
        placement_ratio_large.set_markup("<i>Large</i>")
        placement_ratio = Gtk.HScale()
        placement_ratio.set_range(0, 100)
        placement_ratio.set_increments(1, 1)
        placement_ratio.set_digits(0)

        try:
            placement_ratio.set_value(get_placement_ratio())
        except:
            placement_ratio.set_value(20)

        placement_ratio.connect("value-changed", set_placement_ratio)
        placement_ratio_box = Gtk.HBox()
        placement_ratio_box.pack_start(placement_ratio_small, False, False, 15)
        placement_ratio_box.pack_start(placement_ratio, True, True, 0)
        placement_ratio_box.pack_start(placement_ratio_large, False, False, 15)

        placement_mode_label = Gtk.Label("By default, place windows:")
        placement_mode_void = Gtk.Label(" ")
        placement_mode_label_box = Gtk.HBox()
        placement_mode_label_box.pack_start(placement_mode_label, False, False, 0)
        placement_mode_label_box.pack_start(placement_mode_void, False, False, 0)

        placement_mode_center = Gtk.RadioButton.new_with_label_from_widget(None, "At the center of the screen")
        placement_mode_center.connect("toggled", set_placement_mode, "center")

        if get_placement_mode() == "center":
            placement_mode_center.set_active(True)

        placement_mode_mouse = Gtk.RadioButton.new_from_widget(placement_mode_center)
        placement_mode_mouse.set_label("Under the pointer")
        placement_mode_mouse.connect("toggled", set_placement_mode, "mouse")

        if get_placement_mode() == "mouse":
            placement_mode_mouse.set_active(True)

        placement_mode_box = Gtk.VBox()
        placement_mode_box.pack_start(placement_mode_center, False, False, 0)
        placement_mode_box.pack_start(placement_mode_mouse, False, False, 0)
        placement_mode_wrapper = Gtk.HBox()
        placement_mode_wrapper.pack_start(placement_mode_box, True, True, 10)

        placement_section = Gtk.VBox()
        placement_section.pack_start(placement_ratio_label_box, False, False, 4)
        placement_section.pack_start(placement_ratio_box, False, False, 4)
        placement_section.pack_start(placement_mode_label_box, False, False, 4)
        placement_section.pack_start(placement_mode_wrapper, False, False, 4)
        placement_section_box = Gtk.HBox()
        placement_section_box.pack_start(placement_section, True, True, 30)

        placement_box = Gtk.VBox()
        placement_box.pack_start(placement_label_box, False, False, 4)
        placement_box.pack_start(placement_section_box, False, False, 4)

        page_adv.pack_start(cycling_box, False, False, 10)
        page_adv.pack_start(focus_box, False, False, 0)
        page_adv.pack_start(accessibility_box, False, False, 10)
        page_adv.pack_start(workspaces_box, False, False, 0)
        page_adv.pack_start(placement_box, False, False, 10)

        ##############################
        ### Main window structure. ###
        ##############################
        mainbook = Gtk.Notebook()
        mainbook.append_page(scroll_wman, page_wman_lab)
        mainbook.append_page(scroll_point, page_point_lab)
        mainbook.append_page(scroll_short, page_short_lab)
        mainbook.append_page(scroll_effect, page_effect_lab)
        mainbook.append_page(scroll_adv, page_adv_lab)

        mainb = Gtk.VBox(10, 10)
        mainb.pack_start(mainbook, True, True, 10)
        mainb1 = Gtk.HBox(10, 10)
        mainb1.pack_start(mainb, True, True, 10)

        self.add(mainb1)


if __name__ == '__main__':
    window = ControlCenter()
    window.connect("delete-event", Gtk.main_quit)
    window.show_all()
    Gtk.main()
