#!/usr/bin/python3
import gi, os, subprocess, re, warnings, jwmkit_utils
import xml.etree.ElementTree as ET
from xml.dom import minidom
from shutil import copy2
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GdkPixbuf

# JWM Kit - A set of Graphical Apps to simplify use of JWM (Joe's Window Manager) <https://codeberg.org/JWMKit/JWM_Kit>
# Copyright © 2020-2022 Calvin Kent McNabb <apps.jwmkit@gmail.com>
#
# This file is part of JWM Kit.
#
# JWM Kit is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# JWM Kit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with JWM Kit.  If not, see <https://www.gnu.org/licenses/>.


def on_color_toggle(check, button1, button2):
    if check.get_active():
        button1.set_sensitive(True)
        if button2 != '':
            button2.set_sensitive(True)
    else:
        button1.set_sensitive(False)
        if button2 != '':
            button2.set_sensitive(False)


def opacity_toggle(check, spin):
    if check.get_active():
        spin.set_sensitive(True)
    else:
        spin.set_sensitive(False)


def rgba_to_hex(colors):
    red = int(colors.red * 255)
    green = int(colors.green * 255)
    blue = int(colors.blue * 255)
    return "%02x%02x%02x" % (red, green, blue)


def hex_to_rgba(colors):
    color = Gdk.RGBA()
    color.parse(colors)
    color.to_string()
    return color


def clear_tmp():
    if os.path.isdir('/tmp/button_set'):
        subprocess.run(['rm', '-r', '/tmp/button_set'])


def get_button_colors(theme):
    colours, colors = [], []
    home = os.path.expanduser('~')
    path = '{}/.config/jwm/themes/buttons/{}'.format(home, theme)
    images = ('close.svg', 'max.svg', 'maxact.svg', 'min.svg', 'default.svg', 'menu.svg')
    for image in images:
        file_path = os.path.join(path, image)
        if os.path.isfile(file_path):
            with open(file_path) as f:
                f = f.read().lower().replace('url(', ';;')
                colors = re.findall('(?:fill|stroke|color)[:|=][\'\"]?([^\:\;\"\']+)', f)
        colours.extend(colors)
    while 'none' in colours: colours.remove('none')
    colours = list(set(colours))
    for color in colours:
        if color[0] != '#':
            tmp = hex_to_rgba(color)
            tmp = '#{}'.format(rgba_to_hex(tmp))
            colours[colours.index(color)] = tmp
    colours = [color.upper() for color in colours]
    colours = list(set(colours))
    return list(set(colours))


def check_button_config():
    home = os.path.expanduser('~')
    jwmrc = jwmkit_utils.get_jwmrc()
    config = os.path.join(home, '.config/jwm/buttons')
    xml = '<?xml version="1.0"?>\n<JWM>\n   <Include>exec:jwmkit_button_mu</Include>\n</JWM>\n'
    passed = False
    directory = os.path.dirname(config)
    if not os.path.isdir(directory):
        os.makedirs(directory)
    with open(config, 'w+') as f:
        f.write(xml)
    try:
        tree = ET.parse(jwmrc)
        root = tree.getroot()
        for node in root:
            if node.text.endswith('.config/jwm/buttons'):
                passed = 'True'
        if not passed:
            element = ET.Element("Include")
            element.text = '$HOME/.config/jwm/buttons'
            root.append(element)
            tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
            tree = os.linesep.join([s for s in tree.splitlines() if s.strip()])
            tree = ET.ElementTree(ET.fromstring(tree))
            tree.write(jwmrc, encoding="utf-8", xml_declaration=True)
    except(FileNotFoundError, ET.ParseError):
        # missing or corrupt jwmrc. Give notice
        return False
    return True


def get_styles(theme):
    styles = []
    theme = '{}/.config/jwm/themes/{}'.format(os.path.expanduser('~'), theme)
    try:
        tree = ET.parse(theme)
        root = tree.getroot()
    except (AttributeError, ET.ParseError):
        return False
    for style in ['WindowStyle', 'TrayStyle']:
        style_tmp = []
        theme_style = root.find(style)
        # Get TrayStyle font. if not defined, fallback to WinStyle font
        if style == 'TrayStyle':
            tmp = theme_style.find('Font')
            if not tmp.text:
                theme_win = root.find('WindowStyle')
                tmp = theme_win.find('Font')
            try:
                tmp = tmp.text.strip()
                if not tmp: tmp = ''
            except AttributeError:
                tmp = ''
            # split the font string into ( font, size, style )
            tmp = [e for e in tmp.split(':') if '=' not in e]
            tmp = sum([e.split('-') for e in tmp], [])
            length = len(tmp)
            if length < 2:
                while len(tmp) < 2: tmp.append('')
            if length < 3:
                if not tmp[1].isdigit():
                    tmp.append(tmp[1])
                    tmp[1] = ''
                else:
                    tmp.append('')
            style_tmp.append(tmp)
        # get standard (in-active) Styles
        tags = ('Foreground', 'Background', 'Outline', 'Corner')
        for tag in tags:
            tmp = theme_style.find(tag)
            try:
                tmp = tmp.text.strip()
                if not tmp: tmp = ''
            except AttributeError:
                tmp = ''
            style_tmp.append(tmp)
        # get Active WinStyles
        if style == 'WindowStyle':
            styles.append(style_tmp)
            style_tmp = []
            tags = ('Foreground', 'Background', 'Outline')
            active = theme_style.find('Active')
            for tag in tags:
                try:
                    tmp = active.find(tag)
                    tmp = tmp.text.strip()
                    if not tmp: tmp = ''
                except AttributeError:
                    tmp = ''
                style_tmp.append(tmp)
            style_tmp.append(styles[0][3])
        styles.append(style_tmp)
    return styles


def page_switch(notebook, label, page, switch, button):
    switch.set_visible(True) if page == 1 else switch.set_visible(False)
    button.set_label('Save  ') if page == 2 else button.set_label('Apply')


def on_gradient_check(check, button1, button2):
    if check.get_active():
        button1.set_property("width-request", 42)
        button2.set_visible(True)
    else:
        button1.set_property("width-request", 84)
        button2.set_no_show_all(True)
        button2.set_visible(False)


def create_previews(styles, i, p_type, item):
    if styles:
        if p_type == 'tray':
            jwmkit_utils.create_tray_svg(styles[i], item)
        else:
            jwmkit_utils.create_win_svg(styles[i], item, p_type)
        return '{}-g-{}.svg'.format(item[:-6], p_type)
    else:
        return '/usr/share/pixmaps/jwmkit/theme_no_tray.svg'


class MenusWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="JWM Kit Appearance")
        self.set_border_width(15)
        try:
            self.set_icon_from_file('/usr/share/pixmaps/jwmkit/icons.svg')
        except gi.repository.GLib.Error:
            self.set_icon_name("applications-graphics")
        if not check_button_config():
            jwmkit_utils.app_fail()
            return

        # determine the default color ( color can vary due to GTK Theming)
        # Some versions of Gtk3 have a bug with .get_property()
        # recommended workaround is to fall back to the deprecated get_background_color()
        # using warnings to filter the specific DeprecationWarning
        warnings.filterwarnings('ignore', message='Gtk.StyleContext.get_background_color')
        warnings.filterwarnings('ignore', message='Gtk.Widget.get_state')
        default_color = self.get_style_context()
        self.default_color = default_color.get_background_color(self.get_state())
        self.home = os.path.expanduser('~')
        self.buttons = self.get_buttons()
        self.theme_config = self.get_path()
        if self.theme_config == 'warning_settings':
            jwmkit_utils.warning_settings(self)
            return
        current_buttons = self.theme_config[1]
        self.theme_config = self.theme_config[0]
        main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=15)
        self.add(main_box)
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)
        main_box.add(box)
        self.set_border_width(20)
        image = jwmkit_utils.create_image('/usr/share/pixmaps/jwmkit/icons.svg', 48, 48, False)
        design_button = Gtk.Button(image=image, label='Switch View')
        design_button.set_property("width-request", 140)
        design_button.set_property("height-request", 80)
        design_button.set_always_show_image(True)
        design_button.set_tooltip_text("Toggle View : Default or Theme Designer")
        design_button.set_image_position(Gtk.PositionType.TOP)

        title_label = Gtk.Label()
        title_label.set_markup('<big><b>Appearance</b></big>\nThemes &amp; Buttons')
        box.add(design_button)
        box.add(title_label)

        grid = Gtk.Grid()
        grid.set_row_spacing(5)
        grid.set_column_spacing(5)
        self.theme_combo = Gtk.ComboBoxText()
        self.theme_combo.connect("changed", self.theme_changed)
        self.theme_label = Gtk.Label(label="Edit a Theme", xalign=.1)

        self.clear_button = Gtk.Button(label="Reset", image=Gtk.Image(stock=Gtk.STOCK_REFRESH))
        self.clear_button.set_always_show_image(True)
        self.clear_button.set_tooltip_text('Reset')
        self.clear_button.connect("clicked", self.clear_action)

        self.theme_combo.set_tooltip_text('Select a theme to modify or use as a template')
        grid.attach(self.theme_label, 1, 0, 1, 1)
        grid.attach(self.clear_button, 3, 1, 1, 1)
        grid.attach(self.theme_combo, 1,1, 2, 1)
        box.pack_end(grid, False, False, 0)
        self.theme_combo.set_no_show_all(True)
        self.theme_label.set_no_show_all(True)
        self.clear_button.set_no_show_all(True)

        self.themes = []
        self.theme_directory = '{}{}'.format(self.home, '/.config/jwm/themes/')
        directory_list = sorted(os.listdir(self.theme_directory), key=str.casefold)
        index, count, i = self.get_theme(), 0, 0
        no_preview_tray = '/usr/share/pixmaps/jwmkit/theme_no_tray.svg'
        for item in directory_list:
            if item.endswith('theme') or item.endswith('jwmrc'):
                self.theme_combo.append_text(item)
                if index:
                    if item == os.path.basename(index):
                        i = count
                theme = [item]
                tray_images = ['{}-tray.svg'.format(item[:-6]), '{}-tray.png'.format(item[:-6]),
                               '{}-tray.jpg'.format(item[:-6]), '{}-g-tray.svg'.format(item[:-6])]
                win_images = ['{}-window.svg'.format(item[:-6]), '{}-window.png'.format(item[:-6]),
                              '{}-window.jpg'.format(item[:-6]), '{}-g-window.svg'.format(item[:-6])]
                active_images = ['{}-active.svg'.format(item[:-6]), '{}-active.png'.format(item[:-6]),
                                 '{}-active.jpg'.format(item[:-6]), '{}-g-active.svg'.format(item[:-6])]

                for image in tray_images:
                    if image in directory_list:
                        theme.append(image)
                        break
                if len(theme) < 2:
                    styles = get_styles(item)
                    theme.append(create_previews(styles, 2, 'tray', item))

                for image in win_images:
                    if image in directory_list:
                        theme.append(image)
                        break
                if len(theme) < 3:
                    styles = get_styles(item)
                    theme.append(create_previews(styles, 0, 'window', item))

                for image in active_images:
                    if image in directory_list:
                        theme.append(image)
                        break
                if len(theme) < 4:
                    styles = get_styles(item)
                    theme.append(create_previews(styles, 1, 'active', item))

                self.themes.append(theme)
                count += 1

        scroll = Gtk.ScrolledWindow()
        scroll.set_min_content_width(660)
        scroll.set_min_content_height(400)
        self.listbox = Gtk.ListBox()
        self.listbox.set_selection_mode(Gtk.SelectionMode.SINGLE)
        self.listbox.set_activate_on_single_click(False)

        self.book = Gtk.Notebook()
        self.book.append_page(scroll, Gtk.Label(label='Themes'))
        main_box.pack_start(self.book, True, True, 0)

        # Designer
        self.active_colors = []
        w_grid, t_grid, tb_grid, tl_grid = Gtk.Grid(), Gtk.Grid(), Gtk.Grid(), Gtk.Grid()
        m_grid, p_grid, pop_grid, cl_grid = Gtk.Grid(), Gtk.Grid(), Gtk.Grid(), Gtk.Grid()
        grids = [w_grid, t_grid, tb_grid, tl_grid, m_grid, p_grid, cl_grid, pop_grid]
        self.view = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)

        self.view_combo = Gtk.ComboBoxText()
        self.view_combo.append_text('Dark 1')
        self.view_combo.append_text('Dark 2')
        self.view_combo.append_text('Lite 1')
        self.view_combo.append_text('Lite 2')
        self.view_combo.set_active(0)

        self.preview = Gtk.Image()
        self.view.pack_start(self.preview, True, True, 0)
        self.view_combo.set_no_show_all(True)
        self.view.set_no_show_all(True)
        tab_names = ('Window', 'Tray', 'Tray Button', 'Task List', 'Menu', 'Pager', 'Clock', 'Popup')
        self.book2 = Gtk.Notebook()
        main_box.pack_start(self.view, True, True, 0)
        main_box.pack_start(self.book2, True, True, 0)
        self.book2.set_no_show_all(True)
        for grid, name in zip(grids, tab_names):
            self.book2.append_page(grid, Gtk.Label(label=name))
            grid.set_no_show_all(True)
            grid.set_border_width(15)
            grid.set_row_spacing(20)
            grid.set_column_spacing(15)
        apply_button = Gtk.Button(label='Apply', image=Gtk.Image(stock=Gtk.STOCK_APPLY))
        view_button = Gtk.Button(label='Preview')
        view_button.set_no_show_all(True)
        design_button.connect("clicked", self.design_switch, grids, title_label, apply_button, view_button)
        view_button.connect("clicked", self.view_switch)

        # Designer - Window Style (tab 1) labels
        label = Gtk.Label(label='Decoration: ', xalign=1)
        w_grid.attach(label, 0, 0, 1, 1)
        label = Gtk.Label(label='Align: ', xalign=1)
        w_grid.attach(label, 0, 1, 1, 1)
        label = Gtk.Label(label='Encoding: ', xalign=1)
        w_grid.attach(label, 0, 3, 1, 1)
        label = Gtk.Label(label='Width: ', xalign=1)
        w_grid.attach(label, 5, 2, 2, 1)
        label = Gtk.Label(label='Corner: ', xalign=1)
        w_grid.attach(label, 5, 3, 2, 1)
        label = Gtk.Label(label='Opacity', xalign=.5)
        w_grid.attach(label, 7, 4, 1, 1)
        label = Gtk.Label()
        label.set_markup('<b>Inactive</b>')
        w_grid.attach(label, 0, 5, 1, 1)
        label = Gtk.Label()
        label.set_markup('<b>Active</b>')
        w_grid.attach(label, 0, 6, 1, 1)
        label = Gtk.Label(label='Foreground', xalign=.1)
        w_grid.attach(label, 1, 4, 2, 1)
        w_background_label = Gtk.Label(label='Background', xalign=.1)
        w_grid.attach(w_background_label, 3, 4, 2, 1)
        label = Gtk.Label(label='Outline', xalign=.5)
        w_grid.attach(label, 5, 4, 1, 1)

        # Designer - Window Style (tab 1) Widgets (buttons, combos, entries, etc)
        self.w_font_entry, self.w_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.w_font_entry.set_property("width-request", 160)
        self.w_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"')
        self.w_encoding_entry.set_property("width-request", 20)

        self.w_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.w_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.w_font_button.set_always_show_image(True)
        self.w_font_button.set_property("width-request", 120)
        self.w_font_button.connect("clicked", self.on_font_choice, self.w_font_entry)

        self.w_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.w_antialias_check.set_tooltip_text('Enable Font Antialiasing')
        self.w_height_check = Gtk.CheckButton(label="Height:")

        self.w_decorations_combo = Gtk.ComboBoxText()
        self.w_decorations_combo.append_text('flat')
        self.w_decorations_combo.append_text('motif')
        self.w_decorations_combo.set_property("width-request", 63)

        self.w_align_combo = Gtk.ComboBoxText()
        self.w_align_combo.append_text('left')
        self.w_align_combo.append_text('center')
        self.w_align_combo.append_text('right')

        self.w_width_spin, self.w_height_spin, self.w_corner_spin = Gtk.SpinButton(), Gtk.SpinButton(), Gtk.SpinButton()
        self.w_i_opacity_spin, self.w_a_opacity_spin = Gtk.SpinButton(), Gtk.SpinButton()

        adjustment = Gtk.Adjustment(value=4, lower=1, upper=128, step_increment=1)
        self.w_width_spin.set_tooltip_text('Width of window borders in pixels\nDefault is 4')
        self.w_width_spin.set_adjustment(adjustment)

        adjustment = Gtk.Adjustment(value=1, lower=1, upper=256, step_increment=1)
        self.w_height_spin.set_tooltip_text('Height of window title bars in pixels\n'
                                            '*Recommend same as the title font or larger')
        self.w_height_spin.set_adjustment(adjustment)
        self.w_height_spin.set_sensitive(False)

        adjustment = Gtk.Adjustment(value=4, lower=0, upper=5, step_increment=1)
        self.w_corner_spin.set_tooltip_text('Width of the rounded corner in pixels.\n'
                                            '0 is square.  5 is very round.  Default 4')
        self.w_corner_spin.set_adjustment(adjustment)

        adjustment = Gtk.Adjustment(value=1.0, lower=0.0, upper=1.0, step_increment=0.01)
        self.w_i_opacity_spin.set_digits(2)
        self.w_i_opacity_spin.set_adjustment(adjustment)
        self.w_i_opacity_spin.set_sensitive(False)

        adjustment = Gtk.Adjustment(value=1.0, lower=0.0, upper=1.0, step_increment=0.01)
        self.w_a_opacity_spin.set_digits(2)
        self.w_a_opacity_spin.set_adjustment(adjustment)
        self.w_a_opacity_spin.set_sensitive(False)

        self.w_height_check.set_tooltip_text('Disable & use default')
        self.w_height_check.props.halign = Gtk.Align.END
        self.w_height_check.connect("toggled", self.w_height_default)
        self.w_height_check.set_active(False)

        self.w_color_active_foreground, self.w_color_active_background1 = Gtk.ColorButton(), Gtk.ColorButton()
        self.w_color_active_background2, self.w_color_active_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.w_color_inactive_foreground, self.w_color_inactive_background1 = Gtk.ColorButton(), Gtk.ColorButton()
        self.w_color_inactive_background2, self.w_color_inactive_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.w_opacity_check1 = Gtk.CheckButton()
        self.w_opacity_check2 = Gtk.CheckButton()
        self.w_inactive_gradient_check, self.w_active_gradient_check = Gtk.CheckButton(), Gtk.CheckButton()

        self.w_color_active_foreground.set_property("width-request", 84)
        self.w_color_active_background1.set_property("width-request", 42)
        self.w_color_active_background2.set_property("width-request", 42)
        self.w_color_active_outline.set_property("width-request", 84)
        self.w_color_inactive_foreground.set_property("width-request", 84)
        self.w_color_inactive_background1.set_property("width-request", 42)
        self.w_color_inactive_background2.set_property("width-request", 42)
        self.w_color_inactive_outline.set_property("width-request", 84)

        self.w_color_active_foreground.set_tooltip_text("Set the color of text on the active window's title bar.")
        self.w_color_active_background1.set_tooltip_text("Set the color of the active window's title bar.")
        self.w_color_active_background2.set_tooltip_text("Set the color of the active window's title bar.")
        self.w_color_active_outline.set_tooltip_text("Set the color of the active window's outline")
        self.w_color_inactive_foreground.set_tooltip_text("Set the color of text on the title bar.")
        self.w_color_inactive_background1.set_tooltip_text("Set the color of the title bar")
        self.w_color_inactive_background2.set_tooltip_text("Set the color of the title bar")
        self.w_color_inactive_outline.set_tooltip_text("Set the color of the window outline")
        self.w_opacity_check1.set_tooltip_text('Enable opacity\n* Requires composite manager')
        self.w_opacity_check2.set_tooltip_text('Enable opacity\n* Requires composite manager')
        self.w_inactive_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")
        self.w_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")

        self.w_opacity_check1.connect("toggled", opacity_toggle, self.w_i_opacity_spin)
        self.w_opacity_check2.connect("toggled", opacity_toggle, self.w_a_opacity_spin)
        self.w_active_gradient_check.connect("toggled", on_gradient_check, self.w_color_active_background1,
                                             self.w_color_active_background2)
        self.w_inactive_gradient_check.connect("toggled", on_gradient_check, self.w_color_inactive_background1,
                                               self.w_color_inactive_background2)
        self.w_color_active_foreground.connect('color-set', self.color_activated)
        self.w_color_active_background1.connect('color-set', self.color_activated)
        self.w_color_active_background2.connect('color-set', self.color_activated)
        self.w_color_inactive_foreground.connect('color-set', self.color_activated)
        self.w_color_inactive_background1.connect('color-set', self.color_activated)
        self.w_color_inactive_background2.connect('color-set', self.color_activated)
        self.w_color_active_outline.connect('color-set', self.color_activated)
        self.w_color_inactive_outline.connect('color-set', self.color_activated)

        self.w_color_active_background1.set_visible(True)
        self.w_color_inactive_background1.set_visible(True)
        self.w_inactive_gradient_check.set_active(True)
        self.w_active_gradient_check.set_active(True)
        self.w_inactive_gradient_check.set_visible(True)
        self.w_active_gradient_check.set_visible(True)

        # Designer - Window Style (Tab 1)
        w_grid.attach(self.w_decorations_combo, 1, 0, 1, 1)
        w_grid.attach(self.w_antialias_check, 3, 1, 2, 1)
        w_grid.attach(self.w_height_check, 5, 1, 2, 1)
        w_grid.attach(self.w_height_spin, 7, 1, 1, 1)
        w_grid.attach(self.w_font_button, 0, 2, 1, 1)
        w_grid.attach(self.w_font_entry, 1, 2, 4, 1)
        w_grid.attach(self.w_encoding_entry, 1, 3, 4, 1)

        w_grid.attach(self.w_align_combo, 1, 1, 1, 1)

        w_grid.attach(self.w_width_spin, 7, 2, 1, 1)
        w_grid.attach(self.w_corner_spin, 7, 3, 1, 1)
        w_grid.attach(self.w_color_inactive_foreground, 1, 5, 1, 1)
        w_grid.attach(self.w_color_active_foreground, 1, 6, 1, 1)

        box = Gtk.Box()
        box.add(self.w_color_inactive_background1)
        box.add(self.w_color_inactive_background2)
        box.add(self.w_inactive_gradient_check)
        w_grid.attach(box, 3, 5, 2, 1)

        box = Gtk.Box()
        box.add(self.w_color_active_background1)
        box.add(self.w_color_active_background2)
        box.add(self.w_active_gradient_check)
        w_grid.attach(box, 3, 6, 2, 1)

        w_grid.attach(self.w_color_inactive_outline, 5, 5, 1, 1)
        w_grid.attach(self.w_color_active_outline, 5, 6, 1, 1)
        w_grid.attach(self.w_opacity_check1, 6, 5, 1, 1)
        w_grid.attach(self.w_opacity_check2, 6, 6, 1, 1)
        w_grid.attach(self.w_i_opacity_spin, 7, 5, 1, 1)
        w_grid.attach(self.w_a_opacity_spin, 7, 6, 1, 1)

        # Designer - Tray Style (tab 2) labels
        t_decorations_label = Gtk.Label(label='Decoration: ', xalign=1)
        t_encoding_label = Gtk.Label(label='Encoding: ', xalign=1)
        t_inactive_label, t_active_label = Gtk.Label(), Gtk.Label()
        t_foreground_label = Gtk.Label(label='Foreground', xalign=.1)
        t_background_label = Gtk.Label(label='Background', xalign=.1)
        t_outline_label = Gtk.Label(label='Outline', xalign=.5)
        t_inactive_label.set_markup('<b>Inactive</b>')
        t_active_label.set_markup('<b>Active</b>')

        # Designer - Tray Style (tab 2) Widgets (buttons, combos, entries, etc)
        self.t_font_entry, self.t_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.t_opacity_spin = Gtk.SpinButton()
        self.t_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.t_font_button.set_always_show_image(True)
        self.t_antialias_check = Gtk.CheckButton(label="Font Antialias")

        self.t_decorations_combo = Gtk.ComboBoxText()
        self.t_decorations_combo.append_text('flat')
        self.t_decorations_combo.append_text('motif')
        self.t_decorations_combo.set_property("width-request", 63)

        adjustment = Gtk.Adjustment(value=1.0, lower=0.0, upper=1.0, step_increment=0.01)
        self.t_opacity_spin.set_digits(2)
        self.t_opacity_spin.set_adjustment(adjustment)
        self.t_opacity_spin.set_sensitive(False)

        self.t_font_entry.set_property("width-request", 160)
        self.t_encoding_entry.set_property("width-request", 160)
        self.t_font_button.set_property("width-request", 120)

        self.t_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"')
        self.t_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.t_font_button.connect("clicked", self.on_font_choice, self.t_font_entry)

        self.t_color_active_foreground, self.t_color_active_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.t_color_active_background1, self.t_color_active_background2 = Gtk.ColorButton(), Gtk.ColorButton()
        self.t_color_inactive_foreground, self.t_color_inactive_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.t_color_inactive_background1, self.t_color_inactive_background2 = Gtk.ColorButton(), Gtk.ColorButton()
        self.t_inactive_gradient_check, self.t_active_gradient_check = Gtk.CheckButton(), Gtk.ColorButton()
        self.t_active_gradient_check, self.t_opacity_check = Gtk.CheckButton(), Gtk.CheckButton(label='Opacity')

        self.t_color_active_foreground.set_property("width-request", 84)
        self.t_color_active_background1.set_property("width-request", 42)
        self.t_color_active_background2.set_property("width-request", 42)
        self.t_color_active_outline.set_property("width-request", 84)
        self.t_color_inactive_foreground.set_property("width-request", 84)
        self.t_color_inactive_background1.set_property("width-request", 42)
        self.t_color_inactive_background2.set_property("width-request", 42)
        self.t_color_inactive_outline.set_property("width-request", 84)

        self.t_color_active_foreground.set_tooltip_text("Set the default foreground color")
        self.t_color_active_background1.set_tooltip_text("Set the default active background color")
        self.t_color_active_background2.set_tooltip_text("Set the default active background color")
        self.t_color_active_outline.set_tooltip_text("Set the active tray outline color")
        self.t_color_inactive_foreground.set_tooltip_text("Set the default foreground color")
        self.t_color_inactive_background1.set_tooltip_text("Set the default background color")
        self.t_color_inactive_background2.set_tooltip_text("Set the default background color")
        self.t_color_inactive_outline.set_tooltip_text("Set the tray outline color")
        self.t_opacity_check.set_tooltip_text('Enable opacity\n* Requires composite manager')
        self.t_inactive_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")
        self.t_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")

        self.t_opacity_check.connect("toggled", opacity_toggle, self.t_opacity_spin)
        self.t_inactive_gradient_check.connect("toggled", on_gradient_check, self.t_color_inactive_background1,
                                               self.t_color_inactive_background2)
        self.t_active_gradient_check.connect("toggled", on_gradient_check, self.t_color_active_background1,
                                             self.t_color_active_background2)

        self.t_inactive_gradient_check.set_active(True)
        self.t_active_gradient_check.set_active(True)
        self.t_color_active_background1.set_visible(True)
        self.t_color_active_background2.set_visible(True)
        self.t_color_inactive_background1.set_visible(True)
        self.t_color_inactive_background2.set_visible(True)
        self.t_inactive_gradient_check.set_visible(True)
        self.t_active_gradient_check.set_visible(True)

        self.t_color_active_foreground.connect('color-set', self.color_activated)
        self.t_color_active_background1.connect('color-set', self.color_activated)
        self.t_color_active_background2.connect('color-set', self.color_activated)
        self.t_color_inactive_foreground.connect('color-set', self.color_activated)
        self.t_color_inactive_background1.connect('color-set', self.color_activated)
        self.t_color_inactive_background2.connect('color-set', self.color_activated)
        self.t_color_active_outline.connect('color-set', self.color_activated)
        self.t_color_inactive_outline.connect('color-set', self.color_activated)

        # Designer - Tray Style (tab 2)
        t_grid.attach(Gtk.Label(), 0, 0, 2, 1)
        t_grid.attach(t_decorations_label, 0, 1, 1, 1)
        t_grid.attach(self.t_decorations_combo, 1, 1, 1, 1)
        t_grid.attach(self.t_antialias_check, 4, 1, 1, 1)
        t_grid.attach(self.t_font_button, 0, 2, 1, 1)
        t_grid.attach(self.t_font_entry, 1, 2, 4, 1)
        t_grid.attach(t_encoding_label, 0, 3, 1, 1)
        t_grid.attach(self.t_encoding_entry, 1, 3, 4, 1)

        t_grid.attach(Gtk.Label(), 1, 4, 2, 1)

        t_grid.attach(t_foreground_label, 1, 5, 2, 1)
        t_grid.attach(t_background_label, 3, 5, 2, 1)
        t_grid.attach(t_inactive_label, 0, 6, 1, 1)
        t_grid.attach(t_outline_label, 5, 5, 1, 1)
        t_grid.attach(self.t_color_inactive_foreground, 1, 6, 1, 1)
        t_grid.attach(self.t_color_inactive_outline, 5, 6, 1, 1)
        t_grid.attach(t_active_label, 0, 7, 1, 1)
        t_grid.attach(self.t_color_active_foreground, 1, 7, 1, 1)

        t_grid.attach(self.t_color_active_outline, 5, 7, 1, 1)
        t_grid.attach(Gtk.Label(), 6, 5, 1, 1)
        t_grid.attach(self.t_opacity_check, 6, 1, 1, 1)
        t_grid.attach(self.t_opacity_spin, 6, 2, 1, 1)

        box = Gtk.Box()
        box.add(self.t_color_inactive_background1)
        box.add(self.t_color_inactive_background2)
        box.add(self.t_inactive_gradient_check)
        t_grid.attach(box, 3, 6, 2, 1)

        box = Gtk.Box()
        box.add(self.t_color_active_background1)
        box.add(self.t_color_active_background2)
        box.add(self.t_active_gradient_check)
        t_grid.attach(box, 3, 7, 2, 1)

        # Designer - Tray Button Style (tab 3) Labels
        tb_font_label, tb_encoding_label = Gtk.Label(label='', xalign=1), Gtk.Label(label='Encoding: ', xalign=1)
        tb_foreground_label = Gtk.Label(label='Foreground', xalign=.1)
        tb_background_label = Gtk.Label(label='Background', xalign=.1)
        tb_outline_label, tb_decorations_label = Gtk.Label(label='Outline', xalign=.5), Gtk.Label(label=' ', xalign=1)

        tb_font_label.set_width_chars(5)
        tb_inactive_label = Gtk.Label()
        tb_inactive_label.set_markup('<b>Inactive</b>')
        tb_active_label = Gtk.Label()
        tb_active_label.set_markup('<b>Active</b>')
        tb_decorations_label.set_width_chars(15)

        # Designer - Tray Button Style (tab 3) Widgets (buttons, combos, entries, etc)
        self.tb_font_entry, self.tb_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.tb_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.tb_font_button.set_always_show_image(True)

        self.tb_font_entry.set_property("width-request", 160)
        self.tb_encoding_entry.set_property("width-request", 160)
        self.tb_font_button.set_property("width-request", 120)
        self.tb_font_button.set_tooltip_text('Preview, configure and select from installed fonts')

        self.tb_font_entry.set_tooltip_text('Leave empty to inherit values from Tray Style')
        self.tb_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"\n'
                                                'Ignored if no font is defined')

        self.tb_font_button.connect("clicked", self.on_font_choice, self.tb_font_entry)
        self.tb_color_active_foreground, self.tb_color_active_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.tb_color_active_background1, self.tb_color_active_background2 = Gtk.ColorButton(), Gtk.ColorButton()
        self.tb_color_inactive_foreground, self.tb_color_inactive_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.tb_color_inactive_background1, self.tb_color_inactive_background2 = Gtk.ColorButton(), Gtk.ColorButton()

        self.tb_color_active_foreground.set_property("width-request", 84)
        self.tb_color_active_background1.set_property("width-request", 42)
        self.tb_color_active_background2.set_property("width-request", 42)
        self.tb_color_active_outline.set_property("width-request", 84)
        self.tb_color_inactive_foreground.set_property("width-request", 84)
        self.tb_color_inactive_background1.set_property("width-request", 42)
        self.tb_color_inactive_background2.set_property("width-request", 42)
        self.tb_color_inactive_outline.set_property("width-request", 84)

        self.tb_color_active_foreground.set_tooltip_text("Set the foreground color for the active tray button ")
        self.tb_color_active_background1.set_tooltip_text("Set the background color of the active tray buttons")
        self.tb_color_active_background2.set_tooltip_text("Set the background color of the active tray buttons")
        self.tb_color_active_outline.set_tooltip_text("Set the outline color of the active button")
        self.tb_color_inactive_foreground.set_tooltip_text("Set the foreground color of tray buttons")
        self.tb_color_inactive_background1.set_tooltip_text("Set the background color of tray buttons")
        self.tb_color_inactive_background2.set_tooltip_text("Set the background color of tray buttons")
        self.tb_color_inactive_outline.set_tooltip_text("Set the outline color")

        self.tb_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.tb_inactive_gradient_check, self.tb_active_gradient_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tb_color_af_check, self.tb_color_ab_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tb_color_ao_check, self.tb_color_if_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tb_color_ib_check, self.tb_color_io_check = Gtk.CheckButton(), Gtk.CheckButton()

        self.tb_antialias_check.set_property("height-request", 35)
        self.tb_antialias_check.set_tooltip_text('Ignored if no font is defined')
        self.tb_inactive_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")
        self.tb_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")
        self.tb_color_af_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tb_color_ab_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tb_color_ao_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tb_color_if_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tb_color_ib_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tb_color_io_check.set_tooltip_text('Disable : use Tray Style color values')

        self.tb_inactive_gradient_check.connect("toggled", on_gradient_check, self.tb_color_inactive_background1,
                                                self.tb_color_inactive_background2)
        self.tb_active_gradient_check.connect("toggled", on_gradient_check, self.tb_color_active_background1,
                                              self.tb_color_active_background2)
        self.tb_color_af_check.connect("toggled", on_color_toggle, self.tb_color_active_foreground, '')
        self.tb_color_ab_check.connect("toggled", on_color_toggle, self.tb_color_active_background1,
                                       self.tb_color_active_background2)
        self.tb_color_ao_check.connect("toggled", on_color_toggle, self.tb_color_active_outline, '')
        self.tb_color_if_check.connect("toggled", on_color_toggle, self.tb_color_inactive_foreground, '')
        self.tb_color_ib_check.connect("toggled", on_color_toggle, self.tb_color_inactive_background1
                                       , self.tb_color_inactive_background2)
        self.tb_color_io_check.connect("toggled", on_color_toggle, self.tb_color_inactive_outline, '')

        self.tb_color_af_check.set_active(True)
        self.tb_color_ab_check.set_active(True)
        self.tb_color_ao_check.set_active(True)
        self.tb_color_if_check.set_active(True)
        self.tb_color_ib_check.set_active(True)
        self.tb_color_io_check.set_active(True)
        self.tb_inactive_gradient_check.set_active(True)
        self.tb_active_gradient_check.set_active(True)
        self.tb_color_if_check.set_visible(True)
        self.tb_color_inactive_foreground.set_visible(True)
        self.tb_color_af_check.set_visible(True)
        self.tb_color_active_foreground.set_visible(True)
        self.tb_color_ab_check.set_visible(True)
        self.tb_active_gradient_check.set_visible(True)
        self.tb_color_active_background1.set_visible(True)
        self.tb_color_io_check.set_visible(True)
        self.tb_color_inactive_outline.set_visible(True)
        self.tb_color_inactive_background1.set_visible(True)
        self.tb_color_inactive_background1.set_visible(True)
        self.tb_color_inactive_background1.set_visible(True)
        self.tb_color_ib_check.set_visible(True)
        self.tb_inactive_gradient_check.set_visible(True)
        self.tb_color_ao_check.set_visible(True)
        self.tb_color_active_outline.set_visible(True)

        self.tb_color_active_foreground.connect('color-set', self.color_activated)
        self.tb_color_active_background1.connect('color-set', self.color_activated)
        self.tb_color_active_background2.connect('color-set', self.color_activated)
        self.tb_color_inactive_foreground.connect('color-set', self.color_activated)
        self.tb_color_inactive_background1.connect('color-set', self.color_activated)
        self.tb_color_inactive_background2.connect('color-set', self.color_activated)
        self.tb_color_active_outline.connect('color-set', self.color_activated)
        self.tb_color_inactive_outline.connect('color-set', self.color_activated)

        tb_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        tb_grid.attach(tb_decorations_label, 0, 1, 1, 1)
        tb_grid.attach(self.tb_antialias_check, 4, 1, 1, 1)
        tb_grid.attach(self.tb_font_button, 0, 2, 1, 1)
        tb_grid.attach(self.tb_font_entry, 1, 2, 4, 1)
        tb_grid.attach(tb_encoding_label, 0, 3, 1, 1)
        tb_grid.attach(self.tb_encoding_entry, 1, 3, 4, 1)
        tb_grid.attach(tb_inactive_label, 0, 5, 1, 1)
        tb_grid.attach(tb_foreground_label, 1, 4, 2, 1)
        tb_grid.attach(tb_active_label, 0, 6, 1, 1)
        tb_grid.attach(tb_background_label, 3, 4, 2, 1)
        tb_grid.attach(tb_outline_label, 5, 4, 1, 1)

        box = Gtk.Box()
        box.add(self.tb_color_if_check)
        box.add(self.tb_color_inactive_foreground)
        tb_grid.attach(box, 1, 5, 1, 1)

        box = Gtk.Box()
        box.add(self.tb_color_ib_check)
        box.add(self.tb_color_inactive_background1)
        box.add(self.tb_color_inactive_background2)
        box.add(self.tb_inactive_gradient_check)
        tb_grid.attach(box, 3, 5, 2, 1)
        tb_grid.attach(Gtk.Label(), 6, 4, 1, 1)
        tb_grid.attach(Gtk.Label(label=' '), 0, 7, 1, 1)

        box = Gtk.Box()
        box.add(self.tb_color_af_check)
        box.add(self.tb_color_active_foreground)
        tb_grid.attach(box, 1, 6, 1, 1)

        box = Gtk.Box()
        box.add(self.tb_color_ab_check)
        box.add(self.tb_color_active_background1)
        box.add(self.tb_color_active_background2)
        box.add(self.tb_active_gradient_check)
        tb_grid.attach(box, 3, 6, 2, 1)

        box = Gtk.Box()
        box .add(self.tb_color_io_check)
        box .add(self.tb_color_inactive_outline)
        tb_grid.attach(box , 5, 5, 1, 1)

        box = Gtk.Box()
        box.add(self.tb_color_ao_check)
        box.add(self.tb_color_active_outline)
        tb_grid.attach(box, 5, 6, 1, 1)

        # Designer - TaskList Style Labels (tab 4)
        tl_decorations_label, tl_inactive_label = Gtk.Label(label='Decoration: ', xalign=1), Gtk.Label()
        tl_encoding_label, tl_active_label = Gtk.Label(label='Encoding: ', xalign=1), Gtk.Label()
        tl_foreground_label = Gtk.Label(label='Foreground', xalign=.1)
        tl_background_label = Gtk.Label(label='Background', xalign=.1)
        tl_outline_label = Gtk.Label(label='Outline', xalign=.5)

        tl_inactive_label.set_markup('<b>Inactive</b>')
        tl_active_label.set_markup('<b>Active</b>')
        tl_decorations_label.set_width_chars(15)

        # TaskList Style (tab 4) Widgets (buttons, combos, entries, etc)
        self.tl_font_entry, self.tl_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.tl_font_entry.set_tooltip_text('Leave empty to inherit values from Tray Style')
        self.tl_font_entry.set_property("width-request", 160)

        self.tl_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"\n'
                                                'Ignored if no font is defined')
        self.tl_encoding_entry.set_property("width-request", 160)

        self.tl_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.tl_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.tl_font_button.set_always_show_image(True)
        self.tl_font_button.set_property("width-request", 120)
        self.tl_font_button.connect("clicked", self.on_font_choice, self.tl_font_entry)

        self.tl_group_check, self.tl_list_check = Gtk.CheckButton(label="Group"), Gtk.CheckButton(label="All Windows")
        self.tl_list_check.set_tooltip_text('Show all windows in the task list\nor only windows in current desktop')
        self.tl_group_check.set_tooltip_text('Group windows in the task list')
        self.tl_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.tl_antialias_check.set_tooltip_text('Ignored if no font is defined')

        self.tl_decorations_combo = Gtk.ComboBoxText()
        self.tl_decorations_combo.append_text('flat')
        self.tl_decorations_combo.append_text('motif')
        self.tl_decorations_combo.append_text('disable')
        self.tl_decorations_combo.set_property("width-request", 63)
        self.tl_decorations_combo.set_tooltip_text('Select "disable" to inherit for Tray Style')

        self.tl_color_active_foreground, self.tl_color_active_background1 = Gtk.ColorButton(), Gtk.ColorButton()
        self.tl_color_active_background2, self.tl_color_active_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.tl_color_inactive_foreground, self.tl_color_inactive_background1 = Gtk.ColorButton(), Gtk.ColorButton()
        self.tl_color_inactive_background2, self.tl_color_inactive_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.tl_inactive_gradient_check, self.tl_active_gradient_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tl_color_af_check, self.tl_color_ab_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tl_color_ao_check, self.tl_color_if_check = Gtk.CheckButton(), Gtk.CheckButton()
        self.tl_color_ib_check, self.tl_color_io_check = Gtk.CheckButton(), Gtk.CheckButton()

        self.tl_color_active_foreground.set_property("width-request", 84)
        self.tl_color_active_background1.set_property("width-request", 42)
        self.tl_color_active_background2.set_property("width-request", 42)
        self.tl_color_active_outline.set_property("width-request", 84)
        self.tl_color_inactive_foreground.set_property("width-request", 84)
        self.tl_color_inactive_background1.set_property("width-request", 42)
        self.tl_color_inactive_background2.set_property("width-request", 42)
        self.tl_color_inactive_outline.set_property("width-request", 84)

        self.tl_color_active_foreground.set_tooltip_text("Set the active foreground color of the task list")
        self.tl_color_active_background1.set_tooltip_text("Set the active background color of the task list")
        self.tl_color_active_background2.set_tooltip_text("Set the active background color of the task list")
        self.tl_color_active_outline.set_tooltip_text("Set the active outline color of the task list")
        self.tl_color_inactive_foreground.set_tooltip_text("Set the foreground color of the task list")
        self.tl_color_inactive_background1.set_tooltip_text("Set the background color of the task list")
        self.tl_color_inactive_background2.set_tooltip_text("Set the background color of the task list")
        self.tl_color_inactive_outline.set_tooltip_text("Set the outline color of the task list")
        self.tl_inactive_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")
        self.tl_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")

        self.tl_inactive_gradient_check.connect("toggled", on_gradient_check, self.tl_color_inactive_background1,
                                                self.tl_color_inactive_background2)
        self.tl_active_gradient_check.connect("toggled", on_gradient_check, self.tl_color_active_background1,
                                              self.tl_color_active_background2)

        self.tl_color_af_check.connect("toggled", on_color_toggle, self.tl_color_active_foreground, '')
        self.tl_color_ab_check.connect("toggled", on_color_toggle, self.tl_color_active_background1
                                       , self.tl_color_active_background2)
        self.tl_color_ao_check.connect("toggled", on_color_toggle, self.tl_color_active_outline, '')
        self.tl_color_if_check.connect("toggled", on_color_toggle, self.tl_color_inactive_foreground, '')
        self.tl_color_ib_check.connect("toggled", on_color_toggle, self.tl_color_inactive_background1
                                       , self.tl_color_inactive_background2)
        self.tl_color_io_check.connect("toggled", on_color_toggle, self.tl_color_inactive_outline, '')

        self.tl_color_af_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tl_color_ab_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tl_color_ao_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tl_color_if_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tl_color_ib_check.set_tooltip_text('Disable : use Tray Style color values')
        self.tl_color_io_check.set_tooltip_text('Disable : use Tray Style color values')

        self.tl_color_af_check.set_active(True)
        self.tl_color_ab_check.set_active(True)
        self.tl_color_ao_check.set_active(True)
        self.tl_color_if_check.set_active(True)
        self.tl_color_ib_check.set_active(True)
        self.tl_color_io_check.set_active(True)
        self.tl_inactive_gradient_check.set_active(True)
        self.tl_active_gradient_check.set_active(True)
        self.tl_color_if_check.set_visible(True)
        self.tl_color_inactive_foreground.set_visible(True)
        self.tl_color_af_check.set_visible(True)
        self.tl_color_active_foreground.set_visible(True)
        self.tl_color_ab_check.set_visible(True)
        self.tl_active_gradient_check.set_visible(True)
        self.tl_color_active_background1.set_visible(True)
        self.tl_color_io_check.set_visible(True)
        self.tl_color_inactive_outline.set_visible(True)
        self.tl_color_inactive_background1.set_visible(True)
        self.tl_color_inactive_background2.set_visible(True)
        self.tl_color_ib_check.set_visible(True)
        self.tl_inactive_gradient_check.set_visible(True)
        self.tl_color_ao_check.set_visible(True)
        self.tl_color_active_outline.set_visible(True)

        self.tl_color_active_foreground.connect('color-set', self.color_activated)
        self.tl_color_active_background1.connect('color-set', self.color_activated)
        self.tl_color_active_background2.connect('color-set', self.color_activated)
        self.tl_color_inactive_foreground.connect('color-set', self.color_activated)
        self.tl_color_inactive_background1.connect('color-set', self.color_activated)
        self.tl_color_inactive_background2.connect('color-set', self.color_activated)
        self.tl_color_active_outline.connect('color-set', self.color_activated)
        self.tl_color_inactive_outline.connect('color-set', self.color_activated)

        # TaskList Style (tab 4)
        tl_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        tl_grid.attach(tl_decorations_label, 0, 1, 1, 1)
        tl_grid.attach(self.tl_decorations_combo, 1, 1, 1, 1)
        tl_grid.attach(self.tl_antialias_check, 4, 1, 1, 1)
        tl_grid.attach(self.tl_font_button, 0, 2, 1, 1)
        tl_grid.attach(self.tl_font_entry, 1, 2, 4, 1)
        tl_grid.attach(tl_encoding_label, 0, 3, 1, 1)
        tl_grid.attach(self.tl_encoding_entry, 1, 3, 4, 1)
        tl_grid.attach(tl_inactive_label, 0, 5, 1, 1)
        tl_grid.attach(tl_foreground_label, 1, 4, 2, 1)
        tl_grid.attach(tl_active_label, 0, 6, 1, 1)
        tl_grid.attach(tl_background_label, 3, 4, 2, 1)
        tl_grid.attach(tl_outline_label, 5, 4, 1, 1)
        tl_grid.attach(Gtk.Label(), 6, 4, 1, 1)
        tl_grid.attach(Gtk.Label(label=' '), 0, 7, 1, 1)
        tl_grid.attach(self.tl_group_check, 5, 1, 1, 1)
        tl_grid.attach(self.tl_list_check, 5, 2, 1, 1)
        
        box = Gtk.Box()
        box.add(self.tl_color_if_check)
        box.add(self.tl_color_inactive_foreground)
        tl_grid.attach(box, 1, 5, 1, 1)

        box = Gtk.Box()
        box.add(self.tl_color_ib_check)
        box.add(self.tl_color_inactive_background1)
        box.add(self.tl_color_inactive_background2)
        box.add(self.tl_inactive_gradient_check)
        tl_grid.attach(box, 3, 5, 2, 1)

        box = Gtk.Box()
        box.add(self.tl_color_af_check)
        box.add(self.tl_color_active_foreground)
        tl_grid.attach(box, 1, 6, 1, 1)

        box = Gtk.Box()
        box.add(self.tl_color_ab_check)
        box.add(self.tl_color_active_background1)
        box.add(self.tl_color_active_background2)
        box.add(self.tl_active_gradient_check)
        tl_grid.attach(box, 3, 6, 2, 1)

        box = Gtk.Box()
        box.add(self.tl_color_io_check)
        box.add(self.tl_color_inactive_outline)
        tl_grid.attach(box, 5, 5, 1, 1)
        
        box = Gtk.Box()
        box.add(self.tl_color_ao_check)
        box.add(self.tl_color_active_outline)
        tl_grid.attach(box, 5, 6, 1, 1)

        # Designer - Menu Style (tab 5) labels
        m_decorations_label = Gtk.Label(label='Decoration: ', xalign=1)
        m_encoding_label = Gtk.Label(label='Encoding: ', xalign=1)
        m_inactive_label = Gtk.Label()
        m_inactive_label.set_markup('<b>Inactive</b>')
        m_active_label = Gtk.Label()
        m_active_label.set_markup('<b>Active</b>')
        m_foreground_label = Gtk.Label(label='Foreground', xalign=.1)
        m_background_label = Gtk.Label(label='Background', xalign=.1)
        m_outline_label = Gtk.Label(label='Outline', xalign=.5)
        m_decorations_label.set_width_chars(15)

        # Menu Style (tab 5) Widgets (buttons, combos, entries, etc)
        self.m_font_entry, self.m_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.m_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))

        self.m_font_entry.set_property("width-request", 160)
        self.m_encoding_entry.set_property("width-request", 160)
        self.m_font_button.set_property("width-request", 120)

        self.m_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"')
        self.m_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.m_font_button.set_always_show_image(True)
        self.m_font_button.connect("clicked", self.on_font_choice, self.m_font_entry)

        self.m_decorations_combo = Gtk.ComboBoxText()
        self.m_decorations_combo.append_text('flat')
        self.m_decorations_combo.append_text('motif')
        self.m_decorations_combo.set_property("width-request", 63)

        self.m_opacity_spin = Gtk.SpinButton()
        self.m_opacity_spin.set_digits(2)
        adjustment = Gtk.Adjustment(value=1.0, lower=0.0, upper=1.0, step_increment=0.01)
        self.m_opacity_spin.set_adjustment(adjustment)
        self.m_opacity_spin.set_sensitive(False)

        self.m_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.m_opacity_check, self.m_active_gradient_check = Gtk.CheckButton(label='Opacity'), Gtk.CheckButton()

        self.m_color_active_foreground, self.m_color_active_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.m_color_active_background1, self.m_color_active_background2 = Gtk.ColorButton(), Gtk.ColorButton()
        self.m_color_inactive_foreground, self.m_color_inactive_background = Gtk.ColorButton(), Gtk.ColorButton()
        self.m_color_inactive_outline = Gtk.ColorButton()

        self.m_color_active_foreground.set_property("width-request", 84)
        self.m_color_active_background1.set_property("width-request", 42)
        self.m_color_active_background2.set_property("width-request", 42)
        self.m_color_active_outline.set_property("width-request", 84)
        self.m_color_inactive_foreground.set_property("width-request", 84)
        self.m_color_inactive_background.set_property("width-request", 84)
        self.m_color_inactive_outline.set_property("width-request", 84)

        self.m_opacity_check.set_tooltip_text('Enable opacity\n* Requires composite manager')
        self.m_color_active_foreground.set_tooltip_text("Set the default active foreground color")
        self.m_color_active_background1.set_tooltip_text("Set the default active background color")
        self.m_color_active_background2.set_tooltip_text("Set the default active background color")
        self.m_color_active_outline.set_tooltip_text("Set the active tray outline color")
        self.m_color_inactive_foreground.set_tooltip_text("Set the default foreground color")
        self.m_color_inactive_background.set_tooltip_text("Set the default background color")
        self.m_color_inactive_outline.set_tooltip_text("Set the tray outline color")
        self.m_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")

        self.m_active_gradient_check.connect("toggled", on_gradient_check, self.m_color_active_background1,
                                             self.m_color_active_background2)
        self.m_opacity_check.connect("toggled", opacity_toggle, self.m_opacity_spin)

        self.m_color_active_foreground.connect('color-set', self.color_activated)
        self.m_color_active_background1.connect('color-set', self.color_activated)
        self.m_color_active_background2.connect('color-set', self.color_activated)
        self.m_color_active_outline.connect('color-set', self.color_activated)
        self.m_color_inactive_foreground.connect('color-set', self.color_activated)
        self.m_color_inactive_background.connect('color-set', self.color_activated)
        self.m_color_inactive_outline.connect('color-set', self.color_activated)

        self.m_active_gradient_check.set_active(True)
        self.m_color_inactive_foreground.set_visible(True)
        self.m_color_active_foreground.set_visible(True)
        self.m_active_gradient_check.set_visible(True)
        self.m_color_active_background1.set_visible(True)
        self.m_color_inactive_background.set_visible(True)
        self.m_color_inactive_outline.set_visible(True)
        self.m_color_active_outline.set_visible(True)

        # Menu Style (tab 5)
        m_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        m_grid.attach(m_decorations_label, 0, 1, 1, 1)
        m_grid.attach(self.m_decorations_combo, 1, 1, 1, 1)
        m_grid.attach(self.m_antialias_check, 4, 1, 1, 1)
        m_grid.attach(self.m_font_button, 0, 2, 1, 1)
        m_grid.attach(self.m_font_entry, 1, 2, 4, 1)
        m_grid.attach(m_encoding_label, 0, 3, 1, 1)
        m_grid.attach(self.m_encoding_entry, 1, 3, 4, 1)
        m_grid.attach(m_inactive_label, 0, 5, 1, 1)
        m_grid.attach(self.m_color_inactive_foreground, 1, 5, 1, 1)
        m_grid.attach(m_foreground_label, 1, 4, 2, 1)
        m_grid.attach(m_active_label, 0, 6, 1, 1)
        m_grid.attach(self.m_color_active_foreground, 1, 6, 1, 1)
        m_grid.attach(m_background_label, 3, 4, 2, 1)
        m_grid.attach(m_outline_label, 5, 4, 1, 1)
        m_grid.attach(self.m_color_inactive_outline, 5, 5, 1, 1)
        m_grid.attach(self.m_color_active_outline, 5, 6, 1, 1)
        m_grid.attach(Gtk.Label(), 6, 4, 1, 1)
        m_grid.attach(self.m_opacity_check, 6, 1, 1, 1)
        m_grid.attach(self.m_opacity_spin, 6, 2, 1, 1)
        m_grid.attach(Gtk.Label(label=' '), 0, 7, 1, 1)

        box = Gtk.Box()
        box.add(self.m_color_inactive_background)
        m_grid.attach(box, 3, 5, 2, 1)

        box = Gtk.Box()
        box.add(self.m_color_active_background1)
        box.add(self.m_color_active_background2)
        box.add(self.m_active_gradient_check)
        m_grid.attach(box, 3, 6, 2, 1)

        # Designer - Pager Style(tab 6) Labels
        p_font_label = Gtk.Label(label='', xalign=1)
        p_encoding_label = Gtk.Label(label='Encoding: ', xalign=1)
        p_inactive_label = Gtk.Label()
        p_inactive_label.set_markup('<b>Inactive</b>')
        p_active_label = Gtk.Label()
        p_active_label.set_markup('<b>Active</b>')
        p_foreground_label = Gtk.Label(label='Foreground', xalign=.1)
        p_background_label = Gtk.Label(label='Background', xalign=.1)
        p_text_label = Gtk.Label(label='Text: ', xalign=1)
        p_outline_label = Gtk.Label(label='Outline: ', xalign=1)
        p_decorations_label = Gtk.Label(label=' ', xalign=1)
        p_font_label.set_width_chars(5)
        p_decorations_label.set_width_chars(15)

        # Pager Style (tab 6) Widgets (buttons, combos, entries, etc)
        self.p_font_entry, self.p_encoding_entry  = Gtk.Entry(), Gtk.Entry()
        self.p_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.p_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.p_font_button.set_always_show_image(True)
        self.p_font_button.connect("clicked", self.on_font_choice, self.p_font_entry)
        self.p_color_active_foreground, self.p_color_inactive_foreground = Gtk.ColorButton(), Gtk.ColorButton()
        self.p_color_active_background, self.p_color_outline = Gtk.ColorButton(), Gtk.ColorButton()
        self.p_color_inactive_background, self.p_color_text  = Gtk.ColorButton(), Gtk.ColorButton()

        self.p_antialias_check.set_property("height-request", 35)
        self.p_font_entry.set_property("width-request", 160)
        self.p_encoding_entry.set_property("width-request", 160)
        self.p_font_button.set_property("width-request", 120)
        self.p_color_active_foreground.set_property("width-request", 84)
        self.p_color_active_background.set_property("width-request", 84)
        self.p_color_outline.set_property("width-request", 84)
        self.p_color_inactive_foreground.set_property("width-request", 84)
        self.p_color_inactive_background.set_property("width-request", 84)
        self.p_color_text.set_property("width-request", 84)

        self.p_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.p_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"')
        self.p_color_active_foreground.set_tooltip_text("Set the color of text on the active window's title bar.")
        self.p_color_active_background.set_tooltip_text("Set the color of the active window's title bar.")
        self.p_color_outline.set_tooltip_text("Set the color of the active window's outline")
        self.p_color_inactive_foreground.set_tooltip_text("Set the foreground color for tray button labels")
        self.p_color_inactive_background.set_tooltip_text("Set the color of tray buttons")
        self.p_color_text.set_tooltip_text("Set the outline color")

        self.p_color_active_foreground.connect('color-set', self.color_activated)
        self.p_color_active_background.connect('color-set', self.color_activated)
        self.p_color_outline.connect('color-set', self.color_activated)
        self.p_color_inactive_foreground.connect('color-set', self.color_activated)
        self.p_color_inactive_background.connect('color-set', self.color_activated)
        self.p_color_text.connect('color-set', self.color_activated)

        p_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        p_grid.attach(p_decorations_label, 0, 1, 1, 1)
        p_grid.attach(self.p_antialias_check, 4, 1, 1, 1)
        p_grid.attach(self.p_font_button, 0, 2, 1, 1)
        p_grid.attach(self.p_font_entry, 1, 2, 4, 1)
        p_grid.attach(p_encoding_label, 0, 3, 1, 1)
        p_grid.attach(self.p_encoding_entry, 1, 3, 4, 1)
        p_grid.attach(p_inactive_label, 0, 5, 1, 1)
        p_grid.attach(p_foreground_label, 1, 4, 2, 1)
        p_grid.attach(self.p_color_inactive_foreground, 1, 5, 1, 1)
        p_grid.attach(self.p_color_inactive_background, 3, 5, 1, 1)
        p_grid.attach(p_active_label, 0, 6, 1, 1)
        p_grid.attach(self.p_color_active_foreground, 1, 6, 1, 1)
        p_grid.attach(p_background_label, 3, 4, 2, 1)
        p_grid.attach(self.p_color_active_background, 3, 6, 1, 1)
        p_grid.attach(p_outline_label, 4, 6, 1, 1)
        p_grid.attach(p_text_label, 4, 5, 1, 1)
        p_grid.attach(self.p_color_outline, 5, 6, 1, 1)
        p_grid.attach(self.p_color_text, 5, 5, 1, 1)
        p_grid.attach(Gtk.Label(), 6, 4, 1, 1)
        p_grid.attach(Gtk.Label(label=' '), 0, 7, 1, 1)

        # Designer - Clock Style (tab 7) Labels
        cl_font_label = Gtk.Label(label='', xalign=1)
        cl_encoding_label = Gtk.Label(label='Encoding: ', xalign=1)
        cl_decorations_label = Gtk.Label(label=' ', xalign=1)
        cl_font_label.set_width_chars(5)
        cl_decorations_label.set_width_chars(15)

        # Clock Style (tab 7) Widgets (buttons, combos, entries, etc)
        self.cl_font_entry, self.cl_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.cl_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.cl_font_button.set_always_show_image(True)
        self.cl_antialias_check = Gtk.CheckButton(label="Font Antialias")

        self.cl_antialias_check.set_property("height-request", 35)
        self.cl_font_entry.set_property("width-request", 160)
        self.cl_encoding_entry.set_property("width-request", 160)
        self.cl_font_button.set_property("width-request", 120)

        self.cl_font_entry.set_tooltip_text('Leave empty to inherit values from Tray Style')
        self.cl_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"\n'
                                                'Ignored if no font is defined')
        self.cl_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.cl_antialias_check.set_tooltip_text("Ignored if no font is defined")

        self.cl_font_button.connect("clicked", self.on_font_choice, self.cl_font_entry)

        self.cl_color_foreground = Gtk.ColorButton()
        self.cl_color_background1, self.cl_color_background2 = Gtk.ColorButton(), Gtk.ColorButton()

        self.cl_color_foreground.set_property("width-request", 84)
        self.cl_color_background1.set_property("width-request", 42)
        self.cl_color_background2.set_property("width-request", 42)

        self.cl_color_foreground.set_tooltip_text("Set the clock's text color")
        self.cl_color_background1.set_tooltip_text("Set the clock's background color ")
        self.cl_color_background2.set_tooltip_text("Set the clock's background color ")

        self.cl_foreground_check = Gtk.CheckButton(label='Foreground')
        self.cl_background_check = Gtk.CheckButton(label='Background')
        self.cl_active_gradient_check = Gtk.CheckButton()

        self.cl_foreground_check.set_active(True)
        self.cl_background_check.set_active(True)
        self.cl_active_gradient_check.set_active(True)

        self.cl_foreground_check.set_tooltip_text('Enable to define a custom color\n'
                                                  'Disabled to inherit the Tray Style color')

        self.cl_background_check.set_tooltip_text('Enable to define a custom color\n'
                                                  'Disabled to inherit the Tray Style color')
        self.cl_active_gradient_check.set_tooltip_text("Enable gradients (select 2 colors)")

        self.cl_background_check.connect("toggled", on_color_toggle, self.cl_color_background1
                                         , self.cl_color_background2)
        self.cl_foreground_check.connect("toggled", on_color_toggle, self.cl_color_foreground, '')
        self.cl_active_gradient_check.connect("toggled", on_gradient_check, self.cl_color_background1,
                                              self.cl_color_background2)
        self.cl_color_foreground.connect('color-set', self.color_activated)
        self.cl_color_background1.connect('color-set', self.color_activated)
        self.cl_color_background2.connect('color-set', self.color_activated)

        self.cl_active_gradient_check.set_visible(True)
        self.cl_color_background1.set_visible(True)
        self.cl_color_background2.set_visible(True)

        cl_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        cl_grid.attach(self.cl_antialias_check, 4, 1, 1, 1)
        cl_grid.attach(self.cl_font_button, 0, 2, 1, 1)
        cl_grid.attach(self.cl_font_entry, 1, 2, 4, 1)
        cl_grid.attach(cl_encoding_label, 0, 3, 1, 1)
        cl_grid.attach(self.cl_encoding_entry, 1, 3, 4, 1)
        cl_grid.attach(Gtk.Label(), 0, 4, 1, 1)
        cl_grid.attach(self.cl_foreground_check, 1, 4, 1, 1)
        cl_grid.attach(self.cl_color_foreground, 1, 5, 1, 1)
        cl_grid.attach(self.cl_background_check, 3, 4, 1, 1)

        box = Gtk.Box()
        box.add(self.cl_active_gradient_check)
        box.add(self.cl_color_background1)
        box.add(self.cl_color_background2)
        cl_grid.attach(box, 3, 5, 1, 1)

        # Designer - Popup Style (tab 8) Labels
        pop_font_label, pop_delay_label = Gtk.Label(label='', xalign=1), Gtk.Label(label='Delay: ', xalign=1)
        pop_encoding_label = Gtk.Label(label='Encoding: ', xalign=1)
        pop_foreground_label = Gtk.Label(label='Foreground: ', xalign=1)
        pop_background_label = Gtk.Label(label='Background: ', xalign=1)
        pop_outline_label = Gtk.Label(label='Outline: ', xalign=1)
        pop_enable_label = Gtk.Label()
        pop_enable_label.set_markup('<b>Enable pops for the selected items</b>')

        pop_font_label.set_width_chars(5)
        pop_delay_label.set_width_chars(15)

        # Popup Style (tab 8) Widgets (buttons, combos, entries, etc)
        self.pop_font_entry, self.pop_encoding_entry = Gtk.Entry(), Gtk.Entry()
        self.pop_antialias_check = Gtk.CheckButton(label="Font Antialias")
        self.pop_font_button = Gtk.Button(label=' Font', image=Gtk.Image(stock=Gtk.STOCK_SELECT_FONT))
        self.pop_font_button.set_always_show_image(True)

        self.pop_delay_spin = Gtk.SpinButton()
        adjustment = Gtk.Adjustment(value=600, lower=0, upper=300000, step_increment=1)
        self.pop_delay_spin.set_adjustment(adjustment)

        self.pop_delay_spin.set_property("width-request", 100)
        self.pop_font_entry.set_property("width-request", 160)
        self.pop_encoding_entry.set_property("width-request", 160)
        self.pop_font_button.set_property("width-request", 120)

        self.pop_delay_spin.set_tooltip_text('Set the delay in milliseconds. Default is 600')
        self.pop_encoding_entry.set_tooltip_text('Registered encoding. The most common is "utf8"\n'
                                                 'Leave empty to inherit values from Tray Style')
        self.pop_font_button.set_tooltip_text('Preview, configure and select from installed fonts')
        self.pop_font_button.connect("clicked", self.on_font_choice, self.pop_font_entry)

        self.pop_color_foreground = Gtk.ColorButton()
        self.pop_color_background = Gtk.ColorButton()
        self.pop_color_outline = Gtk.ColorButton()

        self.pop_color_foreground.set_property("width-request", 84)
        self.pop_color_background.set_property("width-request", 84)
        self.pop_color_outline.set_property("width-request", 84)

        self.pop_color_foreground.set_tooltip_text("Set the popup text color")
        self.pop_color_background.set_tooltip_text("Set the popup background color")
        self.pop_color_outline.set_tooltip_text("Set popup outline color")

        self.pop_all_check = Gtk.CheckButton(label="All")
        self.pop_buttons_check = Gtk.CheckButton(label="Buttons")
        self.pop_clock_check = Gtk.CheckButton(label="Clocks")

        self.pop_menu_check = Gtk.CheckButton(label="Menus")
        self.pop_task_check = Gtk.CheckButton(label="Task List")
        self.pop_pagers_check = Gtk.CheckButton(label="Pagers")
        self.pop_none_check = Gtk.CheckButton(label="None")

        self.pop_all_check.set_tooltip_text("Enable All Popups")
        self.pop_none_check.set_tooltip_text("Disable All Popups")
        self.pop_all_check.connect("toggled", self.pop_disabled_checks)
        self.pop_none_check.connect("toggled", self.pop_disabled_checks)

        self.pop_color_foreground.connect('color-set', self.color_activated)
        self.pop_color_background.connect('color-set', self.color_activated)
        self.pop_color_outline.connect('color-set', self.color_activated)

        pop_grid.attach(Gtk.Label(), 0, 0, 1, 1)
        pop_grid.attach(pop_delay_label, 0, 1, 1, 1)
        pop_grid.attach(self.pop_delay_spin, 1, 1, 1, 1)
        pop_grid.attach(self.pop_antialias_check, 2, 1, 2, 1)
        pop_grid.attach(self.pop_font_button, 0, 2, 1, 1)
        pop_grid.attach(self.pop_font_entry, 1, 2, 3, 1)
        pop_grid.attach(pop_encoding_label, 0, 3, 1, 1)
        pop_grid.attach(self.pop_encoding_entry, 1, 3, 3, 1)
        pop_grid.attach(pop_foreground_label, 4, 1, 2, 1)
        pop_grid.attach(self.pop_color_foreground, 6, 1, 1, 1)
        pop_grid.attach(pop_background_label, 4, 2, 2, 1)
        pop_grid.attach(self.pop_color_background, 6, 2, 1, 1)
        pop_grid.attach(pop_outline_label, 4, 3, 2, 1)
        pop_grid.attach(self.pop_color_outline, 6, 3, 1, 1)
        pop_grid.attach(pop_enable_label, 1, 4, 5, 1)
        pop_grid.attach(self.pop_all_check, 1, 5, 1, 1)
        pop_grid.attach(self.pop_buttons_check, 2, 5, 1, 1)
        pop_grid.attach(self.pop_clock_check, 3, 5, 2, 1)
        pop_grid.attach(self.pop_menu_check, 1, 6, 1, 1)
        pop_grid.attach(self.pop_task_check, 2, 6, 1, 1)
        pop_grid.attach(self.pop_pagers_check, 3, 6, 2, 1)
        pop_grid.attach(self.pop_none_check, 5, 6, 2, 1)

        # Appearance - Notebook page 2
        scroll.add(self.listbox)
        for theme in self.themes:
            self.add_theme_row(theme)

        self.listbox2 = Gtk.ListBox()
        self.listbox2.set_selection_mode(Gtk.SelectionMode.SINGLE)
        self.listbox2.set_activate_on_single_click(False)

        # Need to create combo for page 3 now
        self.buttons_combo = Gtk.ComboBoxText()
        # Notebook page 2
        scroll = Gtk.ScrolledWindow()
        scroll.set_min_content_width(500)
        scroll.set_min_content_height(380)
        scroll.add(self.listbox2)
        self.book.append_page(scroll, Gtk.Label(label='Buttons'))

        count, ii = 0, 0
        for button in self.buttons:
            self.buttons_combo.append_text(button.title())
            if button == current_buttons:
                ii = count
            self.add_button_set(button)
            count += 1

        # Notebook page 3
        scroll = Gtk.ScrolledWindow()
        scroll.set_min_content_width(500)
        scroll.set_min_content_height(380)

        self.button_image1, self.button_image2, self.button_image3 = Gtk.Image(), Gtk.Image(), Gtk.Image()
        self.button_image4, self.button_image5, self.button_image6 = Gtk.Image(), Gtk.Image(), Gtk.Image()
        self.book.append_page(scroll, Gtk.Label(label='Recolor'))
        page3 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
        page3.set_border_width(20)
        scroll.add(page3)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        page3.pack_start(row, False, False, 0)
        label = Gtk.Label()
        label.set_markup('<big><b>Create a Modified Button Set</b></big>')
        row.pack_start(label, True, True, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        page3.pack_start(row, False, False, 0)
        box.pack_start(Gtk.Label(label='Based on'), False, False, 0)
        box.pack_start(self.buttons_combo, True, True, 0)
        row.pack_start(box, True, True, 40)

        self.color_column = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        page3.pack_start(self.color_column, True, True, 0)
        self.buttons_combo.connect("changed", self.button_combo_changed)
        self.buttons_combo.set_active(ii)
        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        page3.pack_start(row, True, True, 0)
        row.pack_start(self.button_image6, True, True, 0)
        row.pack_start(self.button_image5, True, True, 0)
        row.pack_start(self.button_image4, True, True, 0)
        row.pack_start(self.button_image3, True, True, 0)
        row.pack_start(self.button_image2, True, True, 0)
        row.pack_start(self.button_image1, True, True, 0)

        self.color_status = Gtk.Label()
        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        page3.pack_start(row, True, True, 0)
        row.pack_start(self.color_status, True, True, 0)

        apply_button.set_property("width-request", 120)
        apply_button.set_always_show_image(True)
        apply_button.connect("clicked", self.apply_theme)

        view_button.set_property("width-request", 120)

        close_button = Gtk.Button(label="Close", image=Gtk.Image(stock=Gtk.STOCK_CANCEL))
        close_button.connect("clicked", Gtk.main_quit)
        close_button.set_property("width-request", 120)
        close_button.set_always_show_image(True)
        about_button = Gtk.Button(image=Gtk.Image(stock=Gtk.STOCK_ABOUT))
        about_button.set_tooltip_text('About')
        about_button.connect('clicked', jwmkit_utils.get_about, self)
        about_button.set_always_show_image(True)
        buttons_switch = Gtk.Switch()
        buttons_switch.set_tooltip_text('OFF : Default buttons\n ON : Enable custom button icons')
        buttons_switch.set_active(True)
        buttons_switch.set_no_show_all(True)
        buttons_switch.connect("notify::active", self.toggle_buttons)
        self.book.connect("switch-page", page_switch, buttons_switch, apply_button)
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        main_box.pack_end(box, False, False, 0)
        box.pack_start(about_button, False, False, 0)
        box.pack_start(view_button, False, False, 0)
        box.pack_start(self.view_combo, False, False, 0)
        box.pack_end(close_button, False, False, 0)
        box.pack_end(apply_button, False, False, 0)
        box.pack_end(buttons_switch, False, False, 0)
        self.listbox.select_row(self.listbox.get_row_at_index(i))
        self.listbox2.select_row(self.listbox2.get_row_at_index(ii))
        if current_buttons == '':
            buttons_switch.set_active(False)

    def update_preview(self):
        colors = self.get_view_colors()
        jwmkit_utils.create_preview(colors, '/tmp/view.svg')
        try:
            pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/tmp/view.svg', 500, 380, preserve_aspect_ratio=True)
        except gi.repository.GLib.Error:
            pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/usr/share/pixmaps/jwmkit/transparent.png', -1, -1,
                                                         preserve_aspect_ratio=True)
        self.preview.set_from_pixbuf(pb)

    def preview_style_change(self, combo):
        self.update_preview()

    def view_switch(self, button):
        vis = self.view.get_visible()
        self.view.set_visible(not vis)
        self.preview.set_visible(not vis)
        self.book2.set_visible(vis)
        if not vis:
            self.update_preview()

    def design_switch(self, button, g, label, a_button, view_button):
        # Toggle content of the main frame between switcher mode and design mode
        vis = self.book.get_visible()
        self.book.set_visible(not vis)
        self.view.set_visible(False)
        self.book2.set_visible(vis)
        self.theme_combo.set_visible(vis)
        self.theme_label.set_visible(vis)
        self.clear_button.set_visible(vis)
        view_button.set_visible(vis)
        self.view_combo.set_visible(vis)
        self.view_combo.connect("changed", self.preview_style_change)
        for grid in g:
            grid.set_visible(vis)
            for gd in grid:
                gd.set_visible(vis)
        if vis:
            a_button.set_label('Save  ')
            label.set_markup('<big><b>Theme Designer</b></big>\nCreate &amp; Edit Themes')
        else:
            a_button.set_label('Apply')
            label.set_markup('<big><b>Appearance</b></big>\nThemes &amp; Buttons')

    def add_theme_row(self, theme):
        row = Gtk.ListBoxRow()
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)
        row.add(box)
        self.listbox.add(row)
        preview_tray = jwmkit_utils.create_image(os.path.join(self.theme_directory, theme[1]), 148, 36, False)
        preview_win = jwmkit_utils.create_image(os.path.join(self.theme_directory, theme[2]), 119, 36, False)
        preview_active = jwmkit_utils.create_image(os.path.join(self.theme_directory, theme[3]), 119, 36, False)
        label = Gtk.Label(label=theme[0][:-6].replace('-', ' ').replace('.', ' ').title())
        box.pack_end(Gtk.Label(), False, False, 0)
        box.pack_end(preview_tray, False, False, 0)
        box.pack_end(preview_win, False, False, 0)
        box.pack_end(preview_active, False, False, 0)
        box.pack_end(label, False, False, 0)

    def get_theme(self):

        def fix_theme_config(output):
            if output:
                if output.startswith(self.home):
                    output = '$HOME{}'.format(output[len(self.home):])
                output = '<JWM>\n  <Include>{}</Include>\n</JWM>'.format(output)
            else:
                output = '<JWM></JWM>'
            with open(self.theme_config, "w+") as f:
                f.write(output)
        try:
            tree = ET.parse(self.theme_config)
            root = tree.getroot()
            node = root[0]
            if node.tag == "Include":
                theme = node.text
            else:
                theme = None
                print('Incorrect structure for the theme config')
                if os.path.islink(self.theme_config):
                    print('File will be overwritten')
                    os.remove(self.theme_config)
                    fix_theme_config(None)
                elif jwmkit_utils.theme_test(self.theme_config) == 'theme':
                    print('File is an jwm theme file and will be moved to the themes folder.')
                    # create themes folder if it does not exist
                    theme_path = '{}/.config/jwm/themes/'.format(self.home)
                    if not os.path.exists(theme_path):
                        os.makedirs(theme_path)
                    filename = 'orginal_default_bk.theme'
                    i = 0
                    while os.path.exists('{}{}'.format(theme_path, filename)):
                        filename = 'orginal_default_bk{}.theme'.format(i)
                        i += 1
                    # copy file to themes folder
                    copy2(self.theme_config, '{}{}'.format(theme_path, filename))
                    # write theme config
                    fix_theme_config('{}{}'.format(theme_path, filename))
                else:
                    print('File will be overwritten')
                    fix_theme_config(None)
        except (ET.ParseError, FileNotFoundError):
            print('error')
            # '<b>Set_Theme config is missing or corrupt</b>\n Save function will create a new file'
            theme = None

        return theme

    def confirm_save(self, type):
        def entry_change(entry):
            warn_label.set_text('')

        def confirm_cancel(button):
            dialog.destroy()

        def confirm_overwrite(check):
            if check.get_active():
                entry.set_sensitive(False)
            else:
                entry.set_sensitive(True)

        def do_save(button):
            if overwrite_check.get_active():
                if type == 'Button Set':
                    fn = self.buttons_combo.get_active()
                    fn = self.buttons[fn]
                else:
                    fn = self.theme_combo.get_active()
                    fn = self.themes[fn][0]
            else:
                fn = entry.get_text()
                try:
                    if not fn[0].isalnum():
                        return
                except IndexError:
                    return
                if type == 'Button Set':
                    if fn in self.buttons:
                        warn_label.set_text('File exist! Try Again')
                        return

                if type == 'Theme' and fn[-6:] not in ('.theme', '.jwmrc', '-theme', '-jwmrc'):
                    fn = '{}.theme'.format(fn)
                    if os.path.exists('{}/.config/jwm/themes/{}'.format(self.home, fn)):
                        warn_label.set_text('File exist! Try Again')
                        return

            if type == 'Button Set':
                path = '{}/.config/jwm/themes/buttons/'.format(self.home)
                tmp_dir = self.buttons[self.buttons_combo.get_active()]
                full_tmp = '/tmp/button_set/{}'.format(tmp_dir)
                if overwrite_check.get_active():
                    subprocess.run(['cp', '-r', full_tmp, path])
                else:
                    subprocess.run(['mv', full_tmp, '/tmp/button_set/{}'.format(fn)])
                    subprocess.run(['cp', '-r', '/tmp/button_set/{}'.format(fn), path])
                    self.buttons.append(fn)
                    self.add_button_set(fn)
                    self.buttons_combo.append_text(fn.title())
                    self.listbox2.show_all()
                    self.buttons_combo.set_active(len(self.buttons) - 1)
            else:
                self.write_theme(fn, overwrite_check.get_active())

            dialog.destroy()

        dialog = Gtk.Dialog('Save {}'.format(type), self, 0)
        # dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK, Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
        dialog.set_default_size(320, -1)
        box = dialog.get_content_area()
        box.set_border_width(20)
        box.set_spacing(10)
        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        box.add(row)
        row.add(Gtk.Label())
        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        box.add(row)
        entry = Gtk.Entry()
        entry.connect("changed", entry_change)
        row.pack_end(entry, True, True, 0)
        row.pack_end(Gtk.Label(label='Filename'), False, False, 0)
        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        box.add(row)

        save_button = Gtk.Button(label='Save', image=Gtk.Image(stock=Gtk.STOCK_SAVE))
        save_button.set_property("width-request", 90)
        save_button.set_always_show_image(True)
        save_button.connect("clicked", do_save)
        entry.connect("activate", do_save)

        cancel_button = Gtk.Button(label='Cancel', image=Gtk.Image(stock=Gtk.STOCK_CANCEL))
        cancel_button.set_property("width-request", 90)
        cancel_button.set_always_show_image(True)
        cancel_button.connect("clicked", confirm_cancel)

        overwrite_check = Gtk.CheckButton(label="Overwrite")
        overwrite_check.connect("toggled", confirm_overwrite)

        warn_label = Gtk.Label(label='')
        row.pack_start(warn_label, False, False, 0)
        if type == 'Theme':
            if self.theme_combo.get_active() != -1:
                row.pack_end(overwrite_check, False, False, 0)
        else:
            row.pack_end(overwrite_check, False, False, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
        box.add(row)
        row.pack_end(cancel_button, False, False, 0)
        row.pack_end(save_button, False, False, 0)
        dialog.show_all()
        dialog.run()

    # Functions specific to Switch mode
    def clear_status(self, entry):
        self.color_status.set_markup('')

    def add_button_set(self, button):
        label = Gtk.Label(label=button.title())
        row = Gtk.ListBoxRow()
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)
        row.add(box)
        self.listbox2.add(row)
        path = os.path.join(self.home, '.config/jwm/themes/buttons/', button)
        missing = '/usr/share/pixmaps/jwmkit/transparent.png'
        button_names = ('close', 'max', 'maxact', 'min', 'default', 'menu')
        box.pack_end(Gtk.Label(), False, False, 0)
        for name in button_names:
            name1 = os.path.join(path, '{}.svg'.format(name))
            name2 = os.path.join(path, '{}.png'.format(name))
            if os.path.isfile(name1):
                image = jwmkit_utils.create_image(name1, 32, 32, False)
            elif os.path.isfile(name2):
                image = jwmkit_utils.create_image(name2, 32, 32, False)
            else:
                image = jwmkit_utils.create_image(missing, 32, 32, False)
            box.pack_end(image, False, False, 0)
        box.pack_end(label, False, False, 0)

    def get_path(self):
        # Find the Set_Theme config
        settings = self.home + '/.config/jwmkit/settings'
        path_ok = False
        if os.path.isfile(settings):
            with open(settings) as f:
                f = f.read()
            f = '\n{}'.format(f)
            try:
                path = re.findall('\ntheme.*=(.+)', f)[0]
                if path.startswith('$HOME'):
                    path = self.home + path[5:]
                path_ok = True
            except IndexError:
                path_ok = False
            try:
                buttons = re.findall('\nbuttons.*=(.+)', f)[0]
            except IndexError:
                buttons = ''
        if not path_ok:
            return 'warning_settings'
        return path, os.path.basename(buttons)

    def button_combo_changed(self, combo):
        clear_tmp()
        current_buttons = self.buttons[combo.get_active()]
        path = os.path.join(self.home, '.config/jwm/themes/buttons/', current_buttons)
        missing = '/usr/share/pixmaps/jwmkit/transparent.png'
        button_names = ('close', 'max', 'maxact', 'min', 'default', 'menu')

        images = (self.button_image1, self.button_image2, self.button_image3, self.button_image4,
                  self.button_image5, self.button_image6)
        for name, image in zip(button_names, images):
            name1 = os.path.join(path, '{}.svg'.format(name))
            name2 = os.path.join(path, '{}.png'.format(name))
            if os.path.isfile(name1):
                pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(name1, 32, 32, preserve_aspect_ratio=False)
            elif os.path.isfile(name2):
                pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(name2, 32, 32, preserve_aspect_ratio=False)
            else:
                pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(missing, 32, 32, preserve_aspect_ratio=False)
            image.set_from_pixbuf(pb)
        for row in self.color_column.get_children():
            self.color_column.remove(row)

        color_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        self.color_column.add(color_row)
        self.colors = get_button_colors(current_buttons)
        count, index = 0, 0
        split_count = (int(len(self.colors) / 8) + 1)
        split_count = int(len(self.colors) / split_count)
        for color in self.colors:
            if count == split_count:
                count = 0
                color_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
                self.color_column.add(color_row)
            count += 1
            color_button = Gtk.ColorButton()
            color_button.set_tooltip_text('Change this color')
            color_button.connect('color-set', self.on_color_set, index)
            color_button.set_rgba(hex_to_rgba(color))
            color_row.pack_start(color_button, True, False, 0)
            index += 1
        if len(self.colors) == 0:
            self.color_column.add(Gtk.Label(label="Color replacement not supported for this button set"))
        self.color_column.show_all()

    def on_color_set(self, button, i, data=None):
        images = (self.button_image1, self.button_image2, self.button_image3, self.button_image4,
                  self.button_image5, self.button_image6)
        current_buttons = self.buttons[self.buttons_combo.get_active()]
        button_dir = '{}/.config/jwm/themes/buttons/{}/'.format(self.home, current_buttons)
        tmp_dir = '/tmp/button_set/'
        tmp_path = '{}{}'.format(tmp_dir, current_buttons)
        if not os.path.isdir(tmp_path):
            os.makedirs(tmp_path)
            subprocess.run(['cp', '-r', button_dir, tmp_dir])

        color = button.get_rgba()
        color = '#{}'.format(rgba_to_hex(color))
        old_color = self.colors[i]
        self.colors[i] = color
        names = ('close.svg', 'max.svg', 'maxact.svg', 'min.svg', 'default.svg', 'menu.svg')
        for name, image in zip(names, images):
            name = '{}/{}'.format(tmp_path, name)
            if os.path.isfile(name):
                with open(name) as f:
                    data = f.read()
            else:
                continue
            data = re.sub(r'(?i){}'.format(old_color), color, data)
            with open(name, 'w') as f:
                f.write(data)
            pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(name, 32, 32, preserve_aspect_ratio=False)
            image.set_from_pixbuf(pb)

    def toggle_buttons(self, buttons_switch, i):
        if buttons_switch.get_active():
            self.listbox2.set_sensitive(True)
        else:
            self.listbox2.set_sensitive(False)

    def get_buttons(self):
        buttons = []
        path = os.path.join(self.home, '.config/jwm/themes/buttons/')
        if not os.path.isdir(path):
            os.makedirs(path)
        directories = [dir for dir in os.listdir(path) if os.path.isdir(os.path.join(path, dir))]
        directories = sorted(directories, key=str.casefold)
        button_names = ('close.svg', 'max.svg', 'maxact.svg', 'min.svg', 'default.svg', 'menu.svg',
                        'close.png', 'max.png', 'maxact.png', 'min.png', 'default.png', 'menu.png')
        for button in directories:
            contents = os.listdir(os.path.join(path, button))
            if set(button_names).intersection(contents):
                buttons.append(button)
        return buttons

    def apply_theme(self, button):
        if not self.book.get_visible():
            self.confirm_save('Theme')
            return
        page = self.book.get_current_page()
        if page == 0:
            row = self.listbox.get_selected_row()
            index = row.get_index()
            select_theme = os.path.join(self.theme_directory, self.themes[index][0])
            if select_theme.startswith(self.home):
                select_theme = '{}{}'.format('$HOME', select_theme[len(self.home):])
            root = ET.Element('JWM')
            child = ET.Element("Include")
            child.text = select_theme
            root.append(child)
            tree = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
            tree = os.linesep.join([s for s in tree.splitlines() if s.strip()])
            tree = ET.ElementTree(ET.fromstring(tree))
            tree.write(self.theme_config, encoding="utf-8", xml_declaration=True)
            os.system('jwm -restart')
        elif page == 1:
            if self.listbox2.get_sensitive():
                row = self.listbox2.get_selected_row()
                index = row.get_index()
                select_buttons = self.buttons[index]
                select_buttons = 'buttons=$HOME/.config/jwm/themes/buttons/{}'.format(select_buttons)
            else:
                select_buttons = ''
            with open(os.path.join(self.home, '.config/jwmkit/settings')) as f:
                settings = f.read()
            settings = settings.replace('\n\n', '\n')
            if not settings.endswith('\n'):
                settings = '{}\n'.format(settings)
            removable = re.findall('(buttons=.+\n)', settings)
            for remove in removable:
                settings = settings.replace(remove, '')
            if select_buttons == '':
                settings = '{}{}'.format(settings, select_buttons)
            else:
                settings = '{}{}\n'.format(settings, select_buttons)
            with open(os.path.join(self.home, '.config/jwmkit/settings'), 'w') as f:
                f.write(settings)
            os.system('jwm -restart')
        else:
            self.confirm_save('Button Set')

    # Functions specific to Theme Designer

    def color_activated(self, button):
        if button not in self.active_colors:
            self.active_colors.append(button)

    def w_height_default(self, check):
        if check.get_active():
            self.w_height_spin.set_sensitive(True)
        else:
            self.w_height_spin.set_sensitive(False)

    def write_theme(self, fn, overwrite):

        def font_element(el, font, check, entry):
            if check.get_active():
                font = '{}:antialias=true'.format(font)
            if entry.get_text():
                font = '{}:encoding={}'.format(font, entry.get_text())
            return font

        def remove_unused():
            if len(a_sub) < 1:
                element.remove(a_sub)
            if len(element) < 1 and len(element.attrib) < 1:
                root.remove(element)

        root = ET.Element('JWM')

        # WindowStyle
        element = ET.SubElement(root, 'WindowStyle')
        if self.w_decorations_combo.get_active() == 1:
            element.attrib['decorations'] = 'motif'
        font = self.w_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.w_antialias_check, self.w_encoding_entry)
            if self.w_align_combo.get_active() not in (-1, 0):
                values = ('center', 'right')
                sub.attrib['align'] = values[self.w_align_combo.get_active() - 1]

        if self.w_height_check.get_active():
            value = self.w_height_spin.get_value()
            sub = ET.SubElement(element, 'Height')
            sub.text = str(int(value))
        value = self.w_width_spin.get_value()
        if value != 4:
            sub = ET.SubElement(element, 'Width')
            sub.text = str(int(value))
        value = self.w_corner_spin.get_value()
        if value != 4:
            sub = ET.SubElement(element, 'Corner')
            sub.text = str(int(value))
        if self.w_opacity_check1.get_active():
            value = self.w_i_opacity_spin.get_value()
            sub = ET.SubElement(element, 'Opacity')
            sub.text = str(value)
        if self.w_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.w_color_inactive_foreground.get_rgba()))
        if self.w_color_inactive_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.w_color_inactive_outline.get_rgba()))
        color = []
        if self.w_color_inactive_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.w_color_inactive_background1.get_rgba())))
        if self.w_inactive_gradient_check.get_active() and self.w_color_inactive_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.w_color_inactive_background2.get_rgba())))
        if color:
            sub = ET.SubElement(element, 'Background')
            sub.text = ':'.join(color)

        a_sub = ET.SubElement(element, 'Active')
        if self.w_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.w_color_active_foreground.get_rgba()))
        if self.w_color_active_outline in self.active_colors:
            sub = ET.SubElement(a_sub, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.w_color_active_outline.get_rgba()))
        color = []
        if self.w_color_active_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.w_color_active_background1.get_rgba())))
        if self.w_active_gradient_check.get_active() and self.w_color_active_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.w_color_active_background2.get_rgba())))
        if color:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = ':'.join(color)
        if self.w_opacity_check2.get_active():
            value = self.w_a_opacity_spin.get_value()
            sub = ET.SubElement(a_sub, 'Opacity')
            sub.text = str(value)
        remove_unused()

        # TrayStyle
        element = ET.SubElement(root, 'TrayStyle')
        if self.t_decorations_combo.get_active() == 1:
            element.attrib['decorations'] = 'motif'
        # for backward compatibility group and list attributes are added here and TrayListStyle
        if self.tl_group_check.get_active():
            element.attrib['group'] = 'true'
        if self.tl_list_check.get_active():
            element.attrib['list'] = 'all'
        font = self.t_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.t_antialias_check, self.t_encoding_entry)

        if self.t_opacity_check.get_active():
            value = self.t_opacity_spin.get_value()
            sub = ET.SubElement(element, 'Opacity')
            sub.text = str(value)

        if self.t_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.t_color_inactive_foreground.get_rgba()))
        if self.t_color_inactive_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.t_color_inactive_outline.get_rgba()))
        color = []
        if self.t_color_inactive_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.t_color_inactive_background1.get_rgba())))
        if self.t_inactive_gradient_check.get_active() and self.t_color_inactive_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.t_color_inactive_background2.get_rgba())))
        if color:
            sub = ET.SubElement(element, 'Background')
            sub.text = ':'.join(color)

        a_sub = ET.SubElement(element, 'Active')
        if self.t_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.t_color_active_foreground.get_rgba()))
        if self.t_color_active_outline in self.active_colors:
            sub = ET.SubElement(a_sub, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.t_color_active_outline.get_rgba()))
        color = []
        if self.t_color_active_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.t_color_active_background1.get_rgba())))
        if self.t_active_gradient_check.get_active() and self.t_color_active_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.t_color_active_background2.get_rgba())))
        if color:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = ':'.join(color)
        remove_unused()

        # TrayButtonStyle
        element = ET.SubElement(root, 'TrayButtonStyle')
        font = self.tb_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.tb_antialias_check, self.tb_encoding_entry)

        if self.tb_color_if_check.get_active() and self.tb_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.tb_color_inactive_foreground.get_rgba()))
        if self.tb_color_io_check.get_active() and self.tb_color_inactive_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.tb_color_inactive_outline.get_rgba()))
        if self.tb_color_ib_check.get_active():
            color = []
            if self.tb_color_inactive_background1 in self.active_colors:
                color.append('#{}'.format(rgba_to_hex(self.tb_color_inactive_background1.get_rgba())))
            if self.tb_inactive_gradient_check.get_active() and self.tb_color_inactive_background2 in self.active_colors:
                color.append('#{}'.format(rgba_to_hex(self.tb_color_inactive_background2.get_rgba())))
            if color:
                sub = ET.SubElement(element, 'Background')
                sub.text = ':'.join(color)

        a_sub = ET.SubElement(element, 'Active')
        if self.tb_color_af_check.get_active() and self.tb_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.tb_color_active_foreground.get_rgba()))
        if self.tb_color_ao_check.get_active() and self.tb_color_active_outline in self.active_colors:
            sub = ET.SubElement(a_sub, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.tb_color_active_outline.get_rgba()))
        if self.tb_color_ab_check.get_active():
            color = []
            if self.tb_color_active_background1 in self.active_colors:
                color.append('#{}'.format(rgba_to_hex(self.tb_color_active_background1.get_rgba())))
            if self.tb_active_gradient_check.get_active() and self.tb_color_active_background2 in self.active_colors:
                color.append('#{}'.format(rgba_to_hex(self.tb_color_active_background2.get_rgba())))
            if color:
                sub = ET.SubElement(a_sub, 'Background')
                sub.text = ':'.join(color)
        remove_unused()

        # TaskListStyle
        element = ET.SubElement(root, 'TaskListStyle')
        if self.tl_decorations_combo.get_active() == 1:
            element.attrib['decorations'] = 'motif'
        if self.tl_group_check.get_active():
            element.attrib['group'] = 'true'
        if self.tl_list_check.get_active():
            element.attrib['list'] = 'all'
        font = self.tl_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.tl_antialias_check, self.tl_encoding_entry)
        if self.tl_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.tl_color_inactive_foreground.get_rgba()))
        if self.tl_color_inactive_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.tl_color_inactive_outline.get_rgba()))
        color = []
        if self.tl_color_inactive_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.tl_color_inactive_background1.get_rgba())))
        if self.tl_inactive_gradient_check.get_active() and self.tl_color_inactive_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.tl_color_inactive_background2.get_rgba())))
        if color:
            sub = ET.SubElement(element, 'Background')
            sub.text = ':'.join(color)

        a_sub = ET.SubElement(element, 'Active')
        if self.tl_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.tl_color_active_foreground.get_rgba()))
        if self.tl_color_active_outline in self.active_colors:
            sub = ET.SubElement(a_sub, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.tl_color_active_outline.get_rgba()))
        color = []
        if self.tl_color_active_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.tl_color_active_background1.get_rgba())))
        if self.tl_active_gradient_check.get_active() and self.tl_color_active_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.tl_color_active_background2.get_rgba())))
        if color:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = ':'.join(color)
        remove_unused()

        # MenuStyle
        element = ET.SubElement(root, 'MenuStyle')
        font = self.m_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.m_antialias_check, self.m_encoding_entry)
        if self.m_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.m_color_inactive_foreground.get_rgba()))
        if self.m_color_inactive_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.m_color_inactive_outline.get_rgba()))
        if self.m_color_inactive_background in self.active_colors:
            sub = ET.SubElement(element, 'Background')
            sub.text = '#{}'.format(rgba_to_hex(self.m_color_inactive_background.get_rgba()))
        if self.m_opacity_check.get_active():
            value = self.m_opacity_spin.get_value()
            sub = ET.SubElement(element, 'Opacity')
            sub.text = str(value)

        a_sub = ET.SubElement(element, 'Active')
        if self.m_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.m_color_active_foreground.get_rgba()))
        if self.m_color_active_outline in self.active_colors:
            sub = ET.SubElement(a_sub, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.m_color_active_outline.get_rgba()))
        color = []
        if self.m_color_active_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.m_color_active_background1.get_rgba())))
        if self.m_active_gradient_check.get_active() and self.m_color_active_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.m_color_active_background2.get_rgba())))
        if color:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = ':'.join(color)
        remove_unused()

        # PagerStyle
        element = ET.SubElement(root, 'PagerStyle')
        font = self.p_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.p_antialias_check, self.p_encoding_entry)
        if self.p_color_inactive_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_inactive_foreground.get_rgba()))
        if self.p_color_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_outline.get_rgba()))
        if self.p_color_text in self.active_colors:
            sub = ET.SubElement(element, 'Text')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_text.get_rgba()))
        if self.p_color_inactive_background in self.active_colors:
            sub = ET.SubElement(element, 'Background')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_inactive_background.get_rgba()))
        a_sub = ET.SubElement(element, 'Active')
        if self.p_color_active_foreground in self.active_colors:
            sub = ET.SubElement(a_sub, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_active_foreground.get_rgba()))
        if self.p_color_active_background in self.active_colors:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = '#{}'.format(rgba_to_hex(self.p_color_active_background.get_rgba()))
        remove_unused()

        # ClockStyle
        element = ET.SubElement(root, 'ClockStyle')
        font = self.cl_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.cl_antialias_check, self.cl_encoding_entry)
        if self.cl_color_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.cl_color_foreground.get_rgba()))
        color = []
        if self.cl_color_background1 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.cl_color_background1.get_rgba())))
        if self.cl_active_gradient_check.get_active() and self.cl_color_background2 in self.active_colors:
            color.append('#{}'.format(rgba_to_hex(self.cl_color_background2.get_rgba())))
        if color:
            sub = ET.SubElement(a_sub, 'Background')
            sub.text = ':'.join(color)
        if len(element) < 1:
            root.remove(element)

        # PopupStyle
        element = ET.SubElement(root, 'PopupStyle')
        value = str(int(self.pop_delay_spin.get_value()))
        if value != '600':
            element.attrib['delay'] = value
        font = self.pop_font_entry.get_text()
        if font:
            sub = ET.SubElement(element, 'Font')
            sub.text = font_element(sub, font, self.pop_antialias_check, self.pop_encoding_entry)
        if self.pop_color_foreground in self.active_colors:
            sub = ET.SubElement(element, 'Foreground')
            sub.text = '#{}'.format(rgba_to_hex(self.pop_color_foreground.get_rgba()))
        if self.pop_color_outline in self.active_colors:
            sub = ET.SubElement(element, 'Outline')
            sub.text = '#{}'.format(rgba_to_hex(self.pop_color_outline.get_rgba()))
        if self.pop_color_background in self.active_colors:
            sub = ET.SubElement(element, 'Background')
            sub.text = '#{}'.format(rgba_to_hex(self.pop_color_background.get_rgba()))
        if self.pop_none_check.get_active():
            element.attrib['enabled'] = 'false'
        elif not self.pop_all_check.get_active():
            values = []
            if self.pop_buttons_check.get_active():
                values.append('button')
            if self.pop_clock_check.get_active():
                values.append('clock')
            if self.pop_menu_check.get_active():
                values.append('menu')
            if self.pop_pagers_check.get_active():
                values.append('pager')
            if self.pop_task_check.get_active():
                values.append('task')
            if values:
                element.attrib['enabled'] = ','.join(values)
        if len(element) < 1 and len(element.attrib) < 1:
            root.remove(element)

        xml = b'\n'.join([s.strip() for s in ET.tostring(root).splitlines() if s.strip()])
        xml = minidom.parseString(xml).toprettyxml(newl='\n', indent='   ')
        xml = ET.ElementTree(ET.fromstring(xml))
        xml.write('{}/.config/jwm/themes/{}'.format(self.home, fn), encoding="utf-8", xml_declaration=True)

        # add new theme to widgets
        if not overwrite:
            self.theme_combo.append_text(fn)
            styles = get_styles(fn)
            theme = [fn, create_previews(styles, 2, 'tray', fn), create_previews(styles, 0, 'window', fn),
                     create_previews(styles, 1, 'active', fn)]
            self.themes.append(theme)
            self.add_theme_row(theme)
            self.theme_combo.set_active(len(self.themes)-1)
            self.listbox.show_all()

    def on_font_choice(self, button, entry):
        font_dialog = Gtk.FontChooserDialog(title="Select a file", parent=self)
        font_dialog.set_default_size(640, 0)
        font_selected = font_dialog.run()
        styles = ["Normal", "Roman", "Oblique", "Italic", "Small-Caps", "Thin", "Ultra-Light", "Extra-Light", "Light",
                  "Semi-Light", "Demi-Light", "Book", "Regular", "Medium", "Semi-Bold", "Demi-Bold", "Bold",
                  "Ultra-Bold", "Extra-Bold", "Heavy", "Black", "Ultra-Black", "Extra-Black", "Ultra-Condensed",
                  "Extra-Condensed", "Condensed", "Semi-Condensed", "Semi-Expanded", "Expanded", "Extra-Expanded",
                  "Ultra-Expanded", "Not-Rotated", "South", "Upside-Down", "North", "Rotated-Left", "East",
                  "Rotated-Right", "West"]
        temp_styles = ''
        if font_selected == Gtk.ResponseType.OK:
            font_size = int(font_dialog.get_font_size() / 1024)
            font_selected = font_dialog.get_font()
            for style in styles:
                if style in font_selected.split(' '):
                    temp_styles += ':' + style
                    font_selected = font_selected.replace(' ' + style, '')
            font_selected = font_selected.replace(' ' + str(font_size), '')
            font_selected = font_selected + '-' + str(font_size) + temp_styles
            entry.set_text(font_selected)

        font_dialog.destroy()

    def pop_disabled_checks(self, check):
        if check.get_active():
            self.pop_buttons_check.set_sensitive(False)
            self.pop_clock_check.set_sensitive(False)
            self.pop_menu_check.set_sensitive(False)
            self.pop_task_check.set_sensitive(False)
            self.pop_pagers_check.set_sensitive(False)
            self.pop_all_check.set_sensitive(False)
            self.pop_none_check.set_sensitive(False)
        else:
            self.pop_buttons_check.set_sensitive(True)
            self.pop_clock_check.set_sensitive(True)
            self.pop_menu_check.set_sensitive(True)
            self.pop_task_check.set_sensitive(True)
            self.pop_pagers_check.set_sensitive(True)
            self.pop_all_check.set_sensitive(True)
            self.pop_none_check.set_sensitive(True)
        check.set_sensitive(True)

    def clear_action(self, button):
        self.theme_combo.set_active(-1)
        self.clear_widgets()
        if self.view.get_visible():
            self.update_preview()

    def clear_widgets(self):
        self.active_colors = []
        # clear widgets
        self.w_align_combo.set_active(-1)
        self.w_color_active_foreground.set_rgba(self.default_color)
        self.w_color_active_background1.set_rgba(self.default_color)
        self.w_color_active_background2.set_rgba(self.default_color)
        self.w_color_active_outline.set_rgba(self.default_color)
        self.w_color_inactive_foreground.set_rgba(self.default_color)
        self.w_color_inactive_background1.set_rgba(self.default_color)
        self.w_color_inactive_background2.set_rgba(self.default_color)
        self.w_color_inactive_outline.set_rgba(self.default_color)
        self.t_color_active_foreground.set_rgba(self.default_color)
        self.t_color_active_background1.set_rgba(self.default_color)
        self.t_color_active_background2.set_rgba(self.default_color)
        self.t_color_active_outline.set_rgba(self.default_color)
        self.t_color_inactive_foreground.set_rgba(self.default_color)
        self.t_color_inactive_background1.set_rgba(self.default_color)
        self.t_color_inactive_background2.set_rgba(self.default_color)
        self.t_color_inactive_outline.set_rgba(self.default_color)
        self.tb_color_active_foreground.set_rgba(self.default_color)
        self.tb_color_active_background1.set_rgba(self.default_color)
        self.tb_color_active_background2.set_rgba(self.default_color)
        self.tb_color_active_outline.set_rgba(self.default_color)
        self.tb_color_inactive_foreground.set_rgba(self.default_color)
        self.tb_color_inactive_background1.set_rgba(self.default_color)
        self.tb_color_inactive_background2.set_rgba(self.default_color)
        self.tb_color_inactive_outline.set_rgba(self.default_color)
        self.tl_color_active_foreground.set_rgba(self.default_color)
        self.tl_color_active_background1.set_rgba(self.default_color)
        self.tl_color_active_background2.set_rgba(self.default_color)
        self.tl_color_active_outline.set_rgba(self.default_color)
        self.tl_color_inactive_foreground.set_rgba(self.default_color)
        self.tl_color_inactive_background1.set_rgba(self.default_color)
        self.tl_color_inactive_background2.set_rgba(self.default_color)
        self.tl_color_inactive_outline.set_rgba(self.default_color)
        self.m_color_active_foreground.set_rgba(self.default_color)
        self.m_color_active_background1.set_rgba(self.default_color)
        self.m_color_active_background2.set_rgba(self.default_color)
        self.m_color_active_outline.set_rgba(self.default_color)
        self.m_color_inactive_foreground.set_rgba(self.default_color)
        self.m_color_inactive_background.set_rgba(self.default_color)
        self.m_color_inactive_outline.set_rgba(self.default_color)
        self.p_color_active_foreground.set_rgba(self.default_color)
        self.p_color_active_background.set_rgba(self.default_color)
        self.p_color_outline.set_rgba(self.default_color)
        self.p_color_inactive_foreground.set_rgba(self.default_color)
        self.p_color_inactive_background.set_rgba(self.default_color)
        self.p_color_text.set_rgba(self.default_color)
        self.pop_color_foreground.set_rgba(self.default_color)
        self.pop_color_background.set_rgba(self.default_color)
        self.pop_color_outline.set_rgba(self.default_color)
        self.cl_color_foreground.set_rgba(self.default_color)
        self.cl_color_background1.set_rgba(self.default_color)
        self.cl_color_background2.set_rgba(self.default_color)

        self.w_decorations_combo.set_active(-1)
        self.w_font_entry.set_text('')
        self.w_encoding_entry.set_text('')
        self.w_antialias_check.set_active(False)
        self.w_opacity_check1.set_active(False)
        self.w_opacity_check2.set_active(False)
        self.w_inactive_gradient_check.set_active(True)
        self.w_active_gradient_check.set_active(True)
        self.w_width_spin.set_value(4)
        self.w_height_spin.set_value(0)
        self.w_height_check.set_active(False)
        self.w_height_spin.set_sensitive(False)
        self.w_corner_spin.set_value(4)
        self.w_i_opacity_spin.set_value(1)
        self.w_a_opacity_spin.set_value(1)
        self.t_decorations_combo.set_active(-1)
        self.t_font_entry.set_text('')
        self.t_encoding_entry.set_text('')
        self.t_antialias_check.set_active(False)
        self.t_opacity_check.set_active(False)
        self.t_inactive_gradient_check.set_active(True)
        self.t_active_gradient_check.set_active(True)
        self.t_opacity_spin.set_value(1)
        self.tl_list_check.set_active(False)
        self.tl_group_check.set_active(False)
        self.tb_font_entry.set_text('')
        self.tb_encoding_entry.set_text('')
        self.tb_antialias_check.set_active(False)
        self.tb_color_af_check.set_active(False)
        self.tb_color_ab_check.set_active(False)
        self.tb_color_ao_check.set_active(False)
        self.tb_color_if_check.set_active(False)
        self.tb_color_ib_check.set_active(False)
        self.tb_color_io_check.set_active(False)
        self.tb_inactive_gradient_check.set_active(True)
        self.tb_active_gradient_check.set_active(True)
        self.tl_decorations_combo.set_active(-1)
        self.tl_font_entry.set_text('')
        self.tl_encoding_entry.set_text('')
        self.tl_inactive_gradient_check.set_active(True)
        self.tl_active_gradient_check.set_active(True)
        self.tl_color_af_check.set_active(False)
        self.tl_color_ab_check.set_active(False)
        self.tl_color_ao_check.set_active(False)
        self.tl_color_if_check.set_active(False)
        self.tl_color_ib_check.set_active(False)
        self.tl_color_io_check.set_active(False)
        self.tl_inactive_gradient_check.set_active(True)
        self.tl_active_gradient_check.set_active(True)
        self.tl_antialias_check.set_active(False)
        self.m_font_entry.set_text('')
        self.m_encoding_entry.set_text('')
        self.m_decorations_combo.set_active(-1)
        self.m_opacity_spin.set_sensitive(False)
        self.m_opacity_check.set_active(False)
        self.m_antialias_check.set_active(False)
        self.p_font_entry.set_text('')
        self.p_encoding_entry.set_text('')
        self.p_antialias_check.set_active(False)
        self.pop_delay_spin.set_value(600)
        self.pop_font_entry.set_text('')
        self.pop_encoding_entry.set_text('')
        self.pop_antialias_check.set_active(False)
        self.pop_all_check.set_active(False)
        self.pop_buttons_check.set_active(False)
        self.pop_clock_check.set_active(False)
        self.pop_menu_check.set_active(False)
        self.pop_task_check.set_active(False)
        self.pop_pagers_check.set_active(False)
        self.pop_none_check.set_active(False)
        self.cl_font_entry.set_text('')
        self.cl_encoding_entry.set_text('')
        self.cl_antialias_check.set_active(False)
        self.cl_foreground_check.set_active(False)
        self.cl_background_check.set_active(False)
        self.cl_active_gradient_check.set_active(False)

    def get_view_colors(self):
        widgets = (self.w_color_active_foreground, self.w_color_active_background1, self.w_color_active_background2,
                   self.w_color_active_outline, self.w_color_inactive_foreground, self.w_color_inactive_background1,
                   self.w_color_inactive_background2, self.w_color_inactive_outline, self.t_color_active_foreground,
                   self.t_color_active_background1, self.t_color_active_background2, self.t_color_active_outline,
                   self.t_color_inactive_foreground, self.t_color_inactive_background1,
                   self.t_color_inactive_background2, self.t_color_inactive_outline, self.tb_color_active_foreground,
                   self.tb_color_active_background1, self.tb_color_active_background2, self.tb_color_active_outline,
                   self.tb_color_inactive_foreground, self.tb_color_inactive_background1,
                   self.tb_color_inactive_background2, self.tb_color_inactive_outline, self.tl_color_active_foreground,
                   self.tl_color_active_background1, self.tl_color_active_background2, self.tl_color_active_outline,
                   self.tl_color_inactive_foreground, self.tl_color_inactive_background1,
                   self.tl_color_inactive_background2, self.tl_color_inactive_outline, self.m_color_active_foreground,
                   self.m_color_active_background1, self.m_color_active_background2, self.m_color_active_outline,
                   self.m_color_inactive_foreground, self.m_color_inactive_background, self.m_color_inactive_outline,
                   self.p_color_active_foreground,  self.p_color_active_background, self.p_color_inactive_foreground,
                   self.p_color_outline, self.p_color_inactive_background, self.p_color_text,
                   self.cl_color_foreground, self.cl_color_background1, self.cl_color_background2,
                   self.pop_color_foreground, self.pop_color_background, self.pop_color_outline)
        win_colors = ('#343434', '#2d3234', '#CECECE', '#CECECE')
        bg_colors = ('#2d3234', '#343434', '#355777', '#7D8287')
        sel = self.view_combo.get_active()
        colors = [win_colors[sel]]
        merge = (3, 7, 11, 15, 19, 23, 27, 31, 35, 48)
        ii = 1
        for i, w in enumerate(widgets):
            if w in self.active_colors:
                value = '#{}'.format(rgba_to_hex(w.get_rgba()))
            else:
                value = ''
            if i + 1 in merge:

                if '' not in (colors[ii-1], value):
                    colors[ii-1] = '{}:{}'.format(colors[ii-1], value)
            else:
                ii += 1
                colors.append(value)
        corn = int(self.w_corner_spin.get_value())
        if corn == '': corn = 4
        colors.append(corn)
        colors.append(bg_colors[sel])
        return colors

    def theme_changed(self, combo):

        def process_font(el, entry1, entry2, check):
            entry_data = ''
            data = el.text.split(':')
            for font_data in data:
                if 'encoding=' in font_data:
                    entry2.set_text(font_data[9:])
                elif font_data == 'antialias=true':
                    check.set_active(True)
                elif font_data == 'antialias=false':
                    check.set_active(False)
                else:
                    entry_data = '{}{}:'.format(entry_data, font_data)
            entry1.set_text(entry_data[:-1])

        def process_gradient(el, check1, check2, button1, button2):
            data = el.text.split(':')
            self.active_colors.append(button1)
            if check2 != '':
                check2.set_active(True)
            button1.set_rgba(hex_to_rgba(data[0]))
            if len(data) > 1:
                check1.set_active(True)
                button2.set_rgba(hex_to_rgba(data[1]))
                self.active_colors.append(button2)
            else:
                check1.set_active(False)

        def process_color(el, check, button):
            if check != '':
                check.set_active(True)
            self.active_colors.append(button)
            button.set_rgba(hex_to_rgba(el.text))

        def process_spin(el, check, spin, opacity):
            try:
                if opacity:
                    value = float(el.text)
                else:
                    value = int(el.text)
            except (TypeError, ValueError):
                if check != '':
                    spin.set_sensitive(False)
                return
            spin.set_value(value)
            if check != '':
                check.set_active(True)
                spin.set_sensitive(True)

        def process_decoration(data, combo):
            if data == 'motif':
                combo.set_active(1)
            elif data == 'flat':
                combo.set_active(0)

        def process_align(data, combo):
            if data == 'center':
                combo.set_active(1)
            elif data == 'right':
                combo.set_active(2)
            else:
                combo.set_active(0)

        i = combo.get_active()
        selection = '{}/.config/jwm/themes/{}'.format(self.home, self.themes[i][0])
        self.clear_widgets()

        tree = ET.parse(selection)
        root = tree.getroot()
        for node in root:
            s_type = node.tag
            if s_type == 'WindowStyle':
                process_decoration(node.get('decorations'), self.w_decorations_combo)
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_align(sub.get('align'), self.w_align_combo)
                        process_font(sub, self.w_font_entry, self.w_encoding_entry, self.w_antialias_check)
                    elif sub_type == 'Width':
                        process_spin(sub,  '', self.w_width_spin, False)
                    elif sub_type == 'Height':
                        process_spin(sub, self.w_height_check, self.w_height_spin, False)
                    elif sub_type == 'Corner':
                        process_spin(sub,  '', self.w_corner_spin, False)
                    elif sub_type == 'Foreground':
                        process_color(sub, '', self.w_color_inactive_foreground)
                    elif sub_type == 'Outline':
                        process_color(sub, '', self.w_color_inactive_outline)
                    elif sub_type == 'Background':
                        process_gradient(sub, self.w_inactive_gradient_check, '', self.w_color_inactive_background1,
                                         self.w_color_inactive_background2)
                    elif sub_type == 'Opacity':
                        process_spin(sub, self.w_opacity_check1, self.w_i_opacity_spin, True)
                    elif sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, '', self.w_color_active_foreground)
                            elif active_type == 'Outline':
                                process_color(active, '', self.w_color_active_outline)
                            elif active_type == 'Background':
                                process_gradient(active, self.w_active_gradient_check, '',
                                                 self.w_color_active_background1, self.w_color_active_background2)
                            elif active_type == 'Opacity':
                                process_spin(active, self.w_opacity_check2, self.w_a_opacity_spin, True)

            elif s_type == 'TrayStyle':
                process_decoration(node.get('decorations'), self.t_decorations_combo)
                # support group/list attributes for older themes
                data = node.get('group')
                if data == 'true':
                    self.tl_group_check.set_active(True)
                elif data == 'false':
                    self.tl_group_check.set_active(False)
                data = node.get('list')
                if data == 'all':
                    self.tl_list_check.set_active(True)
                elif data == ' desktop':
                    self.tl_list_check.set_active(False)
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.t_font_entry, self.t_encoding_entry, self.t_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, '', self.t_color_inactive_foreground)
                    elif sub_type == 'Outline':
                        process_color(sub, '', self.t_color_inactive_outline)
                    elif sub_type == 'Background':
                        process_gradient(sub, self.t_inactive_gradient_check, '',
                                         self.t_color_inactive_background1, self.t_color_inactive_background2)
                    elif sub_type == 'Opacity':
                        process_spin(sub, self.t_opacity_check, self.t_opacity_spin, True)

                    elif sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, '', self.t_color_active_foreground)
                            elif active_type == 'Outline':
                                process_color(active, '', self.t_color_active_outline)
                            elif active_type == 'Background':
                                process_gradient(active, self.t_active_gradient_check, '',
                                                 self.t_color_active_background1, self.t_color_active_background2)

            elif s_type == 'TrayButtonStyle':
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.tb_font_entry, self.tb_encoding_entry, self.tb_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, self.tb_color_if_check, self.tb_color_inactive_foreground)
                    if sub_type == 'Outline':
                        process_color(sub, self.tb_color_io_check, self.tb_color_inactive_outline)
                    if sub_type == 'Background':
                        process_gradient(sub, self.tb_inactive_gradient_check, self.tb_color_ib_check,
                                         self.tb_color_inactive_background1, self.tb_color_inactive_background2)
                    if sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, self.tb_color_af_check, self.tb_color_active_foreground)
                            if active_type == 'Outline':
                                process_color(active, self.tb_color_ao_check, self.tb_color_active_outline)
                            if active_type == 'Background':
                                process_gradient(active, self.tb_active_gradient_check, self.tb_color_ab_check,
                                                 self.tb_color_active_background1, self.tb_color_active_background2)

            elif s_type == 'TaskListStyle':
                process_decoration(node.get('decorations'), self.tl_decorations_combo)
                data = node.get('group')
                if data == 'true':
                    self.tl_group_check.set_active(True)
                elif data == 'false':
                    self.tl_group_check.set_active(False)
                data = node.get('list')
                if data == 'all':
                    self.tl_list_check.set_active(True)
                elif data == ' desktop':
                    self.tl_list_check.set_active(False)
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.tl_font_entry, self.tl_encoding_entry, self.tl_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, self.tl_color_if_check, self.tl_color_inactive_foreground)
                    if sub_type == 'Outline':
                        process_color(sub, self.tl_color_io_check, self.tl_color_inactive_outline)
                    if sub_type == 'Background':
                        process_gradient(sub, self.tl_inactive_gradient_check, self.tl_color_ib_check,
                                         self.tl_color_inactive_background1, self.tl_color_inactive_background2)
                    if sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, self.tl_color_af_check, self.tl_color_active_foreground)
                            if active_type == 'Outline':
                                process_color(active, self.tl_color_ao_check, self.tl_color_active_outline)
                            if active_type == 'Background':
                                process_gradient(active, self.tl_active_gradient_check, self.tl_color_ab_check,
                                                 self.tl_color_active_background1, self.tl_color_active_background2)

            elif s_type == 'MenuStyle':
                process_decoration(node.get('decorations'), self.m_decorations_combo)
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.m_font_entry, self.m_encoding_entry, self.m_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, '', self.m_color_inactive_foreground)
                    elif sub_type == 'Outline':
                        process_color(sub, '', self.m_color_inactive_outline)
                    elif sub_type == 'Background':
                        process_color(sub, '', self.m_color_inactive_background)
                    elif sub_type == 'Opacity':
                        process_spin(sub, self.m_opacity_check, self.m_opacity_spin, True)
                    elif sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, '', self.m_color_active_foreground)
                            elif active_type == 'Outline':
                                process_color(active, '', self.m_color_active_outline)
                            elif active_type == 'Background':
                                process_gradient(active, self.m_active_gradient_check, '',
                                                 self.m_color_active_background1, self.m_color_active_background2)

            elif s_type == 'PagerStyle':
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.p_font_entry, self.p_encoding_entry, self.p_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, '', self.p_color_inactive_foreground)
                    elif sub_type == 'Outline':
                        process_color(sub, '', self.p_color_outline)
                    elif sub_type == 'Text':
                        process_color(sub, '', self.p_color_text)
                    elif sub_type == 'Background':
                        process_color(sub, '', self.p_color_inactive_background)
                    elif sub_type == 'Active':
                        for active in sub:
                            active_type = active.tag
                            if active_type == 'Foreground':
                                process_color(active, '', self.p_color_active_foreground)
                            elif active_type == 'Background':
                                process_color(active, '', self.p_color_active_background)

            elif s_type == 'ClockStyle':
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.cl_font_entry, self.cl_encoding_entry, self.cl_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, self.cl_foreground_check, self.cl_color_foreground)
                    elif sub_type == 'Background':
                        process_gradient(sub, self.cl_active_gradient_check, self.cl_background_check,
                                         self.cl_color_background1, self.cl_color_background2)

            elif s_type == 'PopupStyle':
                value = node.get('delay')
                if value:
                    try:
                        self.pop_delay_spin.set_value(int(value))
                    except (ValueError, TypeError):
                        pass
                value = node.get('enabled')
                if value:
                    if value == 'true':
                        self.pop_all_check.set_active(True)
                    elif value == 'false':
                        self.pop_none_check.set_active(True)
                    else:
                        if 'button' in value:
                            self.pop_buttons_check.set_active(True)
                        if 'clock' in value:
                            self.pop_clock_check.set_active(True)
                        if 'menu' in value:
                            self.pop_menu_check.set_active(True)
                        if 'task' in value:
                            self.pop_task_check.set_active(True)
                        if 'pager' in value:
                            self.pop_pagers_check.set_active(True)
                for sub in node:
                    sub_type = sub.tag
                    if sub_type == 'Font':
                        process_font(sub, self.pop_font_entry, self.pop_encoding_entry, self.pop_antialias_check)
                    if sub_type == 'Foreground':
                        process_color(sub, '', self.pop_color_foreground)
                    elif sub_type == 'Outline':
                        process_color(sub, '', self.pop_color_outline)
                    elif sub_type == 'Background':
                        process_color(sub, '', self.pop_color_background)
        if self.view.get_visible():
            self.update_preview()


win = MenusWindow()
win.connect("delete-event", Gtk.main_quit)
win.set_position(Gtk.WindowPosition.CENTER)
win.show_all()
Gtk.main()

# TODO
#  Order of buttons on the title bar  __ [ ] X
#  ReColor Buttons
#  - Condition for identical colors on Color Replacement
#  -
#  INFO : Enhanced SVG not supported'
#  Hint : Convert with Inkscape > save as > Optimized SVG
