# -*- coding: utf-8 -*-

##
#   ADesk Bar - UI config
##

import os
import sys
import gtk
import gobject
import string
import locale
import gettext
import traceback
import time

import core
import plugins
import plugin
import config
import menu as Menu
import release

locale.setlocale(locale.LC_ALL, '')
#~ gettext.install('adeskbar', './locale', unicode=1)
gettext.bindtextdomain('adeskbar', './locale')
gettext.bind_textdomain_codeset('adeskbar','UTF-8') 
gettext.textdomain('adeskbar')
_ = gettext.gettext

## --

VERSION = 0.3
RC = 7

## --

# position in list
ID_ICON  = 0
ID_NAME = 1
ID_IND = 2
ID_CMD = 2
ID_IMG = 3

def read_config(cfg_file):
    core.logINFO("Reading config ..")
    CONFIG = {}
    LAUNCHER = {}
    DRAWER = {}
    
    CONFIG['ind_launcher'] = []
    
    ## FIXME!
    CONFIG['fade_hidden']=False
    CONFIG['icon_space']=10
    CONFIG['fade_effect']=False
    CONFIG['show_border']=1
    CONFIG['smooth_hide']=1
    CONFIG['background_color']="#333333"
    CONFIG['bg_color_sub']="#EEEEEE"
    CONFIG['border_color_sub']="#7F7F7F"
    CONFIG['bar_size']=100
    CONFIG['rounded_corner']=15
    CONFIG['icon_size']=36
    CONFIG['hidden_size']=5
    CONFIG['opacity']=70
    CONFIG['fade_factor']=30
    CONFIG['border_color']="#313335"
    CONFIG['padding']=4
    CONFIG['zoom_factor']=1.2
    CONFIG['keep_below']=False
    CONFIG['offset_pos']=4
    CONFIG['align']="center"
    CONFIG['timer']=1
    CONFIG['bg_gradient']=True
    CONFIG['auto_hide']=2
    CONFIG['auto_raise']=1
    CONFIG['offset_align']=0
    CONFIG['position']="bottom"
    CONFIG['fake_trans']=False
    CONFIG['tooltips']=True
    CONFIG['fixed_size']=100
    CONFIG['fixed_mode']=True
    CONFIG['reserve_space']=False
    
    ## FIXME!
    
    home = os.environ['HOME']

    ## custom config
    if os.access("%s/.config/adeskbar/%s.cfg" % (home, cfg_file), os.F_OK|os.R_OK):
        core.logINFO("config = %s/.config/adeskbar/%s.cfg" % (home, cfg_file))
        conf_path = "%s/.config/adeskbar/%s.cfg" % (home, cfg_file)

    ## read default config
    elif os.access("default.cfg", os.F_OK|os.R_OK):
        core.logINFO("config = default.cfg")
        conf_path = 'default.cfg'

    ## no config ? exit !
    else:
        core.logINFO("ERROR : can't read config !!!")
        #~ adesk.show_msg("Sorry, but can't read config !!!")
        sys.exit()
    del home

    f = open(conf_path,'r')

    current_cat = None
    current_sub = None
    error_config = False

    for line in f:
        if line == '\n' or line[0]=='#':
            continue
        try:
            line = line.strip('\n')

            ## check if is a category
            if line[0] == '[':
                current_cat = line[1:-1]
                if '/' in current_cat:
                    tmp = current_cat.split('/')
                    current_cat = tmp[0]
                    current_sub = tmp[1]
                    if current_cat == 'LAUNCHER':
                        LAUNCHER[current_sub] = {}
                        CONFIG['ind_launcher'].append(current_sub)
                else:
                    current_sub = None
                continue

            if current_cat == 'CONFIG':
                tmp = line.split('=',1)
                key = tmp[0]
                CONFIG[key] = tmp[1]

            elif current_cat == 'LAUNCHER':
                tmp = line.split('=',1)
                key = tmp[0]
                LAUNCHER[current_sub][key] = tmp[1]

            elif current_cat == 'DRAWER':
                (cmd, icon, desc) = line.split('##')
                if not DRAWER.has_key(current_sub):
                    DRAWER[current_sub] = []
                DRAWER[current_sub].append((cmd.strip(), icon.strip(), desc.strip()))

        except Exception, e:
            traceback.print_exc()
            error_config = True

    f.close()

    ## convert value : str -> int
    for key in ('padding','icon_size','offset_pos','offset_align',
                'rounded_corner','hidden_size','opacity','timer',
                'fade_factor','bar_size','icon_space','auto_hide'):
        CONFIG[key] = int(CONFIG[key])

    ## convert value : str -> True / False
    for key in ('auto_raise','smooth_hide', 'tooltips', #'intellihide',
                'show_border','fade_hidden', 'fixed_mode', 'reserve_space',
                'keep_below','bg_gradient','fade_effect','fake_trans'):

        if CONFIG[key] in ('true','True','1','yes'):
            CONFIG[key] = True
        else:
            CONFIG[key] = False

    CONFIG['bg_color_rgb'] = core.hex2rgb(CONFIG['background_color'])
    CONFIG['border_color_rgb'] = core.hex2rgb(CONFIG['border_color'])

    if CONFIG['hidden_size'] < 1:
        CONFIG['hidden_size'] = 1

    CONFIG['zoom_factor'] = float(CONFIG['zoom_factor'])
    CONFIG['fixed_size'] = float(CONFIG['fixed_size'])

    if error_config:
        ## FIXME!!
        pass
        #~ adesk.show_msg("Error while loading user config .. ( old config file ? )")

    return CONFIG, LAUNCHER, DRAWER

def save_config(cfg_file, config_data, ind_launcher, launchers, drawers):
    """ save config to file"""

    str_cfg = '## ADeskBar config\n'

    str_cfg += '[CONFIG]\n'
    for item in config_data:
        val = config_data[item]
        str_cfg += str(item) + "=" + str(val) + '\n'

    str_cfg += '\n'

    for ind in ind_launcher:
        str_cfg += '[LAUNCHER/%s]\n' % ind
        if launchers[ind].has_key('launcher'):
            launchers[ind].pop('launcher')
        for key in launchers[ind]:
            str_cfg += '%s=%s\n' % (key, launchers[ind][key])
        str_cfg += '\n'

    str_cfg += '\n'

    for ind in drawers:
        str_cfg += '[DRAWER/%s]\n' % ind
        for drawer in drawers[ind]:
            str_cfg += "%s##%s##%s\n" % (drawer[0], drawer[1], drawer[2])
        str_cfg += '\n'

    str_cfg += '\n'

    home = os.environ['HOME']
    if not os.path.exists("%s/.config/adeskbar" % home):
        os.makedirs("%s/.config/adeskbar" % home)

    if cfg_file==None or cfg_file=='None':
        cfg_file = 'default'

    src = "%s/.config/adeskbar/%s.cfg" % (home,cfg_file)

    configfile =  open(src, 'w')
    configfile.write(str_cfg)
    configfile.close()


def set_icon(icon, dst, item=None, size=None):
    
    # update icon for gtk.Image
    if type(dst) == gtk.Image:
        
        if not size:
            size = 64
        
        if os.path.isfile(icon) and '.' in icon:
            # Update property image:
            try:
                dst.set_from_pixbuf(core.pixbuf_from_file(icon, size, size))
            except:
                dst.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
                
        elif core.ICON_THEME.has_icon(icon):
            pixbuf = core.ICON_THEME.load_icon(icon, size, gtk.ICON_LOOKUP_USE_BUILTIN)
            dst.set_from_pixbuf(pixbuf)
        else:
            dst.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
            
    # update icon for "view"
    else:

        # Update icon
        try:
            if os.path.exists(icon) and '.' in icon:
                dst.set_value(item, ID_ICON, core.pixbuf_from_file(icon, 32, 32) )
            elif core.ICON_THEME.has_icon(icon):
                pixbuf = core.ICON_THEME.load_icon(icon, 32, gtk.ICON_LOOKUP_USE_BUILTIN)
                dst.set_value(item, ID_ICON, pixbuf)
            else:
                dst.set_value(item, ID_ICON, core.pixbuf_from_file('images/def_icon.png', 32, 32) )
                
        except:
            print '* Listview Error while adding pixbuf  .. !'
        
class Conf():

    def __init__(self, bar):

        ## tab for (position,align) on screen
        self.pos_align = [(1,0),(1,1),(1,2),
                          (3,0),(3,1),(3,2),
                          (0,0),(0,1),(0,2),
                          (2,0),(2,1),(2,2)]

        self.pos_tab = ['bottom','top','left','right']
        self.align_tab = ['start','center','end']

        self.bar = bar
        self.cfg_file = bar.cfg_file
        self.config = bar.cfg
        self.launcher = bar.launcher
        self.drawer = bar.drawer

        ## Gtk Stuff
        self.ui_Main()
        self.select_from_menu = Select_from_menu(self)

    def ui_Main(self):
        # Create window
        self.window = gtk.Window() #gtk.WINDOW_TOPLEVEL)
        title = _('Settings')
        self.window.set_title("ADeskBar %s - %s" % (title, self.bar.cfg_file))
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.connect("destroy", self.destroy)
        self.window.set_icon_from_file('images/adeskbar.png')
        self.screen_pixbuf = core.pixbuf_from_file('images/conf/display.png')

        self.nbook = gtk.Notebook()
        self.nbook.set_show_tabs(False)
        self.nbook.set_border_width(0)

        # IconView
        frame_iconView = gtk.Frame()
        store = gtk.ListStore(str, gtk.gdk.Pixbuf)

        ## preferences
        pixbuf = core.pixbuf_from_file('images/conf/preferences.png')
        store.append([_('preferences'), pixbuf])

        ## position
        pixbuf = core.pixbuf_from_file('images/conf/position.png')
        store.append([_('position'), pixbuf])

        ## launchers
        pixbuf = core.pixbuf_from_file('images/conf/launchers.png')
        store.append([_('launchers'), pixbuf])

        ## advanced
        pixbuf = core.pixbuf_from_file('images/conf/advanced.png')
        store.append([_('advanced'), pixbuf])

        ## about
        pixbuf = core.pixbuf_from_file('images/conf/about.png')
        store.append([_('about'), pixbuf])



        iconView = gtk.IconView(store)
        iconView.set_text_column(0)
        iconView.set_pixbuf_column(1)
        iconView.set_spacing(0)
        iconView.set_margin(0)
        iconView.set_column_spacing(0)
        iconView.set_row_spacing(0)
        iconView.connect("selection-changed", self.iconView_activated)
        iconView.select_path(0)

        # Containers
        BoxBase = gtk.VBox()
        BoxBase.set_spacing(5)
        BoxBase.set_border_width(10)

        BoxMain = gtk.HBox()
        BoxMain.set_spacing(0)
        BoxMain.set_border_width(0)

        BoxControls = gtk.HBox()
        BoxControls.set_spacing(5)

        ## Main Controls

        # Refresh
        button_refresh = gtk.Button(stock=gtk.STOCK_REFRESH)
        button_refresh.connect("clicked", self.refresh_bar)
        BoxControls.pack_end(button_refresh, False, False)
        # Exit
        button_exit = gtk.Button(stock=gtk.STOCK_CLOSE)
        button_exit.connect("clicked", self.destroy)
        BoxControls.pack_end(button_exit, False, False)

        self.ui_Preferences()
        self.ui_Position()
        self.ui_Launcher()
        self.ui_Advanced()
        self.ui_About()

        BoxMain.add(self.nbook)
        frame_iconView.add(iconView)
        BoxBase.pack_start(frame_iconView, False)
        BoxBase.pack_start(BoxMain, True)
        BoxBase.pack_start(gtk.HSeparator(), False)
        BoxBase.pack_end(BoxControls, False)

        self.window.add(BoxBase)
        self.window.resize(500,400)
        self.window.show_all()

    def iconView_activated(self, widget):
        cursor = widget.get_cursor()
        if cursor:
            self.nbook.set_current_page(cursor[0][0])

    def ui_Preferences(self):
        bBox = gtk.VBox()
        bBox.set_spacing(10)
        bBox.set_border_width(10)

        label_icon_size = gtk.Label(_('Icon size'))
        label_hidden_size = gtk.Label(_('Hidden size'))

        ## Launcher Size ( image )
        adjustment = gtk.Adjustment(value=self.config['icon_size'], lower=10, upper=512, step_incr=1, page_incr=10, page_size=0)
        self.icon_size = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)
        self.icon_size.set_tooltip_text('Icon size in pixel')

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(label_icon_size, False, False)
        box.pack_end(self.icon_size, False, False)
        bBox.pack_start(box, False, True)

        ## Fixed mode
        adjustment = gtk.Adjustment(value=self.config['fixed_size'], lower=1, upper=100, step_incr=0.5, page_incr=0, page_size=0)
        self.fixed_size = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=1)
        self.fixed_size.set_tooltip_text('"panel" size in %')

        self.fixed_mode_checkbox = gtk.CheckButton(_('fixed mode ( aka "panel" )'))
        self.fixed_mode_checkbox.set_active(self.config['fixed_mode'])

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(self.fixed_mode_checkbox, False, False)
        box.pack_end(self.fixed_size, False, False)
        bBox.pack_start(box, False, True)


        ## reserve space at screen edge
        self.reserve_space_checkbox = gtk.CheckButton(_('reserve space at screen edge'))
        self.reserve_space_checkbox.set_active(self.config['reserve_space'])

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label('    '), False, False)
        box.pack_start(self.reserve_space_checkbox, False, False)
        bBox.pack_start(box, False, True)

        ## Size when Hidden
        adjustment = gtk.Adjustment(value=self.config['hidden_size'], lower=1, upper=100, step_incr=1, page_incr=0, page_size=0)
        self.hidden_size = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)
        self.hidden_size.set_tooltip_text('hidden size in pixel')

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(label_hidden_size, False, False)
        box.pack_end(self.hidden_size, False, False)
        bBox.pack_start(box, False, True)

        # Auto-raise
        self.autoraise_checkbox = gtk.CheckButton(_('Show on mouse over'))
        self.autoraise_checkbox.set_active(self.config['auto_raise'])
        bBox.pack_start(self.autoraise_checkbox, False, True)

        # keep_below other window
        self.keep_below_checkbox = gtk.CheckButton(_('Keep below other windows'))
        self.keep_below_checkbox.set_active(self.config['keep_below'])
        bBox.pack_start(self.keep_below_checkbox, False, True)

        ## Auto-hide
        self.hiding = gtk.combo_box_new_text()
        self.hiding.append_text('None')
        self.hiding.append_text('Autohide')
        self.hiding.append_text('Intellihide')
        self.hiding.set_active(self.config['auto_hide'])

        adjustment = gtk.Adjustment(value=self.config['timer'], lower=0, upper=100, step_incr=1, page_incr=2, page_size=0)
        self.timer = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)
        self.timer.set_tooltip_text('time in second')

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Hiding')), False, False)
        box.pack_start(self.hiding, False, False)
        box.pack_end(self.timer, False, False)
        bBox.pack_start(box, False, True)

        # Smooth hide
        self.smooth_hide_checkbox = gtk.CheckButton(_('smooth hiding ( animation )'))
        self.smooth_hide_checkbox.set_active(self.config['smooth_hide'])
        bBox.pack_start(self.smooth_hide_checkbox, False, True)

        # Show tooltips
        self.tooltips_checkbox = gtk.CheckButton(_('Show launchers tooltips'))
        self.tooltips_checkbox.set_active(self.config['tooltips'])
        bBox.pack_start(self.tooltips_checkbox, False, True)

        label = gtk.Label('Preferences')
        self.nbook.append_page(bBox, label)

    def ui_About(self):
        bBox = gtk.VBox()
        bBox.set_border_width(10)
        bBox.set_spacing(10)
        align = gtk.Alignment(0.5,0.5,0,0)
        align.add(bBox)

        img = gtk.Image()
        img.set_from_file('images/adeskbar.png')
        bBox.pack_start(img)

        label = gtk.Label('%s v%s.%s' % ("ADesk Bar", release.VERSION, release.RC))
        bBox.pack_start(label)

        label = gtk.Label('a simple application launcher for Openbox.')
        bBox.pack_start(label)

        label = gtk.Label('David Art [a.k.a] ADcomp - david.madbox@gmail.com')
        bBox.pack_start(label)

        label = gtk.Label('http://www.ad-comp.be/')
        bBox.pack_start(label)

        label = gtk.Label('Default icon : Token by ~brsev\nhttp://brsev.deviantart.com/')
        bBox.pack_start(label)

        label = gtk.Label('About')
        self.nbook.append_page(align, label)

    def ui_Position(self):
        bBox = gtk.VBox()
        bBox.set_border_width(10)
        bBox.set_spacing(10)
        bBox.pack_start(gtk.Label(_("Select position on screen")), False, False)

        align = gtk.Alignment(0.5,0.5,0,0)
        bBox.pack_start(align)

        table = gtk.Table(5, 5, False)

        self.area = gtk.DrawingArea()
        self.area.set_size_request(160, 116)
        self.area.connect("expose-event", self.area_expose)
        self.pangolayout = self.area.create_pango_layout("")

        button_pos = []
        for i in range(12):
            but = gtk.Button()
            if i in (3,4,5,9,10,11):
                but.set_size_request(20, 38)
            else:
                but.set_size_request(50, 20)
            #~ but.set_relief(gtk.RELIEF_NONE)
            but.set_border_width(0)
            but.set_focus_on_click(False)
            but.set_property('can-focus', False)
            but.connect("clicked", self.area_update_pos, i)
            button_pos.append(but)

        table.attach(button_pos[0], 1, 2, 0, 1)
        table.attach(button_pos[1], 2, 3, 0, 1)
        table.attach(button_pos[2], 3, 4, 0, 1)

        table.attach(button_pos[3], 4, 5, 1, 2)
        table.attach(button_pos[4], 4, 5, 2, 3)
        table.attach(button_pos[5], 4, 5, 3, 4)

        table.attach(button_pos[6], 1, 2, 4, 5)
        table.attach(button_pos[7], 2, 3, 4, 5)
        table.attach(button_pos[8], 3, 4, 4, 5)

        table.attach(button_pos[9], 0, 1, 1, 2)
        table.attach(button_pos[10], 0, 1, 2, 3)
        table.attach(button_pos[11], 0, 1, 3, 4)

        table.attach(self.area, 1, 4, 1, 4)
        align.add(table)


        self.position = self.pos_tab.index(self.config['position'])
        self.align = self.align_tab.index(self.config['align'])


        ## OFFSET POSITION
        adjustment = gtk.Adjustment(value=self.config['offset_pos'], lower=-10, upper=1000, step_incr=1, page_incr=10, page_size=0)
        self.spin_offset_pos = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)
        label = gtk.Label(_("Offset - position"))

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(label, False, False)
        box.pack_end(gtk.Label('px'), False, False)
        box.pack_end(self.spin_offset_pos, False, False)
        bBox.pack_start(box, False, True)

        ## OFFSET ALIGN
        adjustment = gtk.Adjustment(value=self.config['offset_align'], lower=0, upper=1000, step_incr=1, page_incr=10, page_size=0)
        self.spin_offset_align = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)
        label = gtk.Label(_("Offset - align"))

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(label, False, False)
        box.pack_end(gtk.Label('px'), False, False)
        box.pack_end(self.spin_offset_align, False, False)
        bBox.pack_start(box, False, True)

        label = gtk.Label('Position')
        self.nbook.append_page(bBox, label)

    def ui_Launcher(self):
        bBox = gtk.HBox(False,0)
        bBox.set_spacing(10)
        bBox.set_border_width(4)

        BoxListControls = gtk.VBox(False,0)

        # ListStore
        self.view = View(self)
        self.view.connect("row-activated", self.edit_item)
        
        for index in self.bar.app_mgr.index:
            name = self.bar.app_mgr.launchers[index].settings['name']
            icon = self.bar.app_mgr.launchers[index].settings['icon']
            self.view.add_launcher(name, icon, index)

        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled.add(self.view)
        frame = gtk.Frame()
        frame.add(scrolled)

        ## Control buttons for list

        # Add from menu
        button = core.image_button(_('add from menu'), 'images/conf/add_app.png', 24)
        button.connect("clicked", self.new_item_menu)
        BoxListControls.pack_start(button, False, False)

        # Add Plugin
        button = core.image_button(_('add plugin'), 'images/conf/add_plugin.png', 24)
        button.connect("clicked", self.new_item_plugin)
        BoxListControls.pack_start(button, False, False)

        # Remove
        button = core.image_button(_('remove'), 'images/conf/remove.png', 24)
        button.connect("clicked", self.remove_item)
        BoxListControls.pack_end(button, False, False)

        # Add Launcher
        button = core.image_button(_('add custom launcher'), 'images/conf/add_custom.png', 24)
        button.connect("clicked", self.new_item_custom)
        BoxListControls.pack_end(button, False, False)

        bBox.pack_start(BoxListControls, False, False)
        bBox.pack_start(frame, True)

        label = gtk.Label('Launcher')
        self.nbook.append_page(bBox, label)


    def ui_Advanced(self):
        bBox = gtk.VBox()
        bBox.set_spacing(10)
        bBox.set_border_width(10)

        ## Opacity (composite)
        adjustment = gtk.Adjustment(value=self.config['opacity'], lower=0, upper=100, step_incr=1, page_incr=10, page_size=0)
        self.opacity = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Opacity')), False, False)
        box.pack_end(gtk.Label('%'), False, False)
        box.pack_end(self.opacity, False, False)
        bBox.pack_start(box, False, True)

        ## bar size factor
        adjustment = gtk.Adjustment(value=self.config['bar_size'], lower=5, upper=100, step_incr=5, page_incr=10, page_size=0)
        self.bar_size = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Bar size')), False, False)
        box.pack_end(gtk.Label('%'), False, False)
        box.pack_end(self.bar_size, False, False)
        bBox.pack_start(box, False, True)

        ## Space beetwen Launcher
        adjustment = gtk.Adjustment(value=self.config['icon_space'], lower=1, upper=32, step_incr=1, page_incr=2, page_size=0)
        self.icon_space = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Space between icon')), False, False)
        box.pack_end(gtk.Label('px'), False, False)
        box.pack_end(self.icon_space, False, False)
        bBox.pack_start(box, False, True)

        ## Icon padding
        adjustment = gtk.Adjustment(value=self.config['padding'], lower=1, upper=32, step_incr=1, page_incr=2, page_size=0)
        self.padding = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Icon padding')), False, False)
        box.pack_end(gtk.Label('px'), False, False)
        box.pack_end(self.padding, False, False)
        bBox.pack_start(box, False, True)

        ## Separator
        bBox.pack_start(gtk.HSeparator(), False, False)

        ## Backgroung color
        map = self.window.get_colormap()
        colour = map.alloc_color(self.config['background_color'])

        self.bt_bg_color  = gtk.ColorButton(colour)

        box = gtk.HBox()
        box.pack_start(gtk.Label(_('Background color [ Bar ]')), False, False)
        box.pack_end(self.bt_bg_color, False, False)
        bBox.pack_start(box, False, True)

        # bg_gradient
        colour = map.alloc_color(self.config['background_gradient_color'])
        self.bt_bg_gradient_color = gtk.ColorButton(colour)

        self.bg_gradient_checkbox = gtk.CheckButton(_('add some gradients'))
        self.bg_gradient_checkbox.set_active(self.config['bg_gradient'])
       
        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(self.bg_gradient_checkbox, False, False)
        box.pack_end(self.bt_bg_gradient_color, False, False)
        bBox.pack_start(box, False, True) 

        # Show border checkbox / color
        self.showborder_checkbox = gtk.CheckButton(_('Show border'))
        self.showborder_checkbox.set_active(self.config['show_border'])

        colour = map.alloc_color(self.config['border_color'])
        self.bt_border_color = gtk.ColorButton(colour)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(self.showborder_checkbox, False, False)
        box.pack_end(self.bt_border_color, False, False)
        bBox.pack_start(box, False, True)



        # Use Image as background
        self.fake_trans = gtk.CheckButton(_('Fake Transparency (if no composite)'))
        self.fake_trans.set_active(self.config['fake_trans'])

        bBox.pack_start(self.fake_trans , False, True)

        ## Separator
        bBox.pack_start(gtk.HSeparator(), False, True)

        ## Color Tooltips/Plugins
        colour = map.alloc_color(self.config['bg_color_sub'])
        self.bt_bg_color_sub  = gtk.ColorButton(colour)

        box = gtk.HBox()
        box.pack_start(gtk.Label(_('Background color [ Tooltips / Plugins ]')), False, False)
        box.pack_end(self.bt_bg_color_sub, False, False)
        bBox.pack_start(box, False, True)


        colour = map.alloc_color(self.config['border_color_sub'])
        self.bt_border_color_sub  = gtk.ColorButton(colour)

        box = gtk.HBox()
        box.pack_start(gtk.Label(_('Border color')), False, False)
        box.pack_end(self.bt_border_color_sub, False, False)
        bBox.pack_start(box, False, True)

        ## Separator
        bBox.pack_start(gtk.HSeparator(), False, True)


        ## Zoom factor
        adjustment = gtk.Adjustment(value=self.config['zoom_factor'], lower=1.0, upper=2, step_incr=0.05, page_incr=0.1, page_size=0)
        self.zoom_factor = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=2)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Zoom Factor')), False, False)
        box.pack_end(self.zoom_factor, False, False)
        bBox.pack_start(box, False, True)

        ## rounded corner
        adjustment = gtk.Adjustment(value=self.config['rounded_corner'], lower=0, upper=100, step_incr=5, page_incr=10, page_size=0)
        self.rounded_corner = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(gtk.Label(_('Rounded')), False, False)
        #~ box.pack_end(gtk.Label('%'), False, False)
        box.pack_end(self.rounded_corner, False, False)
        bBox.pack_start(box, False, True)

        # Fade effect
        self.fade_effect_checkbox = gtk.CheckButton(_('Fade effect when inactive'))
        self.fade_effect_checkbox.set_active(self.config['fade_effect'])

        adjustment = gtk.Adjustment(value=self.config['fade_factor'], lower=0, upper=100, step_incr=5, page_incr=10, page_size=0)
        self.fade_factor = gtk.SpinButton(adjustment=adjustment, climb_rate=0.0, digits=0)

        box = gtk.HBox()
        box.set_spacing(10)
        box.pack_start(self.fade_effect_checkbox, False, False)
        box.pack_end(self.fade_factor, False, False)
        bBox.pack_start(box, False, True)

        # fully transparent when hidden
        self.fade_hidden_checkbox = gtk.CheckButton(_('Fully transparent when hidden'))
        self.fade_hidden_checkbox.set_active(self.config['fade_hidden'])
        bBox.pack_start(self.fade_hidden_checkbox, False, True)

        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scrolled.add_with_viewport(bBox)

        label = gtk.Label('Advanced')
        self.nbook.append_page(scrolled, label)

    def area_expose(self, area, event):
        ## graphic context
        style = area.get_style()
        gc = style.fg_gc[gtk.STATE_NORMAL]
        ## draw pixbuf as "screen"
        area.window.draw_pixbuf(gc, self.screen_pixbuf, 0, 0, 0, 0, -1, -1, gtk.gdk.RGB_DITHER_NORMAL, 0, 0)

        if self.pos_tab[self.position] == "bottom":
            x2, y2 = 50, 10
            if self.align_tab[self.align]== "start":
                x1, y1 = 21, 83
            elif self.align_tab[self.align]== "center":
                x1, y1 = 55, 83
            elif self.align_tab[self.align]== "end":
                x1, y1 = 89, 83

        if self.pos_tab[self.position] == "top":
            x2, y2 = 50, 10
            if self.align_tab[self.align]== "start":
                x1, y1 = 21, 20
            elif self.align_tab[self.align]== "center":
                x1, y1 = 55, 20
            elif self.align_tab[self.align]== "end":
                x1, y1 = 89, 20

        if self.pos_tab[self.position] == "left":
            x2, y2 = 10, 35
            if self.align_tab[self.align]== "start":
                x1, y1 = 21, 20
            elif self.align_tab[self.align]== "center":
                x1, y1 = 21, 40
            elif self.align_tab[self.align]== "end":
                x1, y1 = 21, 57

        if self.pos_tab[self.position] == "right":
            x2, y2 = 10, 35
            if self.align_tab[self.align]== "start":
                x1, y1 = 130, 20
            elif self.align_tab[self.align]== "center":
                x1, y1 = 130, 40
            elif self.align_tab[self.align]== "end":
                x1, y1 = 130, 57

        ## draw bar position on screen
        area.window.draw_rectangle(gc, True, x1, y1, x2, y2)
        return True

    def area_update_pos(self, widget, ind):
        self.position ,self.align = self.pos_align[ind]
        self.window.queue_draw()

    def edit_item(self, view, path=None, view_column=None):
        selection = view.get_cursor()[0][0]
        if (selection is not None):
            model = view.get_model()
            Edit_Item(self.window, self, model, selection)
            self.check_state(model, selection)

    def new_item_custom(self, widget):
        self.view.new_entry(self.launcher)
        self.edit_item(self.view)

    def new_item_plugin(self, widget):
        self.view.new_entry(self.launcher)
        selection = self.view.get_cursor()[0][0]
        if (selection is not None):
            model = self.view.get_model()
            Select_Plugin(self, model, selection)

    def new_item_menu(self, widget):
        self.view.new_entry(self.launcher)
        selection = self.view.get_cursor()[0][0]
        if (selection is not None):
            model   = self.view.get_model()
            self.select_from_menu.run(model, selection)

    def remove_item(self, widget):
        self.view.remove_item()

    def check_state(self, model, selection):
        ind = model.get_value(model.get_iter(selection), ID_IND)
        launcher = self.launcher[ind]
        if launcher['name']=='' and launcher['cmd']=='' and launcher['icon']=='':
            self.remove_item(None)

    def saveconf(self):
        """ Save configuration """

        model = self.view.get_model()
        iter = model.get_iter_root()

        config = {}
        ind_launcher = []

        while (iter):
            ind_launcher.append(model.get_value(iter, ID_IND))
            iter = model.iter_next(iter)

        config['background_color']  = gtk.color_selection_palette_to_string([self.bt_bg_color.get_color()])
        config['background_gradient_color']  = gtk.color_selection_palette_to_string([self.bt_bg_gradient_color.get_color()])
        
        config['bg_color_sub']  = gtk.color_selection_palette_to_string([self.bt_bg_color_sub.get_color()])
        config['border_color']  = gtk.color_selection_palette_to_string([self.bt_border_color.get_color()])
        config['border_color_sub']  = gtk.color_selection_palette_to_string([self.bt_border_color_sub.get_color()])
        config['auto_raise'] = int(self.autoraise_checkbox.get_active())
        config['smooth_hide'] = int(self.smooth_hide_checkbox.get_active())
        config['show_border'] = int(self.showborder_checkbox.get_active())
        config['icon_size'] = int(self.icon_size.get_value())
        config['icon_space'] = int(self.icon_space.get_value())
        config['hidden_size'] = int(self.hidden_size.get_value())
        config['timer'] = int(self.timer.get_value())
        config['opacity'] = int(self.opacity.get_value())

        config['auto_hide'] = int(self.hiding.get_active())
        config['offset_pos'] = int(self.spin_offset_pos.get_value())
        config['offset_align'] = int(self.spin_offset_align.get_value())
        config['position'] = self.pos_tab[self.position]
        config['align'] = self.align_tab[self.align]
        config['keep_below'] = self.keep_below_checkbox.get_active()
        config['tooltips'] = self.tooltips_checkbox.get_active()

        config['zoom_factor'] = float(self.zoom_factor.get_value())
        config['fake_trans']=self.fake_trans.get_active()

        config['rounded_corner'] = int(self.rounded_corner.get_value())
        config['fade_effect'] = self.fade_effect_checkbox.get_active()
        config['bg_gradient'] = self.bg_gradient_checkbox.get_active()
        config['fade_hidden'] = self.fade_hidden_checkbox.get_active()
        config['fade_factor'] = int(self.fade_factor.get_value())
        config['bar_size'] = int(self.bar_size.get_value())
        config['padding'] = int(self.padding.get_value())

        config['fixed_size'] = float(self.fixed_size.get_value())
        config['fixed_mode'] = self.fixed_mode_checkbox.get_active()
        
        config['reserve_space'] = self.reserve_space_checkbox.get_active()

        save_config(self.cfg_file, config, ind_launcher, self.launcher, self.drawer)

    def refresh_bar(self, widget):
        self.saveconf()
        self.bar.win.hide()
        self.bar.load_config()

    def destroy(self, widget=None, data=None):
        self.bar.bar_conf = None
        self.window.hide()
        self.window.destroy()

class Edit_Item:

    def __init__(self, parent, conf, model, selection, from_drawer=False):
        self.conf = conf
        self.model = model
        self.selection = selection
        self.from_drawer = from_drawer

        if from_drawer:
            name = model.get_value(model.get_iter(selection), ID_NAME)
            command = model.get_value(model.get_iter(selection), ID_CMD)
            icon = model.get_value(model.get_iter(selection), ID_IMG)
        else:
            self.ind = model.get_value(model.get_iter(selection), ID_IND)
            launcher = conf.launcher[self.ind]

            name = launcher['name']
            command = launcher['cmd']
            icon = launcher['icon']

        is_plugin = False
        self.is_drawer = False
        self.plugin_conf = None

        if len(command) > 1 and command[0] == '@':
            is_plugin = True
            if command == '@drawer':
                self.is_drawer = True


        # Create window
        self.window = gtk.Dialog(_("Edit"), parent, gtk.DIALOG_MODAL, buttons=None)
        self.window.set_default_size(500, -1)
        self.window.set_position(gtk.WIN_POS_CENTER)

        frame_settings = gtk.Frame()
        frame_settings.set_border_width(5)

        box_settings = gtk.HBox(False, 0)
        box_settings.set_border_width(5)
        box_settings.set_spacing(10)
        frame_settings.add(box_settings)

        label_name = gtk.Label(_("Name:"))
        self.text_name = gtk.Entry()
        self.text_name.set_text(name)

        self.text_command = gtk.Entry()
        command = command.replace("\\\"", "\"")
        self.text_command.set_text(command)

        if is_plugin:
            label_command = gtk.Label(_("Plugin:"))
            self.text_command.set_sensitive(False)
        else:
            label_command = gtk.Label(_("Command:"))

        self.button_command = gtk.Button("...")
        self.button_command.connect("clicked", self.button_command_clicked)

        #Icon options
        label_icon = gtk.Label(_("Icon:"))

        self.text_icon = gtk.Entry()
        self.text_icon.set_text(icon)
        self.text_icon.connect("changed", self.text_icon_change)

        self.button_icon = gtk.Button()
        self.button_icon.connect("clicked", self.button_icon_clicked)

        #Icon image in the frame:
        self.icon_image = gtk.Image()
        self.icon_image.set_size_request(96,96)
        self.button_icon.add(self.icon_image)

        if os.path.isfile(icon) and '.' in icon:
            # Update property image:
            try:
                self.icon_image.set_from_pixbuf(core.pixbuf_from_file(icon,64,64))
            except:
                self.icon_image.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
                
        elif core.ICON_THEME.has_icon(icon):
            pixbuf = core.ICON_THEME.load_icon(icon, 64, gtk.ICON_LOOKUP_USE_BUILTIN)
            self.icon_image.set_from_pixbuf(pixbuf)
        else:
            self.icon_image.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)


        #Table container inside frame
        table = gtk.Table(4,3)
        table.attach(label_name,0,1,0,1, gtk.SHRINK)
        table.attach(self.text_name,1,3,0,1)

        table.attach(label_command,0,1,1,2, gtk.SHRINK)
        table.attach(self.text_command,1,3,1,2)
        if not is_plugin:
            table.attach(self.button_command,3,4,1,2, gtk.SHRINK, gtk.SHRINK)

        table.attach(label_icon,0,1,2,3, gtk.SHRINK)
        table.attach(self.text_icon,1,3,2,3)
        #~ table.attach(self.button_icon,3,4,2,3, gtk.SHRINK, gtk.SHRINK)

        box_settings.pack_start(self.button_icon, False, False)
        box_settings.pack_end(table, True, True)
        self.window.vbox.pack_start(frame_settings, False, False)

        if is_plugin:
            try:
                exec("import plugins.conf.%s as plugin_conf" % command[1:])
                self.plugin_conf = plugin_conf.config(self.conf, self.ind)
                self.window.vbox.pack_start(self.plugin_conf, True) #self.is_drawer)
            except Exception, e:
                #~ pass
                #~ print "EE - '%s': %s" % (command[1:], e)
                traceback.print_exc()

        if self.is_drawer:
            self.window.set_default_size(500, 400)

        ## Controls
        bouton = gtk.Button(stock=gtk.STOCK_CANCEL)
        bouton.connect("clicked", self.close)
        self.window.action_area.pack_start(bouton, True, True, 0)
        bouton.show()

        bouton = gtk.Button(stock=gtk.STOCK_OK)
        bouton.connect("clicked", self.change_item)
        self.window.action_area.pack_start(bouton, True, True, 0)
        bouton.show()

        #Show main window frame and all content
        self.window.show_all()
        self.window.run()

    def change_item(self, data):
        command = self.text_command.get_text()
        name = self.text_name.get_text()
        icon = self.text_icon.get_text()

        item = self.model.get_iter(self.selection)
        self.model.set_value(item, ID_NAME, name)

        if self.from_drawer:
            self.model.set_value(item, ID_CMD, command)
            self.model.set_value(item, ID_IMG, icon)
        else:
            launcher = self.conf.launcher[self.ind]
            launcher['name'] = name
            launcher['cmd'] = command
            launcher['icon'] = icon

        set_icon(icon, self.model, item)

        if self.plugin_conf:
            self.plugin_conf.save_change()

        self.close()

    def close(self, widget=None, event=None):
        self.window.hide()
        self.window.destroy()

    def button_icon_clicked(self, widget):
        dialog = gtk.FileChooserDialog(_("Select image file.."),
                                        None,
                                        gtk.FILE_CHOOSER_ACTION_OPEN,
                                        (gtk.STOCK_CANCEL,
                                        gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN,
                                        gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        filter = gtk.FileFilter()
        filter.set_name(_("Images"))
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/jpeg")
        filter.add_mime_type("image/svg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.jpeg")
        filter.add_pattern("*.svg")
        dialog.add_filter(filter)
        filter = gtk.FileFilter()
        filter.set_name(_("All files"))
        filter.add_pattern("*")
        dialog.add_filter(filter)

        dialog.set_filename(self.text_icon.get_text())
        # Use directory specified in text field, fallback to icons dir
        url = os.path.dirname(self.text_icon.get_text())
        if os.path.exists(url):
            dialog.set_current_folder(url)
        else:
            dialog.set_current_folder('/usr/share/pixmaps/')

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            #Set new icon information in place
            self.text_icon.set_text(dialog.get_filename())
        dialog.destroy()


    def text_icon_change(self, widget):
        #Replace icon to be displayed
        icon = self.text_icon.get_text()
        self.text_icon.modify_text(gtk.STATE_NORMAL, None)
        set_icon(icon, self.icon_image)

    def button_command_clicked(self, widget):
        dialog = gtk.FileChooserDialog(_("Select command.."),
                                        None,
                                        gtk.FILE_CHOOSER_ACTION_OPEN,
                                        (gtk.STOCK_CANCEL,
                                        gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN,
                                        gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        filter = gtk.FileFilter()
        filter.set_name(_("All files"))
        filter.add_pattern("*")
        dialog.add_filter(filter)
        dialog.set_current_folder('/usr/share/applications')

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            ## .desktop file selected ?
            filename = dialog.get_filename()
            if '.desktop' in filename:
                cmd, icon, name, category = Menu.info_desktop(filename)
                #~ print name, cmd, icon
                self.text_command.set_text(cmd)
                self.text_name.set_text(name)
                if icon:
                    icon = Menu.find_icon(icon)
                if not icon:
                    icon = 'images/def_icon.png'
                self.icon_image.set_from_pixbuf(core.pixbuf_from_file(icon, 64, 64))
                self.text_icon.set_text(icon)
            else:
                self.text_command.set_text(filename)
        dialog.destroy()

class View(gtk.TreeView):

    def __init__(self, conf):
        gtk.TreeView.__init__(self)
        self.conf = conf
        self.set_headers_visible(False)
        self.set_reorderable(True)
        self.get_selection().set_mode(gtk.SELECTION_SINGLE)

        self.model = gtk.ListStore(
            gtk.gdk.Pixbuf,         # icon pixbuf
            gobject.TYPE_STRING,    # name
            gobject.TYPE_STRING,    # ind
            )

        self.filtremodele = self.model.filter_new()
        self.set_model(self.model)

        cell_img = gtk.CellRendererPixbuf()
        col_img = gtk.TreeViewColumn(None, cell_img, pixbuf=ID_ICON)
        self.append_column(col_img)

        cell_text = gtk.CellRendererText()
        col_text = gtk.TreeViewColumn(None, cell_text, text=ID_NAME)
        self.append_column(col_text)

        cell_command = gtk.CellRendererText()
        col_command = gtk.TreeViewColumn(None, cell_command, text=ID_IND)
        col_command.set_visible(False)
        self.append_column(col_command)

    def remove_item(self):
        # remove item from configuration
        try:
            #self.view.grab_focus()
            pos = self.get_cursor()[0][0]
            if pos == None: # no selection
                return

            model = self.get_model()
            index = model.get_value(model.get_iter(pos), ID_IND)
            model.remove(model.get_iter(pos))

            #~ self.conf.bar.app_mgr.index.remove(index)
            #~ self.conf.bar.app_mgr.launchers[index].destroy()
            #~ self.conf.bar.app_mgr.launchers.pop(index)
            #~ self.conf.bar.reposition()

            if pos < 0:
                pos = 0
            # Set the focus and cursor correctly
            self.set_cursor(pos);
            self.grab_focus()
        except TypeError:
            print( "> nothing to delete !?" )

    def add_launcher(self, name, icon, ind):
        model = self.get_model()
        item = model.append(None)

        set_icon(icon, model, item)

        model.set_value(item, ID_NAME, str(name))
        model.set_value(item, ID_IND, str(ind))

    # Add new treeview object, position=-1 inserts  into cursor's position
    def new_entry(self, launcher, position=-1, insertAfter=True):
        self.grab_focus()
        model = self.get_model()
        try:
            position = self.get_cursor()[0][0]
            try:
                iter = model.get_iter(position)
            except ValueError:
                print("> Empty list ?")
                iter = model.get_iter()

            if (insertAfter == True):
                item = model.insert_after(iter)
            else:
                item = model.insert_before(iter)
        except TypeError:
            print "typeError _ treeview"
            item = model.append(None)
            self.grab_focus()

        icon = 'images/no_fill.png'
        ind = time.time()
        ind = str(int(ind))
        ## create new launcher
        launcher[ind] = {'name':'', 'icon':'', 'cmd':''}
        ## set default value for new entry
        model.set_value(item, ID_NAME, '')
        model.set_value(item, ID_IND, ind)
        model.set_value(item, ID_ICON, core.pixbuf_from_file(icon, 32, 32))
        ## Set focus to new entry
        path = model.get_path(model.get_iter(position+1))
        self.set_cursor(path)

class Select_Plugin:
    def __init__(self, conf, model, selection):
        self.conf = conf
        self.model = model
        self.selection = selection
        self.ind = model.get_value(model.get_iter(selection), ID_IND)

        # Create window
        self.window = gtk.Window()
        self.window.connect("delete-event", self.close)
        self.window.set_modal(True)
        self.window.set_transient_for(conf.window)
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_default_size(350, 300)

        MainBox = gtk.VBox(False, 10)
        MainBox.set_border_width(5)
        MainBox.set_spacing(2)
        self.window.add(MainBox)

        scrolledBox = gtk.VBox(False, 0)
        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scrolled.add_with_viewport(scrolledBox)

        label = gtk.Label()
        text = '<span size="large"><b>Select a plugin :</b></span>'
        label.set_use_markup(True)
        label.set_markup(text)
        label.set_alignment(0.2, 1)

        MainBox.pack_start(label, False, False)
        MainBox.pack_start(scrolled, True, True)

        plugins_sort = []

        for plugin in plugins.info:
            plugins_sort.append(plugin)

        plugins_sort.sort()

        for plugin in plugins_sort:
            text = '<span size="large"><b>' + plugin + "</b></span>\n" + plugins.info[plugin]['desc']
            img = gtk.Image()
            set_icon(plugins.info[plugin]['icon'], img, size=32)
            #~ button = adesk.image_button(text, plugins.info[plugin]['icon'], 32)
            button = core.image_button(text, img, 32)
            button.connect("button-release-event", self.onClicked, plugin)
            scrolledBox.pack_start(button, False, False)

        self.window.show_all()

    def onClicked(self, widget, event, plugin):

        item    = self.model.get_iter(self.selection)
        self.model.set_value(item, ID_NAME, plugin)
        icon_path = plugins.info[plugin]['icon']
        
        set_icon(icon_path, self.model, item)
        #~ self.model.set_value(item, ID_ICON, adesk.pixbuf_from_file(icon_path,32,32))

        self.conf.launcher[self.ind]['cmd'] = '@' + plugin
        self.conf.launcher[self.ind]['icon'] = icon_path
        self.conf.launcher[self.ind]['name'] = plugins.info[plugin]['desc']

        try:
            exec("import plugins.conf.%s as plugin_conf" % plugin)
            for key in plugin_conf.settings:
                self.conf.launcher[self.ind][key] = plugin_conf.settings[key]
        except Exception, e:
            pass
            #~ print "EE - '%s': %s" % (plugin[0], e)
            #~ traceback.print_exc()

        self.close()

    def close(self, widget=None, event=None):
        self.window.hide()
        self.window.destroy()
        self.conf.check_state(self.model, self.selection)

class Select_from_menu:
    def __init__(self, conf):
        self.conf = conf
        self.model = None
        self.selection = None

        # Create window
        self.window = gtk.Window()
        self.window.set_modal(True)
        self.window.set_transient_for(conf.window)
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_default_size(350, 300)
        self.window.connect("delete-event", self.close)

        self.nbook = gtk.Notebook()
        self.nbook.set_tab_pos(gtk.POS_LEFT)
        self.nbook.set_border_width(0)
        self.nbook.show()
        self.window.add(self.nbook)

        menu_ui = Menu.MakeMenu(conf.bar.menu, self.nbook, self.add_to_list)
        menu_ui.start()

    def run(self, model, selection, from_drawer=False):
        self.model = model
        self.selection = selection
        self.from_drawer = from_drawer
        self.window.show_all()

    def add_to_list(self, widget, event, application):
        item    = self.model.get_iter(self.selection)
        self.model.set_value(item, ID_NAME, application[2])
        
        set_icon(application[1], self.model, item)
        
        if self.from_drawer:
            self.model.set_value(item, ID_CMD, application[0])
            self.model.set_value(item, ID_IMG, application[1])
        else:
            self.ind = self.model.get_value(self.model.get_iter(self.selection), ID_IND)
            launcher = self.conf.launcher[self.ind]

            launcher['name'] = application[2]
            launcher['cmd'] = application[0]
            launcher['icon'] = application[1]

        self.close(widget, event)

    def close(self, widget, event):
        ## FIXME!!
        self.window.hide()
        self.conf.check_state(self.model, self.selection)
        return True


    def doquit(self):
        self.window.hide()
        self.window.destroy()
