#!/usr/bin/env python
# coding= UTF-8
#
#	wbar configuration gui  v0.7.2
#
#	Created by
#		Mika Hynnä <mika.hynna@wippies.com>
#
#	Copyright 2008 Mika Hynnä
# This program is distributed under the terms of the GNU General Public License
# For more info see http://www.gnu.org/licenses/gpl.txt 
#
#
# Requires
# * >=python-2.4
# * >=pygtk-2.10
# * >=gettext-0.16
#

# Read and replaced from wbar's configuration file comment '#wbarlaunchcommand=""
#global wbarcommand
wbarcommand = "wbar -bpress -above-desk"

# "Hard coded" custom config file can be set in here:
customwbarconfigfile = "/path/to/config"

try:
    import os
    import sys
    import pygtk
    import gtk
    import gobject
    import string
    import locale
    from locale import getlocale
except:
    print("*** ERROR ***\n");
    print("All required python dependencies were not found!\n")
    print("Make sure that you have new enough python, pygtk, gobject and gettext installed!\n")
    sys.exit()

# Localization support using gettext
try:
    import gettext
    if (os.path.exists("locale/")):
        gettext.bindtextdomain('wbarconf', './locale/')
    gettext.textdomain('wbarconf')
    _ = gettext.gettext #_('')
except:
    #def _(message):
    print("Gettext error, defaulting to english!")
    #    return message

wbarversion="0.7.2"

ITEM_ID = 0
ITEM_ICON = 1
ITEM_COMMAND = 2
ITEM_TITLE = 3
ITEM_IMAGE = 4

PLACE_ID=0
PLACE_IMAGE=1
PLACE_TITLE=2
PLACE_COMMAND=3
PLACE_ICON=4

DROP_TYPE_TREEVIEWROW=1
DROP_TYPE_DESKTOP=0

commandlinewbarconfigfile=""

## SettingsDialog class BEGINS
class SettingsDialog:
    
        parentClass = None
    
        def combobox_changed(self, itemstr, item):
            self.removeProperty('-'+itemstr, True)
            value = item.get_active_text().split(' ')[0]
            self.addProperty('-'+itemstr, value)

        def position_combobox_changed(self, widget):
            value=''
            self.removeProperty('-pos', True)
            active_item = self.position_combobox.get_active()
            if (active_item != -1):
                value = self.position_items[active_item]
            else:
                value = 'bottom'
            #print('active_item:'+str(active_item))
            self.addProperty('-pos', value)

        def spinbutton_valuechanged(self, itemstr, item):
            #print("Changed: "+itemstr+" Value: "+str(item))
            
            self.removeProperty('-'+itemstr, True)
            self.addProperty('-'+itemstr, item.get_value())

        def removeProperty(self, property, hasparam=False):
                global wbarcommand
                #print(wbarcommand)
                if (wbarcommand.find(property) != -1):
                    cmd = str(wbarcommand).split(' ')
                    wbarcommand=""
                    for i in range(0,len(cmd)):
                        #print(i, len(cmd))
                        if property == cmd[i]:
                            if hasparam:
                                cmd[i+1] = ''
                            cmd[i]=''
                        wbarcommand = wbarcommand.strip() + " " + str(cmd[i])
                    wbarcommand = wbarcommand.strip()
                    
                else:
                    print('Could not find '+property+' so we do nothing here.')
                
                #print("wbarcommand: "+wbarcommand)


        def addProperty(self, property, value=-1):
                global wbarcommand
                #print('wbarcommand: '+wbarcommand)
                if (wbarcommand.find(property) != -1):
                    if (value == -1):
                        print('Property '+property+' already exists!')
                    else:
                        cmd = str(wbarcommand).split(' ')
                        wbarcommand=""
                        for i in range(0,len(cmd)):
                            #print(i, len(cmd))
                            if property == cmd[i]:
                                cmd[i+1] = value
                            wbarcommand = wbarcommand + " " + str(cmd[i])
                        wbarcommand = wbarcommand.strip()
                        
                else:
                    if (value == -1):
                        wbarcommand = wbarcommand + " " +property
                    else:
                        wbarcommand = wbarcommand + " " +property + " " +str(value)
                
                #print("new wbarcommand: "+wbarcommand)

        def checkbutton_toggled(self, item):
            
            if (item == 'bpress'):
                print('bpress')
                if (self.bpress.get_active()):
                    self.addProperty('-bpress')
                else:
                    self.removeProperty('-bpress')
            elif (item == 'abovedesk'):
                print('abovedesk')
                if (self.abovedesk.get_active()):
                    self.addProperty('-above-desk')
                else:
                    self.removeProperty('-above-desk')
            elif (item == 'vbar'):
                print('vbar')
                if (self.vbar.get_active()):
                    self.addProperty('-vbar')
                else:
                    self.removeProperty('-vbar')
            elif (item == 'nofont'):
                print('nofont')
                if (self.nofont.get_active()):
                    self.addProperty('-nofont')
                else:
                    self.removeProperty('-nofont')
            elif (item == 'jfactor'):
                print('jfactor')
                if (self.jumpfactor_checkbutton.get_active() ):
                        self.jumpfactor_spinbutton.set_sensitive(True)
                        self.addProperty('-jumpf', self.jumpfactor_spinbutton.get_value())
                else:
                        self.jumpfactor_spinbutton.set_sensitive(False)
                        self.removeProperty('-jumpf', True)
            elif (item == 'zfactor'):
                print('zfactor')
                if (self.zoomfactor_checkbutton.get_active()):
                        self.zoomfactor_spinbutton.set_sensitive(True)
                        self.addProperty('-zoomf', self.zoomfactor_spinbutton.get_value())
                else:
                        self.zoomfactor_spinbutton.set_sensitive(False)
                        self.removeProperty('-zoomf', True)
            elif (item == 'isize'):
                print('isize')
                if (self.isize_checkbutton.get_active()):
                        self.isize.set_sensitive(True)
                        self.addProperty('-isize', self.isize.get_value())
                else:
                        self.isize.set_sensitive(False)
                        self.removeProperty('-isize', True)
            elif (item == 'idist'):
                print('idist')
                if (self.idist_checkbutton.get_active()):
                        self.idist.set_sensitive(True)
                        self.addProperty('-idist', self.idist.get_value())
                else:
                        self.idist.set_sensitive(False)
                        self.removeProperty('-idist', True)
            elif (item == 'position'):
                print('position')
                if (self.position_checkbutton.get_active()):
                        self.position_combobox.set_sensitive(True)
                        self.addProperty('-pos', self.position_items[self.position_combobox.get_active()] )
                else:
                        self.position_combobox.set_sensitive(False)
                        self.removeProperty('-pos', True)
                        
            elif (item == 'dblclick'):
                print('dblclick')
                if (self.dblclick_checkbutton.get_active()):
                        self.dblclick_spinbutton.set_sensitive(True)
                        self.addProperty('-dblclk', self.dblclick_spinbutton.get_value())
                else:
                        self.dblclick_spinbutton.set_sensitive(False)
                        self.removeProperty('-dblclk', True)
            elif (item == 'balfa'):
                print('balfa')
                if (self.balfa_checkbutton.get_active()):
                        self.balfa_spinbutton.set_sensitive(True)
                        self.addProperty('-balfa', self.balfa_spinbutton.get_value())
                else:
                        self.balfa_spinbutton.set_sensitive(False)
                        self.removeProperty('-balfa', True)
            elif (item == 'falfa'):
                print('falfa')
                if (self.falfa_checkbutton.get_active()):
                        self.addProperty('-falfa', self.falfa_spinbutton.get_value())
                        self.falfa_spinbutton.set_sensitive(True)
                else:
                        self.falfa_spinbutton.set_sensitive(False)
                        self.removeProperty('-falfa', True)
            elif (item == 'filter'):
                print('filter')
                if (self.filter_checkbutton.get_active()):
                        self.filter_combobox.set_sensitive(True)
                        self.addProperty('-filter', self.filter_combobox.get_active_text().split(' ')[0])
                else:
                        self.filter_combobox.set_sensitive(False)
                        self.removeProperty('-filter', True)
            elif (item == 'nanim'):
                print('nanim')
                if (self.nanim_checkbutton.get_active()):
                        self.nanim_spinbutton.set_sensitive(True)
                        self.addProperty('-nanim', self.nanim_spinbutton.get_value())
                else:
                        self.nanim_spinbutton.set_sensitive(False)
                        self.removeProperty('-nanim', True)
            elif (item == 'fc'):
                print('fc')
                if (self.fc_checkbutton.get_active()):
                        self.fc_entry.set_sensitive(True)
                        self.fc_colorbutton.set_sensitive(True)
                        self.addProperty('-fc', self.fc_entry.get_text())
                else:
                        self.fc_colorbutton.set_sensitive(False)
                        self.fc_entry.set_sensitive(False)
                        self.removeProperty('-fc', True)

        def __init__(self, parent):
            self.parentClass = parent
            
            print("SettingsDialog - Init")
            self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.window.set_title(_('Command line settings'))
            self.window.connect("destroy", self.destroy)
            self.window.connect("delete_event", self.delete_event)
            
            self.window.set_default_size(400,300)
            
            container = gtk.VBox()
            container.set_spacing(10)
            
            self.bpress = gtk.CheckButton(_('Icon gets pressed (-bpress)'))
            self.bpress.connect_object('toggled',self.checkbutton_toggled,'bpress')
            
            self.abovedesk = gtk.CheckButton(_('Run over a desktop app (ie: xfdesktop) (-above-desk)'))
            self.abovedesk.connect_object('toggled',self.checkbutton_toggled,'abovedesk')

            self.vbar = gtk.CheckButton(_('Vertical bar (-vbar)'))
            self.vbar.connect_object('toggled',self.checkbutton_toggled,'vbar')

            self.nofont = gtk.CheckButton(_('Disable font rendering (-nofont)'))
            self.nofont.connect_object('toggled',self.checkbutton_toggled,'nofont')
            
            iconsize = gtk.HBox()
            self.isize_checkbutton = gtk.CheckButton(_('Icon size (-isize) '))
            self.isize = gtk.SpinButton(gtk.Adjustment(32,16,100,1), 1,0)
            self.isize.set_range(16, 256)
            self.isize.set_sensitive(False)
            iconsize.pack_start(self.isize_checkbutton)
            iconsize.pack_start(self.isize, False, False)
            self.isize.connect_object('value-changed', self.spinbutton_valuechanged, 'isize', self.isize)
            self.isize_checkbutton.connect_object('toggled',self.checkbutton_toggled,'isize')
            #.connect("value-changed", self.button_font_size_callback)

            icondist = gtk.HBox()
            self.idist_checkbutton = gtk.CheckButton(_('Icon distance (-idist)'))
            self.idist = gtk.SpinButton(gtk.Adjustment(1,0,32,1), 1,0)
            self.idist.set_range(0, 32)
            self.idist.set_sensitive(False)
            icondist.pack_start(self.idist_checkbutton)
            icondist.pack_start(self.idist, False, False)
            self.idist_checkbutton.connect_object('toggled',self.checkbutton_toggled,'idist')
            self.idist.connect_object('value-changed', self.spinbutton_valuechanged, 'idist', self.idist)


            zoomfactor = gtk.HBox()
            self.zoomfactor_checkbutton = gtk.CheckButton(_('Zoom factor (-zoomf)'))
            self.zoomfactor_spinbutton = gtk.SpinButton(gtk.Adjustment(1.8, 0.0, 10.0, 0.1), 1.0, 1)
            self.zoomfactor_spinbutton.set_range(0.0, 10.0)
            self.zoomfactor_spinbutton.set_sensitive(False)
            zoomfactor.pack_start(self.zoomfactor_checkbutton)
            zoomfactor.pack_start(self.zoomfactor_spinbutton, False, False)
            self.zoomfactor_checkbutton.connect_object('toggled',self.checkbutton_toggled,'zfactor')
            self.zoomfactor_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'zoomf', self.zoomfactor_spinbutton)


            jumpfactor = gtk.HBox()
            self.jumpfactor_checkbutton = gtk.CheckButton(_('Jump factor (-jumpf)'))
            self.jumpfactor_spinbutton = gtk.SpinButton(gtk.Adjustment(1.0, -10.0, 10.0, 0.1), 1.0, 1)
            self.jumpfactor_spinbutton.set_range(-10.0, 10.0)
            self.jumpfactor_spinbutton.set_sensitive(False)
            jumpfactor.pack_start(self.jumpfactor_checkbutton)
            jumpfactor.pack_start(self.jumpfactor_spinbutton, False, False)
            self.jumpfactor_checkbutton.connect_object('toggled',self.checkbutton_toggled,'jfactor')
            self.jumpfactor_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'jumpf', self.jumpfactor_spinbutton)


            position = gtk.HBox()
            
            self.position_checkbutton = gtk.CheckButton(_('Position on the screen (-pos)'))
            
            position_liststore = gtk.ListStore(gobject.TYPE_STRING)
            self.position_combobox = gtk.ComboBox(position_liststore)
            cell = gtk.CellRendererText()
            self.position_combobox.set_sensitive(False)
            self.position_combobox.pack_start(cell, True)
            self.position_combobox.add_attribute(cell, 'text', 0)
            self.position_combobox.append_text(_('top'))
            self.position_combobox.append_text(_('bottom'))
            self.position_combobox.append_text(_('left'))
            self.position_combobox.append_text(_('right'))
            self.position_combobox.append_text(_('center'))
            self.position_combobox.append_text(_('top-left'))
            self.position_combobox.append_text(_('top-right'))
            self.position_combobox.append_text(_('bottom-left'))
            self.position_combobox.append_text(_('bottom-right'))

            # Real values to be passed to wbar instead of the localizatiable texts above
            self.position_items = ['top','bottom','left','right','center','top-left', 'top-right',
								   'bot-left','bot-right']

            self.position_combobox.set_active(0)
            
            position.pack_start(self.position_checkbutton)
            position.pack_start(self.position_combobox, False , False)
            self.position_checkbutton.connect_object('toggled',self.checkbutton_toggled, 'position')
            self.position_combobox.connect('changed', self.position_combobox_changed)

            dblclick = gtk.HBox()
            self.dblclick_checkbutton = gtk.CheckButton(_('ms for double click (-dblclk)'))
            self.dblclick_spinbutton = gtk.SpinButton(gtk.Adjustment(250,0,1000,10), 1,0)
            self.dblclick_spinbutton.set_range(0, 1000)
            self.dblclick_spinbutton.set_sensitive(False)
            dblclick.pack_start(self.dblclick_checkbutton)
            dblclick.pack_start(self.dblclick_spinbutton, False, False)
            self.dblclick_checkbutton.connect_object('toggled',self.checkbutton_toggled,'dblclick')
            self.dblclick_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'dblclk', self.dblclick_spinbutton)


            balfa = gtk.HBox()
            self.balfa_checkbutton = gtk.CheckButton(_('Bar alfa level (-balfa)'))
            self.balfa_spinbutton = gtk.SpinButton(gtk.Adjustment(90,0,100,1), 1,0)
            self.balfa_spinbutton.set_range(0, 100)
            self.balfa_spinbutton.set_sensitive(False)
            balfa.pack_start(self.balfa_checkbutton)
            balfa.pack_start(self.balfa_spinbutton,False, False)
            self.balfa_checkbutton.connect_object('toggled',self.checkbutton_toggled,'balfa')
            self.balfa_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'balfa', self.balfa_spinbutton)


            falfa = gtk.HBox()
            self.falfa_checkbutton = gtk.CheckButton(_('Bar unfocused alfa level (-falfa)'))
            self.falfa_spinbutton = gtk.SpinButton(gtk.Adjustment(60,0,100,1), 1, 0)
            self.falfa_spinbutton.set_range(0, 100)
            self.falfa_spinbutton.set_sensitive(False)
            falfa.pack_start(self.falfa_checkbutton)
            falfa.pack_start(self.falfa_spinbutton, False, False)
            self.falfa_checkbutton.connect_object('toggled',self.checkbutton_toggled,'falfa')
            self.falfa_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'falfa', self.falfa_spinbutton)


            filter = gtk.HBox()
            self.filter_checkbutton = gtk.CheckButton(_('Color filter mode (-filter)'))
            
            filter_liststore = gtk.ListStore(gobject.TYPE_STRING)
            self.filter_combobox = gtk.ComboBox(filter_liststore)
            cell = gtk.CellRendererText()
            self.filter_combobox.pack_start(cell, True)
            self.filter_combobox.add_attribute(cell, 'text', 0)
            self.filter_combobox.append_text('0 '+ _('none'))
            self.filter_combobox.append_text('1 '+ _('hovered'))
            self.filter_combobox.append_text('2 '+ _('others'))
            self.filter_combobox.append_text('3 '+ _('all'))
            self.filter_combobox.set_active_iter(filter_liststore.get_iter_first())
            self.filter_combobox.set_sensitive(False)
            filter.pack_start(self.filter_checkbutton)
            filter.pack_start(self.filter_combobox, False, False)
            self.filter_checkbutton.connect_object('toggled',self.checkbutton_toggled,'filter')
            self.filter_combobox.connect_object('changed', self.combobox_changed, 'filter', self.filter_combobox)


            nanim = gtk.HBox()
            self.nanim_checkbutton = gtk.CheckButton(_('Number of animated icons (-nanim)'))
            self.nanim_spinbutton = gtk.SpinButton(gtk.Adjustment(10, 0, 50, 1), 1,0)
            self.nanim_spinbutton.set_range(0, 100)
            self.nanim_spinbutton.set_sensitive(False)
            nanim.pack_start(self.nanim_checkbutton)
            nanim.pack_start(self.nanim_spinbutton, False, False)
            self.nanim_checkbutton.connect_object('toggled',self.checkbutton_toggled,'nanim')
            self.nanim_spinbutton.connect_object('value-changed', self.spinbutton_valuechanged, 'nanim', self.nanim_spinbutton)

            fc = gtk.HBox()
            self.fc_checkbutton = gtk.CheckButton(_('Filter color (-fc)'))
            self.fc_entry = gtk.Entry()
            self.fc_colorbutton = gtk.ColorButton()
            self.fc_entry.set_text("0xff00c800")
            self.fc_entry.set_sensitive(False)
            self.fc_colorbutton.set_sensitive(False)
            fc.pack_start(self.fc_checkbutton)
            fc.pack_start(self.fc_entry, False, False)
            fc.pack_start(self.fc_colorbutton, False, False)
            self.fc_colorbutton.connect('color-set', self.fc_colorbutton_colorset)
            self.fc_checkbutton.connect_object('toggled',self.checkbutton_toggled,'fc')
            self.fc_entry.connect('changed', self.fc_entry_changed)

            container.pack_start(self.bpress)
            container.pack_start(self.abovedesk)
            container.pack_start(self.vbar)
            container.pack_start(self.nofont)
            container.pack_start(position)
            container.pack_start(iconsize)
            container.pack_start(icondist)
            container.pack_start(nanim)
            container.pack_start(zoomfactor)
            container.pack_start(jumpfactor)
            container.pack_start(dblclick)
            container.pack_start(balfa)
            container.pack_start(falfa)
            container.pack_start(filter)
            container.pack_start(fc)

            
            container.set_spacing(5)
            
            container_buttons = gtk.HBox()
            
            button_close = gtk.Button(_('Close'), gtk.STOCK_CLOSE)
            button_close.connect('clicked', self.hide)
            button_close.set_tooltip_text(_('Close this window'))
            container_buttons.pack_end(button_close, False, False, 5)
            
            button_refresh = gtk.Button(_('Refresh'), gtk.STOCK_REFRESH)
            button_refresh.connect('clicked', self.button_refresh_clicked)
            button_refresh.set_tooltip_text(_('Restart wbar to see the changes, don\'t forget to save.'))
            container_buttons.pack_end(button_refresh, False, False)
            
            
            base_container = gtk.VBox()

            base_container.pack_end(container_buttons, False, False)


            frame = gtk.Frame()
            frame.set_border_width(2)
            frame.add(container)
            base_container.pack_start(frame)

            self.window.add(base_container)
            #self.window.add(container)
            #self.window.show_all()
            

            
        def color_to_wbarhex(self, color, alpha):
            string = ""
            
            print "Tohex:", color.red, color.green, color.blue
            
            alpha = int(255.*alpha/65535)
            red = int(255.*color.red/65535)
            blue = int(255.*color.blue/65535)
            green = int(255.*color.green/65535)
            
            print alpha,red,blue,green
            
            alpha = hex(alpha)[2:]
            red = hex(red)[2:]
            blue = hex(blue)[2:]
            green = hex(green)[2:]
            print alpha,red,blue,green
            string = '0x'+alpha+red+green+blue
            print self.fc_colorbutton
            return string
           

        def wbarhex_to_color(self, string):
            
            if string.find('0x') != -1:
                string = string[2:]
            mod = (1.0/256. * 65535)
            alpha = int(int(string[0:2],16) * mod)
            red = int(int(string[3:4],16) * mod)
            green = int(int(string[5:6],16) * mod)
            blue = int(int(string[7:8],16) * mod)
            print alpha,red,green,blue
            
            color = gtk.gdk.Color(red, green, blue);
            print "ToColor:", alpha, red,green,blue
            clr = '#'+string[2:]
            print clr
            color = gtk.gdk.color_parse(clr)
            return color, alpha

        def fc_colorbutton_colorset(self, colorbutton):
            
            string = self.color_to_wbarhex(colorbutton.get_color(), colorbutton.get_alpha())
            self.fc_entry.set_text(string)
            self.addProperty('-fc', string)
            
            return True

        def button_refresh_clicked(self, widget):
            print "Refresh"
            WbarGui.executeWbarRestart(self.parentClass)

        def fc_entry_changed(self, widget):
            print widget.get_text()
            self.removeProperty('-fc', True)
            self.addProperty('-fc', widget.get_text())
            try:
                self.fc_colorbutton.set_color(self.wbarhex_to_color(widget.get_text())[0])
            except:
                print('Invalid hex color value!!')

        def update_dialog_state(self):
            global wbarcommand
            print('Update command: '+wbarcommand)
            cmd = wbarcommand.split(' ')
            for i in range(0, len(cmd)):
            	cmd[i] = str(cmd[i]).strip()
                if (cmd[i] == '-vbar'):
                	self.vbar.set_active(True)
                if (cmd[i] == '-bpress'):
                	self.bpress.set_active(True)
                if (cmd[i] == '-above-desk'):
                	self.abovedesk.set_active(True)
                if (cmd[i] == '-nofont'):
                	self.nofont.set_active(True)
                if (cmd[i] == '-isize'):
                	self.isize_checkbutton.set_active(True)
                	self.isize.set_value(float(cmd[i+1]))
                if (cmd[i] == '-idist'):
                	self.idist_checkbutton.set_active(True)
                	self.idist.set_value(float(cmd[i+1]))
                if (cmd[i] == '-zoomf'):
                	self.zoomfactor_checkbutton.set_active(True)
                	self.zoomfactor_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-jumpf'):
                	self.jumpfactor_checkbutton.set_active(True)
                	self.jumpfactor_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-dblclk'):
                	self.dblclick_checkbutton.set_active(True)
                	self.dblclick_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-balfa'):
                	self.balfa_checkbutton.set_active(True)
                	self.balfa_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-falfa'):
                	self.falfa_checkbutton.set_active(True)
                	self.falfa_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-nanim'):
                	self.nanim_checkbutton.set_active(True)
                	self.nanim_spinbutton.set_value(float(cmd[i+1]))
                if (cmd[i] == '-fc'):
                	self.fc_checkbutton.set_active(True)
                	self.fc_entry.set_text(cmd[i+1])
                	color , alpha = self.wbarhex_to_color(cmd[i+1])
                	self.fc_colorbutton.set_color(color)
                	self.fc_colorbutton.set_alpha(alpha)

                if (cmd[i] == '-filter'):
                	self.filter_checkbutton.set_active(True)
                	treemodelrow = self.filter_combobox.get_model()
                	for item in treemodelrow:
                		print item[0]
                		if (item[0].split(' ')[0] == cmd[i+1]):
                			self.filter_combobox.set_active_iter(item.iter)
                	#self.filter_combobox.set_value(float(cmd[i+1]))
                if (cmd[i] == '-pos'):
                	self.position_checkbutton.set_active(True)
                	#treemodelrow = self.position_combobox.get_model()
                	#for item in treemodelrow:
                	#	print item[0]
                	#	if (item[0] == cmd[i+1]):
                	#		self.position_combobox.set_active_iter(item.iter)
                	#self.position_combobox.set_value(float(cmd[i+1]))
                	
                	# Set the position_combobox active value based on position_items
                	for j in range(0, len(self.position_items)):
                		if (cmd[i+1] == self.position_items[j]):
                			self.position_combobox.set_active(j)
                			break

        def destroy(self, extra):
            print("Destroy")
            self.hide()
            return True
        
        def delete_event(self, widget, extra):
            print("Delete event")
            self.hide()
            return True

        def show(self):
            self.update_dialog_state()
            self.window.show_all()
            print("SettingsDialog show!")

        def hide(self, widget=None):
            self.window.hide_all()
            print("SettingsDialog hid!")

## SettingsDialogs class ENDS



def readconf():
        wbarcmd = "wbar -bpress -above-desk"
        global commandlinewbarconfigfile
        
	lines=0
	lastemptyline=0
	items=list()
	# Defaults to this if can't find entry from config:
        #wbarcommand = "wbar -above-desk -bpress"
	id=0

	userconf = os.path.expanduser('~') + '/.wbar'
	if (os.path.exists(userconf)):
		print "User configuration file found: ~/.wbar"
		conf = userconf
        elif (os.path.exists(commandlinewbarconfigfile)):
            print "Using config file set in command line: '"+commandlinewbarconfigfile+"'"
            conf = commandlinewbarconfigfile
        elif (os.path.exists(customwbarconfigfile)):
            conf = customwbarconfigfile
            print "Using custom wbar config file: '"+customwbarconfigfile+"'"
	elif os.path.exists('/usr/share/wbar/dot.wbar'):
		conf = '/usr/share/wbar/dot.wbar'
		print "Shared configuration found: /usr/share/wbar/dot.wbar"
	elif os.path.exists('/usr/local/share/wbar/dot.wbar'):
		conf = '/usr/local/share/wbar/dot.wbar'
		print "Shared configuration found: /usr/local/share/wbar/dot.wbar"
	else:
		print "No configuration file found, defaulting.."
	
	icons=[]
	titles=[]
	commands=[]
	ids=[]
	item_count=0
	try:
		file = open(conf, "r")
		for line in file:
			line=line.replace('\n','')
			line=line.strip()
			if not line.startswith('#'):	
				if (len(line) > 1):
					twofirst = line[0:2]
					ids.append(item_count)
					ids.append(item_count)
					if (twofirst == "i:"):
						item_count+=1
						icons.append(line[3:].strip())
					elif (twofirst == "c:"):
						commands.append(line[3:].strip())
					elif (twofirst == "t:"):
						titles.append(line[3:].strip())
			else:
				if (line.startswith('#wbarcommand=')):
					wbarcmd=str(line[14:-1])
					print("Found wbarcommand: '"+wbarcmd+"'")
	except:
		if file.closed == False:
			file.close()	
	if file.closed == False:
		file.close()

	print "Config file read"
	configuration = []
	try:
		for i in range(0,item_count):
			configuration.append([0, icons[i], commands[i], titles[i]])
	except:
		print "Configuration parse error: trying to continue.."	

	return (configuration, wbarcmd)

def saveconf(conf, wbarcmd):
	print "Saving in ~/.wbar ...\n"
	try:
		cfile = open(os.path.expanduser('~') + "/.wbar","w")
		cfile.write("# The Bar && Font\n")
		cfile.write("#\n")
		cfile.write('#wbarcommand="'+ wbarcmd + '"\n')
		
		
		for object in conf:
	 		cfile.write("\n")
			num=0
			for item in object:
				num=num+1
				if (num == 2):
					cfile.write("i: "+str(item)+"\n")
				if (num == 3):
	                            cfile.write("c: "+str(item)+"\n")
	                	if (num == 4):
	                            cfile.write("t: "+str(item)+"\n")
		print "Saved!"
	except:
		print "Saving failed." 
		if (cfile.closed == False):
			cfile.close()
	if (cfile.closed == False):
		cfile.close()


class WbarGui:
	configuration = []
	current_selection = 0
        settingsdialog = None 
	
	def delete_event(self, widget, event, data=None):
		print "Delete event: deleting gui\n"
		return False

	def destroy(self, widget, data=None):
		print "Quiting...\n"
		gtk.main_quit()

	def buttonSaveClicked(self, widget):
		#print "Save pressed!"
		self.statusbar.set_text(_("Saving..."))
		
		del self.configuration[1:]
		
		model = self.treeview.get_model()
		try:
			iter = model.get_iter(0)
		except ValueError:
			message = gtk.MessageDialog(self.window, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK , _("Icon list is empty!\n Not saving, sorry!"))
			message.set_title(_("Empty icon list"))
			message.set_position(gtk.WIN_POS_CENTER)
			message.run()
			message.destroy()
			return
		
		while iter:
			icon = model.get_value(iter, PLACE_ICON)
			title = model.get_value(iter, PLACE_TITLE)
			command = model.get_value(iter, PLACE_COMMAND)
			self.configuration.append([1,icon,command,title])
			iter = model.iter_next(iter)
			
#		print str(self.configuration)
		saveconf(self.configuration, wbarcommand)
		
		self.statusbar.set_text(_("Configuration saved!"))
#		notice = gtk.MessageDialog(self.window, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Settings saved!")
#		notice.set_title("Saving changes")
#		notice.set_position(gtk.WIN_POS_CENTER)
#		notice.run()
#		notice.destroy()

        def menuitem_response(self,selection):
            print(selection)
            
            if (selection == "file.close"):
                    # Destroy app
                    self.destroy(self, None)
            elif (selection == "file.settings"):
                    self.settingsdialog.show()
            elif (selection == "help.about"):
                    dialog = gtk.MessageDialog(self.window, 0, gtk.MESSAGE_INFO,gtk.BUTTONS_OK)
                    dialog.set_title(_('About WbarConf'))
                    dialog.set_markup(_("WbarConf  v")+wbarversion+"\n\n"+_("Created by")+" Mika Hynnä\n"+
									    "mika.hynna@wippies.com\n\n"+
									    "http://kapsi.fi/ighea/wbarconf/")
                    dialog.show_all()
                    dialog.run()
                    dialog.destroy()
		
        
        
	def __init__(self):

		#Load configuration & wbarcommand
		self.configuration, wbarcmd = readconf()
                global wbarcommand 
                wbarcommand = wbarcmd
                
		
		#Create window
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.set_resizable(True)
		self.window.set_default_size(500,300)

		# Load icon for the app
		try:
			iconfile="wbarconf.png"
			iconfile = self.FindIcon(iconfile)
			if (os.path.exists(iconfile)):
				self.window.set_icon(gtk.gdk.pixbuf_new_from_file(iconfile))
			else:
				print('File \''+iconfile+'\' not found!')
		except:
			print 'Unknown error while setting icon.. who cares?'

		self.window.set_title(_("WbarConf - wbar configuration tool"))
		self.window.set_position(gtk.WIN_POS_CENTER)
		self.window.connect("destroy", self.destroy)
		self.window.connect("delete_event", self.delete_event)
		

        # MenuBar
                menubar = gtk.MenuBar()
                
                menu_file = gtk.Menu()
                
                menu_file_settings = gtk.MenuItem(_('Settings'))
                menu_file_settings.set_tooltip_text(_('Open command line settings dialog'))
                menu_file_close = gtk.MenuItem(_('Close'))
                menu_file_close.set_tooltip_text(_('Close the application'))
                
                menu_file.append(menu_file_settings)
                menu_file.append(menu_file_close)
                
                menu_file_title = gtk.MenuItem(_('File'))
                menu_file_title.set_submenu(menu_file)
                
                
                menu_help = gtk.Menu()
                
                menu_help_about = gtk.MenuItem(_('About'))
                menu_help.set_tooltip_text(_('About wbarconf'))
                menu_help.append(menu_help_about)
                
                menu_help_title = gtk.MenuItem(_('Help'))
                menu_help_title.set_submenu(menu_help)
                
                menubar.append(menu_file_title)
                menubar.append(menu_help_title)
                
                
                menu_file_close.connect_object("activate", self.menuitem_response, "file.close")
                menu_file_settings.connect_object("activate", self.menuitem_response, "file.settings")
                menu_help_about.connect_object("activate", self.menuitem_response, 'help.about')


		#Containers
		
		self.VBoxBase = gtk.VBox()
                self.VBoxBase.pack_start(menubar,False,False)

		self.VBoxBase.set_spacing(5)
		self.HBoxButtons = gtk.HBox()
		self.HBoxControls = gtk.HBox()
		
		self.VBoxBase.add(self.HBoxControls)

		self.VBoxList = gtk.VBox()
		self.VboxListControls = gtk.HBox()
		self.VboxListControls.show()
		self.VBoxList.show()
		self.HBoxControls.pack_start(self.VBoxList, False)
		self.HBoxControls.set_spacing(5)
		
		self.VBoxEdits = gtk.VBox()
		
		self.VboxListControls.set_spacing(5)

		
        #Icon ListStore

		self.treeview = gtk.TreeView()
		model = gtk.ListStore(gobject.TYPE_INT, gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
		self.treeview.set_model(model)
		
		cell_id = gtk.CellRendererText()
		col_id = gtk.TreeViewColumn("id", cell_id, text=PLACE_ID)
		col_id.set_visible(False)
		self.treeview.append_column(col_id)

		cell_img = gtk.CellRendererPixbuf()
		col_img = gtk.TreeViewColumn(_("Icon"), cell_img, pixbuf = PLACE_IMAGE)
		self.treeview.append_column(col_img)

		cell_text = gtk.CellRendererText()
		col_text = gtk.TreeViewColumn(_("Title"), cell_text, text = PLACE_TITLE)
		self.treeview.append_column(col_text)

		cell_command = gtk.CellRendererText()
		col_command = gtk.TreeViewColumn("command", cell_command, text=PLACE_COMMAND)
		col_command.set_visible(False)
		self.treeview.append_column(col_command)

		cell_icon = gtk.CellRendererText()
		col_icon = gtk.TreeViewColumn("icon path", cell_icon, text=PLACE_ICON)
		col_icon.set_visible(False)
		self.treeview.append_column(col_icon)

		skipfirst=False
		for wbar_item in self.configuration:
			#Lets skip first entry because it contains other than icon information
			if (skipfirst == True):
				item = model.append(None)
				model.set_value(item, PLACE_ID, int(wbar_item[ITEM_ID]))
				try:
					if (os.path.exists(str(wbar_item[ITEM_ICON]))):
						model.set_value(item, PLACE_IMAGE, gtk.gdk.pixbuf_new_from_file_at_size(str(wbar_item[ITEM_ICON]),32,32) )
				except:
					print "Warning: Core melting!!!"
				model.set_value(item, PLACE_TITLE, str(wbar_item[ITEM_TITLE]) )
				model.set_value(item, PLACE_COMMAND, str(wbar_item[ITEM_COMMAND]))
				model.set_value(item, PLACE_ICON, str(wbar_item[ITEM_ICON]))
			else:
				skipfirst = True

		self.treeview.connect("cursor-changed", self.ListItemClicked, "foo")
                #self.treeview.connect("button_release_event", self.ListItemClicked)
                #self.treeview.connect("button_press_event", self.ListItemClicked)
		self.treeview.set_tooltip_text(_("Drag and Drop to change order"))

		self.treeview.set_reorderable(True)
		self.treeview.connect('drag_motion', self.treeview_dnd_motion_callback)
		self.treeview.connect('drag_drop', self.treeview_dnd_drop_callback)
		self.treeview.connect("drag_data_received", self.treeview_dnd_receive_callback)
                self.treeview.get_selection().set_mode(gtk.SELECTION_SINGLE)


		# Set drop data rule
		self.treeview.drag_dest_set(gtk.DEST_DEFAULT_DROP, [('text/uri-list',0,0),('GTK_TREE_MODEL_ROW', 0 ,1)], gtk.gdk.ACTION_COPY)
		#self.treeview.drag_source_set(gtk.gdk.BUTTON1_MASK, [('GTK_TREE_MODEL_ROW', 0 ,1)], gtk.gdk.ACTION_COPY)
		
		self.scrolled = gtk.ScrolledWindow()
		self.scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		self.scrolled.add(self.treeview)
		self.scrolled.set_size_request(100,250)

		self.VBoxList.pack_start(self.scrolled)
		self.VBoxList.pack_start(self.VboxListControls, False)

		self.HBoxControls.pack_start(self.VBoxEdits)

		self.VBoxList.set_spacing(5)
		#Control buttons for list: new, delete and such
		#Add new
		self.button_control_new = gtk.Button(_("Add new"), gtk.STOCK_ADD)
		self.button_control_new.connect("clicked", self.button_control_new_clicked)
		self.button_control_new.show()
		self.button_control_new.set_tooltip_text(_('Add new item'))
		self.VboxListControls.pack_start(self.button_control_new, False)
		#Delete selected
		self.button_control_delete = gtk.Button(_("Remove"), gtk.STOCK_REMOVE)
		self.button_control_delete.connect("clicked", self.button_control_delete_clicked)
		self.button_control_delete.show()
		self.button_control_delete.set_tooltip_text(_('Remove selected item'))
		self.VboxListControls.pack_start(self.button_control_delete, False)
        #Down arrow
                self.button_control_down = gtk.Button(_("Down"), gtk.STOCK_GO_DOWN)
                self.button_control_down.connect("clicked", self.button_control_down_clicked)
                self.VboxListControls.pack_end(self.button_control_down, False)
                self.button_control_down.set_tooltip_text(_('Move selected item downwards'))
        #Up arrow
                self.button_control_up = gtk.Button(_("Up"), gtk.STOCK_GO_UP)
                self.button_control_up.connect("clicked", self.button_control_up_clicked)
                self.VboxListControls.pack_end(self.button_control_up, False)
                self.button_control_up.set_tooltip_text(_('Move selected item upwards'))

		#Font options
		#lets first try parse the configuration for fonts...

		font = self.configuration[0][ITEM_TITLE]
		try:
			fonti = font.rindex('/')
			size = int(font[fonti+1:])
			font = font[:fonti]
		except:
			size = 12

		self.VBoxEditsFont = gtk.VBox()
		self.VBoxEdits.add(self.VBoxEditsFont)
		label_font = gtk.Label()
		label_font.set_label(_("Font:"))
		label_font.show()
		self.VBoxEditsFont.pack_start(label_font,False)

		HBoxFont = gtk.HBox()
		self.VBoxEditsFont.pack_start(HBoxFont, False)

		self.text_font = gtk.Entry()
		self.text_font.insert_text(str(font))
		self.text_font.connect("changed", self.text_font_change)
		HBoxFont.pack_start(self.text_font)
		self.text_font.set_tooltip_text(_("Full font path"))

		button_font = gtk.Button("...")
		button_font.connect("clicked", self.button_font_clicked)
                button_font.set_tooltip_text(_("Open font file selection dialog"))
		HBoxFont.pack_start(button_font, False)
		
		self.button_font_size = gtk.SpinButton(gtk.Adjustment(size,1,99,1), 1,0)
		self.button_font_size.set_range(1,100)
		self.button_font_size.connect("value-changed", self.button_font_size_callback)
		HBoxFont.pack_start(self.button_font_size, False)
		

		#Background options
		self.VBoxEditsBG = gtk.VBox()
		self.VBoxEdits.add(self.VBoxEditsBG)		

		label_bg = gtk.Label()
		label_bg.set_label(_("Background image:"))
		label_bg.show()
		self.VBoxEditsBG.pack_start(label_bg, False)

		HBoxBackground = gtk.HBox()
		self.VBoxEditsBG.pack_start(HBoxBackground, False)

		self.text_bg = gtk.Entry()
		self.text_bg.insert_text(str(self.configuration[0][1]))
		self.text_bg.show()
		self.text_bg.connect("changed", self.text_bg_change)
		HBoxBackground.pack_start(self.text_bg)

		self.button_bg = gtk.Button("...")
		self.button_bg.connect("clicked", self.button_background_clicked)
                self.button_bg.set_tooltip_text(_("Open file selection dialog"))
		HBoxBackground.pack_start(self.button_bg, False)

		# Frame for object's options
		self.frame = gtk.Frame()
		self.VBoxEdits.pack_start(self.frame)
		
		self.frame_inner = gtk.VBox()
		self.frame.add(self.frame_inner)
		self.frame_inner.set_spacing(10)
		
		
		#Title options
		self.VBoxEdits.set_border_width(2)
		self.label_title = gtk.Label()
		self.label_title.set_label(_("Title:"))
		self.label_title.show()

		self.text_title = gtk.Entry()
		self.text_title.show()
		self.text_title.connect("changed", self.text_title_change)

		#Command options
		label_command = gtk.Label()
		label_command.set_label(_("Command:"))
		label_command.show()

		self.text_command = gtk.Entry()
		self.text_command.show()
		self.text_command.connect("changed", self.text_command_change)

		self.button_command = gtk.Button("...")
		self.button_command.show()
		self.button_command.connect("clicked", self.button_command_clicked)
		self.button_command.set_tooltip_text(_("Open selection dialog"))


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

		self.text_icon = gtk.Entry()
		self.text_icon.connect("changed", self.text_icon_change)
		
		self.button_icon = gtk.Button("...")
		self.button_icon.connect("clicked", self.button_icon_clicked)
		self.button_icon.set_tooltip_text(_("Open icon file selection dialog"))

		#Icon image in the frame:
		self.icon_image = gtk.Image()
		self.icon_image.set_size_request(96,96)
		self.frame_inner.add(self.icon_image)
		self.icon_image.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)

#################################################################
		#Table container inside frame
		table = gtk.Table(4,3)
		b = gtk.Button()
		table.attach(self.label_title,0,1,0,1, gtk.SHRINK)
		table.attach(self.text_title,1,3,0,1)
		
		table.attach(label_command,0,1,1,2, gtk.SHRINK)
		table.attach(self.text_command,1,3,1,2)
		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)
		self.frame_inner.add(table)

#################################################################


		#Button Reload
		self.button_wbar_restart = gtk.Button(_("Refresh"),gtk.STOCK_REFRESH)
		self.button_wbar_restart.set_tooltip_text(_("Restart wbar for saved changes to take effect"))
		self.button_wbar_restart.connect("clicked",self.button_refresh_clicked) 
										 #self.buttonWbarRestart)

		#Button Save
		self.button_save = gtk.Button(_("Save"),gtk.STOCK_SAVE)
		self.button_save.set_tooltip_text(_("Save settings"))
		self.button_save.connect("clicked", self.buttonSaveClicked)
#		self.HBoxButtons.add(self.button_save)
		#Button Exit
		self.button_exit = gtk.Button(_("Close"), gtk.STOCK_CLOSE)
		self.button_exit.set_tooltip_text(_("Quit, without saving changes."))
		self.button_exit.connect("clicked", self.destroy)
#		self.HBoxButtons.add(self.button_exit)

		self.HBoxButtons.pack_end(self.button_exit, False, False, 5)
		self.HBoxButtons.pack_end(self.button_save, False, False, 0)
		self.HBoxButtons.pack_end(self.button_wbar_restart, False, False, 5)

		self.VBoxBase.pack_start(self.HBoxButtons, False, False)
		self.window.add(self.VBoxBase)
		
		
		# Statusbar
		
		self.statusbar = gtk.Label("")
		self.statusbar.set_line_wrap(True)
		self.statusbar.set_justify(gtk.JUSTIFY_FILL)
		
		self.HBoxButtons.pack_start(self.statusbar, False, False)
		
                self.settingsdialog = SettingsDialog(self)
		#Show main window frame and all content
		print "All inits ok so far, showing main window."
                self.window.show_all()
                global commandlinewbarconfigfile
                if (os.path.exists(commandlinewbarconfigfile)):
                    print commandlinewbarconfigfile
                    self.statusbar.set_text(_("Please, save settings now to have latest configuration."))
                


#################################################################
#################################################################
#                    EVENTS BEGIN

        def button_refresh_clicked(self, widget):
            self.executeWbarRestart()
            self.button_wbar_restart.grab_focus()

        def executeWbarRestart(self):
                print("Command to kill: " + str(wbarcommand).split(' ')[0])
                print("Whole command: "+str(wbarcommand))
                # No pid found for wbar, running default action aka wbarcommand
                os.system("killall "+wbarcommand.split(' ')[0]+"; nohup "+wbarcommand+" &")
                self.statusbar.set_text(_('Executing: ')+ wbarcommand)
                return True
                
                # Restis code we don't use any more and will be removed soon.
        	
        	cmdline = ""
        	pidfound = False
        	
        	pstream = os.popen('pidof wbar')
        	for data in pstream:
        		if len(data) > 1:
        			pidfound = True
        			pidofwbar = int(data)
        			print("Found pid:"+str(pidofwbar))
        		else:
        			print("No wbar found running..")
        		        pidfound = False
        	
        	
        	if (pidfound == True):
        	  fdata = ""
        	  fstream = open('/proc/'+str(pidofwbar)+'/cmdline', 'r')
        	  for data in fstream:
        	   fdata = fdata + data
        	  fstream.close()
        	  fdata = fdata.replace('\0', ' ')
        	  print ("Executing:"+fdata)
        	  #Update the self.wbarcommand too
        	  #wbarcommand = fdata
        	  os.system("kill "+str(pidofwbar)+"; nohup "+ fdata + " &")
                  self.statusbar.set_text(_('Restarting: ')+ fdata)
        	else:
        		# No pid found for wbar, running default action aka wbarcommand
        		os.system("killall "+wbarcommand.split(' ')[0]+"; nohup "+wbarcommand+" &")
                self.statusbar.set_text(_('Executing: ')+ wbarcommand)
        	return True

        def button_control_up_clicked(self, n):
            print "up"
            self.statusbar.set_text("")
            try:
                cursor = self.treeview.get_cursor()[0][0]
                model = self.treeview.get_model()
                model.move_before(model.get_iter(cursor), model.get_iter(cursor-1))
                self.treeview.set_cursor(cursor-1)
                self.treeview.grab_focus()
            except ValueError:
                print "End Reached"
            except TypeError:
                self.treeview.grab_focus()
                print "Empty list"


        def button_control_down_clicked(self, n):
            print "down"
            self.statusbar.set_text("")
            try:
                cursor = self.treeview.get_cursor()[0][0]
                model = self.treeview.get_model()
                model.move_after(model.get_iter(cursor), model.get_iter(cursor+1))
                self.treeview.set_cursor(cursor+1)
                self.treeview.grab_focus()
            except ValueError:
                print "End Reached"
            except TypeError:
                self.treeview.grab_focus()
                print "Empty List"
            

        def UpdateFontInformationInConf(self):
                font = self.text_font.get_text()
                size = self.button_font_size.get_value_as_int()
                self.configuration[0][ITEM_TITLE] = font+"/"+str(size)
                if (os.path.exists(font)):
                    self.text_font.modify_text(gtk.STATE_NORMAL, None)
                else:
                    self.text_font.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color(50000,0,0,0))




	def button_font_size_callback(self,n):
		#Lets update font data
		self.UpdateFontInformationInConf()

	def ClearObjectFields(self):
                self.icon_image.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
		self.text_command.set_text("")
		self.text_title.set_text("")
		self.text_icon.set_text("")

	def ListItemClicked(self, n, event):
                
		try:
			nsel = n.get_cursor()
			selection = nsel[0][0]
			if (selection is not None):
				model = self.treeview.get_model()
				self.text_title.set_text(model.get_value(model.get_iter(selection), PLACE_TITLE) )
				self.text_command.set_text(model.get_value(model.get_iter(selection), PLACE_COMMAND) )
				self.text_icon.set_text( model.get_value( model.get_iter(selection), PLACE_ICON ) )
				self.frame.set_label(model.get_value(model.get_iter(selection), PLACE_TITLE))
		except TypeError:
			self.ClearObjectFields()
		
	def button_icon_clicked(self, n):
		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/svg")
		filter.add_mime_type("image/png")
		filter.add_mime_type("image/jpeg")
		filter.add_mime_type("image/gif")
		filter.add_pattern("*.svg")
		filter.add_pattern("*.png")
		filter.add_pattern("*.jpg")
		filter.add_pattern("*.gif")
		filter.add_pattern("*.tif")
		filter.add_pattern("*.xpm")
		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/icons/')


		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			#Set new icon information in place
			self.text_icon.set_text(dialog.get_filename())
		elif response == gtk.RESPONSE_CANCEL:
			print 'Closed, no files selected'
		dialog.destroy()

	def button_font_clicked(self, n):
		dialog = gtk.FileChooserDialog(_("Select font 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(_("All files"))
		filter.add_pattern("*")
		dialog.add_filter(filter)

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

		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			#Set new icon information in place
			self.text_font.set_text(dialog.get_filename())
		elif response == gtk.RESPONSE_CANCEL:
			print 'Closed, no files selected'
		dialog.destroy()


	def button_background_clicked(self, n):
		dialog = gtk.FileChooserDialog(_("Select background 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/gif")
		filter.add_mime_type("image/xpm")
		filter.add_pattern("*.png")
		filter.add_pattern("*.jpg")
		filter.add_pattern("*.gif")
		filter.add_pattern("*.xpm")
		dialog.add_filter(filter)

		filter = gtk.FileFilter()
		filter.set_name(_("All files"))
		filter.add_pattern("*")
		dialog.add_filter(filter)

                dialog.set_filename(self.text_bg.get_text())
                
                # Use directory specified in text field, fallback to user homedir
                url = os.path.dirname(self.text_bg.get_text())
                if os.path.exists(url):
                            dialog.set_current_folder(url)
                else:
                            dialog.set_current_folder(os.path.expanduser('~'))

		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			#Set new icon information in place
			self.text_bg.set_text(dialog.get_filename())
		elif response == gtk.RESPONSE_CANCEL:
			print 'Closed, no files selected'
		dialog.destroy()


	def text_icon_change(self, n):
		#Replace icon to be displayed
		iconfile = str(n.get_text())
		image = gtk.Image()
		model = self.treeview.get_model()
                
                self.text_icon.modify_text(gtk.STATE_NORMAL, None)
		try:
			selection=self.treeview.get_cursor()[0][0]
		except:
			print("Empty list? - icon change")
			return False
		
		if (os.path.exists(iconfile)):
			# Update property image:
			self.icon_image.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file_at_size(iconfile,64,64))

			# Update treeview image:
			model.set_value(model.get_iter(selection), PLACE_ICON, iconfile)
		
			model.set_value(model.get_iter(selection) , PLACE_IMAGE, gtk.gdk.pixbuf_new_from_file_at_size(iconfile,32,32))
			self.statusbar.set_text("")
		else:
			print "No icon image '"+ iconfile+"' found..."
			self.statusbar.set_text(_("File '")+ iconfile+_("' not found..."))
			self.icon_image.set_from_stock(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
			model.set_value(model.get_iter(selection) , PLACE_IMAGE, None)
			model.set_value(model.get_iter(selection), PLACE_ICON, iconfile)
                        self.text_icon.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color(50000,0,0,0))

			


	def text_title_change(self, n):
		#Update Icon file in configuration
		try:
			model = self.treeview.get_model()
			model.set_value(model.get_iter(self.treeview.get_cursor()[0][0]), PLACE_TITLE, str(n.get_text()))
			model.set_value(model.get_iter(self.treeview.get_cursor()[0][0]) , 2, n.get_text())
		except TypeError:
			print "Empty fields with title?"
		
	def text_command_change(self, n):
		try:
			model = self.treeview.get_model()
			model.set_value(model.get_iter(self.treeview.get_cursor()[0][0]), PLACE_COMMAND, str(n.get_text()))
		except TypeError:
			print "Empty fields with command?"


	def button_command_clicked(self, n):
		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)

                # Use directory specified in text field, fallback to user homedir
                url = os.path.dirname(self.text_command.get_text())
                if os.path.exists(url):
                            dialog.set_current_folder(url)
                else:
                            dialog.set_current_folder(os.path.expanduser('~'))


		response = dialog.run()
		if response == gtk.RESPONSE_OK:
			#Set new icon information in place
			self.text_command.set_text(dialog.get_filename())
		elif response == gtk.RESPONSE_CANCEL:
			print 'Closed, no files selected'
		dialog.destroy()


        def text_bg_change(self, n):
            background = ""
            background = str(n.get_text())
            self.configuration[0][ITEM_ICON] = background
            if (os.path.exists(background)):
                self.text_bg.modify_text(gtk.STATE_NORMAL, None)
            else:
                self.text_bg.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color(50000,0,0,0))


	def text_font_change(self, n):
		self.UpdateFontInformationInConf()

# Add new treeview object, position=-1 inserts  into cursor's position
	def new_treeview_entry(self, title, command, icon, position=-1, insertAfter=False):
		model = self.treeview.get_model()
		#item = model.append(None)
		try:
			if (position == -1):
				position = self.treeview.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:
			item = model.append(None)
			self.treeview.grab_focus()
			
		model.set_value(item, PLACE_ID, 0)
		model.set_value(item, PLACE_TITLE, title)
		model.set_value(item, PLACE_COMMAND, command)
		model.set_value(item, PLACE_ICON, icon)

		# Update treeview icon if image exists
		if (os.path.exists(icon)):
			model.set_value(item , PLACE_IMAGE, gtk.gdk.pixbuf_new_from_file_at_size(icon,32,32))
		else:
		  model.set_value(item, PLACE_IMAGE, None )
		
		
		return (item, position)

	def button_control_new_clicked(self, n):
		new_item_iter, position = self.new_treeview_entry(_('New item'), _('command'), _('icon.png'), -1 , True)
                sel = self.treeview.get_selection()
                sel.select_iter(new_item_iter)
                self.treeview.set_cursor(position+1)
                self.treeview.grab_focus()
                
                return True
		
		
	def button_control_delete_clicked(self, n):
 		#remove item from configuration
 		try:
                        self.treeview.grab_focus()
  	 		pos = self.treeview.get_cursor()[0][0]
 	  	 	model = self.treeview.get_model()
                        self.treeview.set_cursor(pos-1)
                        self.treeview.grab_focus()
  	 	 	model.remove(model.get_iter(pos))
  	  	 	if pos < 0:
  	  	  		pos = 0
  	  	  	#self.treeview.set_cursor(pos-1)
                  
            # Set the focus and cursor correctly
  	  	  	self.treeview.set_cursor(pos);
                        self.treeview.grab_focus()
  	  	except TypeError:
  	  		print "No items in the list, nothing to delete"
  	  		#model = self.treeview.get_model()
  	  		#select = self.treeview.get_selection()
  	  		#select.select_iter(model.get_iter(0))
 
########
## Treeview drag and drop functionality
	def treeview_dnd_motion_callback(self, wid, context, x, y, time):
                #cur = self.treeview.get_cursor()
		# print(context.targets)
		
		try:
                    
                    pos = int(self.treeview.get_path_at_pos(x,y)[0][0])
                    #model = self.treeview.get_model()
                    #count = len(model)
                    #height = self.treeview.get_allocation().height


                    #column = self.treeview.get_column(pos)
                    #print column.cell_get_size()
                    #cell_height = column.cell_get_size()[4]
                    #print ("diff", height,"count", count)
                    
                    self.treeview.scroll_to_point(-1,22*(pos))
                    
                    #print("pos:",pos,"y:",y)
                except:
                    print("Err...")
		#self.treeview.grab_focus()
		
                context.drag_status(gtk.gdk.ACTION_COPY, time)
		return True

	def treeview_dnd_drop_callback(self, widget, context, x, y, time):
		#print("DROP:")
		
		#if (context.get_source_widget() == None):
		#print(context.targets)
#			for i in range(0, len(context.targets)):
#				print(widget.drag_get_data(context, context.targets[i], time))
		
#			pla = gtk.TreeView()
#			print(widget.drag_source_get_target_list())
#			self.window.drag_get_data(context, context.targets[i], time)
		
		
#		print(widget.drag_get_data(context, widget.drag_dest_find_target(context, context.targets)))
		return True

	def treeview_dnd_receive_callback(self, widget, context, x, y, info, targetType, time):
	
		
		if (targetType == DROP_TYPE_TREEVIEWROW):
                        # in TypeError == out of area, default to last position
                        model = self.treeview.get_model()
			try:
                            posto = int(self.treeview.get_path_at_pos(x,y)[0][0])
                        except TypeError:
                            posto = len(model)

			posfrom = int(string.split(info.data, '\x08')[1].replace('\0', ''))
			try:
                                model.move_before(model.get_iter(posfrom), model.get_iter(posto))
                        except:
                                posto = len(model)-1
                                model.move_after(model.get_iter(posfrom), model.get_iter(posto))
                        self.treeview.grab_focus()
			# Finished drag & drop
			context.finish(True, False, time)
			#done.

		if (targetType == DROP_TYPE_DESKTOP):
                        title=""
                        lctitle=""
                        clctitle=""
            
                        lc, ec = getlocale(locale.LC_MESSAGES)
                        print lc, ec
                        clc = lc.split('_')[0]
                        print clc

			context.finish(True, False, time)
			if ( str(info.data).find('.desktop') != -1 ):
				
				filename = str(info.data).replace('file://','')
				filename = filename.replace('\r','')
				filename = filename.replace('\n','')
				filename = filename.replace('%20',' ')
				print(filename)
				
				file = open(filename, "r")
				for line in file:
					line=str(line)
					line = line.replace('\n','')
					line = line.replace('\r','')
					#print(line)
					if (line.find('Name=') != -1 and line.find('Name=') == 0):
						title = line.replace('Name=','')
                                        if (line.find('Name['+lc+']=') != -1 and line.find('Name['+lc+']=') == 0):
                                            lctitle = line.replace('Name['+lc+']=','') 
                                        if (line.find('Name['+clc+']=') != -1 and line.find('Name['+clc+']=') == 0):
                                            clctitle = line.replace('Name['+clc+']=','') 
					if (line.find('Exec=') != -1 and line.find('Exec=') == 0):
						command = line.replace('Exec=','')
					if (line.find('Icon=') != -1):
						icon = line.replace('Icon=','')
				#Name, Exec, Icon
				file.close()
			
				# In case of weird icon "files" will check out /usr/share/
				# and also tries to find a valid image icon file
				if os.path.exists(icon) == False:
					icon = self.FindIcon(icon)
				
				# Get the position of the drop in the treeview
				try:
					pos = int(self.treeview.get_path_at_pos(x,y)[0][0])
				except TypeError:
					pos = 0
				except:
					print("Unknown error!?")
				#print(pos)
				#print (title, command, icon, pos)
				
                                
                                print("title: "+title)
                                print("clctitle: "+clctitle)
                                print("lctitle: "+lctitle)
                                        
                                if (len(lctitle.strip()) > 0):
                                    title = lctitle
                                elif (len(clctitle.strip()) > 0):
                                    title = clctitle
				# Add the drop to the treeview
				try:
					new_item_iter, pos = self.new_treeview_entry(title, command, icon, pos)
					self.treeview.set_cursor(pos)
					self.treeview.grab_focus()
				except:
					print("Error with external drop source while creating new entry")
		return True

# Find the best icon with highest resolution for the launcher
	def FindIcon(self, icon):
		foundiconfile="Notfound.png"
		
		iconbase=('gnome','hicolor','locolor')
		iconpath='/usr/share/icons/'
		sizelist =('256x256', '128x128', '64x64', '48x48', '32x32', '24x24')
		categorylist=('apps',"devices", 'categories','filesystems','')
		extensionlist = ('png', 'jpg')
		
		iconimagelist=[]
		
		for extension in extensionlist:
			if (icon.find('.'+extension) != -1):
				icon = icon.replace('.'+extension,'')
		
		for size in sizelist:
			for extension in extensionlist:
				for category in categorylist:
					for iconbasecat in iconbase:
						iconfile = iconpath+"/"+iconbasecat+'/'+size+'/'+category+'/'+icon+'.'+extension
						iconimagelist.append(iconfile)

		for extension in extensionlist:
			iconfile = '/usr/share/pixmaps/'+icon+'.'+extension
			iconimagelist.append(iconfile)
			
		
		# seek from current dir
		for extension in extensionlist:
			iconfile = os.path.abspath('.')+'/' +icon+'.'+extension
			iconimagelist.append(iconfile)
		
		# Seek if the files in pre-generated list exists.. first match is the best
		# return it
		for iconimage in iconimagelist:
			if os.path.exists(iconimage):
				foundiconfile = iconimage
				print("Found:"+foundiconfile)
				return foundiconfile
		
		return icon
		

 	def main(self):
		gtk.main()


if __name__ == "__main__":
	# Command line params:
        ccmd = 1
        #exit after commandlines
        startwbar=False
        startwbarandexit=False
        #print "Argc :"+str(len(sys.argv))
        for arg in sys.argv:
            #print arg
            try:
                if (arg == "--wbar"):
                    startwbar=True
                if (arg == "--config"):
                    commandlinewbarconfigfile = sys.argv[ccmd]
                    print "Found command line configuration file '"+commandlinewbarconfigfile+"', will be used if ~/.wbar does not exists."
            except TypeError:
                print("Unexpected error, trying to continue...")
            ccmd+=1
        if (startwbar):
            conf, wbarcmd = readconf()
            # Launch wbar with params and quit:
            print("Executing: "+str(wbarcmd))
            os.system("nohup "+wbarcmd+" &")
            print("Exiting...")
            exit()
	# The prog:
	print "wbar configuration gui, v"+str(wbarversion)
	print "Copyright 2008 Mika Hynnä <mika.hynna@wippies.com>"
	print "\nThis program is distributed under the terms of the GNU General Public License\n"
	gui = WbarGui()
	gui.main()


