#!/usr/bin/env python
# -*- coding: utf-8 -*-


# MagIcons is an application to modify iconsets in a simple way.
#
# Copyright (C) 2010 Alexander Bucher <alex.b.mail@gmx.de>
#
# MagIcons is free software; you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 3 
# of the License, or (at your option) any later version.
#
# MagIcons is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty 
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public 
# License along with this program; 
# if not, see <http://www.gnu.org/licenses/>.


__author__ = 'Alexander Bucher <alex.b.mail@gmx.de>'
__version__ = '0.2'
__copyright__ = 'Copyright (c) 2010 Alexander Bucher'
__license__ = 'GNU General Public License'

try:
  import sys, os
  import pygtk
  pygtk.require("2.0")
  import gtk, gtk.glade
  import ConfigParser
  import string
  import shutil
  import Image
  import tarfile
  import gconf
  import locale, gettext
except:
  print "One or more dependencies are missing!"
  sys.exit(1)

# Import further MagIcons scripts
sys.path.append('./src')
import MI_FirstRun
import MI_Iconcut
import MI_Painter
import MI_Functions

APP_NAME = 'MagIcons'
PRAEFIX = '/'
HOME_FOLDER = os.path.expanduser('~')
LOCAL_ICON_PATH = os.path.join(HOME_FOLDER, '.icons')
SYSTEM_ICON_PATH = os.path.join(PRAEFIX+'usr', 'share', 'icons')
INSTALL_PATH = os.path.join(PRAEFIX+'usr', 'share', APP_NAME.lower())
PRIVATE_PATH = os.path.join(HOME_FOLDER, '.'+APP_NAME.lower())
TEMP_PATH = os.path.join(PRIVATE_PATH, 'temp')
CACHE_PATH = os.path.join(PRIVATE_PATH, 'cache')
SETTINGS_PATH = os.path.join(PRIVATE_PATH, 'settings')
PREVIEW_AMMOUNT = 3
MAX_PREVIEW_AMMOUNT = 5

#if os.path.isdir('../../../DEBIAN/'):  # While I'm in development, don't use the installed files.
#  GLADE_FILE = 'src/MagIcons.glade'
#  LOCALE_PATH = os.path.realpath('../locale/')
#else:
GLADE_FILE = os.path.join(INSTALL_PATH, 'src', 'MagIcons.glade')
LOCALE_PATH = os.path.realpath('/usr/share/locale/')


################################################
########  Language stuff #######################

try:locale.setlocale(locale.LC_ALL, '')
except (ImportError, locale.Error): pass

# Init the list of languages to support
langs = []
#Check the default locale
lc, encoding = locale.getdefaultlocale()
if (lc):
  #If we have a default, it's the first in the list
  langs = [lc]
# Now let's get all of the supported languages on the system
language = os.environ.get('LANG', None)
if (language): langs += language.split(":")
language = os.environ.get('LANGUAGE', None)
if (language): langs += language.split(":")
# The last of the list are our known translations
langs += ["en_US", "en", "de_DE", "de"]
# Now Tell the script where the language files (mo-files) are stored
for module in gettext, gtk.glade:
  module.bindtextdomain(APP_NAME.lower(), LOCALE_PATH)
  module.textdomain(APP_NAME.lower())
locale.bindtextdomain(APP_NAME.lower(),LOCALE_PATH)
# Get the language to use (walk trough our List)
LANG = gettext.translation(APP_NAME.lower(), LOCALE_PATH, languages=langs, fallback = True)
# And finally do the translation
###"global _"; "_ = LANG.gettext"
import __builtin__
__builtin__._ = LANG.gettext


class MagIcons:
  all_icons = []
  isdirty = False
  icon_errors = []
  preview_ammount = PREVIEW_AMMOUNT

  def __init__(self):

    ################################################
    ########  Check if files+folders are prtesent ##

    # Run the firstrun script to install all needed folders and files if they are not in place.
    checkfiles = MI_FirstRun.Firstrun(PRIVATE_PATH, INSTALL_PATH, CACHE_PATH, TEMP_PATH)
    # Load the other modules
    global functions
    functions = MI_Functions.Functions()
    global painter
    painter = MI_Painter.Painter(functions)


    ################################################
    ########  Mainwindow stuff #####################

    # Connecting the glade file and draw the window

    # Set up the glade file
    self.gladefile=os.path.join(GLADE_FILE)
    windowname="MainWindow"
    self.wTreeMain=gtk.glade.XML(self.gladefile, windowname, domain=APP_NAME.lower())
    dic = { \
            "on_apply_previev"  : self.buttonShowPreview, \
            "on_color_set"      : self.colorChanged, \
            "on_scale_changed"  : self.colorChanged, \
            "on_sw_change"      : self.colorChanged, \
            "on_prev_bg_set"    : self.backgroundChanged, \
            "on_auto_r_toggle"  : self.autoRefreshToggle, \
            "on_iconset_change" : self.setIconset, \
            "on_scheme_change"  : self.setScheme, \
            "on_about_window"   : self.showAboutWindow, \
            "on_delete_iconset" : self.deleteIconset, \
            "on_install_iconset": self.installIconset, \
            "on_install_scheme" : self.showInstallSchemeWindow, \
            "on_save_scheme"    : self.schemeNameWin, \
            "on_delete_scheme"  : self.deleteScheme, \
            "on_export_active_scheme": self.showActiveSchemeWindow, \
            "on_save_to_disc"        : self.saveToDisc, \
            "on_install_and_apply"   : self.installAndApplyScheme, \
            "on_win_resize"     : self.windowResize, \
            "on_area_expose_preview" : self.area_expose_preview_cb, \
            "on_expander_change": self.expanderChange, \
            "on_quit"           : (gtk.main_quit), \
            "on_window_destroy" : (gtk.main_quit) \
          }
    self.wTreeMain.signal_autoconnect(dic)
    self.window = self.wTreeMain.get_widget("MainWindow")
    self.last_width, self.last_height = 0,0
    self.new_width, self.new_height = self.window.get_size()
    self.expander_collapsed = False
    # Reading the config file
    self.magicons_config = ConfigParser.ConfigParser()
    self.magicons_config.read(os.path.join(SETTINGS_PATH, 'magicons.dat'))
    # Doing some further initial things
    self.doUpdateStuff()          # If this is the first run after an update, than do something
    self.refresh_state = self.wTreeMain.get_widget("autorefresh").get_active()       # Preset the refresh state
    self.backgroundChanged(None, self.magicons_config.get('config', 'background'))   # Draw the background
    self.getInstalledIcons()      # Search for all installed Iconsets
    self.fillIconsetCombox()      # Fill the combobox with all installed icons
    self.deleteTempFiles()        # Delete temp-files (from further run with bad shutdown)
    self.windowResize(enforce=True) # Redraw the preview part with new positions
    
    # Now showing the Main-Window
    self.window.show()
    

  ################################################
  ########  Collecting all the data ##############

  def getInstalledIcons(self):
    print _("Searching for installed iconsets and schemes...")
    self.schemes_config = ConfigParser.ConfigParser()
    self.schemes_config.read(os.path.join(SETTINGS_PATH, 'schemes.dat'))
    self.all_icons = {}
    self.all_icons_order = []
    # Searching for Iconsets at the install-path and at the private path
    paths = os.path.join(INSTALL_PATH, 'iconsets'), os.path.join(PRIVATE_PATH, 'iconsets')
    for path in paths:
      for folder in os.listdir(path):
        this_path = os.path.join(path, folder)
        if os.path.isdir(this_path):
          this_set = os.path.basename(this_path)
          self.iconset_config = ConfigParser.ConfigParser()
          self.iconset_config.read(os.path.join(this_path, 'magicons.control'))
          this_version = self.iconset_config.get('iconset', 'version')
          # Searching for available schemes for this iconset
          all_schemes = {}
          all_schemes_order = []
          # schemes from iconset-author
          for section in self.iconset_config.sections():
            if section[:7] == 'scheme_':
              this_scheme = self.iconset_config.get(section, "name")
              this_source = 'author'
              this_settings = {}
              for sec in self.iconset_config.sections():
                if sec[:6] == 'color_':
                  this_settings[sec] = self.iconset_config.get(section, sec)
                if sec[:9] == 'switcher_':
                  this_settings[sec] = self.iconset_config.get(section, sec)
                if sec == 'colorize':
                  this_settings['png-color'] = self.iconset_config.get(section, 'png-color')
                  this_settings['png-contrast'] = self.iconset_config.get(section, 'png-contrast')
                  this_settings['png-saturation'] = self.iconset_config.get(section, 'png-saturation')
              all_schemes[this_scheme] = {'source':this_source, 'settings':this_settings}
              all_schemes_order.append(this_scheme)
          # schemes from schemes-conf file
          for sec_names in self.schemes_config.sections():
            installed_scheme = sec_names.split('_', 2)
            if installed_scheme[0] == this_set:
              this_scheme = installed_scheme[1]
              this_source = 'userfile'
              this_settings = {}
              for sec in self.iconset_config.sections():
                if sec[:6] == 'color_':
                  this_settings[sec] = self.schemes_config.get(sec_names, sec)
                if sec[:9] == 'switcher_':
                  this_settings[sec] = self.schemes_config.get(sec_names, sec)
                if sec == 'colorize':
                  this_settings['png-color'] = self.schemes_config.get(sec_names, 'png-color')
                  this_settings['png-contrast'] = self.schemes_config.get(sec_names, 'png-contrast')
                  this_settings['png-saturation'] = self.schemes_config.get(sec_names, 'png-saturation')
              all_schemes[this_scheme] = {'source':this_source, 'settings':this_settings}
              all_schemes_order.append(this_scheme)
          all_schemes_order.sort()
          self.all_icons[this_set] = {'path':this_path, 'version':this_version, 'schemes':all_schemes}
          updated = False
          for s in self.all_icons_order:
            if s[0] == this_set: updated = True
            break
          if updated == False:
            self.all_icons_order.append([this_set, all_schemes_order])
          else:
            self.all_icons_order[self.getIconsetIndex(this_set)] = [this_set, all_schemes_order]
    self.all_icons_order.sort()


  ################################################
  ########  Setting the Iconset and scheme #######

  def setIconset(self, widget=None):
    self.clearFields()
    comb_iconset = self.wTreeMain.get_widget("comb_iconset")
    if self.comb_iconset.get_active() >= 0 and self.comb_iconset.get_active() < len(self.all_icons_order):
      self.active_iconset_name = comb_iconset.get_active_text()
      self.active_iconset_index = comb_iconset.get_active()
      print (_("Active iconset: %(iconset)s (%(#)d)") % \
              {'iconset':self.active_iconset_name, '#':self.active_iconset_index})
      self.active_iconset_path = self.all_icons[self.active_iconset_name]['path']
      # ----Now read the control-file and apply------
      self.iconset_config = ConfigParser.ConfigParser()
      self.iconset_config.read(os.path.join(self.active_iconset_path, 'magicons.control'))
      # set the about text for the iconset
      self.setInfoText()
      # set the sensitivity of the buttons
      self.sensitiveButtons(uninstall_set=False)
      if self.all_icons[self.active_iconset_name]['path'][:len(PRIVATE_PATH)] == PRIVATE_PATH:
        self.sensitiveButtons(uninstall_set=True)
      # draw the sliced icon
      self.drawSlicedIcon()
      # reading the sections of the control file, to see which buttons and labels shoud be shown
      self.isdirty = True
      for section in self.iconset_config.sections():
        # show the usable colorbuttons
        searching = 'color_'
        if section[:len(searching)] == searching:
          col_button = self.wTreeMain.get_widget('colorbutton_'+section[-1:])
          col_button.show()
          col_label = self.wTreeMain.get_widget('colorlabel_'+section[-1:])
          col_label.set_text(self.iconset_config.get(section, "text"))
          col_label.show()
        # show the usable switchers
        searching = 'switcher_'
        if section[:len(searching)] == searching:
          sw_button = self.wTreeMain.get_widget('sw_button_'+section[-1:])
          sw_button.show()
          sw_label = self.wTreeMain.get_widget('sw_label_'+section[-1:])
          sw_label.set_text(self.iconset_config.get(section, "text"))
          sw_label.show()
        # show the usable png-things
        searching = 'colorize'
        if section[:len(searching)] == searching:
          col_button_png = self.wTreeMain.get_widget('colorbutton_png')
          col_button_png.show()
          col_label_png = self.wTreeMain.get_widget('colorlabel_png')
          col_label_png.show()
          con_label_png = self.wTreeMain.get_widget('contrastlabel_png')
          con_label_png.show()
          con_scale_png = self.wTreeMain.get_widget('contrastscale_png')
          con_scale_png.show()
          sat_label_png = self.wTreeMain.get_widget('saturationlabel_png')
          sat_label_png.show()
          sat_scale_png = self.wTreeMain.get_widget('saturationscale_png')
          sat_scale_png.show()
      # append installed schemes to combobox
      for scheme in self.all_icons_order[self.active_iconset_index][1]:
        self.comb_scheme.append_text(scheme)
      self.comb_scheme.append_text(_("Import scheme..."))
      self.isdirty = False
      # everything is done, now set the first predefined scheme
      # this will cause a "setScheme()"
      self.comb_scheme.set_active(0)
    elif self.comb_iconset.get_active() == len(self.all_icons_order):
      self.installIconset()

  def isScheme(self, ics_idx, sch_idx):
    retval = False
    if ics_idx >= 0 and sch_idx >= 0:
      if sch_idx < len(self.all_icons_order[ics_idx][1]):
        retval = True
    return retval

  def setScheme(self, widget=None):
    if self.isdirty == False:
      if self.comb_scheme.get_active() >= 0 :
        if self.isScheme(self.comb_iconset.get_active(), self.comb_scheme.get_active()):
          self.isdirty = True
          self.active_scheme_name = self.comb_scheme.get_active_text()
          self.active_scheme_index = self.comb_scheme.get_active()
          schemesettings = self.all_icons[self.active_iconset_name]['schemes'][self.active_scheme_name]['settings']
          # disable/enable buttons
          self.sensitiveButtons(save_scheme=False, delete_scheme=False)
          if self.all_icons[self.active_iconset_name]['schemes'][self.active_scheme_name]['source'] == 'userfile':
            self.sensitiveButtons(delete_scheme=True)
          print (_('Active scheme: %(scheme)s (%(#)d)') % \
                {'scheme':self.active_scheme_name, '#':self.active_scheme_index})
          # Getting all the possible settings
          for section in self.iconset_config.sections():
            # setting the colors
            searching = 'color_'
            if section[:len(searching)] == searching:
              col_button = self.wTreeMain.get_widget('colorbutton_'+section[-1:])
              color_text = '#'+schemesettings[section]
              # Apply the found value
              color = gtk.gdk.color_parse(color_text)
              col_button.set_color(color)
            # setting the switchers
            searching = 'switcher_'
            if section[:len(searching)] == searching:
              sw_button = self.wTreeMain.get_widget('sw_button_'+section[-1:])
              setting = schemesettings[section]
              # Apply the found value
              sw_button.set_active(functions.string2bool(setting))
            searching = 'colorize'
            if section[:len(searching)] == searching:
              col_button_png = self.wTreeMain.get_widget('colorbutton_png')
              con_scale_png = self.wTreeMain.get_widget('contrastscale_png')
              sat_scale_png = self.wTreeMain.get_widget('saturationscale_png')
              color_text = '#'+schemesettings['png-color']
              contr_text = schemesettings['png-contrast']
              satur_text = schemesettings['png-saturation']
              # Apply the found value
              color = gtk.gdk.color_parse(color_text)
              col_button_png.set_color(color)
              con_scale_png.set_value(float(contr_text))
              sat_scale_png.set_value(float(satur_text))
          self.isdirty = False
          if self.refresh_state == True:
            self.buttonShowPreview(widget)
        else:
          self.showInstallSchemeWindow()


  # Get the choosen colors from the window or scheme and store the values
  # in web-format (6 digits) into the dict.
  def getColors(self, ics='', sch=''):
    colors_dict = {}
    if ics == '' or sch == '':
    # Searching for actual settings on Main-Window
      for section in self.iconset_config.sections():
        searching = 'color_'
        if section[:len(searching)] == searching:
          color_number = self.wTreeMain.get_widget("colorbutton_"+section[-1:]).get_color()
          color_number = str(color_number)[1:]
          color_number = functions.cleanColorString(color_number)
          colors_dict['col_'+section[-1:]] = color_number
        searching = 'colorize'
        if section[:len(searching)] == searching:
          color_number = self.wTreeMain.get_widget("colorbutton_png").get_color()
          color_number = str(color_number)[1:]
          color_number = functions.cleanColorString(color_number)
          colors_dict['png_col'] = color_number
          con_scale_png = self.wTreeMain.get_widget('contrastscale_png')
          colors_dict['png_con'] = con_scale_png.get_value()
          sat_scale_png = self.wTreeMain.get_widget('saturationscale_png')
          colors_dict['png_sat'] = sat_scale_png.get_value()
        searching = 'switcher_'
        if section[:len(searching)] == searching:
          sw_setting = self.wTreeMain.get_widget('sw_button_'+section[9:]).get_active()
          colors_dict['sw_'+section[-1:]] = functions.string2bool(sw_setting)
    else:
    # Searching for settings from a saved scheme
      ics_index = self.getIconsetIndex(ics)
      sch_index = self.getSchemeIndex(ics, sch)
      schemesettings = self.all_icons[ics]['schemes'][sch]['settings']
      control_path = os.path.join(self.all_icons[ics]['path'], 'magicons.control')
      self.selected_ics_config = ConfigParser.ConfigParser()
      self.selected_ics_config.read(control_path)
      for section in self.selected_ics_config.sections():
        searching = 'color_'
        if section[:len(searching)] == searching:
          if section in schemesettings: colors_dict['col_'+section[-1:]] = schemesettings[section]
          else: colors_dict['col_'+section[-1:]] = '000000'
        searching = 'switcher_'
        if section[:len(searching)] == searching:
          if section in schemesettings: 
            colors_dict['sw_'+section[-1:]] = functions.string2bool(schemesettings[section])
          else: colors_dict['sw_'+section[-1:]] = True
        searching = 'colorize'
        if section[:len(searching)] == searching:
          if 'png-color' in schemesettings: color_number = schemesettings['png-color']
          else: color_number = '000000'
          if 'png-contrast' in schemesettings: con_scale_png =  float(schemesettings['png-contrast'])
          else: con_scale_png = 0.5
          if 'png-saturation' in schemesettings: sat_scale_png =  float(schemesettings['png-saturation'])
          else: sat_scale_png = 0.5
          colors_dict['png_col'] = color_number
          colors_dict['png_con'] = con_scale_png
          colors_dict['png_sat'] = sat_scale_png
    return colors_dict

  def collectSchemeData(self, name_of_scheme):
    text = ''
    if name_of_scheme != '':
      text += '['+self.active_iconset_name+'_'+name_of_scheme+']'
      text += '\n'+APP_NAME+'_Version: '+__version__
      colors_dict = self.getColors()
      for section in self.iconset_config.sections():
        searching = 'color_'
        if section[:len(searching)] == searching:
          new_color = eval('colors_dict[\"col_'+section[-1:]+'\"]')
          text += '\n'+section+': '+new_color
        searching = 'switcher_'
        if section[:len(searching)] == searching:
          sw_button = self.wTreeMain.get_widget('sw_button_'+section[-1:])
          new_setting = sw_button.get_active()
          text += '\n'+section+': '+str(new_setting)
        searching = 'colorize'
        if section[:len(searching)] == searching:
          new_col = colors_dict['png_col']
          text += '\npng-color: '+str(new_col)
          new_con = colors_dict['png_con']
          text += '\npng-contrast: '+str(new_con)
          new_sat = colors_dict['png_sat']
          text += '\npng-saturation: '+str(new_sat)
    return text

  # set the about text for the iconset
  def setInfoText(self, width=0):
    ver0val, ver1val = _("Version:"), self.iconset_config.get("iconset", "version")
    aut0val, aut1val = _("Authors:"), self.iconset_config.get("iconset", "author")
    lic0val, lic1val = _("License:"), self.iconset_config.get("iconset", "license")
    abo0val, abo1val = _("About:")  , self.iconset_config.get("iconset", "about")
    self.about_text_head.set_text("<b>"+self.active_iconset_name+"</b> ")
    self.about_text_head.set_use_markup(True)
    aboutentries = ('ver0', 'ver1', 'aut0', 'aut1', 'lic0', 'lic1', 'abo0', 'abo1')
    i=0
    for word in aboutentries:
      i+=1
      eval('self.about_text_'+word+'.set_text('+word+'val)')
      eval('self.about_text_'+word+'.set_use_markup(True)')
      if i==2:
        eval('self.about_text_'+word+'.set_line_wrap(True)')
        if width == 0:
          eval('self.about_text_'+word+'.set_size_request(self.window.get_size()[0]-120, -1)')
        else:
          eval('self.about_text_'+word+'.set_size_request('+str(width)+', -1)')
        i=0


  ################################################
  ########  Creating the preview #################

  # Redraw the preview image
  def buttonShowPreview(self, widget=None):
    self.refresh_state = self.wTreeMain.get_widget("autorefresh").get_active()
    if self.refresh_state == True:
      if self.isdirty == False:
        self.createPreviewIcons(ics='', sch='', draw=True)

  def createPreviewIcons(self, ics='', sch='', draw=False):
    colors_dict = self.getColors(ics, sch)
    if ics == '' or sch == '':
      ics = self.active_iconset_name
      sch = self.active_scheme_name
      self.selected_ics_config = self.iconset_config
      ics_path = self.active_iconset_path
    else:
      ics_index = self.getIconsetIndex(ics)
      ics_path = self.all_icons[ics]['path']
      control_path = os.path.join(ics_path, 'magicons.control')
      self.selected_ics_config = ConfigParser.ConfigParser()
      self.selected_ics_config.read(control_path)
    preview_ammount = 0
    for section in self.selected_ics_config.sections():
      searching = 'preview_'
      if section[:len(searching)] == searching:
        if int(section[-1:]) > 0 and int(section[-1:]) <= MAX_PREVIEW_AMMOUNT:
          preview_ammount += 1
          preview_pic_source = os.path.join(ics_path, self.selected_ics_config.get(section, 'path'))
          fname, ext = os.path.splitext(preview_pic_source)
          cached_file = ics+'_'+sch+'_prev'+section[-1:]+'.png'
          if os.path.isfile(os.path.join(CACHE_PATH, cached_file)) and sch != '':
            preview_pic = os.path.join(CACHE_PATH, cached_file)
          else:
            preview_pic = os.path.join(CACHE_PATH, 'preview_'+section[-1:]+ext)
            self.createIcon(preview_pic_source, preview_pic, colors_dict)
            img = gtk.gdk.pixbuf_new_from_file(preview_pic)
            width,height = img.get_width(), img.get_height()
            im = Image.fromstring("RGBA",(width,height),img.get_pixels())
            im.save(os.path.join(CACHE_PATH, cached_file))
          new_preview_image = gtk.gdk.pixbuf_new_from_file(preview_pic)
          width,height = new_preview_image.get_width(), new_preview_image.get_height()
          if width == height and width > 48:
            im = Image.fromstring("RGBA",(width, height),new_preview_image.get_pixels())
            im2 = im.resize((48, 48))
            preview_pic = os.path.join(TEMP_PATH, 'tmp_preview.png')
            im2.save(preview_pic)
          elif width > height and width > 48:
            im = Image.fromstring("RGBA",(width, height),new_preview_image.get_pixels())
            im2 = im.resize((48, 48*width/48))
            preview_pic = os.path.join(TEMP_PATH, 'tmp_preview.png')
            im2.save(preview_pic)
          elif height > 48:
            im = Image.fromstring("RGBA",(width, height),new_preview_image.get_pixels())
            im2 = im.resize((48*height/48, 48))
            preview_pic = os.path.join(TEMP_PATH, 'tmp_preview.png')
            im2.save(preview_pic)
          
          if draw == True:
            widget_name = 'preview_image_'+section[-1:]
            img_widget = self.wTreeMain.get_widget(widget_name)
            new_preview_image = gtk.gdk.pixbuf_new_from_file(preview_pic)
            img_widget.set_from_pixbuf(new_preview_image)
    if preview_ammount != PREVIEW_AMMOUNT: self.preview_ammount = preview_ammount

  ################################################
  ########  New name for scheme ##################

  def schemeNameWin(self, widget=None, suggestion=''):
    new_scheme_name = self.inputName(suggestion)
    if new_scheme_name != '':
      name_exists = False
      for existing_scheme in  self.all_icons[self.active_iconset_name]['schemes']:
        if existing_scheme == new_scheme_name:
          name_exists = True
          break
      if name_exists == False:
        self.new_scheme_name = new_scheme_name
        self.saveScheme()
        return self.new_scheme_name
      else:
        alert = self.showAlert(_("The name \"%(scheme)s\" is already in use!") % {'scheme':new_scheme_name}, "error")
        self.schemeNameWin(None, suggestion=new_scheme_name)
    else: return ''
        

  ################################################
  ########  Save scheme ##########################

  def saveScheme(self):
    text = self.collectSchemeData(self.new_scheme_name)
    schemefile = open(os.path.join(SETTINGS_PATH, 'schemes.dat'), 'r')
    schemetext = schemefile.read()
    schemefile.close()
    schemetext = schemetext+'\n\n'+text
    schemefile = open(os.path.join(SETTINGS_PATH, 'schemes.dat'), 'w')
    schemefile.write(schemetext)
    schemefile.close()
    self.schemes_config = ConfigParser.ConfigParser()
    self.schemes_config.read(os.path.join(SETTINGS_PATH, 'schemes.dat'))
    self.getInstalledIcons()
    self.setIconset(self.active_iconset_name)
    self.comb_scheme.set_active(self.getSchemeIndex(self.active_iconset_name, self.new_scheme_name))

  ################################################
  ########  Creating an icon #####################

  # For manipulating iconsets (called by dirwalker)
  def prae_iconcreate(self, filepath):
    if os.path.islink(filepath) == False:
      self.createIcon(filepath, filepath, self.colors_dict)

  def createIcon(self, preview_pic_source, preview_pic, colors_dict, controlfile=''):
    if preview_pic_source != preview_pic:
      shutil.copy(preview_pic_source, preview_pic)
    if controlfile != '':
      icon_config = ConfigParser.ConfigParser()
      icon_config.read(controlfile)
    else:
      icon_config = self.iconset_config
      got_icon = painter.paint(preview_pic, colors_dict, icon_config, self.errorAdder)    

  def errorAdder(self, errorstring):
    self.icon_errors.append(errorstring)

  ################################################
  ########  Installing Schemes ###################

  def showInstallSchemeWindow(self, widget=None):
    self.lastscheme = self.active_scheme_index
    windowname="InstallSchemeWindow"
    self.wTreeInstSch=gtk.glade.XML(self.gladefile,windowname)
    inst_sch_dic = { \
            "on_close_install_scheme_win" : self.closeInstallSchemeWin, \
            "on_install_scheme"           : self.installScheme \
          }
    self.wTreeInstSch.signal_autoconnect(inst_sch_dic)
    self.inst_scheme_window = self.wTreeInstSch.get_widget(windowname)
    self.install_scheme_text = gtk.TextBuffer(None)
    install_scheme_text = self.wTreeInstSch.get_widget('install_scheme_text')
    install_scheme_text.set_buffer(self.install_scheme_text)
    self.inst_scheme_window.show()
    
  def installScheme(self, widget=None):
    got_scheme = False
    startiter = self.install_scheme_text.get_start_iter()
    enditer = self.install_scheme_text.get_end_iter()
    text = self.install_scheme_text.get_text(startiter,enditer)

    schemefile = open(os.path.join(TEMP_PATH, 'installing'), 'w')
    schemefile.write(text)
    schemefile.close()

    installscheme = ConfigParser.ConfigParser()
    try:
      installscheme.read(os.path.join(TEMP_PATH, 'installing'))
      for section in installscheme.sections():
        newname = section.split('_', 2)
      iconset_name = newname[0]
      scheme_name = newname[1]
      set_exists = False
      for existing_iconset in self.all_icons:
        if existing_iconset == iconset_name:
          set_exists = True
          break
      if set_exists == True:
        name_exists = False
        for existing_scheme in self.all_icons[iconset_name]['schemes']:
          if existing_scheme == scheme_name:
            name_exists = True
            break
        if name_exists == False:
          if scheme_name != _("Import scheme..."):
            print _("Installing scheme: \"%(scheme)s\" (iconset: \"%(iconset)s\")...") % {'iconset':iconset_name, 'scheme':scheme_name}
            schemefile = open(os.path.join(SETTINGS_PATH, 'schemes.dat'), 'r')
            schemetext = schemefile.read()
            schemefile.close()
            schemetext = schemetext+'\n\n'+text
            schemefile = open(os.path.join(SETTINGS_PATH, 'schemes.dat'), 'w')
            schemefile.write(schemetext)
            schemefile.close()
            got_scheme = True
          else:
            self.showAlert(_("The name \"%(installscheme)s\" is not allowed!") % \
                  {'installscheme':_("Import scheme...")}, "error")
        else:
          self.showAlert(_("This scheme already exists!"), "error")
      else:
        self.showAlert(_("Please, install the iconset \"%(iconset)s\" first.") % \
              {'iconset':iconset_name}, "error")
    except:
      self.showAlert(_("This is not a valid MagIcons scheme!"), "error")
    self.inst_scheme_window.destroy()
    self.deleteTempFiles()
    if got_scheme == True:
      self.schemes_config = ConfigParser.ConfigParser()
      self.schemes_config.read(os.path.join(SETTINGS_PATH, 'schemes.dat'))
      self.getInstalledIcons()
      self.fillIconsetCombox()
      self.comb_iconset.set_active(self.getIconsetIndex(iconset_name))
      self.comb_scheme.set_active(self.getSchemeIndex(iconset_name, scheme_name))

  def closeInstallSchemeWin(self, widget=None, data=None):
    self.comb_scheme.set_active(self.lastscheme)
    self.inst_scheme_window.destroy()

  ################################################
  ########  Deleteing Schemes ####################

  def deleteScheme(self, widget=None, data=None, ics='', sch='', dont_ask=False):
    if ics != "" and sch != "":
      iconset = ics
      scheme = sch
      reload_after = False
    else:
      iconset = self.active_iconset_name
      scheme = self.active_scheme_name
      reload_after = True
    self.last_set = self.active_iconset_index
    alert = False
    if dont_ask == False:
      alerttext = _("Are you certain you want to uninstall \"%(scheme)s\"?") % {'scheme':scheme}
      alert = self.showAlert(alerttext, "question", question=True)
    if alert == True or dont_ask == True:
      print _("Deleting scheme \"%(scheme)s\" (iconset: \"%(iconset)s\")...") % \
            {'scheme':scheme, 'iconset':iconset}
      config = ConfigParser.RawConfigParser()
      filepath = os.path.join(SETTINGS_PATH, 'schemes.dat')
      config.read(filepath)
      config.remove_section(iconset+'_'+scheme)
      with open(filepath, 'wb') as configfile:
        config.write(configfile)
      self.schemes_config = config = ConfigParser.ConfigParser()
      self.schemes_config.read(os.path.join(SETTINGS_PATH, 'schemes.dat'))
      self.deleteCacheFiles(ics=iconset, sch=scheme)
      if reload_after == True:
        self.getInstalledIcons()
        self.fillIconsetCombox()
        self.comb_iconset.set_active(self.last_set)

  ################################################
  ########  Active scheme window (text mode) #####
  
  def showActiveSchemeWindow(self, widget=None):
    if self.comb_scheme.get_active() >= 0:
      name_of_scheme = self.comb_scheme.get_active_text()
      if name_of_scheme != '':
        windowname="ShowSchemeWindow"
        self.wTreeActiveSch=gtk.glade.XML(self.gladefile,windowname)
        show_sch_dic = { \
                "on_close_scheme_win"  : self.closeSchemeWin \
              }
        self.wTreeActiveSch.signal_autoconnect(show_sch_dic)
        self.show_scheme_window = self.wTreeActiveSch.get_widget(windowname)
        text = self.collectSchemeData(name_of_scheme)
        schemebuffer = gtk.TextBuffer(None)
        schemebuffer.set_text(text)
        scheme_text = self.wTreeActiveSch.get_widget('scheme_text')
        scheme_text.set_buffer(schemebuffer)
        self.show_scheme_window.show()
      else:
        self.showAlert(_("Please, specify a name for your scheme."), "info")
    else: self.showAlert(_("Please, save your current scheme first."), "info")

  def closeSchemeWin(self, widget=None, data=None):
    self.show_scheme_window.destroy()

  ################################################
  ########  About window #########################

  def showAboutWindow(self, widget=None):
    windowname="AboutWindow"
    self.wTreeInstSch=gtk.glade.XML(self.gladefile,windowname)
    about_dic = { \
            "on_close_about_win"  : self.closeAboutWin \
          }
    self.wTreeInstSch.signal_autoconnect(about_dic)
    self.about_window = self.wTreeInstSch.get_widget(windowname)
    self.about_window.show()

  def closeAboutWin(self, widget=None, data=None):
    self.about_window.destroy()

  ################################################
  ########  Alert window #########################
  
  def showAlert(self, alert_text, image='error', question=False):
    print _("Alert:\n%(alerttext)s") % {'alerttext':alert_text}
    windowname="AlertWindow"
    wTree=gtk.glade.XML(self.gladefile,windowname)
    alert_dic = {}
    wTree.signal_autoconnect(alert_dic)
    alert_window = wTree.get_widget(windowname)
    ok_button = alert_window.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
    if question == True:
      cancel_button = alert_window.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
    text = wTree.get_widget("alert_text")
    text.set_text(alert_text)
    img = wTree.get_widget("alertimage")
    if image == 'ok':
      img.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_DIALOG)
    elif image == 'info':
      img.set_from_stock(gtk.STOCK_DIALOG_INFO, gtk.ICON_SIZE_DIALOG)
    elif image == 'question':
      img.set_from_stock(gtk.STOCK_DIALOG_QUESTION, gtk.ICON_SIZE_DIALOG)
    else:
      img.set_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_DIALOG)
    if alert_window.run() == gtk.RESPONSE_OK:
      alert_window.destroy()
      return True
    else:
      alert_window.destroy()
      return False

  ################################################
  ########  File-open Window #####################

  def dialog_file_open(self, filter_pattern=None, filter_name=None, curr_folder=None):
    chooser = gtk.FileChooserDialog( title = _("Open"),
                          parent=self.window,
                          action=gtk.FILE_CHOOSER_ACTION_OPEN,
                          buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK) )
    chooser.set_current_folder(curr_folder)
    if filter_pattern != None:
      filter = gtk.FileFilter()
      filter.set_name(filter_name)
      filter.add_pattern(filter_pattern)
      chooser.add_filter(filter)
    if chooser.run() == gtk.RESPONSE_OK:
      filepath = chooser.get_filename()
      chooser.destroy()
      return filepath
    else:
      chooser.destroy()
      return None

  ################################################
  ########  File-save Window #####################

  def dialog_file_save_as(self, filename=None, filter_pattern=None, filter_name=None, curr_folder = None):
    chooser = gtk.FileChooserDialog( title = _("Save as"),
                                     parent=self.window,
                                     action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                     buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK) )
    if curr_folder == None or os.path.isdir(curr_folder) == False:
      chooser.set_current_folder(os.path.expanduser('~'))
    else:
      chooser.set_current_folder(curr_folder)
    if filename != None:
      chooser.set_current_name(filename)
    if filter_pattern != None:
      filter = gtk.FileFilter()
      filter.set_name(filter_name)
      filter.add_pattern(filter_pattern)
      chooser.add_filter(filter)
    filter_all = gtk.FileFilter()
    filter_all.set_name('all (*.*)')
    filter_all.add_pattern('*.*')
    chooser.add_filter(filter_all)
    if chooser.run() == gtk.RESPONSE_OK:
      filepath = chooser.get_filename()
      extension = filter_pattern[1:]
      if filepath.find(extension) < 0:
        a, b = os.path.splitext(filepath)
        filepath = a+extension
      if os.path.isfile(filepath):
        chooser.destroy()
        alerttext = _("A file called \n\"%(file)s\" \nalready exists. Do you want to replace the existing file?") % {'file':os.path.basename(filepath)}
        alert = self.showAlert(alerttext, "question", question=True)
        if alert == True:
          return filepath
        else:
          return None
      else:
        chooser.destroy()
        return filepath
    else:
      chooser.destroy()
      return None

  ################################################
  ########  scheme name Window ###################

  def inputName(self, value=''):
    windowname="SchemeNameWindow"
    wTree = gtk.glade.XML(self.gladefile,windowname)
    dialog = wTree.get_widget(windowname)
    entry = wTree.get_widget("name_entry")
    entry.set_text(value)
    cancel_button = dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
    ok_button = dialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
    ok_button.set_sensitive(False)
    def nameFieldChanged(widget=None, event=None, data=None):
      if entry.get_text() == "":
        ok_button.set_sensitive(False)
      else:
        ok_button.set_sensitive(True) 
    win_dic = {"on_name_field_changed": nameFieldChanged}
    wTree.signal_autoconnect(win_dic)
    # Anzeigen und zurueck geben
    if dialog.run() == gtk.RESPONSE_OK:
      retval = entry.get_text()
      dialog.destroy()
      if retval == None: retval = ''
      return retval
    else:
      self.sensitiveButtons(delete_scheme=False)
      dialog.destroy()
      return ''

  ################################################
  ########  Saving and applying iconsets #########

  def installAndApplyScheme(self, widget=None, iconset='', scheme=''):
    if iconset == '':
      iconset = self.active_iconset_name
    if scheme == '':
      scheme = self.active_scheme_name
    if scheme == '':
      scheme = self.schemeNameWin()
    if scheme != '':
      self.saveToDisc(None, LOCAL_ICON_PATH, iconset, scheme)
      # Now activating the scheme in system
      client = gconf.client_get_default ()
      client.add_dir ("/desktop/gnome/interface/icon_theme",gconf.CLIENT_PRELOAD_NONE)
      client.set_string ("/desktop/gnome/interface/icon_theme", APP_NAME)
      alert = self.showAlert(_("The iconset has been applied."), 'ok')


  def saveToDisc(self, widget=None, destpath='', iconset='', scheme=''):
    self.deleteTempFiles()
    if iconset == '':
      iconset = self.active_iconset_name
    if scheme == '':
      scheme = self.active_scheme_name
    if scheme == '':
      scheme = self.schemeNameWin()
    if scheme != '':
      if destpath == '': 
        filesavestring = self.dialog_file_save_as(filename=iconset+'_'+scheme+'.tar.bz2', 
                                              filter_pattern="*.tar.bz2",
                                              filter_name="MagIcons Iconset (*.tar.bz2)",
                                              curr_folder=os.path.expanduser('~'))
        if filesavestring != None:
          if filesavestring[-1:] == '/': filesavestring = filesavestring[:-1]
          destpath = os.path.dirname(filesavestring)
          destext  = os.path.splitext(os.path.splitext(filesavestring)[0])[1]+os.path.splitext(filesavestring)[1]
          if len(destext) > 0: destname = os.path.basename(filesavestring)[:-len(destext)]
          else:                destname = os.path.basename(filesavestring)
      else: 
        destext = ''
        destname = APP_NAME
      if destpath != '':
        iconset_new_path = os.path.join(destpath, destname)
        iconset_tmp_path = os.path.join(TEMP_PATH, destname)
        iconset_path = self.all_icons[iconset]['path']
        shutil.copytree(iconset_path, iconset_tmp_path, True)
        self.colors_dict = self.getColors(iconset, scheme)
        self.icon_errors = []
        functions.dirwalker(iconset_tmp_path, self.prae_iconcreate)
        if len(self.icon_errors) > 0:
          text = _("The following icons produced errors. Please check their integrity:\n")
          for error in self.icon_errors:
            text += "\n"+error
          #self.showAlert(text)  #TODO: disable this in perferences
          print text
        try:
          # Edit the index.theme file
          indexpath = os.path.join(iconset_tmp_path, 'index.theme')
          indexfile = open(indexpath, 'r')
          indextext = indexfile.read()
          indexfile.close()
          indextext = indextext.replace(iconset, destname)
          indexfile = open(indexpath, 'w')
          indexfile.write(indextext)
          indexfile.close()
        except:
          self.showAlert(_("An error occured while creating the \"index.theme\" file."), "error")
          pass
        if destpath != LOCAL_ICON_PATH:
          # Creating the *.tar.bz2
          dst = iconset_tmp_path+'.tar.bz2'
          out = tarfile.TarFile.open(dst, 'w:bz2')
          out.add(iconset_tmp_path, arcname=destname)
          out.close()
          shutil.copy(iconset_tmp_path+'.tar.bz2', iconset_new_path+'.tar.bz2')
          self.deleteTempFiles()
          saved_path = iconset_new_path+'.tar.bz2'
          self.showAlert(_("The iconset has been saved to:\n\"%(path)s\"") % {'path':saved_path}, "ok")
        else:
          if os.path.isdir(iconset_new_path):
            if self.actualSystemIcons() == APP_NAME:
              client = gconf.client_get_default ()
              client.add_dir ("/desktop/gnome/interface/icon_theme",gconf.CLIENT_PRELOAD_NONE)
              client.set_string ("/desktop/gnome/interface/icon_theme", "default")
            shutil.rmtree(iconset_new_path, ignore_errors=True)
          shutil.copytree(iconset_tmp_path, iconset_new_path, True)
          self.deleteTempFiles()
        return True


  ################################################
  ########  Installing iconsets ##################

  def installIconset(self, widget=None):
    filepath = self.dialog_file_open(filter_pattern="*.tar.bz2",
                          filter_name="MagIcons Iconset (*.tar.bz2)",
                          curr_folder=os.path.expanduser('~'))
    if filepath != None:
      self.deleteTempFiles()
      print _("Installing a new iconset...")
      foldername = os.path.dirname(filepath)
      filename =  os.path.basename(filepath)
      temptar =  os.path.join(TEMP_PATH, filename)
      shutil.copy(filepath, temptar)
      cwd = os.getcwd()
      os.chdir(TEMP_PATH)
      tar = tarfile.open(temptar)
      tar.extractall()
      tar.close()
      os.chdir(cwd)
      new_iconset_name = ''
      for files in os.listdir(TEMP_PATH):
        if os.path.isdir(os.path.join(TEMP_PATH, files)) == True:
          new_iconset_name = files
          break
      if new_iconset_name != '':
        installdir = os.path.join(PRIVATE_PATH, 'iconsets', new_iconset_name)
        if os.path.isfile(os.path.join(TEMP_PATH, new_iconset_name, 'index.theme')) \
                 and os.path.isfile(os.path.join(TEMP_PATH, new_iconset_name, 'magicons.control')):
          # Check if iconset exists and needs to update
          tmp_config = ConfigParser.ConfigParser()
          tmp_config.read(os.path.join(TEMP_PATH, files, 'magicons.control'))
          if new_iconset_name in self.all_icons:
            installed_version = self.all_icons[new_iconset_name]['version']
            this_version = tmp_config.get('iconset', 'version')
            if this_version != installed_version and os.path.isdir(installdir) == True:
              #print 'updating iconset)
              shutil.rmtree(installdir, ignore_errors=True)
          if os.path.isdir(os.path.join(PRIVATE_PATH, 'iconsets', new_iconset_name)) == False:
            shutil.copytree(os.path.join(TEMP_PATH, new_iconset_name), os.path.join(PRIVATE_PATH, 'iconsets', new_iconset_name), True)
            self.getInstalledIcons()
            self.fillIconsetCombox()
            self.showAlert(_("\"%(iconset)s\" was installed successfully!") % {'iconset':new_iconset_name}, 'ok')
            self.comb_iconset.set_active(self.getIconsetIndex(new_iconset_name))
          else:
            self.showAlert(_("This iconset is already installed!"), 'info')
        else:
          self.showAlert(_("This is not a valid MagIcons iconset!"), 'error')
      else:
        self.showAlert(_("This is not a valid MagIcons iconset!"), 'error')
      self.deleteTempFiles()
    else:
      if self.comb_iconset.get_active() == len(self.all_icons_order):
        self.comb_iconset.set_active(0)


  ################################################
  ########  Delete an Iconset ####################

  def deleteIconset(self, widget=None):
    if self.active_iconset_name != '':
      ics = self.active_iconset_name
      delete, keepschemes = self.deleteIconsetWindow(ics)
      if delete == True:
        if keepschemes == False:
          print _("Deleting all schemes for \"%(iconset)s\"..." % {'iconset':ics})
          for deletescheme in self.all_icons[ics]['schemes']:
            if self.all_icons[ics]['schemes'][deletescheme]['source'] == 'userfile':
              self.deleteScheme(widget=None, data=None, ics=ics, sch=deletescheme, dont_ask=True)
        print _("Deleting the iconset \"%(iconset)s\"..." % {'iconset':ics})
        path = self.all_icons[ics]['path']
        shutil.rmtree(path, ignore_errors=True)
        self.getInstalledIcons()
        self.fillIconsetCombox()
        self.deleteCacheFiles(ics=ics)

  def deleteIconsetWindow(self, ics):
    windowname="DeleteIconsetWindow"
    wTree = gtk.glade.XML(self.gladefile,windowname)
    win_dic = {}
    wTree.signal_autoconnect(win_dic)
    dialog = wTree.get_widget(windowname)
    keep_btn = wTree.get_widget("keep_schemes")
    text = wTree.get_widget("delete_iconset_label")
    text.set_text(_("Are you sure you want to uninstall \"%(iconset)s\" and all its schemes?") % \
                     {'iconset':ics})
    cancel_button = dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
    ok_button = dialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
    # Anzeigen und zurueck geben
    if dialog.run() == gtk.RESPONSE_OK:
      retval = keep_btn.get_active()
      dialog.destroy()
      return True, retval
    else:
      dialog.destroy()
      return False, True


  ################################################
  ########  Some further functions ###############

  # Get the index of an iconset
  def getIconsetIndex(self, ics):
    ics_index = 0
    for x in self.all_icons_order:
      if x[0] == ics:
        break
      ics_index += 1
    return ics_index

  # Get the index of a scheme 
  def getSchemeIndex(self, ics, sch):
    ics_index = self.getIconsetIndex(ics)
    sch_index = 0
    for x in self.all_icons_order[ics_index][1]:
      if x == sch:
        break
      sch_index += 1
    return sch_index

  # A scheme has been modified
  def colorChanged(self, widget=None):
    if self.isdirty == False:
      self.comb_scheme.set_active(-1)
      self.active_scheme_name = ''
      self.sensitiveButtons(save_scheme=True, delete_scheme=False)
      if self.refresh_state == True:
        self.buttonShowPreview(widget)

  # Control the "auto refresh" button
  def autoRefreshToggle(self, widget=None):
    refresh_button = self.wTreeMain.get_widget("refresh")
    self.refresh_state = self.wTreeMain.get_widget("autorefresh").get_active()
    if self.refresh_state == True:
      refresh_button.set_sensitive(False)
    else:
      refresh_button.set_sensitive(True)

  # Delete old temporary-files
  def deleteTempFiles(self):
    print _("Cleaning up...")
    for files in os.listdir(TEMP_PATH):
      if os.path.isfile(os.path.join(TEMP_PATH, files)) == True:
        os.remove(os.path.join(TEMP_PATH, files))
      else:
        shutil.rmtree(os.path.join(TEMP_PATH, files), ignore_errors=True)

  # Delete cache-files
  def deleteCacheFiles(self, ics=None, sch=None, clean_all=False):
    for files in os.listdir(CACHE_PATH):
      if ics and sch:
        if files[:len(ics+'_'+sch)] == ics+'_'+sch:
          if os.path.isfile(os.path.join(CACHE_PATH, files)) == True:
            os.remove(os.path.join(CACHE_PATH, files))
      elif ics:
        if files[:len(ics)] == ics:
          if os.path.isfile(os.path.join(CACHE_PATH, files)) == True:
            os.remove(os.path.join(CACHE_PATH, files))
      if clean_all == True:
        os.remove(os.path.join(CACHE_PATH, files))


  # Which iconscheme is actually in use by the OS?
  def actualSystemIcons(self):
    client = gconf.client_get_default ()
    in_use = client.get_string ("/desktop/gnome/interface/icon_theme")
    return in_use

  # Control the sensitivity of the buttons and menuelements
  def sensitiveButtons(self, **kwargs):
    for key in kwargs:
      if key == 'save_scheme': 
        safebutton = self.wTreeMain.get_widget('save_scheme')
        safemenu = self.wTreeMain.get_widget('menu_save_scheme')
        safebutton.set_sensitive(kwargs[key])
        safemenu.set_sensitive(kwargs[key])
      if key == 'delete_scheme': 
        deletebutton = self.wTreeMain.get_widget('delete_scheme')
        deletemenu = self.wTreeMain.get_widget('menu_delete_scheme')
        deletebutton.set_sensitive(kwargs[key])
        deletemenu.set_sensitive(kwargs[key])
      if key == 'uninstall_set': 
        uninstallmenu = self.wTreeMain.get_widget('menu_uninstall_iconset')
        uninstallmenu.set_sensitive(kwargs[key])

  # Print all available iconsets to the combobox
  def fillIconsetCombox(self):
    self.isdirty = True
    self.comb_iconset = self.wTreeMain.get_widget("comb_iconset")
    for number in range(len(self.all_icons_order)+2):
      self.comb_iconset.remove_text(0)
    for iconset in self.all_icons_order:
      name = iconset[0]
      self.comb_iconset.append_text(name)
    self.comb_iconset.append_text(_("Install iconset..."))
    self.comb_iconset.set_active(0)
    self.isdirty = False

  # Clear and hide all manipulating-fields (on choosing another iconset)
  def clearFields(self):
    # clear the color buttons
    for number in range(10):
      col_button = self.wTreeMain.get_widget('colorbutton_'+str(number+1))
      col_label = self.wTreeMain.get_widget('colorlabel_'+str(number+1))
      col_button.hide()
      col_label.set_text('')
      col_label.hide()
    # clear the switcher buttons
    for number in range(5):
      sw_button = self.wTreeMain.get_widget('sw_button_'+str(number+1))
      sw_label = self.wTreeMain.get_widget('sw_label_'+str(number+1))
      sw_button.hide()
      sw_label.set_text('')
      sw_label.hide()
    # clear png settings
    col_button_png = self.wTreeMain.get_widget('colorbutton_png')
    col_button_png.hide()
    col_label_png = self.wTreeMain.get_widget('colorlabel_png')
    col_label_png.hide()
    con_label_png = self.wTreeMain.get_widget('contrastlabel_png')
    con_label_png.hide()
    con_scale_png = self.wTreeMain.get_widget('contrastscale_png')
    con_scale_png.hide()
    sat_label_png = self.wTreeMain.get_widget('saturationlabel_png')
    sat_label_png.hide()
    sat_scale_png = self.wTreeMain.get_widget('saturationscale_png')
    sat_scale_png.hide()
    # clear the scheme combobox
    self.isdirty = True
    self.comb_scheme = self.wTreeMain.get_widget("comb_scheme")
    for number in range(100):
      self.comb_scheme.remove_text(0)
    self.isdirty = False
    # clear the about text
    aboutentries = ('head','ver0', 'ver1', 'aut0', 'aut1', 'lic0', 'lic1', 'abo0', 'abo1')
    for word in aboutentries:
      exec('self.about_text_'+word+' = self.wTreeMain.get_widget(\"about_text_'+word+'\")')
      eval('self.about_text_'+word+'.set_text(\"\")')

  # Change the background color in the preview area
  def backgroundChanged(self, widget=None, color='', width=0):
    if color == '':
      color_number = self.wTreeMain.get_widget("bg_colorbutton").get_color()
      color_number = str(color_number)[1:]
      color_number = functions.cleanColorString(color_number)
    else:
      color_number = color
      self.wTreeMain.get_widget("bg_colorbutton").set_color(gtk.gdk.color_parse('#'+color_number))
    if width == 0: width = 1000
    bg_newimage = Image.new("RGB", (width, 100), '#'+color_number)
    bg_image = self.wTreeMain.get_widget("preview_background")
    new_bg_image = functions.image2pixbuf(bg_newimage)
    bg_image.set_from_pixbuf(new_bg_image)
    if self.magicons_config.get('config', 'background') != color_number:
      config = ConfigParser.RawConfigParser()
      filepath = os.path.join(SETTINGS_PATH, 'magicons.dat')
      config.read(filepath)
      config.set('config', 'background', color_number)
      with open(filepath, 'wb') as configfile:
        config.write(configfile)
    self.magicons_config.read(os.path.join(SETTINGS_PATH, 'magicons.dat'))

  # Creating the sliced Iconset-Icon
  def drawSlicedIcon(self):
    if not os.path.isfile(os.path.join(CACHE_PATH, self.active_iconset_name+'.png')):
      file0 = None
      file1 = None
      file2 = None
      file3 = None
      i = 0
      for sch in self.all_icons_order[self.getIconsetIndex(self.active_iconset_name)][1]:
        self.createPreviewIcons(self.active_iconset_name, sch, False)
        i += 1
        if i >= 4:
          break
      filext = '.png'
      if os.path.isfile(os.path.join(CACHE_PATH, self.active_iconset_name+'_'+self.all_icons_order[self.getIconsetIndex(self.active_iconset_name)][1][1]+'_prev1.svg')):
        filext = '.svg'
      i = 0
      for sch in self.all_icons_order[self.getIconsetIndex(self.active_iconset_name)][1]:
        exec('file'+str(i)+' = os.path.join(CACHE_PATH, self.active_iconset_name+\'_\'+self.all_icons_order[self.getIconsetIndex(self.active_iconset_name)][1]['+str(i)+']+\'_prev1\'+filext)')
        i += 1
        if i >= 4:
          break
      destination = os.path.join(CACHE_PATH, self.active_iconset_name+'.png')
      slice_icon = MI_Iconcut.Iconcut(destination, file0, file1, file2, file3, size=48)
    if os.path.isfile(os.path.join(CACHE_PATH, self.active_iconset_name+'.png')):
      iconset_image = gtk.gdk.pixbuf_new_from_file(os.path.join(CACHE_PATH, self.active_iconset_name+'.png'))
      iconset_image_field = self.wTreeMain.get_widget('iconset_image')
      iconset_image_field.set_from_pixbuf(iconset_image)
      self.window.set_icon_from_file(os.path.join(CACHE_PATH, self.active_iconset_name+'.png'))

  # Resizing the window
  def windowResize(self, widget=None, enforce=False):
    if self.expander_collapsed == True:
      self.window.resize(self.new_width, self.unexp_height)
      self.expander_collapsed = False
    self.last_width, self.last_height = self.new_width, self.new_height
    self.new_width, self.new_height = self.window.get_size()
    if self.last_width != self.new_width or enforce == True:
      sizeborder = self.wTreeMain.get_widget("preview_area")
      rect = sizeborder.get_allocation()
      prev_space = rect[2]
      pitch = abs(prev_space/(2*self.preview_ammount))
      for i in range(self.preview_ammount):
        exec("img"+str(i+1)+" = self.wTreeMain.get_widget(\"preview_image_"+str(i+1)+"\")")
        exec("sizeborder.move(img"+str(i+1)+", "+str(2*(i+1)-1)+"*pitch-24, 9)")
      if self.wTreeMain.get_widget("about_expander").get_expanded() == True:
        sizeborder = self.wTreeMain.get_widget("about_text_abo0")
        rect = sizeborder.get_allocation()
        about_width = self.window.get_size()[0] - rect[2] - 55
        self.setInfoText(width=about_width)
    return True

  def area_expose_preview_cb(self, area, event):
    self.windowResize(enforce=True)
    return True

  def expanderChange(self, widget=None, data=None):
    expander = self.wTreeMain.get_widget("about_expander")
    if expander.get_expanded() == True:
      self.expander_collapsed = True
    else:
      width, self.unexp_height = self.window.get_size()


  def doUpdateStuff(self):
    v_old = 'xxx'
    if self.magicons_config.has_option('config', 'MagIcons_Version'):
      v_old = self.magicons_config.get('config', 'MagIcons_Version')
    if v_old != __version__:
      ## Do the following!
      self.deleteCacheFiles(clean_all=True)
      
      ## Rewrite config
      config = ConfigParser.RawConfigParser()
      filepath = os.path.join(SETTINGS_PATH, 'magicons.dat')
      config.read(filepath)
      config.set('config', 'MagIcons_Version', __version__)
      with open(filepath, 'wb') as configfile:
        config.write(configfile)
      self.magicons_config.read(os.path.join(SETTINGS_PATH, 'magicons.dat'))

  ################################################
  ########  START ################################

  def main(self):
    gtk.main()

if __name__ == "__main__":
  magicons = MagIcons()
  magicons.main()

