#!/usr/bin/env python
# encoding=utf-8

##    Qemulator 0.4.4 - a qemu gui written in python and GTK/Glade.
##    Copyright (C) 2006  rainer haage
##
##    This program 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 2
##    of the License, or (at your option) any later version.
##    
##    This program 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, write to the Free Software
##    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import sys
import os
from os import path
import popen2
from popen2 import Popen3
import gobject
import gettext
import string
import pickle
import time
import threading
from threading import Thread
import shutil
import webbrowser


#from shared import Shared
try:
    from egg import trayicon
    nognomextras = False
except :
    nognomextras = True
#nognomextras = True


import re
from copy import copy
from copy import deepcopy

try:
    import gettext
    import locale
except:
    print "locale and/or gettext for language support not installed"
    sys.exit(1)


try:
    import pygtk
    pygtk.require("2.0")
    
except:
      print "pygtk 2.0 is not installed"
try:
    import gtk
    import gtk.glade
    gtk.gdk.threads_init()
    
except:
    print "gtk and/or glade is not installed - exiting..."
    sys.exit(1)
    
encoding = locale.getpreferredencoding()
utf8conv = lambda x : unicode(x, encoding).encode('utf8')
    
#for param in os.environ.keys():
#    print "%20s %s" % (param,os.environ[param])
    
current_path = os.path.realpath(__file__)
basedir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(basedir, "main.py")):
    if os.path.exists(os.path.join(os.getcwd(), "main.py")):
        basedir = os.getcwd()
sys.path.insert(0, basedir)
os.chdir(basedir)  
#print "basedir: " + basedir
basedir = basedir.replace ( '/bin', '' ) 
basedir = basedir.replace ( '/lib/qemulator', '' ) 
sys.path.append(basedir)   
bindir = basedir + "/bin"
#print "bindir: " + bindir
libdir = basedir + "/lib/qemulator"
#print "libdir: " + libdir
sharedir = basedir + "/share/qemulator"
#print "sharedir: " + sharedir
pixmapdir = basedir + "/share/pixmaps/qemulator"
#print "pixmapdir: " + pixmapdir     
homedir = os.path.expanduser('~/.qemulator')
configdir = homedir + "/config"
#print "configdir: " + configdir           
icondirs = [sharedir + "/icons",homedir + "/icons"] 

## Import all Qemulator classes 
import qml_network
import qml_controlmon
import qml_ptsmanager
#import qml_runqemu
import qml_configuration     
import qml_filehandlers
import qml_style
import qml_tools
#import qml_installwizzard
from qml_installwizzard import Installwizzard
from qml_machinesetup import Machinesetup
 
from qml_imagecreation import CreateImage
#import qml_imagecreation
#import qml_audioenviron
from qml_audioenviron import Audio_environment
#from Run_Defaultapp import BaseController

APP = 'Qemulator'
#DIR = 'locale'
DIR = basedir + '/share/locale'
#print "DIR: " + DIR
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
_ = gettext.gettext

gtk.glade.bindtextdomain(APP, DIR)
gtk.glade.textdomain(APP)
tooltips = gtk.Tooltips() 

#print "home: " + os.environ["HOME"]

def storetofile(indata, filename):
    #print "storefile: " + filename
    dumpf = open(configdir + "/" + filename ,"w")        
    pickle.dump(indata, dumpf)
    dumpf.close()
    
## Universal Function to open the pickle'd configfiles        
def getfromfile(filename):
    try:
        abs_path = path.abspath(configdir + "/" + filename)  
        dumpf = open( abs_path ,"r")       
        outdata = pickle.load(dumpf)
        dumpf.close()
        return outdata        
    except:
        outdata  = { }
        print "File not found: " + str(filename)
        return outdata
    
class Splashscreen ( Thread ):

    def __init__ (self):
        Thread.__init__(self) 
        self.gladefile = libdir + "/qemulator.glade"

    def init_gui(self):
        logo_file = None
        logo_file = pixmapdir + "/splashscreen05.png"
        
        #gtk.gdk.threads_enter()
        self.wTree_splash = gtk.glade.XML(self.gladefile, "window_splashscreen", APP)
        self.window_splashscreen = self.wTree_splash.get_widget("window_splashscreen")
        self.image_splashscreen = self.wTree_splash.get_widget("image_splashscreen")
        self.progressbar_splashscreen = self.wTree_splash.get_widget("progressbar_splashscreen")
        self.label_progress_splashscreen = self.wTree_splash.get_widget("label_progress_splashscreen")                
        
        self.image_splashscreen.set_from_file( logo_file)
        gobject.timeout_add(15000, self.splash_destroy) # 5*1000 miliseconds
        #time.sleep(0.1)
        self.window_splashscreen.show()
        #gtk.gdk.threads_leave()     
        
    def run(self): 
        
        gtk.gdk.threads_enter()
        self.init_gui()
        gtk.gdk.threads_leave()
        
    def increase_progress(self, amount):
        self.progress = self.progress + amount
        #print "progress: " + str(self.progress)
        try:
            self.progressbar_splashscreen.set_fraction(self.progress) 
        except:
            pass

    def set_progress(self, amount):
        self.progress = amount
        #print "progress: " + str(self.progress)
        #gtk.gdk.threads_enter()
        try:
            self.progressbar_splashscreen.set_fraction(self.progress) 
        except:
            pass
        #gtk.gdk.threads_leave()
        
    def set_progresstext(self, text):
        #gtk.gdk.threads_enter()
        try:
            self.progressbar_splashscreen.set_text(text)
        except:
            pass

    def splash_destroy(self):
        self.window_splashscreen.destroy()
     

class Qemulator(Thread):

## Start main app ##################################
    def __init__(self, settings):
    #def __init__ (self,ip):
        Thread.__init__(self)
        self.currimage_settings = QemuConfig()
        self.sighandlers = {}
        self.basedir = basedir 
        #print "basedir: " + self.basedir 
        self.bindir = self.basedir + "/bin"
        self.libdir = self.basedir + "/lib/qemulator"
        self.sharedir = self.basedir + "/share/qemulator"
        self.pixmapdir = pixmapdir
        self.homedir = os.path.expanduser('~/.qemulator')
        self.configdir = self.homedir + "/config"           
        self.icondirs = [self.sharedir + "/icons",self.homedir + "/icons"]
        self.statefiles_dir = homedir + "/statefiles"
        self.screenshot_dir = homedir + "/screenshots"
        self.capture_dir = homedir + "/capture"
        self.gladefile = self.libdir + "/qemulator.glade"
        self.restoreaction = False
        self.currimage_settings.cdrmedium = ""
        self.imagespath = ""
        self.ilist_data = []
        self.default_machine_icon = self.icondirs[0] + "/default.png"
        self.currentimage = ""
        self.selected_bookmark = None
        self.statefile = None
        self.joblist_data = []
        self.machinecommand = ""
        self.jobmessage = []
        self.dorun = True
        self.doexit = False
        self.block_jobmon_update = False
        self.jobmanager = None
        self.hdcmode = 'hdc'
        self.settings_autoshow = True
        self.settings_autohide = True
        self.default_iconsize = 32  
        self.jobmanagers = {}
        self.image_settings  = None
        self.qemu_commandset = 'old'

        ## Instanciate used helper classes
        self.settings = settings
        self.traypop = None
        self.stateshandler = None
        self.sceenshothandler = None
        self.capturehandler = None 
        self.audioenviron = Audio_environment(self.apply_audioenv)
        
        self.qemu_version = qemu_version()
        print 'detected qemu_version: ' + str(self.qemu_version)
        if self.qemu_version >= '0.9.0':
            print 'qemu 0.9.x detected, using 0.9 command set'
            self.qemu_commandset = 'new'
        else:
            print 'detected an older qemu release, using 0.8 command set'
            self.qemu_commandset = 'old'             
            
    def run(self):        
        self.preload_gui()
        
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.2, _("Preloaded GUI"))
            gtk.gdk.threads_leave()
            time.sleep(0.2)
        
        self.image_settings  = QemuConfig()  
        self.jobwatcher = QemuWatcher(self.joblist.remove_job2)
        self.load_joblist()
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.3, _("Loaded joblist"))
            gtk.gdk.threads_leave()
            time.sleep(0.2)
            
        self.check_firstrun()
        
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.4, _("Check first run"))
            gtk.gdk.threads_leave()
            time.sleep(0.2)

        self.fetch_settings()
        
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.6, _("Loaded settings from file"))
            gtk.gdk.threads_leave()
            time.sleep(0.2)           

        self.init_imagesettings()  
            
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.8, _("Loaded image settings from file"))
            gtk.gdk.threads_leave()
            time.sleep(0.2)

        self.load_bookmarks()
        
        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(0.9, _("Loaded My machines from file"))
            gtk.gdk.threads_leave()
            time.sleep(0.2) 

        self.init_gui()

        if splashscreen != None:
            gtk.gdk.threads_enter()
            self.update_splashscreen(1.0, _("Qemulator started"))
            gtk.gdk.threads_leave()
            time.sleep(0.3)
            #gtk.gdk.threads_enter()
            #splashscreen.splash_hide()
            splashscreen.splash_destroy()
            #gtk.gdk.threads_leave()
        else:
            print "NO SPLASH!"
        
    def init_joblist(self): 
        self.joblist.jobmanagers = self.jobmanagers
        self.joblist.load_joblist()
        self.joblist.buildtree_joblist()
        
    def init_imagesettings(self):
        try:
            self.image_settings = getfromfile("image_settings")
            #self.cleanup_emu_settings()
        except:
            print "no image settings found"        
        
        
    def update_splashscreen(self, value, text=None):
        splashscreen.set_progress(value)
        if text != None:
            splashscreen.set_progresstext(text)
        
    def preload_gui(self):
        
        ## Init GUI
        gtk.gdk.threads_enter()
        self.wTree = gtk.glade.XML(self.gladefile, "window1", APP)
        self.vpaned_mainwindow = self.wTree.get_widget("vpaned_mainwindow")
        self.mainwindow = self.wTree.get_widget("window1")
        self.viewport_settings_hardware = self.wTree.get_widget("viewport_settings_hardware")
        
        self.filechooserdialogUniversal = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal")
        self.filechooserdialogUniversal.hide()
        self.sighandlers['filechooserdialogUniversal'] = self.filechooserdialogUniversal.connect("response",  self.on_filechooserdialogUniversal_response)
        #, "on_filechooserdialogUniversal_response" : self.on_filechooserdialogUniversal_response
        self.combobox_runmode = self.wTree.get_widget("combobox_runmode")
        self.toolbutton_launch = self.wTree.get_widget("toolbutton_launch")
        toolbutton_launch_style = qml_style.WidgetStyle(self.toolbutton_launch)
        toolbutton_launch_style.set_bg('#9AD08F')
        self.vbox_topane = self.wTree.get_widget("vbox_topane")
        self.vbox_bottompane = self.wTree.get_widget("vbox_bottompane")
        self.viewport_bottompane = self.wTree.get_widget("viewport_bottompane")
        
        self.logo_mainwindow = self.wTree.get_widget("logo_mainwindow")
        self.button_togglesettings = self.wTree.get_widget("button_togglesettings")
        self.checkbutton_autoshow_settings = self.wTree.get_widget("checkbutton_autoshow_settings")
        self.checkbutton_autohide_settings = self.wTree.get_widget("checkbutton_autohide_settings")
        
        self.menu_widgets_mainmenu = gtk.glade.XML(self.gladefile,"menubar1", APP)
        self.menu_mainmenu = self.menu_widgets_mainmenu.get_widget("menubar1")
        
        self.menu_widgets_settingsmenu = gtk.glade.XML(self.gladefile,"menuitem_edit_menu", APP)
        self.item_set_autohide = self.menu_widgets_settingsmenu.get_widget("item_set_autohide")
        self.item_set_autoshow = self.menu_widgets_settingsmenu.get_widget("item_set_autoshow")
        
        
        self.notebook_mainlists = self.wTree.get_widget("notebook_mainlists")
        
        self.isolist = self.wTree.get_widget("treeviewBootimages")
        self.treeviewBookmarks = self.wTree.get_widget("treeviewBookmarks")
        self.treeview_joblist = self.wTree.get_widget("treeview_joblist")
        self.treeviewCDdrives = self.wTree.get_widget("treeviewCDdrives")
        
        self.notebook_imgsettings = self.wTree.get_widget("notebook_imgsettings")
        
        ''' Widgets for general settings '''
        #self.comboboxImagedevice = self.wTree.get_widget("comboboxImagedevice")
        
        self.expanderCDrom = self.wTree.get_widget("expanderCDrom")
        self.comboboxCDromdrive = self.wTree.get_widget("comboboxCDromdrive")
        self.comboboxAudiohw = self.wTree.get_widget("comboboxAudiohw")
        self.comboboxEmusystem = self.wTree.get_widget("comboboxEmusystem")
        self.comboboxMachinetype = self.wTree.get_widget("comboboxMachinetype")

        #self.eventboxImagecdrom = self.wTree.get_widget("eventboxImagecdrom")
        #self.filechooserdialogImagecdrom = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal")      
        #self.filechooserdialogImagecdrom.set_name('filechooserdialogImagecdrom')
        #self.filechooserdialogImagecdrom.hide()

        #self.sighandlers['filechooserdialogImagecdrom'] = self.filechooserdialogImagecdrom.connect("response",  self.on_filechooserdialogImagecdrom_response)
        #self.sighandlers['filechooserdialogImagecdrom'] = self.filechooserdialogImagecdrom.connect("hide",  self.on_filechooserdialogImagecdrom_hide_event)

        #table13 = self.wTree.get_widget("table13")
        #self.filechooserbuttonImagecdrom = self.wTree.get_widget("filechooserbuttonImagecdrom")
        #table13.remove(self.filechooserbuttonImagecdrom)
        #self.eventboxImagecdrom.remove(self.filechooserbuttonImagecdrom)
        #self.filechooserbuttonImagecdrom = gtk.FileChooserButton(self.filechooserdialogImagecdrom)
        #table13.attach(self.filechooserbuttonImagecdrom, 0, 1, 4, 5, gtk.FILL)
        #self.eventboxImagecdrom.add(self.filechooserbuttonImagecdrom)
        #self.filechooserbuttonImagecdrom.show_all()
        
        self.filechooserdialogHDA = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal") 
        self.filechooserdialogHDA.set_name('filechooserdialogHDA')
        self.filechooserdialogHDA.hide()      
        #self.sighandlers['filechooserdialogHDA'] = self.filechooserdialogHDA.connect("response",  self.on_filechooserdialogHDA_response)

        self.sighandlers['filechooserdialogHDA'] = self.filechooserdialogHDA.connect("response",  self.on_filechooserdialogHDA_response)
        self.sighandlers['filechooserdialogHDA'] = self.filechooserdialogHDA.connect("hide",  self.on_filechooserdialogHDA_hide_event)
        
        #table5 = self.wTree.get_widget("table5")
        self.eventboxHDA = self.wTree.get_widget("eventboxHDA")
        self.filechooserbuttonHDA = self.wTree.get_widget("filechooserbuttonHDA")
        #table5.remove(self.filechooserbuttonHDA) 
        self.eventboxHDA.remove(self.filechooserbuttonHDA)
        self.filechooserbuttonHDA = gtk.FileChooserButton(self.filechooserdialogHDA)
        self.filechooserbuttonHDA.set_size_request(200, -1)
        #self.filechooserbuttonHDA.set_
        #table5.attach(self.filechooserbuttonHDA, 1, 2, 0, 1, gtk.FILL, gtk.FILL)
        self.eventboxHDA.add(self.filechooserbuttonHDA)
        self.filechooserbuttonHDA.show_all()

        self.eventboxHDB = self.wTree.get_widget("eventboxHDB")
        self.filechooserdialogHDB = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal")
        self.filechooserdialogHDB.set_name('filechooserdialogHDB')
        self.filechooserdialogHDB.hide()      
        self.sighandlers['filechooserdialogHDB'] = self.filechooserdialogHDB.connect("response",  self.on_filechooserdialogHDB_response)
        
        #self.sighandlers['filechooserdialogHDA'] = self.filechooserdialogHDA.connect("response",  self.on_filechooserdialogHDA_response)
        self.sighandlers['filechooserdialogHDB'] = self.filechooserdialogHDB.connect("hide",  self.on_filechooserdialogHDB_hide_event)        
        
        #table5 = self.wTree.get_widget("table5")
        self.filechooserbuttonHDB = self.wTree.get_widget("filechooserbuttonHDB")
        #table5.remove(self.filechooserbuttonHDB) 
        self.eventboxHDB.remove(self.filechooserbuttonHDB)
        self.filechooserbuttonHDB = gtk.FileChooserButton(self.filechooserdialogHDB)
        #table5.attach(self.filechooserbuttonHDB, 1, 2, 1, 2, gtk.FILL, gtk.FILL)
        self.eventboxHDB.add(self.filechooserbuttonHDB)
        self.filechooserbuttonHDB.show_all()
        
        self.filechooserdialogHDC = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal")  
        self.filechooserdialogHDC.set_name('filechooserbuttonHDC')
        self.filechooserdialogHDC.hide()      
        self.sighandlers['filechooserdialogHDC'] = self.filechooserdialogHDC.connect("response",  self.on_filechooserdialogHDC_response)
        self.sighandlers['filechooserdialogHDC'] = self.filechooserdialogHDC.connect("hide",  self.on_filechooserdialogHDC_hide_event)
        
        #table5 = self.wTree.get_widget("table5")
        self.iconHDC = self.wTree.get_widget("iconHDC")
        self.eventboxHDC = self.wTree.get_widget("eventboxHDC")
        self.filechooserbuttonHDC = self.wTree.get_widget("filechooserbuttonHDC")
        #table5.remove(self.filechooserbuttonHDC) 
        self.eventboxHDC.remove(self.filechooserbuttonHDC)
        self.filechooserbuttonHDC = gtk.FileChooserButton(self.filechooserdialogHDC)
       # table5.attach(self.filechooserbuttonHDC, 1, 2, 2, 3, gtk.FILL, gtk.FILL)
        self.eventboxHDC.add(self.filechooserbuttonHDC)
        self.filechooserbuttonHDC.show_all()        
                
        #self.filechooserbuttonHDC = self.wTree.get_widget("filechooserbuttonHDC")
        
        self.eventboxHDD = self.wTree.get_widget("eventboxHDD")
        self.filechooserdialogHDD = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal") 
        self.filechooserdialogHDD.set_name('filechooserdialogHDD')
        self.filechooserdialogHDD.hide()      
        self.sighandlers['filechooserdialogHDD'] = self.filechooserdialogHDD.connect("response",  self.on_filechooserdialogHDD_response)
        self.sighandlers['filechooserdialogHDD'] = self.filechooserdialogHDD.connect("hide",  self.on_filechooserdialogHDD_hide_event)
        
        #table5 = self.wTree.get_widget("table5")
        self.filechooserbuttonHDD = self.wTree.get_widget("filechooserbuttonHDD")
        #table5.remove(self.filechooserbuttonHDD) 
        self.eventboxHDD.remove(self.filechooserbuttonHDD)
        self.filechooserbuttonHDD = gtk.FileChooserButton(self.filechooserdialogHDD)
        #table5.attach(self.filechooserbuttonHDD, 1, 2, 3, 4, gtk.FILL, gtk.FILL)        
        self.eventboxHDD.add(self.filechooserbuttonHDD)
        self.filechooserbuttonHDD.show_all()
        
        #self.filechooserbuttonHDD = self.wTree.get_widget("filechooserbuttonHDD")
        
        
        self.filechooserdialogFDA = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal")
        self.filechooserdialogFDA.set_name('filechooserdialogFDA')
        self.filechooserdialogFDA.hide()      
        self.sighandlers['filechooserdialogFDA'] = self.filechooserdialogFDA.connect("response",  self.on_filechooserdialogFDA_response)
        self.sighandlers['filechooserdialogFDA'] = self.filechooserdialogFDA.connect("hide",  self.on_filechooserdialogFDA_hide_event)
        
        #table5 = self.wTree.get_widget("table5")
        self.eventboxFDA = self.wTree.get_widget("eventboxFDA")
        self.filechooserbuttonFDA = self.wTree.get_widget("filechooserbuttonFDA")
        #table5.remove(self.filechooserbuttonFDA) 
        self.eventboxFDA.remove(self.filechooserbuttonFDA)
        self.filechooserbuttonFDA = gtk.FileChooserButton(self.filechooserdialogFDA)
        #table5.attach(self.filechooserbuttonFDA, 1, 2, 4, 5, gtk.FILL, gtk.FILL)        
        self.eventboxFDA.add(self.filechooserbuttonFDA)
        self.filechooserbuttonFDA.show_all()        
        
        #self.filechooserbuttonFDA = self.wTree.get_widget("filechooserbuttonFDA")
        
        
        self.filechooserdialogFDB = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP).get_widget("filechooserdialogUniversal") 
        self.filechooserdialogFDB.set_name('filechooserdialogFDB')
        self.filechooserdialogFDB.hide()      
        self.sighandlers['filechooserdialogFDB'] = self.filechooserdialogFDB.connect("response",  self.on_filechooserdialogFDB_response)
        self.sighandlers['filechooserdialogFDB'] = self.filechooserdialogFDB.connect("hide",  self.on_filechooserdialogFDB_hide_event)
        self.eventboxFDB = self.wTree.get_widget("eventboxFDB")
        #table5 = self.wTree.get_widget("table5")
        self.filechooserbuttonFDB = self.wTree.get_widget("filechooserbuttonFDB")
        #table5.remove(self.filechooserbuttonFDB) 
        self.eventboxFDB.remove(self.filechooserbuttonFDB)
        self.filechooserbuttonFDB = gtk.FileChooserButton(self.filechooserdialogFDB)
        #self.filechooserbuttonFDB.
        #table5.attach(self.filechooserbuttonFDB, 1, 2, 5, 6, gtk.FILL, gtk.FILL)         
        self.eventboxFDB.add(self.filechooserbuttonFDB)
        self.filechooserbuttonFDB.show_all()
        
        #self.filechooserbuttonFDB = self.wTree.get_widget("filechooserbuttonFDB") 
        self.comboboxMediatypeHDC = self.wTree.get_widget("comboboxMediatypeHDC")
        
        self.button_eject_imagecdrom = self.wTree.get_widget("button_eject_imagecdrom")
        self.button_eject_hda = self.wTree.get_widget("button_eject_hda")
        self.button_eject_hdb = self.wTree.get_widget("button_eject_hdb")
        self.button_eject_hdc = self.wTree.get_widget("button_eject_hdc")
        self.button_eject_hdd = self.wTree.get_widget("button_eject_hdd")
        self.button_eject_fda = self.wTree.get_widget("button_eject_fda")
        self.button_eject_fdb = self.wTree.get_widget("button_eject_fdb") 
        self.button_eject_kernelimage = self.wTree.get_widget("button_eject_kernelimage") 
        self.button_eject_initrd = self.wTree.get_widget("button_eject_initrd")
        
        self.radiobuttonBootHDA = self.wTree.get_widget("radiobuttonBootHDA")
        self.radiobuttonBootHDC = self.wTree.get_widget("radiobuttonBootHDC")
        self.radiobuttonBootFDA = self.wTree.get_widget("radiobuttonBootFDA")
        self.radiobuttonBootDlinux = self.wTree.get_widget("radiobuttonBootDlinux")  
        
        self.radiobuttonCDromtype = self.wTree.get_widget("radiobuttonCDromtype")
        self.radiobuttonCDromtype1 = self.wTree.get_widget("radiobuttonCDromtype1")
        self.radiobuttonCDromtype2 = self.wTree.get_widget("radiobuttonCDromtype2")
        
        self.radiobuttonNokqemu = self.wTree.get_widget("radiobuttonNokqemu")
        self.radiobuttonKqemu = self.wTree.get_widget("radiobuttonKqemu") 
        self.radiobuttonKKqemu = self.wTree.get_widget("radiobuttonKKqemu") 
        self.button_show_commandline = self.wTree.get_widget("button_show_commandline") 
        
        # Widgets for the boot options
        self.expander_dlinuxboot = self.wTree.get_widget("expander_dlinuxboot")
        self.checkbuttonDlinuxboot = self.wTree.get_widget("checkbuttonDlinuxboot")
        self.frame_dlinuxboot = self.wTree.get_widget("frame_dlinuxboot")
        self.buttonHideDlinuxboot = self.wTree.get_widget("buttonHideDlinuxboot")
        self.filechooserbuttonKernelimage = self.wTree.get_widget("filechooserbuttonKernelimage")
        self.filechooserbuttonInitrd = self.wTree.get_widget("filechooserbuttonInitrd")
        self.entryKernelcmd = self.wTree.get_widget("entryKernelcmd")
        self.table_imagedevice = self.wTree.get_widget("table_imagedevice")
        self.checkbuttonSnapshotmode = self.wTree.get_widget("checkbuttonSnapshotmode")
        self.checkbuttonNoacpi = self.wTree.get_widget("checkbuttonNoacpi")
        self.checkbuttonNoreboot = self.wTree.get_widget("checkbuttonNoreboot")
        self.checkbuttonStartpaused = self.wTree.get_widget("checkbuttonStartpaused")
        
        self.checkbuttonUsevga = self.wTree.get_widget("checkbuttonUsevga") 
        self.checkbuttonNovga = self.wTree.get_widget("checkbuttonNovga") 
        self.checkbuttonFullscreen = self.wTree.get_widget("checkbuttonFullscreen")
        self.checkbuttonStartvnc = self.wTree.get_widget("checkbuttonStartvnc")
        self.checkbuttonEnableUSB = self.wTree.get_widget("checkbuttonEnableUSB")
                
        self.checkbuttonLocaltime = self.wTree.get_widget("checkbuttonLocaltime")
        
        self.spinbuttonVncdisplay = self.wTree.get_widget("spinbuttonVncdisplay")
        self.spinbuttonMemory = self.wTree.get_widget("spinbuttonMemory")
        
        ''' Widgets for extended settings '''
        self.entryRedirectSerial = self.wTree.get_widget("entryRedirectSerial")
        self.buttonClearSerial = self.wTree.get_widget("buttonClearSerial")        
        self.entryRedirectParallel = self.wTree.get_widget("entryRedirectParallel")
        self.buttonClearParallel = self.wTree.get_widget("buttonClearParallel")        
        self.button_audioenviron = self.wTree.get_widget("button_audioenviron")
        self.checkbuttonDefaultaudioenv = self.wTree.get_widget("checkbuttonDefaultaudioenv")
        self.spinbuttonCPUs = self.wTree.get_widget("spinbuttonCPUs")
        self.checkbuttonDaemonize = self.wTree.get_widget("checkbuttonDaemonize")
        self.entryPidfile = self.wTree.get_widget("entryPidfile")
        self.buttonClearPidfile = self.wTree.get_widget("buttonClearPidfile")
        self.checkbuttonWaitgdb = self.wTree.get_widget("checkbuttonWaitgdb")
        self.entryGdbport = self.wTree.get_widget("entryGdbport")
        self.buttonClearGdbport = self.wTree.get_widget("buttonClearGdbport")
        self.entryOptionrom = self.wTree.get_widget("entryOptionrom")
        self.buttonClearOptionrom = self.wTree.get_widget("buttonClearOptionrom")
        
        ''' general gui widgets ''' 
        self.modulewindow = self.wTree.get_widget("vbox2")
        self.button_openimage_cancel = self.wTree.get_widget("button_openimage_cancel")
        self.entry_current_image = self.wTree.get_widget("entry_current_image")
        
        self.entry_networkline = self.wTree.get_widget("entry_networkline")
        self.entryAdditionalCommandline = self.wTree.get_widget("entryAdditionalCommandline")
        
        self.toolbutton_add_bookmark = self.wTree.get_widget("toolbutton_add_bookmark")
        #self.toolbutton_remove_bookmark = self.wTree.get_widget("toolbutton_remove_bookmark")
        
        self.button_apply_imagesettings = self.wTree.get_widget("button_apply_imagesettings")
        self.button_restore_imagesettings = self.wTree.get_widget("button_restore_imagesettings")
        self.label_imgsettings = self.wTree.get_widget("label_imgsettings")
        self.menu_widgets_imagelist = gtk.glade.XML(self.gladefile,"menu_popup_imagelist", APP)
        self.menu_popup_imagelist = self.menu_widgets_imagelist.get_widget("menu_popup_imagelist")

        self.menu_widgets_devices = gtk.glade.XML(self.gladefile,"menu_popup_devices", APP)
        self.menu_popup_devices = self.menu_widgets_devices.get_widget("menu_popup_devices")        
        gtk.gdk.threads_leave()
        
        dic_menu_imagelist = {"on_item_info_activate" : self.show_infomessage
        , "on_item_bookmark_activate" : self.add_bookmark_from
        }
        self.menu_widgets_imagelist.signal_autoconnect(dic_menu_imagelist)
        
        #dic_menu_imagelist = {"on_item_info_activate" : self.show_infomessage
        #, "on_item_bookmark_activate" : self.add_bookmark
        #}
        self.menu_widgets_devices.signal_autoconnect(dic_menu_imagelist)
                
        gtk.gdk.threads_enter()
        self.menu_widgets_bookmarks = gtk.glade.XML(self.gladefile,"menu_popup_bookmarks", APP)
        self.menu_popup_bookmarks = self.menu_widgets_bookmarks.get_widget("menu_popup_bookmarks")
        self.item_show_settings = self.menu_widgets_bookmarks.get_widget("item_show_settings")
        self.item_hide_settings = self.menu_widgets_bookmarks.get_widget("item_hide_settings")
        gtk.gdk.threads_leave()
        dic_menu_bookmarks = {"on_bookmark_info_activate" : self.show_infomessage_bookmark
        , "on_delete_bookmark_activate" : self.on_delete_bookmark_activate
        , "on_edit_bookmark_activate" : self.edit_bookmark
        , "on_item_show_settings_activate" : self.show_settings
        , "on_item_hide_settings_activate" : self.hide_settings
        , "on_item_show_commandline_activate" : self.show_commandline_clicked
        }
        self.menu_widgets_bookmarks.signal_autoconnect(dic_menu_bookmarks)       
        gtk.gdk.threads_enter()
        self.menu_widgets_joblist = gtk.glade.XML(self.gladefile,"menu_popup_joblist", APP)
        self.menu_popup_joblist = self.menu_widgets_joblist.get_widget("menu_popup_joblist")
        self.item_stop_job = self.menu_widgets_joblist.get_widget("item_stop_job")
        self.item_cont_job = self.menu_widgets_joblist.get_widget("item_cont_job")
        self.item_reset_job = self.menu_widgets_joblist.get_widget("item_reset_job")
        self.item_kill_job = self.menu_widgets_joblist.get_widget("item_kill_job")
        gtk.gdk.threads_leave()
        dic_menu_joblist = {"on_item_jobmonoitor_activate" : self.run_jobmanager
        ,"on_item_stop_job_activate" : self.pause_job
        , "on_item_cont_job_activate" : self.cont_job
        #,"on_item_stop_job_activate" : self.jobmanagers[self.selected_job[1]].pause_job
        ,"on_item_reset_job_activate" : self.reset_job
        , "on_item_kill_job_activate" : self.stop_job        
        }
        self.menu_widgets_joblist.signal_autoconnect(dic_menu_joblist)      
        
        gtk.gdk.threads_enter()
        self.wTreePopupScreenshots = gtk.glade.XML(self.gladefile,"menu_popup_screenshots", APP)
        self.menu_popup_screenshots = self.wTreePopupScreenshots.get_widget("menu_popup_screenshots")
        self.item_use_as_icon = self.wTreePopupScreenshots.get_widget("item_use_as_icon")
        gtk.gdk.threads_leave()
        
        dic_menu_popup_screenshots = {"on_item_use_as_icon_activate" : self.scr2icon
        }
        self.wTreePopupScreenshots.signal_autoconnect(dic_menu_popup_screenshots)                

        # Network widgets
        gtk.gdk.threads_enter()
        
        
        #self.wTree.get_data()
        self.frame_network_usermode = self.wTree.get_widget("frame_network_usermode")
        self.frame_network_custom = self.wTree.get_widget("frame_network_custom")
        
        self.radiobutton_network_nonet = self.wTree.get_widget("radiobutton_network_nonet")
        self.radiobutton_network_usermode = self.wTree.get_widget("radiobutton_network_usermode")
        self.radiobutton_network_customsetup = self.wTree.get_widget("radiobutton_network_customsetup")
        
        self.toolbutton_network_netcard_add = self.wTree.get_widget("toolbutton_network_netcard_add")
        self.toolbutton_network_redir_add = self.wTree.get_widget("toolbutton_network_redir_add")
        #self.button_network_edit = self.wTree.get_widget("button_network_edit")
        
        self.toolbutton_network_netcard_edit = self.wTree.get_widget("toolbutton_network_netcard_edit")
        self.toolbutton_network_redir_edit = self.wTree.get_widget("toolbutton_network_redir_edit")
        
        #self.button_network_remove = self.wTree.get_widget("button_network_remove")
        
        self.toolbutton_network_netcard_delete = self.wTree.get_widget("toolbutton_network_netcard_delete")
        self.toolbutton_network_redir_delete = self.wTree.get_widget("toolbutton_network_redir_delete")
        
        self.treeview_networkcards = self.wTree.get_widget("treeview_networkcards")
        self.treeview_redirects = self.wTree.get_widget("treeview_redirects")
        self.label_network_netcards = self.wTree.get_widget("label_network_netcards")
        self.label__network_redirects = self.wTree.get_widget("label__network_redirects")
        self.filechooserbuttonNetworkSmbshare = self.wTree.get_widget("filechooserbuttonNetworkSmbshare")
        self.checkbuttonSmbshare = self.wTree.get_widget("checkbuttonSmbshare")
        self.entryNetworkHostname = self.wTree.get_widget("entryNetworkHostname")
        self.hbox_usernet_vlan = self.wTree.get_widget("hbox_usernet_vlan")
        self.label_hostname = self.wTree.get_widget("label_hostname")
        self.spinbuttonUsernetVlan = self.wTree.get_widget("spinbuttonUsernetVlan")
        self.frame_statefiles = self.wTree.get_widget("frame_statefiles")

        self.treeview_statefiles = self.wTree.get_widget("treeview_statefiles")
        self.toolbutton_delstate = self.wTree.get_widget("toolbutton_delstate")
        self.eventbox_delstate = self.wTree.get_widget("eventbox_delstate")
        
        if self.qemu_commandset == 'old':
            self.toolbutton_delstate.set_sensitive(True)
            
        else:
            tooltips.set_tip(self.eventbox_delstate, _('Since Qemu 0.9 snapshots can only be deleted in control monitor'))        
            self.toolbutton_delstate.set_sensitive(False)
        self.iconview_screenshots = self.wTree.get_widget("iconview_screenshots")
        
        self.treeview_capture = self.wTree.get_widget("treeview_capture")
        
        
        self.joblist = Joblist(self.treeview_joblist, self.joblist_data)  
        #self.jobwatcher = QemuWatcher(self.joblist.remove_job2) 
        gtk.gdk.threads_leave()

        self.imageselection = self.entry_current_image.connect("changed",  self.select_image_from_widget)
                   
        self.maindic = {"on_window1_delete_event" : self.delete_event
                ######################
                ,"on_beenden1_activate" : self.exit_app_event
                
                , "on_item_about_activate" : self.on_item_about_activate
                , "on_item_donate_activate" : self.dodonate
                
                , "on_item_create_image_activate" : self.init_create_image
                , "on_item_create_new_machine_activate" : self.add_bookmark
                , "on_item_install_system_activate" : self.installwizzard
                , "on_item_settings_activate" : self.open_settings
                , "on_item_homepage_activate" : self.open_website
                
                , "on_checkbutton_autohide_settings_toggled" : self.menu_toggle_settings_autohide
                , "on_checkbutton_autoshow_settings_toggled" : self.menu_toggle_settings_autoshow
                
                , "on_item_quit_activate" : self.exit_app_event
                
                , "on_toolbutton1_clicked" : self.get_soundhw
                , "on_toolbutton4_clicked" : self.open_settings
                , "on_toolbutton_launch_clicked" : self.run_qemu
                , "on_button_togglesettings_clicked" : self.toggle_settingsview
                
                , "on_notebook_mainlists_switch_page" : self.notebook_mainlists_change
                , "on_treeviewBootimages_button_release_event" : self.treeviewBootimages_button_press_event
                , "on_treeviewBookmarks_drag_end" : self.treeviewBookmarks_drag_end
                , "on_treeview_joblist_cursor_changed" : self.on_treeview_joblist_cursor_changed
                , "on_treeview_joblist_button_press_event" : self.on_treeview_joblist_button_press_event
                , "on_treeview_joblist_button_release_event" : self.on_treeview_joblist_button_release_event
                
                , "on_button_apply_imagesettings_clicked" : self.store_emu_settings
                ##, "on_button_restore_imagesettings_clicked": self.restore_emu_settings
                , "on_button_restore_imagesettings_clicked": self.restore_emu_config
                ####################
                #, "on_comboboxImagedevice_changed" : self.comboboxImagedevice_changed
                , "on_filechooserdialogUniversal_response" : self.on_filechooserdialogUniversal_response
                , "on_comboboxEmusystem_changed" : self.comboboxEmusystem_changed
                
                , "on_button_eject_imagecdrom_clicked" : self.clear_filechooser
                , "on_button_eject_hda_clicked" : self.clear_filechooser
                , "on_button_eject_hdb_clicked" : self.clear_filechooser
                , "on_button_eject_hdc_clicked" : self.clear_filechooser
                , "on_button_eject_hdd_clicked" : self.clear_filechooser
                , "on_button_eject_fda_clicked" : self.clear_filechooser
                , "on_button_eject_fdb_clicked" : self.clear_filechooser
                , "on_button_eject_kernelimage_clicked" : self.clear_filechooser
                , "on_button_eject_initrd_clicked" : self.clear_filechooser

                , "on_button_show_commandline_clicked" : self.show_commandline_clicked
                , "on_button_load_image_clicked" : self.fileChooser_emuimage
                , "on_item_load_image_activate" : self.fileChooser_emuimage
                , "on_filechooserdialog_openimage_response" : self.fileChooser_emuimage_response
                
                , "on_toolbutton_add_bookmark_clicked" : self.on_toolbutton_add_bookmark_clicked
                #, "on_toolbutton_remove_bookmark_clicked" : self.remove_bookmark
                
                # handlers for the network widgets
                , "on_toolbutton_network_netcard_add_clicked"  : self.init_networksetup
                , "on_toolbutton_network_redir_add_clicked" : self.init_network_redirect
                #, "on_button_network_remove_clicked" : self.remove_netcard
                
                , "on_toolbutton_network_netcard_delete_clicked" : self.remove_netcard
                , "on_toolbutton_network_redir_delete_clicked" : self.remove_netcard
                
                #, "on_button_network_edit_clicked"  : self.init_networksetup
                
                , "on_toolbutton_network_netcard_edit_clicked"  : self.init_networksetup
                , "on_toolbutton_network_redir_edit_clicked"  : self.init_networksetup
                
                , "on_radiobutton_network_nonet_toggled" : self.toggle_networkuse
                , "on_radiobutton_network_usermode_toggled" : self.toggle_networkuse
                , "on_radiobutton_network_customsetup_toggled" : self.toggle_networkuse
                , "on_treeview_networkcards_cursor_changed" : self.select_networkcard
                , "on_treeview_redirects_cursor_changed" : self.select_networkredir
                , "on_button_clear_serial_pressed" : self.on_button_clear_serial_pressed
                , "on_button_clear_parallel_pressed" : self.on_button_clear_parallel_pressed
                
                , "on_button_audioenviron_clicked" : self.on_button_audioenviron_clicked
                # handlers for the new image dialog
                #, "on_filechooserbutton_newimage_dest_current_folder_changed" : self.set_newimage_folder
                #, "on_entry_newimage_name_changed" : self.set_newimage_name
                #, "on_combobox_newimage_format_changed" : self.set_newimageformat
                #, "on_spinbutton_newimage_size_changed" : self.set_newimagesize
                #, "on_combobox_newimage_sizeunit_changed" : self.set_newimagesize
                #, "on_button_create_image_clicked" : self.create_newimage
                
                #, "on_button_savestate_clicked" : self.store_statefile
                , "on_toolbutton_runstate_clicked" : self.load_statefile_clicked
                , "on_toolbutton_delstate_clicked" : self.delete_statefile_clicked
                , "on_toolbutton_refresh_statefiles_clicked" : self.refresh_statefiles
                
                #, "on_toolbutton_storescreenshot_clicked" : self.store_screenshot
                , "on_iconview_screenshots_button_press_event"  : self.screenshot_clicked
                , "on_toolbutton_viewscreenshot_clicked"  : self.run_imageviewer
                , "on_toolbutton_deletescreenshot_clicked"  : self.delete_screenshot_clicked
                , "on_toolbutton_refresh_screenshots_clicked" : self.refresh_screenshots
                            
                #, "on_toggletoolbutton_record_toggled" : self.toggle_capture
                , "on_toolbutton_trashaudio_clicked" : self.delete_capture_clicked
                , "on_treeview_capture_button_press_event"  : self.run_audioplayer
                , "on_toolbutton_playaudio_clicked"  : self.run_audioplayer
                , "on_toolbutton_refresh_captures_clicked" : self.refresh_captures
                }
        
        
        
        self.wTree.signal_autoconnect(self.maindic)
        
        self.autoconnect()

        
    def autoconnect(self):
        self.rgx = re.compile('on_([^_]+)_(\w+)')
        self.connectionIds = []
        #Shared = self.wTree.get_data()
        #Shared_widgets = self.wTree
        for name in dir(self):
            #print 'searching ' + str(name)
            if not callable(getattr(self, name)): continue
            m = self.rgx.match(name)
            if m is None: continue
            wName, signal = m.group(1), m.group(2)
            #print 'wName: ' + str(wName) + ' signal: ' + str(signal)
            thisWidget = self.wTree.get_widget(wName)
            if thisWidget is None: continue
            #print str(thisWidget) + ' exists'
            try:
                id = thisWidget.connect(signal, getattr(self, name))
                #print str(wName) + ' connected to: ' + str(signal)
            except TypeError, msg: continue
                
            self.connectionIds.append( (thisWidget, id) )
#        print '-----------------------'
#        print 'All handlers connected'
#        print '-----------------------'     


    def disconnect(self):
        for w, id in self.connectionIds:
            w.disconnect(id)  
        self.connectionIds = []
#        print '-----------------------'
#        print 'All handlers disconnected'
#        print '-----------------------'        

    ## initialisation of the widgets default settings and models ##
    def init_gui(self, *widget):
        
        
        logo_file = pixmapdir + "/icon3-32.png"
        icon_file = pixmapdir + "/icon3-16.png"
        
        gtk.gdk.threads_enter()
        self.mainwindow.set_icon_from_file( icon_file)
        self.logo_mainwindow.set_from_file( logo_file)
        self.switch_settingsview("hide")
        self.combobox_runmode.set_active(0)
        self.radiobuttonKqemu.set_active(True)
        #self.comboboxImagedevice.set_active(1)
        #self.comboboxImagedevice_changed(self.comboboxImagedevice)
        self.toggle_settings_autohide(self.settings_autohide)
        self.toggle_settings_autoshow(self.settings_autoshow)
        gtk.gdk.threads_leave()
        
        try:
            data=os.listdir(self.settings["imagespath"])
            data.sort()
        except:
            data = ["", _('Please go to settings and select a default images folder as the Home for your qemu-images'), ""]
           
        for entry in data:
            path = str(self.imagespath) + "/" + str(entry)
            haveconfig = self.check_haveconfig(path)
            self.ilist_data.append((path, haveconfig))  
                      
        gtk.gdk.threads_enter()    
        ilistmodel = self.create_model_ilist(self.ilist_data)      
        self.isolist.set_model( ilistmodel)
        self.add_columns( self.isolist)
        
        cdlistmodel = self.create_model_cdromdrives(self.settings["cdromdrives"])
        self.treeviewCDdrives.set_model(cdlistmodel)
        self.add_columns_cdromdrives(self.treeviewCDdrives, cdlistmodel)         
        
        cdmodel = self.comboboxCDromdrive.get_model()
        cdmodel.clear()

        cdmodel.append(row=(None,))
        for dev in self.settings["cdromdrives"]:
            name = dev[0]
            device = dev[1]
            cdmodel.append(row=(name,))
            self.comboboxCDromdrive.set_model(cdmodel)
            
        if self.qemu_commandset == 'old':    
            self.add_columns_statefiles(self.treeview_statefiles)
        else:
            self.add_columns_snapshots(self.treeview_statefiles)
        
        self.add_columns_capture(self.treeview_capture)
        self.add_columns_screenshots(self.iconview_screenshots)
        
        try:
            self.filechooserdialogUniversal.add_shortcut_folder(self.settings["imagespath"])
            #print "added imagespath to filechooserbuttonImagecdrom"
        except:
            #print "imagespath allready on filechooserbuttonImagecdrom"
            pass
        try:
            self.filechooserdialogUniversal.add_shortcut_folder("/dev/")
        except:
            pass        
        self.filechooserdialogUniversal.add_filter(filter_shall())
        self.filechooserdialogUniversal.add_filter(filter_devs(self.settings))
        self.filechooserdialogUniversal.set_filter(filter_shall())      
        
#        try:
#            self.filechooserbuttonImagecdrom.add_shortcut_folder(self.settings["imagespath"])
#            #print "added imagespath to filechooserbuttonImagecdrom"
#        except:
#            #print "imagespath allready on filechooserbuttonImagecdrom"
#            pass
#        try:
#            self.filechooserbuttonImagecdrom.add_shortcut_folder("/dev/")
#        except:
#            pass        
        #self.filechooserbuttonImagecdrom.add_filter(filter_shall())
        #self.filechooserbuttonImagecdrom.add_filter(filter_devs(self.settings))
        #self.filechooserbuttonImagecdrom.set_filter(filter_shall())
        
        try:
            self.filechooserbuttonHDA.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass
        try:
            self.filechooserbuttonHDA.add_shortcut_folder("/dev/")
        except:
            pass        
        self.filechooserbuttonHDA.add_filter(filter_shall())
        self.filechooserbuttonHDA.add_filter(filter_devs(self.settings))
        self.filechooserbuttonHDA.set_filter(filter_shall())
        try:        
            self.filechooserbuttonHDB.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass 
        try:        
            self.filechooserbuttonHDB.add_shortcut_folder("/dev/")
        except:
            pass             
        self.filechooserbuttonHDB.add_filter(filter_shall())
        self.filechooserbuttonHDB.add_filter(filter_devs(self.settings))
        self.filechooserbuttonHDB.set_filter(filter_shall())
        try:         
            self.filechooserbuttonHDC.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass   
        try:              
            self.filechooserbuttonHDC.add_shortcut_folder("/dev/")
        except:
            pass               
        self.filechooserbuttonHDC.add_filter(filter_shall())
        self.filechooserbuttonHDC.add_filter(filter_devs(self.settings))
        self.filechooserbuttonHDC.set_filter(filter_shall())
        try:        
            self.filechooserbuttonHDD.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass    
        try:             
            self.filechooserbuttonHDD.add_shortcut_folder("/dev/")
        except:
            pass         
        self.filechooserbuttonHDD.add_filter(filter_shall())
        self.filechooserbuttonHDD.add_filter(filter_devs(self.settings))
        self.filechooserbuttonHDD.set_filter(filter_shall())
        try:        
            self.filechooserbuttonFDA.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass   
        try:              
            self.filechooserbuttonFDA.add_shortcut_folder("/dev/")
        except:
            pass         
        self.filechooserbuttonFDA.add_filter(filter_devs(self.settings))
        self.filechooserbuttonFDA.add_filter(filter_shall())
        self.filechooserbuttonFDA.set_filter(filter_shall())
        try:        
            self.filechooserbuttonFDB.add_shortcut_folder(self.settings["imagespath"])
        except:
            pass   
        try:              
            self.filechooserbuttonFDB.add_shortcut_folder("/dev/")
        except:
            pass         
        self.filechooserbuttonFDB.add_filter(filter_shall())
        self.filechooserbuttonFDB.add_filter(filter_devs(self.settings))
        self.filechooserbuttonFDB.set_filter(filter_shall())

        self.radiobutton_network_usermode.set_active(True)
        self.toggle_networkuse(self.radiobutton_network_usermode)
        
        
        netmodel = self.create_model_networkcards([])        
        self.treeview_networkcards.set_model(netmodel)
        self.add_columns_networkcards(self.treeview_networkcards,netmodel)  
        
        redirmodel = self.create_model_redirects([])    
        self.treeview_redirects.set_model(redirmodel) 
        self.add_columns_redirects(self.treeview_redirects,redirmodel)             
        
        gtk.gdk.threads_leave()  
        self.get_soundhw()
        
        gtk.gdk.threads_enter()
        self.refresh_soundhw() 
        gtk.gdk.threads_leave()
        
        self.get_machine()
        
        gtk.gdk.threads_enter()
        self.refresh_machineslist()
        
        
        ## initializing the systems listbox
        sysmodel = self.comboboxEmusystem.get_model()
        try:
            sysmodel.clear()
        except:
            #print "nothing to clear"
            pass
        for commands in self.settings["qemuapps"]:
            name = commands[0]
            path = commands[1]
            #print "path: " + name + " - " + path
            
            sysmodel.append(row=(name,))
        self.comboboxEmusystem.set_model(sysmodel)  
        self.comboboxEmusystem.set_active(0);      
        self.currimage_settings.emusystem = self.settings["qemuapps"][0][0]
        #gtk.gdk.threads_leave()
        
        self.init_joblist()
        
        #gtk.gdk.threads_enter()
        self.mainwindow.present()
        
        gtk.gdk.threads_leave() 
        
    
#    def filter_nodirs(self, filter_info):
#        file = filter_info[1]
#        #print file
#        if path.isdir(file):
#            #print "isdir"
#            return False
#        else:
#            #print "nodir"
#            return True   
        
    def show_commandline_clicked(self, widget):
            dialogtitle = "Qemu command line for this machine"
            dialogtext = self.qemu_command('')
            delrequest = qml_tools.Dialog("longtext", dialogtext, dialogtitle)               
    
    def create_model_ilist(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                          gtk.gdk.Pixbuf)
        config_icon = gtk.Image()
        try:        
            for item in data:
                iter = store.append()
                itempath = item[0]
                haveconfig = item[1]
                if haveconfig == True:
                    config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-yes.png')
                else:
                    config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-no.png')                
                store.set(iter, 0, itempath, 1, config_icon)
    
            return store
        except:
            print "recieved no correct data for treemodel creation"
            
    def refresh_mainview(self, *widget): 
        '''Manages all refreshes of the main window after any changes.'''
        currentpage = self.notebook_mainlists.get_current_page()
        
        if currentpage == 0:
            self.refresh_bookmarks()
        elif currentpage == 1:
            self.refresh_ilist()
            
    def refresh_all(self, *widget): 
        '''Manages all refreshes of the main window after any changes.'''
        #currentpage = self.notebook_mainlists.get_current_page()
        #if currentpage == 0:
        self.refresh_bookmarks()
        #elif currentpage == 1:
        self.refresh_ilist()  
        self.refresh_devlist()          
        
    def refresh_bookmarks(self, *widget): 
        '''refresh the bookmark list after any changes. No options, widget is just 
        set to avoid errors when function is called from a GTK widget.'''
        self.disconnect()
        model, iter = self.treeviewBookmarks.get_selection().get_selected()
        try:
            path = model.get_path(iter)
            
            #print 'iter:' + str(iter)
        except:
            pass
        self.load_bookmarks()    
        try:
            #time.sleep(0.1)
            self.treeviewBookmarks.set_cursor_on_cell(path)
        except:
            print 'nothing to reselect'
        self.autoconnect()
        
    def select_bookmark(self, name): 
        '''select a bookmark by given name.'''
        #self.disconnect()
        model = self.treeviewBookmarks.get_model()
        match_iter = self.search(model, model.iter_children(None), 
                           self.match_func, (1, name))   

        try:
            path = model.get_path(match_iter)
        except:
            pass
        #self.load_bookmarks()    
        try:
            #time.sleep(0.1)
            self.treeviewBookmarks.set_cursor_on_cell(path)
        except:
            print 'nothing to reselect'
        #self.autoconnect()  
        
    def match_func(self, model, iter, data):
        column, key = data # data is a tuple containing column number, key
        value = model.get_value(iter, column)
        return value == key
    def search(self, model, iter, func, data):
        while iter:
            if func(model, iter, data):
                return iter
            result = self.search(model, model.iter_children(iter), func, data)
            if result: return result
            iter = model.iter_next(iter)
        return None

             
        
    def refresh_ilist(self, *widget): 
        self.ilist_data = []   
        
        model, iter = self.isolist.get_selection().get_selected()
        try:
            path = model.get_path(iter)
        except:
            pass
        
        #ilistmodel = self.isolist.get_model() 
        model.clear()
        #print "refresh ilist imagespath: " + self.settings["imagespath"]
        data=os.listdir(self.settings["imagespath"])
        data.sort()
        for entry in data:
            imgpath = str(self.settings["imagespath"]) + "/" + str(entry)
            #print "path: " + path
            haveconfig = self.check_haveconfig(imgpath)
            #print "haveconfig: " + str(haveconfig)
            self.ilist_data.append((imgpath, haveconfig))
        
        model = self.create_model_ilist(self.ilist_data) 
        #print "refresh ilistmodel: " + str(ilistmodel)   
        setmod = self.isolist.set_model(model)
        #print "set ilistmodel: " + str(setmod)
        try:
            self.isolist.set_cursor(path)
        except:
            print 'nothing to reselect'             
        
    def notebook_mainlists_change(self, widget, *event):
        currentpage = event[1] 
        #print currentpage
        #print widget   
        if currentpage == 0:
            sel = self.isolist.get_selection()
            #sel.unselect_all()
        elif currentpage == 1:
            sel = self.treeviewBookmarks.get_selection()
            #sel.unselect_all()
            #self.treeviewBookmarks.unselect_all()
        if currentpage <= 1:
            sel.unselect_all()
            
        self.entry_current_image.set_text('')
               
        
    def add_columns(self, treeview):
        model = self.isolist.get_model()
        #renderer = gtk.CellRendererToggle()
        column = gtk.TreeViewColumn(_('Qemu Images'), gtk.CellRendererText(), text=0)
        column.set_resizable(True)
        column2 = gtk.TreeViewColumn(_('configured'), gtk.CellRendererPixbuf(), pixbuf=1)
        column2.set_resizable(True)
        treeview.append_column(column)
        treeview.append_column(column2)
        
    def create_model_statefiles(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING)
        data.sort()
        try:
            for item in data:
                iter = store.append()
                filename = item
                string.strip(filename)
                #print filename

                store.set(iter, 0, filename)
            return store          
        except:
            print "recieved no correct data for statefiles treemodel creation"           
       
    def add_columns_statefiles(self, treeview):
    
        #renderer = gtk.CellRendererToggle()
        column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0)
        treeview.append_column(column)
        
    def refresh_statefiles(self, *widget):
        if self.qemu_commandset == 'old':  
            try:
                model = self.treeview_statefiles.get_model()
                model.clear()
            except:
                pass          
            data = self.stateshandler.load_statefiles()
            #print "Statefiles data: " + str(data)
            ddata = self.stateshandler.statefiles_displaynames(data)
            model = self.create_model_statefiles(ddata)
            self.treeview_statefiles.set_model(model)
        else:
            self.refresh_snapshots_list(widget) 

    def delete_statefile_clicked(self, widget):
        error = False
        try:
            model, iter = self.treeview_statefiles.get_selection().get_selected()
            row = model[iter]
            item = row[0]            
        except:
            error = True
            dialogtext = "<b>No file selected to delete</b>"
            delrequest = qml_tools.Dialog("message", dialogtext, "Message")
        if error != True:
            realname = str(item.replace ( ' ', '_' ))
            dialogtext = "<b>Do you really want to delete the\n"\
            "selected state file\n"\
            "from your harddisk?</b>\n\n"\
            "File: " + realname
            dialogtitle = "Confirm delete"
            delrequest = qml_tools.Dialog("request", dialogtext, dialogtitle, self.delete_statefile, [realname])        

    def delete_statefile(self, filename):
        self.stateshandler.delete_statefile(filename)
        self.refresh_statefiles()        
                
    def load_statefile_clicked(self, widget):
        model, iter = self.treeview_statefiles.get_selection().get_selected()
        row = model[iter]
        item = row[0]
        if self.qemu_commandset == 'old':
            realname = str(item.replace ( ' ', '_' ))
            self.statefile = realname
        else:
            self.statefile = item
        self.run_qemu(widget)
        return self.statefile

    def create_model_snapshots(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING)
        data.sort()
        try:
            for item in data:
                iter = store.append()
                id = item[0]
                tag = item[1]
                vmsize = item[2]
                date = item[3]
                vmclock = item[4]            
                #string.strip(filename)
                #print filename
                #store.set(iter, 0, filename)
                store.set(iter, 0, item[0], 1, item[1], 2, item[2], 3, item[3], 4, item[4])
            return store          
        except:
            print "recieved no correct data for treemodel creation"
            
    def add_columns_snapshots(self, treeview, *model):
    
        #renderer = gtk.CellRendererToggle()
        columns = []
        columns.append(gtk.TreeViewColumn(_('ID'), gtk.CellRendererText(), text=0))
        columns.append(gtk.TreeViewColumn(_('TAG'), gtk.CellRendererText(), text=1))
        columns.append(gtk.TreeViewColumn(_('VM SIZE'), gtk.CellRendererText(), text=2))
        columns.append(gtk.TreeViewColumn(_('DATE'), gtk.CellRendererText(), text=3))
        columns.append(gtk.TreeViewColumn(_('VM CLOCK'), gtk.CellRendererText(), text=4))
        for column in columns:
            column.set_resizable(True)
            treeview.append_column(column)    
            
    def refresh_snapshots(self, *widget):
        #print 'refreshing snapshots'
        try:
            model = self.treeview_statefiles.get_model()
            model.clear()
        except:
            pass           
        data=self.snapshots_list
        #print str(data)
        data.sort()
        model = self.create_model_snapshots(data)    
        self.treeview_statefiles.set_model(model)         
       
    def refresh_snapshots_list(self, widget=None, event=None):
        #print "monitor command launched: " + str(widget)
        #command = "info snapshots"
        image = self.currentimage
        #print 'imagefile: ' + str(image)
        info = self.fetch_image_info(image)
        infolist = info.split('\n')
        #print 'imageinfo: ' + str(infolist)
        self.refresh_snapshots_command(infolist)
                 
        
    def refresh_snapshots_command(self, data):  
        outlist = filter(None, data)
        lc = 0
        self.snapshots_list = []
        
        #listexp = re.compile('([0-9]+)(\W+)(\B|\w+)(\W+)(\b\w+)(\W+)([0-9\-]+)(\W+)([0-9:]+)(\W+)([0-9:\.]+)')
        listexp1 = re.compile('([0-9]+)(\W+)(\w+)(\W+)(\w+)(\W+)([0-9]{4}-[0-9]{2}-[0-9]{2}\W{1}[0-9]{2}:[0-9]{2}:[0-9]{2})(\W+)([0-9:\.]+)')
        listexp2 = re.compile('([0-9]+)(\W+)(\w+)(\W+)([0-9]{4}-[0-9]{2}-[0-9]{2}\W{1}[0-9]{2}:[0-9]{2}:[0-9]{2})(\W+)([0-9:\.]+)')
        
        versolate1 = "\g<1>,\g<3>,\g<5>,\g<7>,\g<9>"
        versolate2 = "\g<1>, ,\g<3>,\g<5>,\g<7>"
        #print '-------Snapshots------------------'
        for line in outlist:
            line = string.strip(line)
            #print '---'
            #print 'line: ' + str(line)
            #snaprender = listexp.search(line)
            snaprender = None
            snaprender1 = listexp1.search(line)
            snaprender2 = listexp2.search(line)
            
            if snaprender1 != None and snaprender1 != '':
                snapstr = snaprender1.group()
                snapstr = string.strip(snapstr)
                snapsub = listexp1.sub(versolate1, snapstr)
                #print 'snapsub:' + str(snapsub) 
                devdata = snapsub.split(",", 5)
                self.snapshots_list.append(devdata)
            elif snaprender2 != None and snaprender2 != '':
                snapstr = snaprender2.group()
                snapstr = string.strip(snapstr)
                snapsub = listexp2.sub(versolate2, snapstr)
                #print 'snapsub:' + str(snapsub)    
                devdata = snapsub.split(",", 5)    
                self.snapshots_list.append(devdata)    
            #else:   
            #    #print "line sepparated manually"
            #    devdata = [str(line),"-","-","-","-"]  
            #    self.snapshots_list.append(devdata)    
            #print '---'
            
        #print '------- end Snapshots------------------'
        #if self.snapshots_list != []:
        self.refresh_snapshots()              
    
    def create_model_capture(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING)
        data.sort()
        try:
            for item in data:
                iter = store.append()
                filename = item
                string.strip(filename)
                store.set(iter, 0, filename)
            return store          
        except:
            print "recieved no correct data for captures treemodel creation"
       
    def add_columns_capture(self, treeview):
    
        #renderer = gtk.CellRendererToggle()
        column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0)
        treeview.append_column(column)
 
    def refresh_captures(self, *widget): 
        try:
            model = self.treeview_capture.get_model()
            model.clear()
        except:
            pass           
        data = self.capturehandler.load_captures()
        ddata = self.capturehandler.captures_displaynames(data)
        model = self.create_model_capture(ddata)
        self.treeview_capture.set_model(model)
        #print "refreshed captures"
        
    def delete_capture_clicked(self, widget):
        error = False
        try:
            model, iter = self.treeview_capture.get_selection().get_selected()
            row = model[iter]
            item = row[0]            
        except:
            error = True
            dialogtext = "<b>" + _("No file selected to delete") + "</b>"
            delrequest = qml_tools.Dialog("message", dialogtext, "Message")
        if error != True:
            realname = str(item.replace ( ' ', '_' )) + ".wav"
            dialogtext = "<b>" + _("Do you really want to delete the\n"\
            "selected wave file\n"\
            "from your harddisk?") + "</b>\n\n"\
            "File: " + realname
            dialogtitle = _("Confirm delete")
            delrequest = qml_tools.Dialog("request", dialogtext, dialogtitle, self.delete_capture, [realname])        
        
        
    def delete_capture(self, filename):
        self.capturehandler.delete_capture(filename)
        self.refresh_captures()             
            
    def run_audioplayer(self, widget, event=None):
        if event == None or event.type == gtk.gdk._2BUTTON_PRESS:
            model, iter = self.treeview_capture.get_selection().get_selected()
            row = model[iter]
            audiofile = row[0]    
            realname = str(audiofile.replace ( ' ', '_' )) + ".wav"           
            if audiofile != "":
                self.capturehandler.run_audioplayer(realname)
                
    def pop_up_screenshots(self, widget, event):    
        if event.button == 3:            
            try:  
                path, renderer = self.iconview_screenshots.get_cursor()
                model = self.iconview_screenshots.get_model()
                iter = model.get_iter(path)        
                self.selected_screenshot = model.get_value(iter, 0)
                self.menu_popup_screenshots.popup( None, None, None, 3, 0)
            except:
                print "no screenshot selected"
        else:
            pass
        
    def screenshot_clicked(self, widget, event=None):
        if event.button == 3: 
            isbookmark = self.search_bookmark(self.currentimage, "index")
            if isbookmark != None:
                #print "is bookmark: " + str(isbookmark) 
                self.item_use_as_icon.set_sensitive(True)
            else:
                self.item_use_as_icon.set_sensitive(False)          
            self.pop_up_screenshots(widget, event)
        elif event == None or event.type == gtk.gdk._2BUTTON_PRESS:
            self.run_imageviewer(widget, event)
        
    def scr2icon(self, *widget):
        #print "use as icon!"
        isbookmark = self.search_bookmark(self.currentimage, "index")
        if isbookmark != None:
            currbookmark = isbookmark
        self.translated_name = self.currentimage.replace ( '/', '_' )    
        thisjobdir = self.screenshot_dir + "/" + self.translated_name
        screenshot = thisjobdir + "/" + self.selected_screenshot
        self.bookmarks[currbookmark].icon = screenshot
        self.storetofile(self.bookmarks, "bookmarks")
        self.refresh_bookmarks()
                                
    def create_model_screenshots(self, data):
        model = gtk.ListStore(str, gtk.gdk.Pixbuf)
        data.sort()
        for item in data:
            filename = item
            string.strip(filename)
            filepath = self.screenshot_dir + "/" + self.translated_name + "/" + filename
            pixbuf = gtk.gdk.pixbuf_new_from_file(filepath)
            pwidth = pixbuf.get_width()
            pheight = pixbuf.get_height()
            pfact = pwidth / 64
            oheight = pheight / pfact
            icon = pixbuf.scale_simple(64, oheight, 3)
            model.append([filename, icon])
        return model          

    def add_columns_screenshots(self, iconview=None):
        iniconview = iconview
        iniconview.set_text_column(0)
        iniconview.set_pixbuf_column(1)
                
    def refresh_screenshots(self, *widget):
        try:
            model = self.iconview_screenshots.get_model()
            model.clear()
        except:
            pass             
        data = self.sceenshothandler.load_screenshots()
        model = self.create_model_screenshots(data)
        self.iconview_screenshots.set_model(model)    
            
    def delete_screenshot_clicked(self, widget):
        error = False
        try:
            path, renderer = self.iconview_screenshots.get_cursor()
            model = self.iconview_screenshots.get_model()
            iter = model.get_iter(path)            
            screenshot = model.get_value(iter, 0)
        except:
            error = True
            dialogtext = "<b>No file selected to delete</b>"
            delrequest = qml_tools.Dialog("message", dialogtext, "Message")
        if error != True and screenshot != "":
            dialogtext = "<b>Do you really want to delete the\n"\
            "selected screenshot file\n"\
            "from your harddisk?</b>\n\n"\
            "File: " + screenshot
            dialogtitle = "Confirm delete"
            delrequest = qml_tools.Dialog("request", dialogtext, dialogtitle, self.delete_screenshot, [screenshot])        

    def delete_screenshot(self, filename):
        self.sceenshothandler.delete_screenshot(filename)
        self.refresh_screenshots() 

    def run_imageviewer(self, widget, event=None):
        if event == None or event.type == gtk.gdk._2BUTTON_PRESS:
            path, renderer = self.iconview_screenshots.get_cursor()
            model = self.iconview_screenshots.get_model()
            iter = model.get_iter(path)            
            screenshot = model.get_value(iter, 0)        
            if screenshot != "":
                self.sceenshothandler.run_imageviewer(screenshot)
            
            
    ## Universal Function to pickle-store the configfiles
    def storetofile(self, indata, filename):
        #print "storefile: " + filename
        dumpf = open(self.configdir + "/" + filename ,"w")        
        pickle.dump(indata, dumpf)
        dumpf.close()
        
    ## Universal Function to open the pickle'd configfiles        
    def getfromfile(self, filename):
        try:
            abs_path = path.abspath(self.configdir + "/" + filename)
            #print "opened file absolute path: " + abs_path 
            dumpf = open( abs_path ,"r")       
            outdata = pickle.load(dumpf)
            dumpf.close()
            return outdata        
        except:
            outdata  = { }
            print "File not found: " + str(abs_path)
            return outdata
       
   
    ## Searches for the index for a 1 dimensional treemodel
    def search_combolist(self, combobox, searchstring):
        ct = 0
        outct = None
        cdmodel = combobox.get_model()
        for row in cdmodel:

            if searchstring == row[0]:
                outct = ct
                break
            ct = ct + 1           
        return outct
        
    def fetch_image_info(self, image):
        info = _('no valid image selected')  
       
        try:
            command = "qemu-img info " + image
            info = os.popen(command).read()
        except:
            info = _('no valid image selected')  
        return info  
    
    def fetch_machine_vars(self): # for debug only!
        print dir(self.currimage_settings)
        for var in dir(self.currimage_settings):
            print 'var: ' + str(var)
            val = getattr(self.currimage_settings, str(var))
            print 'val: ' + str(val)
            print '----------------------------------------------'
               
    
    ## Fetch the stored configuration for the selected image
    def restore_emu_config(self, widget=None):
        self.currimage_settings = QemuConfig(self.currentimage)
        haveconfig = False
        if self.selected_bookmark != None:
            #print 'bookmark: ' + str(self.selected_bookmark)
            haveconfig = self.check_haveconfig(str(self.selected_bookmark))
            if haveconfig == True:
                #print "bookmark Config found for :" + str(self.selected_bookmark)
                newvals = vars(self.image_settings[self.selected_bookmark])
            #else:
            #    print 'no bookmark Config found'
        if haveconfig == False:
            #print 'checking for imageconfig...'
            haveconfig = self.check_haveconfig(self.currentimage)
            #print '...result: ' + str(haveconfig)
            if haveconfig == True:
                newvals = vars(self.image_settings[self.currentimage])
            else:
                #print "No config found for :" + str(self.currentimage)
                self.label_imgsettings.set_markup(_('<b>Create new Settings for Current selected image</b>'))
        if haveconfig == True:
            if self.settings_autohide == True:
                self.switch_settingsview("hide")

            oldvals = vars(self.currimage_settings)
            for key in newvals.keys():
                
                var = key
                val = newvals[key]
                #print 'key: ' + str(key) + ' val: ' + str(val)
                oldvals[var] = val
            self.restoreaction = True
            refreshsettings = True
            self.refresh_settings_gui()
            self.restoreaction = False
                           
            self.toggle_storebuttons(False, "restore_emu_config configured")
            if self.traypop != None:
                self.traypop.close_balloon()              
        else:
            self.currimage_settings.main_image = self.currentimage
            if self.settings_autoshow == True:
                self.switch_settingsview("show")

            self.autodetect_newimage(self.currentimage)
            self.refresh_settings_gui()            
            self.toggle_storebuttons(True, "restore_emu_config noconfig") 

        
    def autodetect_newimage(self, imagefile): 
        fileparser = qml_tools.ImageInfo()
        fileinfo = fileparser.get_file_info(str(imagefile))
        print 'file info: ' + str(fileinfo)
        if fileinfo['medium'] == 'hda':
            #comboboxImagedevice.set_active(0)
            self.currimage_settings.hda_image = imagefile
            self.currimage_settings.main_image = imagefile
            self.currimage_settings.bootmedium = 'hda'
            self.currimage_settings.boot_driveletter = 'c'
            
        if fileinfo['medium'] == 'cdrom':
            self.currimage_settings.cdrimage = imagefile
            self.currimage_settings.main_image = imagefile
            self.currimage_settings.bootmedium = 'cdrom'
            self.currimage_settings.boot_driveletter = 'd'
        if fileinfo['medium'] == 'fda':
            self.currimage_settings.fda_image = imagefile
            self.currimage_settings.main_image = imagefile
            self.currimage_settings.bootmedium = 'fda'
            self.currimage_settings.boot_driveletter = 'a'
        if fileinfo.has_key('suggestion'):
            #label_suggestions.set_text(fileinfo['suggestion']) 
            filesuggestion = fileinfo['suggestion']
        else:
            filesuggestion = None
        if self.item_hide_settings.get_property('visible'):
            statusmessage = '<b>' + _('No configuration found for this image!') + '</b>\n'
            if filesuggestion != None:
                statusmessage = statusmessage + _('I have tried to find out the file type and set up \
an instant configuration with this image on the right place to boot this type:\n\n')
                statusmessage = statusmessage + filesuggestion + '\n'
            else:
                statusmessage = statusmessage + '<span foreground="red">' + _('I have tried to find out the file type but can\'t recognize it. \
If this is a valid image, you have to set up the boot options manually.\n') + '</span>'
            statusmessage = statusmessage + _('\nIf you want to keep this setup, please store it in the settings panel.')
            
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)
            
    def refresh_settings_gui(self):
        self.vbox_bottompane.set_sensitive(False)
        refresher = qml_tools.DelayedGUIactions(self.do_refresh_settings_gui)
        refresher.start()
        
    def do_refresh_settings_gui(self):
        #self.notebook_imgsettings.set_sensitive(False)
        
        self.stateshandler = qml_filehandlers.Statefiles(self.currentimage, self.settings)
        self.sceenshothandler = qml_filehandlers.Screenshots(self.currentimage, self.settings)
        self.capturehandler = qml_filehandlers.Wavecaptures(self.currentimage, self.settings)  
        self.translated_name = self.currentimage.replace ( '/', '_' )
        self.refresh_statefiles()
        self.refresh_screenshots()
        self.refresh_captures()
        self.statefile = None
        self.label_imgsettings.set_markup(_('<b>Stored Settings for Current selected image</b>'))
        self.disconnect()
        if self.currimage_settings.emusystem == "":    
            self.currimage_settings.emusystem = str(self.comboboxEmusystem.get_active())           
               
        self.qemubin = self.emusystem_path_by_name(self.currimage_settings.emusystem)
        find_emusystem = self.search_combolist(self.comboboxEmusystem, self.currimage_settings.emusystem)

        if find_emusystem != None:
            
            self.comboboxEmusystem.set_active(find_emusystem)  
             
        else:
            self.comboboxEmusystem.set_active(0)
            self.comboboxEmusystem_changed(self.comboboxEmusystem)
        self.machinecommand = self.machine_path_by_name(self.currimage_settings.machine) 
        find_machine = self.search_combolist(self.comboboxMachinetype, self.currimage_settings.machine)
        if find_machine != None:
            self.comboboxMachinetype.set_active(find_machine)
        else:
            self.get_machine()
            self.comboboxMachinetype.set_active(0)
            self.on_comboboxMachinetype_changed(self.comboboxMachinetype)  
        if self.currimage_settings.kqemu_param ==  "-no-kqemu":
            self.radiobuttonNokqemu.set_active(True )
        elif self.currimage_settings.kqemu_param ==  "-kernel-kqemu":
            self.radiobuttonKKqemu.set_active(True )  
        else:
            self.radiobuttonKqemu.set_active(True )
        if self.currimage_settings.hda_image != None and path.isfile(self.currimage_settings.hda_image): 
            self.filechooserbuttonHDA.set_filename(str(self.currimage_settings.hda_image))
        elif self.currimage_settings.bootmedium == 'hda' and path.isfile(self.currimage_settings.main_image):
            #print 'main_image: ' + str(self.currimage_settings.main_image)
            self.currimage_settings.hda_image = self.currimage_settings.main_image
            self.filechooserbuttonHDA.set_filename(path.abspath(self.currimage_settings.hda_image))
        else:
            self.filechooserbuttonHDA.set_current_folder(self.settings["imagespath"])          
        if self.currimage_settings.hdb_image != None and path.isfile(self.currimage_settings.hdb_image):
            self.filechooserbuttonHDB.set_filename(path.abspath(self.currimage_settings.hdb_image))
        else:
            self.filechooserbuttonHDB.set_current_folder(self.settings["imagespath"])
        if self.currimage_settings.cdrmedium != None:
            find_cdrmedium = self.search_combolist(self.comboboxCDromdrive, self.currimage_settings.cdrmedium)
            if find_cdrmedium != None:
                self.hdcmode = 'cdrom'
                self.comboboxCDromdrive.set_active(find_cdrmedium)
                self.currimage_settings.hdc_image = None
                self.currimage_settings.cdrimage = None
                self.currimage_settings.cdrmode = 'mount'          
            else:
                self.comboboxCDromdrive.set_active(0)
            self.comboboxMediatypeHDC.set_active(1)
            print "find_cdrmedium: " + str(find_cdrmedium)          
        elif self.currimage_settings.hdc_image != None and path.isfile(self.currimage_settings.hdc_image):
            self.currimage_settings.cdrimage = None
            self.currimage_settings.cdrmedium = None
            #print 'hdc_image: ' + str(self.currimage_settings.hdc_image)
            self.filechooserbuttonHDC.set_filename(path.abspath(self.currimage_settings.hdc_image))
            self.comboboxMediatypeHDC.set_active(0)
            self.hdcmode = 'hdc'
            #self.expanderCDrom.hide()
        elif str(self.currimage_settings.cdrimage) != 'None' and path.isfile(self.currimage_settings.cdrimage):
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrmedium = None 
            self.currimage_settings.cdrmode = 'image'
            #print 'cdrimage: ' + str(self.currimage_settings.cdrimage)
            self.hdcmode = 'cdrom'
            #self.expanderCDrom.show()
            self.expanderCDrom.set_expanded(False)
            self.filechooserbuttonHDC.set_filename(path.abspath(self.currimage_settings.cdrimage))
            self.comboboxMediatypeHDC.set_active(1)
        elif self.currimage_settings.bootmedium == 'cdrom' and path.isfile(self.currimage_settings.main_image):
            #print 'main_image: ' + str(self.currimage_settings.main_image)
            self.currimage_settings.cdrimage = self.currimage_settings.main_image
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrmedium = None  
            self.currimage_settings.cdrmode = 'image'
            self.filechooserbuttonHDC.set_filename(path.abspath(self.currimage_settings.cdrimage))
            self.comboboxMediatypeHDC.set_active(1)    
            self.hdcmode = 'cdrom'                            
        else:
            #print 'no hdc_image: ' + str(self.currimage_settings.hdc_image)
            #print 'no cdrimage: ' + str(self.currimage_settings.cdrimage)
            self.comboboxMediatypeHDC.set_active(0)
            self.hdcmode = 'hdc'
            self.filechooserbuttonHDC.set_current_folder(self.settings["imagespath"]) 

        self.refresh_cdrmode_gui() 
        self.refresh_bootmode_gui()           
        try:  
            self.switch_hdcicon()
        except:
            print 'hdcicon not switched!'
        if self.currimage_settings.hdd_image != None and path.isfile(self.currimage_settings.hdd_image):
            self.filechooserbuttonHDD.set_filename(path.abspath(self.currimage_settings.hdd_image))
        else:
            self.filechooserbuttonHDD.set_current_folder(self.settings["imagespath"])    
        if self.currimage_settings.fda_image != None and path.isfile(self.currimage_settings.fda_image):
            self.filechooserbuttonFDA.set_filename(path.abspath(self.currimage_settings.fda_image))
        elif self.currimage_settings.bootmedium == 'fda' and path.isfile(self.currimage_settings.main_image):
            #print 'main_image: ' + str(self.currimage_settings.main_image)
            self.currimage_settings.fda_image = self.currimage_settings.main_image
            self.filechooserbuttonFDA.set_filename(path.abspath(self.currimage_settings.fda_image))
        else:
            self.filechooserbuttonFDA.set_current_folder(self.settings["imagespath"])
        if self.currimage_settings.fdb_image != None and path.isfile(self.currimage_settings.fdb_image):
            self.filechooserbuttonFDB.set_filename(path.abspath(self.currimage_settings.hdb_image))
        else:
            self.filechooserbuttonFDB.set_current_folder(self.settings["imagespath"])   
        find_soundhw = self.search_combolist(self.comboboxAudiohw, self.currimage_settings.soundhw)
        #print "find_soundhw " + str(find_soundhw)
        if find_soundhw:
            self.comboboxAudiohw.set_active(find_soundhw)     
        else:
            self.comboboxAudiohw.set_active(0)
        
        ## Select the vgamode and setup GUI    

        if self.currimage_settings.vgamode == "std-vga":
            self.checkbuttonUsevga.set_active(True)
        else:
            self.checkbuttonUsevga.set_active(False)  

        ## Select usevnc and setup GUI

        self.checkbuttonStartvnc.set_active(self.currimage_settings.usevnc)
         
                        
        ## Select vncdisplay and setup GUI
         
        self.spinbuttonVncdisplay.set_value(self.currimage_settings.vncdisplay)
        #print "usevnc: " + str(self.currimage_settings.usevnc)
        #time.sleep(1)   
        
        ## Select useusb and setup GUI
     
        self.checkbuttonEnableUSB.set_active(self.currimage_settings.useusb)
        #print "useusb: " + str(self.currimage_settings.useusb)
        #time.sleep(1)   
        
        ## Select novga and setup GUI

        self.checkbuttonNovga.set_active(self.currimage_settings.novga)
        
        #print "novga: " + str(self.currimage_settings.novga)
        #time.sleep(1)  
                        
        ## Select fullscreen mode and setup GUI

        #print "fullscreenmode: " + str(self.currimage_settings.fullscreenmode)
        self.checkbuttonFullscreen.set_active(self.currimage_settings.fullscreenmode)
        #print "fullscreenmode: " + str(self.currimage_settings.fullscreenmode)
        #time.sleep(1)
        
        ## Select dlinuxboot and setup GUI

        #self.checkbuttonDlinuxboot.set_active(self.currimage_settings.dlinuxboot)
        #self.frame_dlinuxboot.hide()
        #self.expander_dlinuxboot.set_visible(self.currimage_settings.dlinuxboot)
        if self.currimage_settings.dlinuxboot == True:
            self.expander_dlinuxboot.show()
        else:
            self.expander_dlinuxboot.hide()
        #self.buttonHideDlinuxboot.set_label(_("Show settings"))
        
        #print "dlinuxboot: " + str(self.currimage_settings.dlinuxboot) 
        #time.sleep(1)
        
        ## Select the kernelimage and setup GUI

        if self.currimage_settings.kernelimage != None and path.isfile(self.currimage_settings.kernelimage): 
            #self.filechooserbuttonKernelimage._block = TRUE
            self.filechooserbuttonKernelimage.set_filename(path.abspath(self.currimage_settings.kernelimage))    
        else:
            self.filechooserbuttonKernelimage.unselect_all()
            #self.filechooserbuttonKernelimage._block = FALSE
            #time.sleep(0.1)
        ## Select the initrd and setup GUI

        if self.currimage_settings.initrd != None and path.isfile(self.currimage_settings.initrd): 
            self.filechooserbuttonInitrd.set_filename(path.abspath(self.currimage_settings.initrd))       
        else:
            self.filechooserbuttonInitrd.unselect_all()
        ## Select extra kernel parameters and setup GUI
            
        self.entryKernelcmd.set_text(self.currimage_settings.kernelcmd)                                                                         
        
        ## Select snapshotmode and setup GUI

        self.checkbuttonSnapshotmode.set_active(self.currimage_settings.snapshotmode)
        
        ## Select startpaused and setup GUI

        self.checkbuttonStartpaused.set_active(self.currimage_settings.startpaused)
        
        ## Select localtimemode and setup GUI

        self.checkbuttonLocaltime.set_active(self.currimage_settings.localtimemode)

        ## Select memory and setup GUI
           
        self.spinbuttonMemory.set_value(self.currimage_settings.memory)
        #print "memory loaded: " + str(self.currimage_settings.memory)
        
        ## Select customoptions and setup GUI
          
        self.entryAdditionalCommandline.set_text(self.currimage_settings.customoptions)                                                                         
        #print "customoptions: " + str(self.currimage_settings.customoptions)   
        #time.sleep(1)
        ## Select bootfromcd and setup GUI
        
        ## Select networkmode and setup GUI
            
        if self.currimage_settings.networkmode == "nonet":
            self.radiobutton_network_nonet.set_active(True)
        elif self.currimage_settings.networkmode == "usermode" or self.currimage_settings.networkmode == "":
            self.radiobutton_network_usermode.set_active(True)
            self.usernetwork = self.currimage_settings.usernetwork
        elif self.currimage_settings.networkmode == "custom":
            self.radiobutton_network_customsetup.set_active(True)
        else:
            self.radiobutton_network_usermode.set_active(True)
                                                                                     

        ## Select hostname and setup GUI
        #print "Network hostname: " + str(self.currimage_settings.usernetwork.hostname)
        #self.entryNetworkHostname.set_text(self.currimage_settings.network_hostname)
        self.entryNetworkHostname.set_text(str(self.currimage_settings.usernetwork.hostname))            
                
        ## Select usesmb and setup GUI
           
        self.checkbuttonSmbshare.set_active(self.currimage_settings.smbsettings.usesmb)
        self.filechooserbuttonNetworkSmbshare.unselect_all()
        
        ## Select smbpath and setup GUI
         
        if os.path.isfile(str(self.currimage_settings.smbsettings.smbpath)):
            self.filechooserbuttonNetworkSmbshare.set_filename(path.abspath(self.currimage_settings.smbsettings.smbpath))
            #self.network_hostname = "emu"
        
        ## Select vlan and setup GUI
        self.spinbuttonUsernetVlan.set_value(int(self.currimage_settings.usernetwork.vlan))

        ''' setup gui for xtra settings '''
        
        ## Select extra kernel parameters and setup GUI
        
        self.entryRedirectSerial.set_text(self.currimage_settings.redirect_serial) 
        self.entryRedirectParallel.set_text(self.currimage_settings.redirect_parallel) 
        
        #if self.currimage_settings.noacpi != "" and self.currimage_settings.noacpi != False:
        self.checkbuttonNoacpi.set_active(self.currimage_settings.noacpi)
        self.checkbuttonNoreboot.set_active(self.currimage_settings.noreboot)
        
        self.checkbuttonDaemonize.set_active(self.currimage_settings.daemonize)
        self.checkbuttonWaitgdb.set_active(self.currimage_settings.waitgdb)      
        if self.currimage_settings.pidfile != None:
            self.entryPidfile.set_text(str(self.currimage_settings.pidfile))
        else:
            self.entryPidfile.set_text('')
        if self.currimage_settings.gdbport != None:
            self.entryGdbport.set_text(str(self.currimage_settings.gdbport))
        else:
            self.entryGdbport.set_text('')
        if self.currimage_settings.optionrom != None:
            self.entryOptionrom.set_text(self.currimage_settings.optionrom)
        else:
            self.entryOptionrom.set_text('')

        self.spinbuttonCPUs.set_value(int(self.currimage_settings.cpus))
        #print 'refreshed self.currimage_settings.audioenvironment: ' + str(self.currimage_settings.audioenvironment)
        #time.sleep(1)
        if self.currimage_settings.audioenvironment == 'Default':
            self.checkbuttonDefaultaudioenv.set_active(True)
            self.button_audioenviron.set_sensitive(False)
        else:
            self.checkbuttonDefaultaudioenv.set_active(False)
            self.button_audioenviron.set_sensitive(True)
        #print "networksettings loaded"
        #print "networkredirs loaded"
        self.refresh_networkcards()
        self.refresh_redirects() 
      
        self.restoreaction = False

        #self.notebook_imgsettings.set_sensitive(True)
        
        self.autoconnect()
        self.toggle_storebuttons(False, "refresh_settings_gui")
        self.vbox_bottompane.set_sensitive(True)

        return True
            
            
    def refresh_cdrmode_gui(self):
        if self.currimage_settings.cdrmode == 'mount':
            self.expanderCDrom.show()
            self.expanderCDrom.set_expanded(True)
            self.filechooserbuttonHDC.set_sensitive(False)
            self.button_eject_hdc.set_sensitive(False)
            self.comboboxMediatypeHDC.set_sensitive(False)
        elif self.currimage_settings.cdrmode == 'image':
            self.expanderCDrom.show()
            self.expanderCDrom.set_expanded(False)
            self.filechooserbuttonHDC.set_sensitive(True)
            self.button_eject_hdc.set_sensitive(True)
            self.comboboxMediatypeHDC.set_sensitive(True)  
        else:
            self.expanderCDrom.hide()
            self.expanderCDrom.set_expanded(False)
            self.filechooserbuttonHDC.set_sensitive(True)
            self.button_eject_hdc.set_sensitive(True)
            self.comboboxMediatypeHDC.set_sensitive(True) 
            
    def refresh_bootmode_gui(self):
        #print 'refresh_bootmode_gui: ' + str(self.currimage_settings.bootmedium)
        if self.currimage_settings.bootmedium == 'hda':
            self.radiobuttonBootHDA.set_active(True)
            self.comboboxMediatypeHDC.set_sensitive(True)
        elif self.currimage_settings.bootmedium == 'cdrom':
            self.radiobuttonBootHDC.set_active(True)
            self.comboboxMediatypeHDC.set_sensitive(False)
        elif self.currimage_settings.bootmedium == 'fda':
            self.radiobuttonBootFDA.set_active(True)
            self.comboboxMediatypeHDC.set_sensitive(True)
        elif self.currimage_settings.bootmedium == 'dlinux':
            self.radiobuttonBootDlinux.set_active(True)
            self.comboboxMediatypeHDC.set_sensitive(True)

    
    def cleanup_emu_settings(self):
        #print '*****************************************************'
        print '************cleanin up orphaned config entrys *******'
        #print '*****************************************************'
        delct = 0
        dels = []
        for setup in self.image_settings.keys():
            #print str(setup)
            checkbookmark = self.checkexist_bookmark(str(setup))
            if self.checkexist_bookmark(str(setup)) == True:
                #print str(setup) + ' is a bookmark'
                pass
            else:
                #print str(setup) + ' is not a bookmark'
                if os.path.exists(setup):
                    #print setup + ' device exists'
                    pass
                else:
                    #print setup + ' file not found'
                    del self.image_settings[setup]
                    #print 'configuration ' + setup + ' deleted'
                    delct = delct + 1
                    dels.append(setup)
        
        #print '*****************************************************'
        if delct != 0: 
            print 'Deleted ' + str(delct) + ' configurations: '
            for delstr in dels:
                print delstr
        else:
            print 'No orphaned configurations found'
        #print '*****************************************************'
        print '*****************************************************'  
        
#    def cleanup_image_settings(self): 
#        pass
#    
#    def cleanup_bookmark_settings(self):  
#        pass                      
        
    def store_emu_settings(self, *widget):
        if self.currentimage != "":
            if self.currimage_settings.kqemu_param == "":
                store_kqemu_param = "NULL"
            else:
                store_kqemu_param = self.currimage_settings.kqemu_param
            if self.currimage_settings.emusystem == "":    
                self.currimage_settings.emusystem = str(self.comboboxEmusystem.get_active())
            
            #print 'storing currimage_settings: ' + str(self.currimage_settings)
            newvals = vars(self.currimage_settings)
            for key in newvals.keys():
                var = key
                val = newvals[key]
                #print 'key: ' + str(key) + ' val: ' + str(val)
                
            if self.selected_bookmark != None:
                #print 'storing bookmark settings: '
                #self.currentimage = self.currimage_settings.main_image
                self.image_settings[self.selected_bookmark] = self.currimage_settings
            else:
                #print 'storing path based settings: '
                self.image_settings[self.currentimage] = self.currimage_settings
            
            self.cleanup_emu_settings()
            
            storedata = self.image_settings
            filename = "image_settings"
            self.storetofile(storedata, filename)
            #self.refresh_ilist()
            #self.refresh_bookmarks()
            if self.selected_bookmark != None:
                model, iter = self.treeviewBookmarks.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))                                           
                if self.bookmarks[counter].path != self.currimage_settings.main_image:
                    self.bookmarks[counter].path = self.currimage_settings.main_image
                    self.storetofile(self.bookmarks, "bookmarks")            
            self.refresh_mainview()
            self.label_imgsettings.set_markup(_('<b>Stored Settings for Current selected image</b>'))
        else:
            print "no image selected"
        self.toggle_storebuttons(False, "store_emu_settings")

    def delete_event(self, widget, event, data=None):
        
        if tray != None and self.settings["closetotray"] == True:
            print "close to tray enabled, only hiding window"
            self.position = widget.get_position()
            widget.hide()
            return True
        else:  
            print "close to tray not enabled, exiting.."  
            self.doexit = True
            self.dorun = False
            time.sleep(0.5)
            print "exit"
            exit
            gtk.main_quit()
            return False
    
    def exit_app_event(self, widget, *event):
        self.doexit = True
        self.dorun = False
        time.sleep(0.5)        
        print "exit"
        exit
        gtk.main_quit()  
        return False    
    def on_filechooserdialogUniversal_response(self, dialog=None, response_id=None, userdata=None):
        #callback(dialog, response_id, user_param1, ...)
#        params = dir(dialog)
#        print 'dialog: ' + str(dialog)
#        for data in params:
#            print 'data: ' + str(data)
        print 'file: ' + str(dialog.get_filename())
        print 'response_id: ' + str(response_id)
        #print 'userdata: ' + str(userdata)
        print 'name: ' + str(dialog.get_name())
        
        #print 'get_response_for_widget: ' + str(dialog.get_response_for_widget())
        print 'get_role: ' + str(dialog.get_role())
        print 'get_toplevel: ' + str(dialog.get_toplevel())
        
                    
    
#    def on_filechooserdialogImagecdrom_response(self, dialog=None, response=None, userdata=None):
#        if response == gtk.RESPONSE_OK:        
#            file = copy(str(dialog.get_filename()))
#            print 'file Imagecdrom: ' + file
#            self.currimage_settings.cdrimage = file
#            return file 
    
#    def on_filechooserdialogImagecdrom_hide_event(self, widget, *event):
#        print 'after Imagecdrom: ' + str(self.currimage_settings.cdrimage)
#        self.filechooserbuttonImagecdrom.set_filename(self.currimage_settings.cdrimage)
#        self.toggle_storebuttons(True, "on_filechooserdialogImagecdrom_hide_event")
#        
    def on_filechooserdialogHDA_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            print 'file Imagecdrom: ' + file
            self.currimage_settings.hda_image = file
            return file
    
    def on_filechooserdialogHDA_hide_event(self, widget, *event):
        if os.path.exists(self.currimage_settings.hda_image ):
            self.filechooserbuttonHDA.set_filename(self.currimage_settings.hda_image)
            self.check_bootstatus(self.currimage_settings.hda_image, 'hda')
            self.toggle_storebuttons(True, "on_filechooserdialogHDA_hide_event")  
            
    def on_eventboxHDA_drag_begin(self, widget, *dragdata):
        print 'drag begun for hda: ' + str(widget) + ' ' + str(dragdata)
        
    
    def on_filechooserdialogHDB_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            self.currimage_settings.hdb_image = file
            return file
    
    def on_filechooserdialogHDB_hide_event(self, widget, *event):
        if os.path.exists(self.currimage_settings.hdb_image ):
            self.filechooserbuttonHDB.set_filename(self.currimage_settings.hdb_image)
            self.toggle_storebuttons(True, "on_filechooserdialogHDB_hide_event")    
        
    def on_filechooserdialogHDC_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            #self.currimage_settings.hdc_image = file
            self.set_hdc_type(file)
            
            if self.hdcmode == 'hdc':
                self.currimage_settings.hdc_image = file
                self.currimage_settings.cdrimage = None
            else:
                self.currimage_settings.cdrimage = file
                self.currimage_settings.hdc_image = None
                            
            return file
        
    def on_filechooserdialogHDC_hide_event(self, widget, *event):
        if self.currimage_settings.hdc_image != None and os.path.exists(self.currimage_settings.hdc_image):
            self.filechooserbuttonHDC.set_filename(self.currimage_settings.hdc_image)
        elif self.currimage_settings.cdrimage != None and os.path.exists(self.currimage_settings.cdrimage):
            self.filechooserbuttonHDC.set_filename(self.currimage_settings.cdrimage)
            self.check_bootstatus(self.currimage_settings.cdrimage, 'cdrom')
        
            self.toggle_storebuttons(True, "on_filechooserdialogHDC_hide_event")         
        
    def on_filechooserdialogHDD_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            self.currimage_settings.hdd_image = file
            return file
    
    def on_filechooserdialogHDD_hide_event(self, widget, *event):
        if os.path.exists(self.currimage_settings.hdd_image ):
            self.filechooserbuttonHDD.set_filename(self.currimage_settings.hdd_image)
            self.toggle_storebuttons(True, "on_filechooserdialogHDD_hide_event")     
        
    def on_filechooserdialogFDA_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            self.currimage_settings.fda_image = file
            return file
    
    def on_filechooserdialogFDA_hide_event(self, widget, *event):
        if os.path.exists(self.currimage_settings.fda_image ):
            self.filechooserbuttonFDA.set_filename(self.currimage_settings.fda_image)
            self.check_bootstatus(self.currimage_settings.fda_image, 'fda')            
            self.toggle_storebuttons(True, "on_filechooserdialogFDA_hide_event")     
        
    def on_filechooserdialogFDB_response(self, dialog=None, response=None, userdata=None):
        if response == gtk.RESPONSE_OK:
            file = copy(str(dialog.get_filename()))
            self.currimage_settings.fdb_image = file
            return file
    
    def on_filechooserdialogFDB_hide_event(self, widget, *event):
        if os.path.exists(self.currimage_settings.fdb_image ):
            self.filechooserbuttonFDB.set_filename(self.currimage_settings.fdb_image)
            self.toggle_storebuttons(True, "on_filechooserdialogFDB_hide_event") 
            

            
    def on_comboboxMediatypeHDC_changed(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.hdcmode = item
        #print 'switched hdcmode to: ' + str(self.hdcmode)
        if item == 'hdc':
            self.expanderCDrom.hide()
            self.expanderCDrom.set_expanded(False)
            self.currimage_settings.hdc_image = self.filechooserbuttonHDC.get_filename()
            self.currimage_settings.cdrimage = None
            self.currimage_settings.cdrmode = 'nocd'
        else:
            self.expanderCDrom.show()
            self.currimage_settings.cdrimage = self.filechooserbuttonHDC.get_filename()
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrmode = 'image'
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_comboboxMediatypeHDC_changed")
        self.switch_hdcicon() 
            
    def switch_hdcicon(self):
        if self.hdcmode == 'cdrom':
        #if self.currimage_settings.cdrimage != None or self.currimage_settings.cdrmedium != None:
            self.switch_stockicon(self.iconHDC, gtk.STOCK_CDROM, gtk.ICON_SIZE_BUTTON)
        else:
            self.switch_stockicon(self.iconHDC, gtk.STOCK_HARDDISK, gtk.ICON_SIZE_BUTTON)
    
    def switch_stockicon(self, imageobject, stocktype, gtksize=gtk.ICON_SIZE_BUTTON):
        image = gtk.Image()
        setimage = imageobject.set_from_stock(stocktype, gtksize)
        #setimage = imageobject.set_image(image)
        return setimage                        
            
    def on_radiobuttonBootHDA_toggled(self, widget):
        if widget.get_active() == True:
            self.toggle_bootmode('hda')
                
    def on_radiobuttonBootHDC_toggled(self, widget):
        if widget.get_active() == True:
            self.toggle_bootmode('cdrom')
            
    def on_radiobuttonBootFDA_toggled(self, widget):
        if widget.get_active() == True:
            self.toggle_bootmode('fda')
        
    def on_radiobuttonBootDlinux_toggled(self, widget):
        if widget.get_active() == True:
            self.toggle_bootmode('dlinux')    
                
    def toggle_bootmode(self, bootmedium):
        print '------------------------------------------------'        
        self.currimage_settings.dlinuxboot = False
        print 'Changed boot volume to: ' + str(bootmedium)
        uncomplete = True
        self.currimage_settings.bootmedium = bootmedium
        if bootmedium == 'hda':
            self.currimage_settings.dlinuxboot = False
            setupresult = self.setup_bootmode_hda()
            #self.comboboxMediatypeHDC.set_sensitive(True)
        elif bootmedium == 'cdrom':
            self.currimage_settings.dlinuxboot = False
            setupresult = self.setup_bootmode_cdrom()
            
        elif bootmedium == 'fda':
            self.currimage_settings.dlinuxboot = False
            setupresult = self.setup_bootmode_fda()
            #self.comboboxMediatypeHDC.set_sensitive(True)
        if bootmedium == 'dlinux':
            setupresult = self.setup_bootmode_dlinux()
            #self.comboboxMediatypeHDC.set_sensitive(True)
        else:
            self.expander_dlinuxboot.hide()
        print str(self.currimage_settings.main_image)    
        if self.restoreaction == False:
            if setupresult == True:
                self.toggle_storebuttons(True, "toggle_bootmode")
            else:
                self.toggle_storebuttons(False, "toggle_bootmode")
                
    def setup_bootmode_hda(self):
        complete = False 
        print 'Setting up boot hda'
        self.comboboxMediatypeHDC.set_sensitive(True)
        self.currimage_settings.bootmedium = 'hda'
        self.currimage_settings.boot_driveletter = 'c'
        #self.currimage_settings.bootmedium = bootmedium
        print 'boot hda: ' + str(self.currimage_settings.hda_image)
        if self.check_bootmode_hda() == True:
            self.currimage_settings.main_image = self.currimage_settings.hda_image
            complete = True  
        return complete
    
    def check_bootmode_hda(self):                          
        if str(self.currimage_settings.hda_image) == 'None':
            print 'no image found for ' + str(self.currimage_settings.bootmedium)
            statusmessage = '<span foreground="red">' + _("You selected boot from hda but there is no image selected for hda. Please select a hda image to make this machine work.") + '</span>'
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)
            return False
        else:
            return True                     
                
    def setup_bootmode_cdrom(self):
        print 'Setting up boot cdrom'
        complete = False
        ## first resetting all other bootmodes
        #self.currimage_settings.dlinuxboot = False
        ## Now setting the new variables that are required for next steps
        self.comboboxMediatypeHDC.set_active(1)
        self.comboboxMediatypeHDC.set_sensitive(False)
        self.currimage_settings.bootmedium = 'cdrom'
        if self.currimage_settings.cdrmode == 'nocd':
            self.currimage_settings.cdrmode = 'image'
        print 'cdrmode: ' + str(self.currimage_settings.cdrmode)
        
        if self.currimage_settings.cdrmode == 'mount':
            complete = self.setup_bootmode_cdrmedium()
        elif self.currimage_settings.cdrmode == 'image':
            complete = self.setup_bootmode_cdrmimage()
        else:
            if str(self.currimage_settings.cdrmedium) != 'None':
                self.currimage_settings.cdrmode = 'mount'
                complete = self.setup_bootmode_cdrmedium()
            elif str(self.currimage_settings.cdrimage) != 'None':
                self.currimage_settings.cdrmode = 'image'
                complete = self.setup_bootmode_cdrmimage()
            else:
                print 'no cdrom medium: ' + str(self.currimage_settings.cdrmedium)
                print 'no cdrom image: ' + str(self.currimage_settings.cdrimage)                
                statusmessage = '<span foreground="red">' + _("You selected boot from cdrom but there is no image or medium selected for cdrom. Please select a cdrom image or medium to make this machine work.") + '</span>'
                self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)                
        self.currimage_settings.boot_driveletter = 'd'
        #self.currimage_settings.bootmedium = bootmedium
        return complete
    
    def setup_bootmode_cdrmedium(self):
        complete = False
        print 'boot cdrom medium: ' + str(self.currimage_settings.cdrmedium)
        if self.check_bootmode_cdrmedium() == True:                    
            self.currimage_settings.main_image = self.cdrom_path_by_name(self.currimage_settings.cdrmedium)
            #self.set_hdc_type(self.currimage_settings.main_image)
            complete = True
        return complete
    
    def check_bootmode_cdrmedium(self):                          
        if str(self.currimage_settings.cdrmedium) == 'None':
            print 'no image found for ' + str(self.currimage_settings.bootmedium)
            statusmessage = '<span foreground="red">' + _("You selected boot from real cdrom but there is no medium selected for cdrom. Please select a cdrom image or medium to make this machine work.") + '</span>'
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)
            return False
        else:
            return True 
            
    def setup_bootmode_cdrmimage(self):
        complete = False
        if str(self.currimage_settings.hdc_image) != 'None':
            #self.currimage_settings.cdrimage = copy(self.currimage_settings.hdc_image)
            #self.currimage_settings.hdc_image = None
            #self.comboboxMediatypeHDC.set_active(1)
            self.set_hdc_type(self.currimage_settings.cdrimage, True)
            complete = True
        print 'boot cdrom image: ' + str(self.currimage_settings.cdrimage)
        if self.check_bootmode_cdrimage() == True:
            #self.comboboxMediatypeHDC.set_active(1)
            self.set_hdc_type(self.currimage_settings.cdrimage, True)
            self.currimage_settings.main_image = self.currimage_settings.cdrimage
            #self.set_hdc_type(self.currimage_settings.main_image)
            complete = True
        return complete     
    
    def check_bootmode_cdrimage(self):                          
        if str(self.currimage_settings.cdrimage) == 'None':
            print 'no image found for ' + str(self.currimage_settings.bootmedium)
            statusmessage = '<span foreground="red">' + _("You selected boot from cdrom but there is no image selected for cdrom. Please select a cdrom image or medium to make this machine work.") + '</span>'
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)
            return False
        else:
            return True        
        
    def setup_bootmode_fda(self):
        complete = False  
        self.comboboxMediatypeHDC.set_sensitive(True)    
        print 'boot fda image: ' + str(self.currimage_settings.fda_image)
        if self.check_bootmode_fda() == True:     
            self.currimage_settings.main_image = self.currimage_settings.fda_image
            complete = True
        self.currimage_settings.boot_driveletter = 'a'
        #self.currimage_settings.bootmedium = bootmedium
        return complete
    
    def check_bootmode_fda(self):                          
        if str(self.currimage_settings.fda_image) == 'None':
            print 'no image found for ' + str(self.currimage_settings.bootmedium)
            statusmessage = '<span foreground="red">' + _("You selected boot from fda but there is no image selected for fda. Please select a fda image to make this machine work.") + '</span>'
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)  
            return False
        else:
            return True     
        
    def setup_bootmode_dlinux(self):
        complete = False
        self.comboboxMediatypeHDC.set_sensitive(True)
        if self.check_bootmode_dlinux() == True:             
            self.currimage_settings.main_image = self.currimage_settings.kernelimage
            complete = True
        self.currimage_settings.boot_driveletter = 'c'
        #self.currimage_settings.bootmedium = bootmedium
        self.currimage_settings.dlinuxboot = True
        self.expander_dlinuxboot.show()
        return complete
    
    def check_bootmode_dlinux(self):                          
        if str(self.currimage_settings.kernelimage) == 'None':
            print 'no image found for ' + str(self.currimage_settings.bootmedium)
            statusmessage = _("You selected boot directly from linux kernel image but there is no kernel image selected. Please select a kernel image to make this machine work.")
            self.traypop = qml_tools.PopupInfo(statusmessage, None, 12, self.traypop)
            return False
        else:
            return True      
            
    def set_hdc_type(self, imagefile, warnonly=False): 
        fileparser = qml_tools.ImageInfo()
        fileinfo = fileparser.get_file_info(str(imagefile))
        print 'file info set_hdc_type: ' + str(fileinfo)
        if fileinfo['medium'] == 'hda' or fileinfo['medium'] == 'fda' or fileinfo['medium'] == None:
            if self.currimage_settings.bootmedium == 'cdrom':
                statusmessage = '<b>' + _("You selected boot from cdrom but the type of this image has been recognized as harddisk image. \
Bootable harddisk images can only get booted as hda. If You are sure, that the selected image is a bootable removable medium, please ignore this message. \
Else you should select this image as hda instead of cdrom and change the boot medium to hda.") + '</b>'
                self.traypop = qml_tools.PopupInfo(statusmessage, None, 30, self.traypop)
            else:
#                hdcfile = self.filechooserbuttonHDC.get_filename()
#                if hdcfile != None:
#                    self.currimage_settings.hdc_image = str(hdcfile)
                if warnonly != True:
                    self.comboboxMediatypeHDC.set_active(0)           
        elif fileinfo['medium'] == 'cdrom':
#            hdcfile = self.filechooserbuttonHDC.get_filename()
#            if hdcfile != None:
#                self.currimage_settings.cdrimage = str(hdcfile)
            if warnonly != True:
                self.comboboxMediatypeHDC.set_active(1)
        else:
            if warnonly != True:
                self.comboboxMediatypeHDC.set_active(0)                                 
            
                

          
    ## performs all actions when selecting an image
    def comboboxImagedevice_changed(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.currimage_settings.bootmedium = item
        if self.currimage_settings.bootmedium != "hda":
            self.filechooserbuttonHDA.set_sensitive( True )

        if self.currimage_settings.bootmedium != "fda":       
            self.filechooserbuttonFDA.set_sensitive( True )
        if self.currimage_settings.bootmedium == "hda":
            self.currimage_settings.boot_driveletter = "c"
            #self.activate_xtracdrom(True)      
            self.filechooserbuttonHDA.unselect_all()
            self.filechooserbuttonHDA.set_sensitive( False )   
        elif self.currimage_settings.bootmedium == "cdrom":            
            self.currimage_settings.boot_driveletter = "d"
            #self.activate_xtracdrom(False) 
        elif self.currimage_settings.bootmedium == "fda":            
            self.currimage_settings.boot_driveletter = "a"
            #self.activate_xtracdrom(True)  
            self.filechooserbuttonFDA.unselect_all() 
            self.filechooserbuttonFDA.set_sensitive( False )             
        else:
            self.currimage_settings.boot_driveletter = "c"
            #self.activate_xtracdrom(True) 
        #print "-" + self.currimage_settings.bootmedium + " -boot " + self.currimage_settings.boot_driveletter
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "comboboxImagedevice_changed")

        
#    def select_cdromdrive1(self, widget):
#        active = widget.get_active()
#        model = widget.get_model()
#        row = model[active]
#        item = row[0]
#        self.currimage_settings.cdrmedium = item
#        if self.restoreaction == False:
#            self.toggle_storebuttons(True, "select_cdromdrive1")
    
    def on_comboboxCDromdrive_changed(self, widget):  
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]          
        self.currimage_settings.cdrmedium = item
        
        self.check_bootstatus(self.cdrom_path_by_name(self.currimage_settings.cdrmedium), 'cdrom')

        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_comboboxCDromdrive_changed")
            
    def check_bootstatus(self, image, bootvolume):
        if self.currimage_settings.bootmedium == bootvolume:
            self.currimage_settings.main_image = image;
            self.currentimage = image
            self.toggle_bootmode(self.currimage_settings.bootmedium)
                    
#    def load_cdromdrive(self, widget):   
#        try:
#            active = widget.get_active()
#            model = widget.get_model()
#            row = model[active]
#            item = row[0]
#        except:
#            item = widget.get_filename()        
#        self.filechooserbutton_cdromdrive.unselect_all()
#        self.currimage_settings.cdrmedium = item
#        if self.currimage_settings.cdrmedium != "None" and self.currimage_settings.cdrmedium != None: 
#            self.filechooserbutton_cdromdrive.set_filename(str(self.currimage_settings.cdrmedium))
#        if self.restoreaction == False:
#            self.toggle_storebuttons(True, "load_cdromdrive")
            
    def on_expanderCDrom_activate(self, *widget):
        

        expstat = self.expanderCDrom.get_expanded()
        self.filechooserbuttonHDC.set_sensitive(expstat)
        self.button_eject_hdc.set_sensitive(expstat)
       
        if expstat == False:
            print 'aufgeklappt'
            self.currimage_settings.cdrmode = 'mount'
            self.comboboxCDromdrive.set_active(1)
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrimage = None
            self.filechooserbuttonHDC.unselect_all()
                
        else:
            print 'zugeklappt'
            self.currimage_settings.cdrmode = 'image'
            self.comboboxCDromdrive.set_active(0)           
            #self.currimage_settings.cdrimage = self.filechooserbuttonHDC.get_filename()
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrimage = None            
        print 'cdrmode expander: ' + str(self.currimage_settings.cdrmode)            
        
#    def select_cdromimage1(self, widget):
#        active = widget.get_active()
#        model = widget.get_model()
#        row = model[active]
#        item = row[0]
#        self.currimage_settings.cdrimage = item
#        if self.restoreaction == False:
#            self.toggle_storebuttons(True, "select_cdromimage1")
        
#    def on_filechooserbuttonImagecdrom_selection_changed(self, widget, event=None): 
#        if event != None:
#            print "Event: " + str(event)
#        item = str(widget.get_filename())

#    def on_filechooserbuttonImagecdrom_button_press_event(self, widget=None, *event):
#        #print str(widget)
#        print "filechooserbuttonImagecdrom widget: " + str(widget)
#        #print str(event)
#        print "filechooserbuttonImagecdrom event: " + str(event)


                                                
            
    def comboboxEmusystem_changed(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.currimage_settings.emusystem = item 
        self.qemubin = self.emusystem_path_by_name(self.currimage_settings.emusystem)
        self.get_soundhw()
        self.refresh_soundhw() 
        
        self.get_machine()
        self.refresh_machineslist()

        if self.restoreaction == False:
            self.toggle_storebuttons(True, "comboboxEmusystem_changed")       
        
    def on_comboboxMachinetype_changed(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.currimage_settings.machine = item
        self.machinecommand = self.machine_path_by_name(self.currimage_settings.machine) 
        self.get_soundhw()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_comboboxMachinetype_changed")      

    def on_comboboxAudiohw_changed(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.currimage_settings.soundhw = item   
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_comboboxAudiohw_changed")

    def on_checkbuttonUsevga_toggled(self, *widget):
        if self.checkbuttonUsevga.get_active() == True:
                self.currimage_settings.vgamode = "std-vga"
        else:
                #self.vgamode = "default"
                self.currimage_settings.vgamode = "default"
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonUsevga_toggled")
        
    def on_checkbuttonNovga_toggled(self, *widget):
        self.currimage_settings.novga = self.checkbuttonNovga.get_active()
        print "No VGA state changed: " + str(self.currimage_settings.novga)
        if self.currimage_settings.novga == False:
            self.checkbuttonUsevga.set_sensitive(True)
            self.checkbuttonStartvnc.set_sensitive(True)
            self.spinbuttonVncdisplay.set_sensitive(True)
            self.checkbuttonFullscreen.set_sensitive(True)
        else:
            self.checkbuttonUsevga.set_active(False)
            self.checkbuttonUsevga.set_sensitive(False)
            self.checkbuttonStartvnc.set_active(False)
            self.checkbuttonStartvnc.set_sensitive(False)
            self.spinbuttonVncdisplay.set_sensitive(False)
            self.checkbuttonFullscreen.set_active(False)
            self.checkbuttonFullscreen.set_sensitive(False)
            
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonNovga_toggled")  
        
    def on_checkbuttonFullscreen_toggled(self, *widget):
        fullscreenmode = self.checkbuttonFullscreen.get_active()
        self.currimage_settings.fullscreenmode = fullscreenmode
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonNovga_toggled")          
    
             
                
    def on_checkbuttonStartvnc_toggled(self, *widget):
        if self.checkbuttonStartvnc.get_active() == True:
                self.currimage_settings.usevnc = True
        else:
                self.currimage_settings.usevnc = False
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonStartvnc_toggled")   
                
    def on_spinbuttonVncdisplay_changed(self, *widget):
        value = self.spinbuttonVncdisplay.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.currimage_settings.vncdisplay = valint
        #print valint
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_spinbuttonVncdisplay_changed")
        
    def on_spinbuttonMemory_changed(self, widget, *data):
        value = self.spinbuttonMemory.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.currimage_settings.memory = valint
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_spinbuttonMemory_changed")
            
    def on_spinbuttonCPUs_changed(self, widget, *data):
        value = self.spinbuttonCPUs.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.currimage_settings.cpus = valint
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_spinbuttonMemory_changed")            
        
    def on_checkbuttonEnableUSB_toggled(self, *widget):
        self.currimage_settings.useusb = self.checkbuttonEnableUSB.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonEnableUSB_toggled")
        
#    def set_dlinuxboot(self, *widget):
#        self.currimage_settings.dlinuxboot = self.checkbuttonDlinuxboot.get_active()
#        if self.restoreaction == False:
#            self.toggle_storebuttons(True, "set_dlinuxboot")
        
    def on_filechooserbuttonKernelimage_selection_changed(self, widget): 
        #print 'on_filechooserbuttonKernelimage_selection_changed'
        item = ''
        item = widget.get_filename() 
        #print 'item ' + str(item)
        self.currimage_settings.kernelimage = str(item)
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_filechooserbuttonKernelimage_selection_changed")
        
    def on_filechooserbuttonInitrd_selection_changed(self, widget): 
        item = widget.get_filename() 
        self.currimage_settings.initrd = str(item)
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_filechooserbuttonInitrd_selection_changed")
        
    def on_entryKernelcmd_changed(self, widget): 
        item = widget.get_text() 
        self.currimage_settings.kernelcmd = item
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryKernelcmd_changed")             
        
    def on_checkbuttonSnapshotmode_toggled(self, *widget):
        self.currimage_settings.snapshotmode = self.checkbuttonSnapshotmode.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonSnapshotmode_toggled")
            
    def on_checkbuttonNoacpi_toggled(self, *widget):
        self.currimage_settings.noacpi = self.checkbuttonNoacpi.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonSnapshotmode_toggled")
            
    def on_checkbuttonNoreboot_toggled(self, *widget):
        self.currimage_settings.noreboot = self.checkbuttonNoreboot.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonSnapshotmode_toggled")            
                        
    def on_checkbuttonStartpaused_toggled(self, *widget):
        self.currimage_settings.startpaused = self.checkbuttonStartpaused.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonStartpaused_toggled")
            
    def on_checkbuttonDaemonize_toggled(self, *widget):
        self.currimage_settings.daemonize = self.checkbuttonDaemonize.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonStartpaused_toggled")
            
    def on_checkbuttonWaitgdb_toggled(self, *widget):
        self.currimage_settings.waitgdb = self.checkbuttonWaitgdb.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonStartpaused_toggled")                        
        
    def on_checkbuttonLocaltime_toggled(self, *widget):
        self.currimage_settings.localtimemode = self.checkbuttonLocaltime.get_active()
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonLocaltime_toggled")     
     
    def on_entryAdditionalCommandline_changed(self, widget):
        
        self.currimage_settings.customoptions = widget.get_text()
        #print "changed cutomopts: " + str(self.currimage_settings.customoptions)
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryAdditionalCommandline_changed")   
                        
    def cdrom_path_by_name(self, name):
        cdrdrives = self.settings["cdromdrives"]
        path = "None"
        dev = "None"
        if len(cdrdrives) != 0:
            for setting in cdrdrives:
                if setting[0] == name:
                    path = setting[1]
                    #print "cdrom path for " + str(name) + ": " + str(path)
        return path
        
    def soundhw_path_by_name(self, name):
        audiohws = self.audio_devlist
        dev = "None"
        if len(audiohws) != 0:
            for setting in audiohws:
                if setting[1] == name:
                    dev = setting[0]
                    #print "sounddev: " + dev
        return dev        
        
    def cdrom_name_by_path(self, path):
        cdromdrives = self.settings["cdromdrives"]
        path = "None"
        if len(cdromdrives) != 0:
            for setting in cdromdrives:
                if setting[1] == path:
                    name = setting[0]
                    #print "name: " + name
                    #print "cdrom name for " + str(path) + ": " + str(name)
        return path
        
    def emusystem_path_by_name(self, name):
        qemuapps = self.settings["qemuapps"]
        path = "None"
        if len(qemuapps) != 0:
            for setting in qemuapps:
                if setting[0] == name:
                    path = setting[1]
                    #print "path: " + path
        return path        
        
    def machine_path_by_name(self, name):
        machines = self.machineslist
        path = ""
        if len(machines) != 0:
            for setting in machines:
                #print "found: " + str(setting[0])
                if setting[1] == name:
                    path = setting[0]
                    #print "machinecommand: " + str(path)
        return path         

    def on_radiobuttonNokqemu_toggled(self, widget):
        self.currimage_settings.kqemu_param = "-no-kqemu"
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_radiobuttonNokqemu_toggled")
        
    def on_radiobuttonKqemu_toggled(self, widget):
        self.currimage_settings.kqemu_param = ""
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_radiobuttonKqemu_toggled")
        
    def on_radiobuttonKKqemu_toggled(self, widget):
        self.currimage_settings.kqemu_param = "-kernel-kqemu"
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_radiobuttonKKqemu_toggled")
            
            
    ''' Functions to setup Extended settings '''
    
    def on_entryRedirectSerial_changed(self, widget): 
        value = widget.get_text() 
        self.currimage_settings.redirect_serial = value
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryRedirectSerial_changed")
            
    def on_entryRedirectParallel_changed(self, widget): 
        value = widget.get_text() 
        self.currimage_settings.redirect_parallel = value
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryRedirectParallel_changed")
            
    def on_button_clear_serial_pressed(self, widget):
        self.entryRedirectSerial.set_text('')
        
    def on_button_clear_parallel_pressed(self, widget):
        self.entryRedirectParallel.set_text('')
        
    def on_entryPidfile_changed(self, widget): 
        value = widget.get_text() 
        self.currimage_settings.pidfile = value
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryPidfile_changed")
            
    def on_entryGdbport_changed(self, widget): 
        value = widget.get_text() 
        self.currimage_settings.gdbport = value
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryGdbport_changed")
            
    def on_entryOptionrom_changed(self, widget): 
        value = widget.get_text() 
        self.currimage_settings.optionrom = value
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_entryOptionrom_changed")            
            
    def on_buttonClearPidfile_pressed(self, widget):
        self.entryPidfile.set_text('')
        
    def on_buttonClearGdbport_pressed(self, widget):
        self.entryGdbport.set_text('')                                
        
    def on_buttonClearOptionrom_pressed(self, widget):
        self.entryOptionrom.set_text('') 
                
    def on_button_audioenviron_clicked(self, widget):
        #self.entryRedirectParallel.set_text('')
        #audioenviron = qml_audioenviron.Audio_environment
        #self.audioenviron = Audio_environment()
        self.audioenviron.init_gui(self.currimage_settings.audioenvironment)
        #print "audioenviron opened with: " + str(self.currimage_settings.audioenvironment)
        
    def on_checkbuttonDefaultaudioenv_toggled(self, widget):
        #print 'on_checkbuttonDefaultaudioenv_toggled: ' + str(widget.get_active())
        if widget.get_active() == True:
            self.button_audioenviron.set_sensitive(False)
            self.currimage_settings.audioenvironment = 'Default'
            self.toggle_storebuttons(True, "apply_audioenv")
        else:
            self.button_audioenviron.set_sensitive(True)
            #self.audioenviron.init_gui()
            #if self.currimage_settings.audioenvironment == 'Default':
            #    self.currimage_settings.audioenvironment = {}
            
    def apply_audioenv(self, audioenvironment):
        #print 'Stored audio environment: ' + str(audioenvironment)
        if audioenvironment != None and audioenvironment != '':
            self.currimage_settings.audioenvironment = audioenvironment
            self.toggle_storebuttons(True, "apply_audioenv")
            #print 'stored:' + str(self.currimage_settings.audioenvironment)
                
        
    def delete_openimagedialog(self): # dummy function
        pass
        
    def fileChooser_emuimage(self, widget):
        
        dic = {"on_filechooserdialog_openimage_destroy" : self.delete_openimagedialog
        , "on_filechooserdialog_openimage_response" : self.fileChooser_emuimage_response
        }
        
        self.TreeFilechooserdialog_openimage = gtk.glade.XML(self.gladefile, "filechooserdialog_openimage", APP)
        self.filechooserdialog_openimage = self.TreeFilechooserdialog_openimage.get_widget("filechooserdialog_openimage")
        #self.filechooserdialog_openimage = gtk.glade.XML(self.gladefile, "filechooserdialog_openimage", APP)
        
        
        self.TreeFilechooserdialog_openimage.signal_autoconnect(dic)
        self.filechooserdialog_openimage.show_all()
        
#    def fileChooser_response(self, widget, response, *entry):
#        #print 'widget: ' + str(widget)
#        #print 'response: ' + str(response)
#        file = None
#        entrytext = widget.get_filename()
#        #print 'entry: ' + entrytext
#        if response == gtk.RESPONSE_OK:
#            file = widget.get_filename ()
#            widget.destroy ()
#            #print 'File selected: ' + file       
#            #self.set_currentimage(file)
#            return file      
#        elif response == gtk.RESPONSE_CANCEL:
#            widget.destroy ()   
#            #return None               
#        return file        

    def fileChooser_emuimage_response(self, widget, response, *entry):
        #print 'widget: ' + str(widget)
        #print 'response: ' + str(response)
        entrytext = widget.get_filename()
        #print 'entry: ' + entrytext
        if response == gtk.RESPONSE_OK:
            file = widget.get_filename ()
            widget.destroy ()
            #print 'File selected: ' + file       
            self.set_currentimage(file)
            return file      
        elif response == gtk.RESPONSE_CANCEL:
            widget.destroy ()   
            return None               
        return None    

    def activate_launchbuttons(self, switchstate):
        self.toolbutton_launch.set_sensitive(switchstate)
        self.combobox_runmode.set_sensitive(switchstate)
            
#    def activate_xtracdrom(self, switchstate):
#        #self.comboboxCDromdrive.set_sensitive(switchstate)  
#        self.radiobuttonCDromtype1.set_sensitive(switchstate)
#        self.radiobuttonCDromtype2.set_sensitive(switchstate)    
#        if switchstate == True:
#            self.radiobuttonCDromtype.set_active( False )
#        elif switchstate == False:
#            self.radiobuttonCDromtype.set_active( True )             
    
 ## Function to prebuild the qemu network commands
    def qemu_network_command(self):    
        qemu_netcommand = " "
        if self.currimage_settings.networkmode == "nonet":
            qemu_netcommand = " -net none"
        elif self.currimage_settings.networkmode == "usermode" or self.currimage_settings.networkmode == "":
            qemu_netcommand = self.currimage_settings.usernetwork.create_qemucommand()
            #qemu_netcommand = " -net nic,vlan=0 -net user,vlan=0,hostname=" + self.network_hostname            
        elif self.currimage_settings.networkmode == "custom":
            if len(self.currimage_settings.networksetup) != 0:
                for netcard in self.currimage_settings.networksetup:
                    command = netcard.create_qemucommand()
                    qemu_netcommand = qemu_netcommand + command
            if len(self.currimage_settings.networkredirs) != 0:
                for redir in self.currimage_settings.networkredirs:
                    command = redir.create_qemucommand()
                    qemu_netcommand = qemu_netcommand + command
                
        if self.currimage_settings.networkmode != "nonet":
                command = self.currimage_settings.smbsettings.create_qemucommand()
                qemu_netcommand = qemu_netcommand + command

        return qemu_netcommand
    
        #return version
 ## Function to build the qemu command
    def qemu_runmode(self, *widget):    
        actmode = str(self.combobox_runmode.get_active())
        model = self.combobox_runmode.get_model()
        row = model[actmode]
        runmode  = row[0]    
        return runmode
    
    def envars_command(self):
        commandline = ''
        
        audioline = self.envars_audio_command()
        commandline = commandline + audioline
        return commandline
    
    def envars_audio_command(self):
        commandline = ''
        commandline_params = ''
        commandline_driver = ''
        commandline_driverparams = ''
        if self.currimage_settings.audioenvironment != 'Default':
            try:    
                audiodriver = self.currimage_settings.audioenvironment['driver']
                commandline_driver = 'export ' + 'QEMU_AUDIO_DRV=' + audiodriver + ' && '
                commandline = commandline + str(commandline_driver)
            except:
                audiodriver = ''
                            
            audioparams = self.currimage_settings.audioenvironment['audioparams']
            
            pkeys = audioparams.keys()
            pkeys.sort()            
            for key in pkeys:   
                var = str(key) 
                outval = audioparams[key]['defaultval']
                #print var + ' = ' + str(outval)            
                commandline_params = commandline_params + 'export ' + var + '=' + outval + ' && '
            #print str(commandline_params)
            commandline = commandline + str(commandline_params)
            
        try:    
            driverparams = self.currimage_settings.audioenvironment['driverparams']
            dkeys = driverparams.keys()
            dkeys.sort()            
            for key in dkeys:   
                var = str(key) 
                outval = driverparams[key]['defaultval']
                #print var + ' = ' + str(outval)            
                commandline_driverparams = commandline_driverparams + 'export ' + var + '=' + outval + ' && '
            #print str(commandline_driverparams)
        except:
            commandline_driverparams = '' 
                 
        commandline = commandline + str(commandline_driverparams)
        return commandline    
    
 ## Function to build the qemu command
    def qemu_command(self, rmode):
        bootdriveletter = "c"
        netcommand = ""
        basecommand = ""
#        statecommand = ""
        
        qemuparams = {}
        if self.machinecommand != "":
            qemuparams['machinecommand'] = " -M " + self.machinecommand
        
        qemuparams['memorycommand'] = " -m " + str(self.currimage_settings.memory)
        
        if self.currimage_settings.kqemu_param != "":
            qemuparams['kqemucommand'] = " " + self.currimage_settings.kqemu_param
        
        #print "mode: " + self.currimage_settings.cdrmode        
        if self.currimage_settings.cdrmode == "mount" and self.currimage_settings.cdrmedium != None and self.currimage_settings.cdrmedium != "None" and self.currimage_settings.cdrmedium != "":
            cdrpath = self.cdrom_path_by_name(self.currimage_settings.cdrmedium)
            qemuparams['cdrcommand'] = " -cdrom " + cdrpath
        elif self.currimage_settings.cdrmode == "image" and self.currimage_settings.cdrimage != None and self.currimage_settings.cdrimage != "None" and self.currimage_settings.cdrimage != "":
            qemuparams['cdrcommand'] = " -cdrom " + self.currimage_settings.cdrimage            

        if self.currimage_settings.soundhw != "" and self.currimage_settings.soundhw != "None":
            soundhw = self.soundhw_path_by_name(self.currimage_settings.soundhw)
            qemuparams['soundhwcommand'] = " -soundhw " + soundhw

        if self.currimage_settings.novga == True:
            qemuparams['novgacommand'] = " -nographic" 
            
        if self.currimage_settings.fullscreenmode == True: 
            qemuparams['fullscreencommand'] = " -full-screen"         
            
        if self.currimage_settings.vgamode == "std-vga":
            qemuparams['vgacommand'] = " -std-vga"

        if self.currimage_settings.usevnc == True:
            if self.qemu_commandset == 'old':
                qemuparams['vnc_command'] = " -usbdevice tablet -vnc " + str(self.currimage_settings.vncdisplay)              
            else:
                qemuparams['vnc_command'] = " -usbdevice tablet -vnc :" + str(self.currimage_settings.vncdisplay)
        
        if self.currimage_settings.useusb == True:
            qemuparams['usb_command'] = " -usb" 

        if self.currimage_settings.snapshotmode == True:
            qemuparams['snapsot_command'] = " -snapshot" 
            
        if self.currimage_settings.startpaused == True:
            qemuparams['startpaused_command'] = " -S"

        if self.currimage_settings.localtimemode == True:
            qemuparams['localtime_command'] = " -localtime"                             
        
        if self.currimage_settings.hda_image != None and self.currimage_settings.hda_image != "" and self.currimage_settings.hda_image != "None":
            qemuparams['hda_command'] = " -hda " + str(self.currimage_settings.hda_image)
        #print 'hda_command: ' + str(hda_command)
        if self.currimage_settings.hdb_image != None and self.currimage_settings.hdb_image != "" and self.currimage_settings.hdb_image != "None":
            qemuparams['hdb_command'] = " -hdb " + str(self.currimage_settings.hdb_image)
        
        if self.currimage_settings.hdc_image != None and self.currimage_settings.hdc_image != "" and self.currimage_settings.hdc_image != "None":
            qemuparams['hdc_command'] = " -hdc " + str(self.currimage_settings.hdc_image)          
        
        if self.currimage_settings.hdd_image != None and self.currimage_settings.hdd_image != "" and self.currimage_settings.hdd_image != "None":
            qemuparams['hdd_command'] = " -hdd " + str(self.currimage_settings.hdd_image)
        
        if self.currimage_settings.fda_image != None and self.currimage_settings.fda_image != "" and self.currimage_settings.fda_image != "None":
            qemuparams['fda_command'] = " -fda " + str(self.currimage_settings.fda_image)
                    
        if self.currimage_settings.fdb_image != None and self.currimage_settings.fdb_image != "" and self.currimage_settings.fdb_image != "None":
            qemuparams['fdb_command'] = " -fdb " + str(self.currimage_settings.fdb_image)
            
        ''' Commands from extra settings '''
        if self.currimage_settings.redirect_serial != "" and self.currimage_settings.redirect_serial != None:
                qemuparams['redirect_serial_command'] = " -serial " + self.currimage_settings.redirect_serial
                #print "kernelimage: " + str(self.currimage_settings.kernelimage)
                #time.sleep(1)
                
        if self.currimage_settings.redirect_parallel != "" and self.currimage_settings.redirect_parallel != None:
                qemuparams['redirect_parallel_command'] = " -parallel " + self.currimage_settings.redirect_parallel
                #print "kernelimage: " + str(self.currimage_settings.kernelimage)
                #time.sleep(1)
        if self.currimage_settings.noacpi != "" and self.currimage_settings.noacpi != False:
                qemuparams['noacpi_command'] = " -no-acpi"
                
        if self.currimage_settings.noreboot != "" and self.currimage_settings.noreboot != False:
                qemuparams['noreboot_command'] = " -no-reboot" 
                
        if self.currimage_settings.daemonize != "" and self.currimage_settings.daemonize != False:
                qemuparams['daemonize_command'] = " -daemonize"                     
                
        if int(self.currimage_settings.cpus) > 1:
                qemuparams['cpus_command'] = " -smp " + str(self.currimage_settings.cpus)
                
        if self.currimage_settings.pidfile != "" and self.currimage_settings.pidfile != None:
                qemuparams['pidfile_command'] = " -pidfile " + str(self.currimage_settings.pidfile)
                
        if self.currimage_settings.waitgdb != "" and self.currimage_settings.waitgdb != False:
                qemuparams['waitgdb_command'] = " -s"
                
        if self.currimage_settings.gdbport != "" and self.currimage_settings.gdbport != None:
                qemuparams['gdbport_command'] = " -p " + str(self.currimage_settings.gdbport)
                
        if self.currimage_settings.optionrom != "" and self.currimage_settings.optionrom != None:
                qemuparams['optionrom_command'] = " -option-rom " + str(self.currimage_settings.optionrom)                
                
        if self.statefile != None:
            if self.qemu_commandset == 'old':
                thisjobdir = self.statefiles_dir + "/" + self.translated_name
                statefile_path = path.abspath(self.statefiles_dir + "/" + self.translated_name + "/" + self.statefile)
                qemuparams['statecommand'] = " -loadvm " + statefile_path
            else:
                qemuparams['statecommand'] = " -loadvm " + self.statefile
        
        if self.currimage_settings.customoptions != "":
            qemuparams['customoptions'] = " " + self.currimage_settings.customoptions      

        bootdriveletter = self.currimage_settings.boot_driveletter
        monitor_command = " -monitor pty"
        netcommand = self.qemu_network_command()

        #print 'customoptions' + str(customoptions)
        basecommand = ''
        for key in qemuparams.keys():
            option = qemuparams[key]
            basecommand = basecommand + option
        basecommand = self.qemubin + basecommand + netcommand
        #basecommand = self.qemubin + machinecommand + memorycommand + statecommand + redirect_serial_command + redirect_parallel_command + noacpi_command + noreboot_command +  +snapsot_command + startpaused_command + localtime_command + " " + self.currimage_settings.kqemu_param + netcommand + usb_command + vgacommand + novgacommand + fullscreencommand + soundhwcommand + vnc_command + customoptions + cdrcommand + hda_command + hdb_command + hdc_command + hdd_command + fda_command + fdb_command
        self.basecommand = basecommand
        #print "qemu run mode: " + str(rmode)
        #self.loadvm_command = self.qemubin + machinecommand + memorycommand + statecommand + redirect_serial_command + redirect_parallel_command + snapsot_command + startpaused_command + localtime_command + " " + self.currimage_settings.kqemu_param + netcommand + usb_command + vgacommand + novgacommand + fullscreencommand + soundhwcommand + vnc_command + customoptions + cdrcommand + hda_command + hdb_command + hdc_command + hdd_command + fda_command + fdb_command

        managed_command = basecommand + monitor_command
        unmanaged_command = basecommand
        
        if self.currimage_settings.dlinuxboot == True:
            kernelparam = ""
            if self.currimage_settings.kernelcmd != "" and self.currimage_settings.kernelcmd != None:
                kernelparam = " -append " + self.currimage_settings.kernelcmd
                #print "kernelimage: " + str(self.currimage_settings.kernelimage)
                #time.sleep(1)
            
            initrdcommand = ""
            if self.currimage_settings.initrd != "" and self.currimage_settings.initrd != None:
                initrdcommand = " -initrd " + str(self.currimage_settings.initrd)
                
#            bootcommand =  lambda x : x + " -kernel " + str(self.currimage_settings.kernelimage) + str(initrdcommand) + str(kernelparam)
#        else:
#            bootcommand =  lambda x : x + " -" + self.currimage_settings.bootmedium  + " " + self.currentimage + " -boot " + bootdriveletter
            bootcommand =  lambda x : x + " -kernel " + str(self.currimage_settings.kernelimage) + str(initrdcommand) + str(kernelparam)
        else:
            bootcommand =  lambda x : x + " -boot " + bootdriveletter
        
        
        #envars_command = 'export QEMU_OSS_FRAGSIZE=4096 && '
        envars_command = self.envars_command()
        #envars_command = ''
        #envars_check = ' echo $QEMU_OSS_FRAGSIZE && '
        try:
            if rmode== "Managed":
                qemucommand = envars_command + bootcommand(managed_command)
            else:
                qemucommand = envars_command + bootcommand(unmanaged_command)
        except:
            qemucommand = bootcommand(unmanaged_command)
        #print "Qemu command1: " + str(qemucommand)
        return qemucommand
    
    ## Function to launch Qemu
    def run_qemu(self, widget):
        runmode = self.qemu_runmode()
        #qemu_version = self.qemu_version()
        #print 'qemu_version: ' + str(self.qemu_version)

        if widget.name != "toolbutton_runstate":
            self.statefile = None
        print "qemu called with command: " + str(self.qemu_command(runmode))
        #print "from widget: " + str(widget.name)
        #print "-------------------------Run Qemu--------------------------------------"
        if runmode == "Managed":
            command = self.qemu_command(runmode)
            child = popen2.Popen3(command, 1)
            #child = popen2.Popen3(command)  
            if self.currimage_settings.bootmedium == 'cdrom' and str(self.currimage_settings.cdrmedium) != 'None':
                print 'waiting for cdrom drive...'
                time.sleep(3)                   
            child_stdin, child_stdout, child_stderr = child.tochild, child.fromchild, child.childerr
            
            child_stdin.close()
            pid = str(child.pid)
            print "started qemu with pid: " + str(pid)

            qemumonout = QemuGetPts(pid, child_stdout, child_stderr)
            qemumonout.start()   
            time.sleep(0.3)
            maxtry = 60
            trycount = 1
            #print "Looking for the launched pts terminal..."
            errormesg = _("No Message returned")
            while trycount < maxtry:
                try:
                    self.currentpts = qemumonout.currentpts
                    #print "Used pts device: " + str(self.currentpts)
                    break
                except:
                    try:
                        
                        errormesg = qemumonout.errormessage
                    except:
                        pass
                    #print "waiting for pts answer " + str(trycount) + " " + str(maxtry)
                    time.sleep(0.3)
                    trycount = trycount+1
            #print "vergleich " + str(trycount) + " " + str(maxtry)                
            if trycount == maxtry:
                print "timeout!"
                dialogtitle = _('Error!')
                dialogtext = _('Qemu exited with Error message:\n')
                dialog_markup = "<b>" + dialogtext + "</b>" + errormesg
                errordialog = qml_tools.Dialog("error", dialog_markup, dialogtitle)
            else:    
                selected_job_displaymode = "default"
                if self.currimage_settings.usevnc == True:
                    selected_job_displaymode = "vnc"
                elif self.currimage_settings.novga == True:
                    selected_job_displaymode = "novga"   
                    
                if self.currimage_settings.startpaused == True:
                    runstat = 0
                else:
                    runstat = 1   
                if self.selected_bookmark != None:
                    jname = self.selected_bookmark
                else:
                    jname = '--'      
                #ljob = [pid, self.currentpts, self.currentimage, selected_job_displaymode, runstat, jname]
                ljob = [jname, self.currentimage, pid, self.currentpts, selected_job_displaymode, runstat]
                wjob = [pid, self.currentpts, self.currentimage]
    
                if self.jobwatcher.status == "stopped":
                    self.jobwatcher = QemuWatcher(self.joblist.remove_job2)
                self.joblist.add_job(ljob)
                self.jobwatcher.joblist.append(wjob)
                if self.jobwatcher.status == "stopped":
                    self.jobwatcher.start()
                if self.settings["controlmon_autostart"] == True:
                    time.sleep(0.3)
                    if os.path.exists(self.currentpts):
                        self.selected_job = [jname, self.currentimage, pid, self.currentpts, selected_job_displaymode, runstat]
                        #self.selected_job = self.bookmarkify_job(self.selected_job)
                        #print "JOB: " + str(self.selected_job)
                        self.run_jobmanager()
                    else:
                        errormesg = copy(str(child_stderr.readlines(1024)).strip('[]').strip())
                        dialogtitle = _('Error!')
                        dialogtext = _('Qemu exited with Error message:\n')
                        dialog_markup = "<b>" + dialogtext + "</b>\n" + errormesg
                        errordialog = qml_tools.Dialog("error", dialog_markup, dialogtitle)
                child_stderr.close()
                child_stdout.close()
     
        elif runmode == "Unmanaged":  
            os.popen(self.qemu_command(runmode) + "&")
        elif runmode == "Terminal":  
            os.popen("xterm -hold -e %s &" %self.qemu_command(runmode))
            #os.popen("konsole --noclose -e %s &" %self.qemu_command(runmode))
        #print 'qemu startfunction finished'
        
#########################################
## Functions for the settings dialog        
    def create_model_cdromdrives(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                          gobject.TYPE_STRING)
        if len(data) != 0:
            for item in data:
                iter = store.append()
                itempath = item[0]
                itemname = item[1]
                store.set(iter, 0, item[0], 1, item[1])
        return store    

    def add_columns_cdromdrives(self, treeview, model):
    
        #renderer = gtk.CellRendererToggle()
        column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0)
        column.set_resizable(True)
        column2 = gtk.TreeViewColumn(_('Device'), gtk.CellRendererText(), text=1)
        column2.set_resizable(True)
        treeview.append_column(column)   
        treeview.append_column(column2) 
        
    def check_haveconfig(self, bootimage):
        
        #print 'configcheck started with image: ' + bootimage
        img_haveconfig = False
        try:
            if len(self.image_settings.keys()) != 0:
                for key in self.image_settings.keys():
                    #print 'key: ' + key
                    if bootimage == key:
                        img_haveconfig = True
                        break

        except:       
            #print "No config for " + str(bootimage) + " found"
            img_haveconfig = False
        return img_haveconfig
        
    def load_bookmarks(self, *widget):
        self.bookmarks = []
        try:
            outdata = getfromfile("bookmarks")
            if outdata  == { } or outdata == "":
                bookmarks = []
            else:
                bookmarks = outdata
        except:
            bookmarks = []
        if bookmarks != []:
            for entry in bookmarks:
               
                try:
                    if len(entry) == 4:
                        itemicon = entry[0]
                        itemname = entry[1]
                        itempath = entry[2] 
                        isoldconfig = True                 
                    elif len(entry) == 3 or len(entry) == 2:
                        itemicon = self.default_machine_icon
                        itemname = entry[0]
                        itempath = entry[1] 
                        isoldconfig = True
                except:
                    itemicon = entry.icon
                    itemname = entry.name
                    itempath = entry.path             
                    isoldconfig = False 
                
                haveconfig = self.check_haveconfig(itemname)
                if haveconfig == False:
                    haveconfig = self.check_haveconfig(itempath)
                if isoldconfig == True:
                    self.bookmarks.append((itemicon, itemname, itempath, haveconfig))
                else:
                    entry.haveconfig = haveconfig
                    self.bookmarks.append(entry)
        try:
            model = self.treeviewBookmarks.get_model()
            model.clear()
            model = self.create_model_bookmarks(self.bookmarks)
            self.treeviewBookmarks.set_model( model)
        except:
            model = self.create_model_bookmarks(self.bookmarks)
            self.treeviewBookmarks.set_model( model)
            self.add_columns_bookmarks( self.treeviewBookmarks, model)
   
    def create_model_bookmarks(self, data):
        store = gtk.ListStore(gtk.gdk.Pixbuf,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gtk.gdk.Pixbuf,
                          gobject.TYPE_STRING,)
        
        config_icon = gtk.Image()
        for item in data:
            iter = store.append()
            try:
                if len(item) == 4:
                    itemicon = item[0]
                    itemname = item[1]
                    itempath = item[2]
                    haveconfig = item[3] 
                    isoldconfig = True                 
                elif len(item) == 3:
                    itemicon = self.default_machine_icon
                    itemname = item[0]
                    itempath = item[1] 
                    haveconfig = item[2]
                    isoldconfig = True               
            except:
                itemicon = str(item.icon)
                itemname = str(item.name)
                itempath = str(item.path)
                haveconfig = item.haveconfig 
                modeldata = item.get_modeldata() 
                #print "modeldate: " + str(modeldata)
                isoldconfig = False
                #print "load new bookmark"  
            #print "haveconfig: " + str(haveconfig)
            markup_info = ''
            markup_info = markup_info + 'Name:            <b>' +itemname + '</b>\n'
            markup_info = markup_info + 'Bootimage:    <i>' +itempath + '</i>'
            #markup_info = markup_info + '</tr></table>'
            #markup_info = markup_itemname + '\n' + markup_itempath
            system_icon = None
            try:
                system_icon = gtk.gdk.pixbuf_new_from_file(itemicon)
            except:
                try:
                    icondir = icondirs[0]
                    system_icon = gtk.gdk.pixbuf_new_from_file(icondir + "/default.png")
                except:
                    pass
            
            if isoldconfig == False:
                config_icon = modeldata[3]
            else:
                if haveconfig == True:
                    config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-yes.png')
                else:
                    config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-no.png')
            #print "haveconfig: " + str(haveconfig) + " icon: " + str(config_icon) + "for item: " + str(itempath)
            icon = system_icon
            try:
                pwidth = system_icon.get_width()
                pheight = system_icon.get_height()
                pfact = float(pwidth) / float(pheight)
                oheight = float(self.default_iconsize) / pfact
                oheight = self.default_iconsize / pfact
                icon = system_icon.scale_simple(int(self.default_iconsize), int(oheight), 3)            
            except: 
                icon = system_icon
                          
            store.set(iter, 0, icon, 1, itemname, 2, itempath, 3, config_icon, 4, markup_info)

                #store.set(iter, 0, system_icon, 1, itemname, 2, itempath, 3, config_icon)
        return store  
   
    def add_columns_bookmarks(self, treeview, model):
    
        #renderer = gtk.CellRendererToggle()
        column_icon = gtk.TreeViewColumn(_('Icon'), gtk.CellRendererPixbuf(), pixbuf=0)
        #column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=1)
        
        column = gtk.TreeViewColumn(_('System'), gtk.CellRendererText(), markup=4)
        
        column.set_resizable(True)
        #column2 = gtk.TreeViewColumn(_('Boot image'), gtk.CellRendererText(), text=2)
        #column2.set_resizable(True)
        column3 = gtk.TreeViewColumn(_('configured'), gtk.CellRendererPixbuf(), pixbuf=3)
        column3.set_resizable(True)
        treeview.append_column(column_icon)
        treeview.append_column(column)   
        #treeview.append_column(column2)  
        treeview.append_column(column3)
        
    def search_bookmark(self, searchstring, returnval):
        ct = 0
        outct = None
        if len(self.bookmarks) != 0:
            for row in self.bookmarks:
                #print "row: " + str(row[0]) + " - " + str(row[1]) + " - " + str(row[2])
                if searchstring == row.path:
                    if returnval == "index":
                        outct = ct
                    elif returnval == "icon":
                        outct = row.icon                   
                    else:
                        outct = row.name
                    break
                
            ct = ct + 1      
        #print "search bookmark result: " + str(outct)            
        return outct
    
    def checkexist_bookmark(self, bookmarkname):
        #ct = 0
        doublecheck = False
        if len(self.bookmarks) != 0:
            for row in self.bookmarks:
                #print "row: " + str(row.name) + ' ' + str(row.path)
                if bookmarkname == row.name:
                    doublecheck = True
                    break
            #ct = ct + 1      
        #print "search bookmark result: " + str(outct)            
        return doublecheck    
           
        
#    def on_get_path_depr(self, node):
#        '''returns the tree path (a tuple of indices at the various
#        levels) for a particular node.'''
#        #print("on_get_path", node)
#        path = []
#        while node.parent:
#            path.append(node.index)
#            node = node.parent
#        path.reverse()
#        return tuple(path)

    def load_joblist(self, *widget):
        self.joblist = Joblist(self.treeview_joblist)
        self.joblist.jobmanagers = self.jobmanagers
        if os.path.exists(self.configdir + "/joblist"):
            self.joblist.load_joblist()
        if self.joblist.joblist_data and self.joblist.joblist_data != []:
            jc = 0    
            
            #self.jobwatcher = QemuWatcher(self.joblist.remove_job2) 
            if len(self.joblist.joblist_data) != 0:           
                for job in self.joblist.joblist_data:
                    #time.sleep(0.1)
                    
                    pid = job[2]
                    pts = job[3]
                    path = job[1]
                    displaymode = job[3]
                    ljob = [pid, pts, path]
                    wjob = [pid, pts, path]
                    chcommand = "ps -e | grep " + str(pid)
                    #print "chcommand: " + chcommand
                    checkpid = os.popen("ps -e | grep " + str(pid)).readlines()
                    #print "checking for pid " + str(pid) + ": " + str(checkpid)
                    if os.path.exists(pts) and checkpid != []:
                        if self.jobwatcher.status == "stopped":
                            self.jobwatcher = QemuWatcher(self.joblist.remove_job2)
                        self.jobwatcher.joblist.append(wjob)
                        if self.jobwatcher.status == "stopped":
                            self.jobwatcher.start()
                        time.sleep(0.1)
                    else:
                        #print "job is not running, remove from list"
                        self.joblist.remove_job2(ljob)
                        try:
                            jindex = self.jobwatcher.joblist.index(wjob)
                            del self.jobwatcher.joblist[jindex]
                            #print "removed from watcher daemon"
                        except:
                            #print "not in list"
                            pass
                    jc = jc+1
                
    ## actions when an image file was selected
    def on_treeviewBootimages_cursor_changed(self, widget):
        model, iter = widget.get_selection().get_selected()
        row = model[iter]
        item = row[0]
        #print "item: %s" %item
        self.set_currentimage(item) 
        self.selected_bookmark = None
        #print "item: %s" %item

    ## Function to set the current emu-image when clicking an Entry
    def set_currentimage(self, imgstring):
        if imgstring != None and imgstring != "":
            self.activate_launchbuttons(True)
            #print "Image: " + imgstring + " - selected"
            #_hid = self.entry_current_image.get_data('imageselection')
            _hid = self.imageselection
            #print "_hid: " + str(_hid)
            self.entry_current_image.handler_block(_hid)
            self.entry_current_image.set_text(imgstring)
            self.entry_current_image.handler_unblock(_hid)
            c = 0
            while self.entry_current_image.get_text() == "":
                c = c+1
                time.sleep(0.2)
                #print "waiting for selection"
                if c == 30: break 
            time.sleep(0.2)           
            self.select_image_from_path(imgstring)
        else:
            print "No image selected set current"
        return                
       
    def on_treeviewBookmarks_cursor_changed(self, widget):
        try:
            model, iter = widget.get_selection().get_selected()
            row = model[iter]
            name = row[1]
            item = row[2]
            #print "selected bookmark item: %s" %item
            self.selected_bookmark = name
            #print 'selected_bookmark: ' + str(self.selected_bookmark)
            self.set_currentimage(item)  
        except:
            pass

    def on_toolbutton_add_bookmark_clicked(self, widget, *event):
        menuitem = widget.get_name()
        if menuitem == "item_bookmark" or menuitem == "toolbutton_add_bookmark":
            self.add_bookmark(self, widget, event)
        if menuitem == "item_edit_bookmark":
            self.edit_bookmark(self, widget, event)
            response = self.edit_bookmark_response
            
    def add_bookmark(self, widget, *event):
        setupdiag = Machinesetup(self)
        
    def add_bookmark_from(self, widget, *event):
        setupdiag = Machinesetup(self, self.currentimage)        
     
            
    def edit_bookmark(self, widget, *event):
        GoOn = False
        mode = "add"

        response = self.edit_bookmark_response
            
        self.dialog_bookmarks = gtk.glade.XML(self.gladefile, "dialogEditBookmarks", APP)
        self.dialog_bookmarks_widget = self.dialog_bookmarks.get_widget("dialogEditBookmarks")
        self.dialog_bookmarks_widget.set_keep_above(True)
        try:
            self.dialog_bookmarks_widget.set_title("Edit selected Machine entry")
            model, iter = self.treeviewBookmarks.get_selection().get_selected()
            counter = int(model.get_string_from_iter(iter))
            #print "counter: " + str(counter)
            self.bookmark_tmpitem = self.bookmarks[counter]
            try:
                name = self.bookmark_tmpitem.name
                #inpath = self.bookmark_tmpitem.path
                icon = self.bookmark_tmpitem.icon
            except:
                name = self.bookmark_tmpitem[1]
                #inpath = self.bookmark_tmpitem[2]
                icon = path.abspath(self.bookmark_tmpitem[0])  
                if icon == "" or str(icon) == 'None':
                    icon = path.abspath(self.default_machine_icon)
            GoOn = True             
        except:
            print "No machine selected"
            GoOn = False        
 
        if GoOn != False:
            Name_field = self.dialog_bookmarks.get_widget("entry_bookmark_name")
            #Path_field = self.dialog_bookmarks.get_widget("entry_bookmark_path")
            filechooserbutton_machine_icon = self.dialog_bookmarks.get_widget("filechooserbutton_machine_icon")
            image_iconpreview = self.dialog_bookmarks.get_widget("image_iconpreview")
            
            #Path_field.set_text(inpath)

            Name_field.set_text(name)
            iconpath = str(icon)                

            filechooserbutton_machine_icon.set_filename(iconpath)
            try:
                preview_icon = gtk.gdk.pixbuf_new_from_file(iconpath)
                preview_icon2 = preview_icon.scale_simple(32, 32, 3)
                image_iconpreview.set_from_pixbuf(preview_icon2)
            except:
                pass
            Name = Name_field.get_text()
            #Path = Path_field.get_text()
            
            dic = {"on_dialogEditBookmarks_response" : response,
                   "on_filechooserbutton_machine_icon_selection_changed" : self.update_bm_iconprev
            }
            self.dialog_bookmarks.signal_autoconnect(dic)
                        
            
    def update_bm_iconprev(self, widget):
        filechooserbutton_machine_icon = self.dialog_bookmarks.get_widget("filechooserbutton_machine_icon")
        image_iconpreview = self.dialog_bookmarks.get_widget("image_iconpreview")
        entry_icon = str(filechooserbutton_machine_icon.get_filename())
        if entry_icon != 'None':
            preview_icon = gtk.gdk.pixbuf_new_from_file(entry_icon)
            preview_icon2 = preview_icon.scale_simple(32, 32, 3)
            image_iconpreview.set_from_pixbuf(preview_icon2)              
                
    def edit_bookmark_response(self, widget, response, *entry):
        #print 'widget: ' + str(widget)
        #print 'response: ' + str(response)
        entryname = self.dialog_bookmarks.get_widget("entry_bookmark_name")
        #entrypath = self.dialog_bookmarks.get_widget("entry_bookmark_path")
        #filechooserbutton_machine_icon = self.dialog_bookmarks.get_widget( "filechooserbutton_machine_icon")
        filechooserbutton_machine_icon = self.dialog_bookmarks.get_widget("filechooserbutton_machine_icon")
        fname = filechooserbutton_machine_icon.get_filename()
        entry_icon = str(fname)
        entry_icon_pixbuf = gtk.gdk.pixbuf_new_from_file(entry_icon)
        entry_name = str(entryname.get_text())
        #entry_path = str(entrypath.get_text())
        haveconfig = str(self.check_haveconfig(self.currentimage))
        if haveconfig == True:
            config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-yes.png')
        else:
            config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-no.png')
        #print 'entryname: ' + entry_name
        #print 'entrypath: ' + entry_path
        if response == gtk.RESPONSE_OK:
            check_keepname = self.checkexist_bookmark(entry_name)
            #print 'check_keepname: ' + str(check_keepname)
            if check_keepname == False:
                #print 'Updating config...'
                #dialogtext = "<b>" + _("A Machine with this name allready exists, please choose another one") + "</b>"
                #delrequest = qml_tools.Dialog("error", dialogtext, "Name exists")
                if haveconfig == True:
                    oldsettings = self.currimage_settings
                    #newsettings = self.image_settings[self.selected_bookmark]
                    print 'entry_name: ' + str(entry_name)
                    print 'self.selected_bookmark: ' + str(self.selected_bookmark)
                    self.image_settings[entry_name] = copy(self.image_settings[self.selected_bookmark])
                    del self.image_settings[self.selected_bookmark]
                    storedata = self.image_settings
                    filename = "image_settings"
                    self.storetofile(storedata, filename)
                self.selected_bookmark = entry_name 
            #else: 
                
            model, iter = self.treeviewBookmarks.get_selection().get_selected()
            counter = int(model.get_string_from_iter(iter))                                           
            editbookmark = Bookmark()
            editbookmark.icon = entry_icon
            editbookmark.name = entry_name
            #editbookmark.path = entry_path
            editbookmark.path = self.currentimage
            editbookmark.haveconfig = haveconfig
            self.bookmarks[counter] = editbookmark
            self.storetofile(self.bookmarks, "bookmarks")
            self.refresh_bookmarks()
                

            widget.destroy()
            return entryname      
        elif response == gtk.RESPONSE_CANCEL:
            widget.destroy()   
            return None               
        return None
    
    def on_delete_bookmark_activate(self, *widget):
        model, iter = self.treeviewBookmarks.get_selection().get_selected()
        counter = int(model.get_string_from_iter(iter))
        #print "bookmark to remove: " + str(self.bookmarks[counter].name)        
        dialogtext = "<b>Do you really want to delete the\n"\
        "selected machine and it's configuration?</b>\n\n"\
        "Machine: " + self.bookmarks[counter].name
        dialogtitle = "Confirm delete"
        delrequest = qml_tools.Dialog("request", dialogtext, dialogtitle, self.remove_bookmark)         
    
    def remove_bookmark(self, *widget):
        #entry_path = self.selected_bookmark
        #print 'widget: ' + str(widget)
        #print 'entry: ' + str(entry_path)
        model, iter = self.treeviewBookmarks.get_selection().get_selected()
        counter = int(model.get_string_from_iter(iter))
        #print "bookmark to remove: " + str(self.bookmarks[counter].name)
        #print "bookmark ct to remove: " + str(counter)
        del self.bookmarks[counter]
        self.storetofile(self.bookmarks, "bookmarks")
        self.refresh_bookmarks()
        
    def treeviewBookmarks_drag_end(self, *widget):
        bookmarks = []
        #time.sleep(0.1)
        model = self.treeviewBookmarks.get_model() 
        for row in model:
            itemicon = row[0]
            itemname = row[1]
            itempath = row[2]
            haveconfig = self.check_haveconfig(itempath)
            newbookmark = Bookmark()
            iconpath = self.search_bookmark(itempath, "icon")
            newbookmark.icon = iconpath
            newbookmark.name = itemname
            newbookmark.path = itempath
            newbookmark.haveconfig = haveconfig
            try:
                bookmarks.append(newbookmark)
            except:
                bookmarks = [(newbookmark)]
        self.bookmarks = bookmarks                       
        self.storetofile(self.bookmarks, "bookmarks")
        
        
    def installwizzard(self, *widget):        
        installwizzard = Installwizzard(self)      

    
         
    def toggle_storebuttons(self, state, caller=None):

        self.button_apply_imagesettings.set_sensitive(state) 
        self.button_restore_imagesettings.set_sensitive(state)

    def select_image_from_widget(self, widget):
        currentpath = widget.get_text()
        self.select_image_from_path(currentpath)
    
    def select_image_from_path(self, srcpath):
        current = srcpath
        #self.vbox_bottompane.set_sensitive(False)
        if os.path.exists(current):   
            isbookmark = None
            isbookmark = self.search_bookmark(self.currentimage, "index")     
            #self.notebook_imgsettings.set_sensitive(True)
            
            self.currentimage = current
            self.restore_emu_config()
            self.activate_launchbuttons(True)
            #self.vbox_bottompane.set_sensitive(True)
        else:
            self.label_imgsettings.set_markup( _('<b>No image selected</b>'))
            self.activate_launchbuttons(False)
            #self.notebook_imgsettings.set_sensitive(False)  
            self.vbox_bottompane.set_sensitive(False)
            #self.toolbutton_add_bookmark.set_sensitive(False) 
            #print "No image selected from path: " + srcpath 
        
    def on_treeviewBookmarks_button_release_event(self, widget, event):    
        if event.button == 3:         
            try:  
                model, iter = self.treeviewBookmarks.get_selection().get_selected()
                row = model[iter]
                name = row[1]
                path = row[2]
                #print "selected bookmark item: %s" %path
                self.selected_bookmark = name      
                self.menu_popup_bookmarks.popup( None, None, None, 3, 0)
            except:
                print "no bookmark selected"
        else:
            pass                     
            
    #def cdrive_selection(self, widget, path, *view_column):
    def on_treeviewCDdrives_cursor_changed(self, widget):
        model, iter = widget.get_selection().get_selected()
        row = model[iter]
        item = row[1]
        #print "item: %s" %item
        self.set_currentimage(item)
        
    def clear_filechooser(self, widget):
        #print "name: " + str(widget.name)
        #fcb = None
        wname = None
        if widget == self.button_eject_hda:
            wname = self.filechooserbuttonHDA
            self.currimage_settings.hda_image = None
#            fcb = self.wTree[wname]
        elif widget == self.button_eject_hdb:
            wname = self.filechooserbuttonHDB
            self.currimage_settings.hdb_image = None
            #fcb = self.filechooserbuttonHDB
        elif widget == self.button_eject_hdc:
            wname = self.filechooserbuttonHDC
            self.currimage_settings.hdc_image = None
            self.currimage_settings.cdrimage = None                
            #fcb = self.filechooserbuttonHDC 
        elif widget == self.button_eject_hdd:
            wname = self.filechooserbuttonHDD
            self.currimage_settings.hdd_image = None
            #fcb = self.filechooserbuttonHDD 
        elif widget == self.button_eject_fda:
            wname = self.filechooserbuttonFDA
            fcb = self.filechooserbuttonFDA
            self.currimage_settings.fda_image = None                       
        elif widget == self.button_eject_fdb:
            wname = self.filechooserbuttonFDB
            self.currimage_settings.fdb_image = None
        elif widget == self.button_eject_kernelimage:
            wname = self.filechooserbuttonKernelimage
            self.currimage_settings.kernelimage = None
            if self.currimage_settings.bootmedium == 'dlinux':   
                if self.check_bootmode_dlinux() != True:
                    self.toggle_storebuttons(False, "check emptyboot")              
        elif widget == self.button_eject_initrd:
            wname = self.filechooserbuttonInitrd
            self.currimage_settings.initrd = None                     
        else:
            wname = None
        if wname != None: 
            fcb = wname
        self.toggle_storebuttons(True, "clear_filechooser")        
    
           
        try:
            #print 'changed to: ' + str(self.settings["imagespath"])
            fcb.set_current_folder(self.settings["imagespath"])
        except:
            #print 'cleared'
            fcb.unselect_all()
                
        if self.currimage_settings.bootmedium == 'hda':
            if self.check_bootmode_hda() != True:
                self.toggle_storebuttons(False, "check emptyboot")     
        elif self.currimage_settings.bootmedium == 'cdrom':
            if self.check_bootmode_cdrimage() != True:
                self.toggle_storebuttons(False, "check emptyboot") 
        elif self.currimage_settings.bootmedium == 'fda':   
            if self.check_bootmode_fda() != True:
                self.toggle_storebuttons(False, "check emptyboot")                                        
        else:
            self.toggle_storebuttons(True, "clear_filechooser")                               
                   
    def treeviewBootimages_button_press_event(self, widget, event):
        
        if event.button == 3:
            sel = self.isolist.get_selection().get_selected()
            model = self.isolist.get_model()
            try:
                self.selected_image = model.get_value(sel[1], 0)
                self.currentimage = self.selected_image
                self.menu_popup_imagelist.popup( None, None, None, 3, 0)
            except:
                print "no image selected"      
                
    def on_treeviewCDdrives_button_release_event(self, widget, event):
        
        if event.button == 3:
            sel = self.treeviewCDdrives.get_selection().get_selected()
            model = self.treeviewCDdrives.get_model()
            self.selected_image = model.get_value(sel[1], 1)
            self.currentimage = self.selected_image
            self.menu_popup_devices.popup( None, None, None, 3, 0)
                
    def on_treeview_joblist_cursor_changed(self, widget):
    #try:
        model, iter = widget.get_selection().get_selected()
        row = model[iter]
        selected_job_name = row[0]
        selected_job_path = row[1]
        selected_job_pid = row[2]
        selected_job_pty = row[3]
        selected_job_displaymode = row[4]
        selected_job_runstat = row[5]
        #print "selected job : %s" %selected_job_pty
        self.selected_job = [selected_job_name, selected_job_path, selected_job_pid, selected_job_pty, selected_job_displaymode, selected_job_runstat]
        #self.selected_job = self.bookmarkify_job(self.selected_job)
        
        if selected_job_runstat == "1":
            self.item_cont_job.hide()
            self.item_stop_job.show()
            #print "running"
        else:
            self.item_cont_job.show()
            self.item_stop_job.hide()
            #print "stopped"
    #except:
    #    print "no job selected" 
            
    def pause_job(self, widget):
        job = self.selected_job
        try:
            self.jobmanagers[job[2]].pause_job(widget)
            #print "jobmanager found, stopping through its method"
        except:
            self.joblist.pause_job(widget, job)
        
    def cont_job(self, widget):
        job = self.selected_job
        try:
            self.jobmanagers[job[2]].cont_job(widget)
            #print "jobmanager found, starting through its method"
        except:
            self.joblist.cont_job(widget, job)   

    def reset_job(self, widget):
        job = self.selected_job
        try:
            self.jobmanagers[job[2]].reset_job(widget)
            #print "jobmanager found, starting through its method"
        except:
            self.joblist.reset_job(widget, job)
            
    def stop_job(self, widget):
        job = self.selected_job
        
        self.joblist.stop_job(widget, job) 
        #print "stopped job!"              

    def on_treeview_joblist_button_press_event(self, widget, event):
    #try:
        selected_job_name = self.selected_job[0]
        selected_job_path = self.selected_job[1]
        selected_job_pid = self.selected_job[2]
        selected_job_pty = self.selected_job[3]
        selected_job_displaymode = self.selected_job[4]
        selected_job_runstat = self.selected_job[5]
        self.currentpts = selected_job_pty
        
        if event.type == gtk.gdk._2BUTTON_PRESS:
            self.run_jobmanager(widget, self.selected_job)
        elif event.button == 3:
        #    self.menu_popup_joblist.popup(None, None, None, 3, 0)
            if event.type == gtk.gdk.BUTTON_RELEASE:
                self.menu_popup_joblist.popup(None, None, None, 3, 0)            
    #except:
    #    print "no job selected"   
    def on_treeview_joblist_button_release_event(self, widget, event):
        self.on_treeview_joblist_button_press_event(widget, event)
        
    
     
    def show_infomessage(self, *widget):
        image = self.selected_image
        info = self.fetch_image_info(image)
        title = _('image info')
        if info == '':
            info = 'no informations repeated, maybe this is not a valid image or\
device not mounted'
        #self.init_messages_dialog(info, title)
        infodialog = qml_tools.Dialog("longtext", info, title)
        
    def show_infomessage_bookmark(self, *widget):
        image = self.currentimage
        info = self.fetch_image_info(image)
        title = _('image info')
        #self.init_messages_dialog(info, title)      
        infodialog = qml_tools.Dialog("longtext", info, title) 

    def fetch_settings(self, *widget):
        self.qemubin = self.settings["qemuapps"][0][1]

        if self.settings.has_key("imagespath"):
            self.imagespath = self.settings["imagespath"]

        if self.settings.has_key("settings_autoshow"):
            self.settings_autoshow = self.settings["settings_autoshow"]

        if self.settings.has_key("settings_autohide"):        
            self.settings_autohide = self.settings["settings_autohide"]

        if self.settings.has_key("default_iconsize"):           
            self.default_iconsize = self.settings["default_iconsize"]

        self.get_soundhw()
            
    def get_soundhw(self, *event):
        qemucommand = self.qemubin
        prog = os.popen(str(qemucommand) + " -soundhw ?")
        #print 'get_soundhw' + str(prog)
        output = prog.readlines()
        output2 = []
        self.audio_devlist = []
        fc = 0
        for f in output:
            f = string.strip(f)
            if f != "":
                output2.append(f)
                fc = fc+1
        for f in output2:
            if f != output2[0] and f != output2[fc-1]:
                
                devdata = f.split(" ", 1)
                devdata = filter(None, devdata)
                devdata[0] = string.strip(devdata[0])
                devdata[1] = string.strip(devdata[1])
                self.audio_devlist.append(devdata) 
    
    def refresh_soundhw(self, *event):
        audiomodel = self.comboboxAudiohw.get_model()
        audiomodel.clear()
        audiomodel.append(row=("None",))
        for dev in self.audio_devlist:
            device = dev[0]
            name = dev[1]
            #print "dev: " + name + " - " + device
            audiomodel.append(row=(name,))
        self.comboboxAudiohw.set_model(audiomodel)      
        self.comboboxAudiohw.set_active(0)  
        
    ## Fetch the available machines for the selected emu system
    def get_machine(self, *event):
        #print "get machine"  
        #print "qemu system: " + str(self.qemubin)
        prog = os.popen(str(self.qemubin) + " -M ?")
        #print 'get_machine' + str(prog)
        output = prog.readlines()
        output2 = []
        self.machineslist = []
        fc = 0
        if len(output) != 0:
            for f in output:
                #print "count machines: " + str(fc)
                f = string.strip(f)
                #print "f: " + str(f)
                if f != "":
                    output2.append(f)
                    fc = fc+1
        if len(output2) != 0:
            for f in output2:
                if f != output2[0]:
                    devdata = f.split(" ", 1)
                    devdata = filter(None, devdata)
                    devdata[0] = string.strip(devdata[0])
                    devdata[1] = string.strip(devdata[1])
                    self.machineslist.append(devdata)   
            
    def refresh_machineslist(self, *event):
        machinemodel = self.comboboxMachinetype.get_model()
        machinemodel.clear()
        if len(self.machineslist) != 0:
            for dev in self.machineslist:
                device = str(dev[0])
                name = str(dev[1])
                #print "dev: " + name + " - " + device
                #print str(dev[0]) + " - " + str(dev[1])
                machinemodel.append(row=(name,))
                self.comboboxMachinetype.set_model(machinemodel)  
        self.comboboxMachinetype.set_active(0)     
                

        
    def refresh_devlist(self, *widget): 
        devlist_data = []   
        model = self.treeviewCDdrives.get_model() 
        model.clear()
        model = self.create_model_cdromdrives(self.settings["cdromdrives"]) 
        setmod = self.treeviewCDdrives.set_model(model)
        

      

            
## Open settings dialog

    def open_settings(self, *widget):
        self.settingsdialog = qml_configuration.Configuration(self.settings_callback)
        
    def settings_callback(self):
        self.settings = load_settings()
        self.fetch_settings()
        self.refresh_all()
        try:
            qemulator.refresh_bookmarks()
        except:
            pass
        self.toggle_settings_autoshow(self.settings_autoshow)
        self.toggle_settings_autohide(self.settings_autohide)
        #gtk.gdk.threads_leave()
        
    
#    def create_model_qemupaths(self, data):
#        store = gtk.ListStore(gobject.TYPE_STRING,
#                          gobject.TYPE_STRING)
#        for item in data:
#            iter = store.append()
#            itempath = item[0]
#            itemname = item[1]
#            #print itempath
#            #print itemname
#            store.set(iter, 0, item[0], 1, item[1])
#        return store        
#        
#    def add_columns_qemupaths(self, treeview, model):
#    
#        #renderer = gtk.CellRendererToggle()
#        column = gtk.TreeViewColumn('Name', gtk.CellRendererText(), text=0)
#        column2 = gtk.TreeViewColumn('Path', gtk.CellRendererText(), text=1)
#        treeview.append_column(column)   
#        treeview.append_column(column2)           
    
#    def settings_get_qemupath(self, widget, path, view_column):
#
#        model = widget.get_model()
#        row = model[path]
#        item = row[0]
#        #print "item: %s" %item
#        self.settings_set_currentqemupath(row)    
#        
#    def settings_set_currentqemupath(self, device_list):
#    
#            nameinput = self.dialog_settings.get_widget("entry_settings_qemuname")
#            devinput = self.dialog_settings.get_widget("entry_settings_qemupath")
#            
#            nameinput.set_text(device_list[0])
#            devinput.set_text(device_list[1])  
#    
#    def settings_add_qemupath(self, widget):
#            #print "new qemupath"
#            name = self.dialog_settings.get_widget("entry_settings_qemuname").get_text()
#            path = self.dialog_settings.get_widget("entry_settings_qemupath").get_text()
#            qemulist = self.dialog_settings.get_widget("treeview_qemupaths")
#            model = qemulist.get_model()
#            model.append(row=(name, path))
#            #print "qemuapp: " + name + " : " + path
#            
#            try:
#                self.settings["qemuapps"].append((name, path))
#                #self.bookmarks.append((name, entry_path))
#            except:
#                self.settings["qemuapps"] = [(name, path)]    
#                
#    def settings_remove_qemupath(self, widget):
#        qemulist = self.dialog_settings.get_widget("treeview_qemupaths")
#        name = self.dialog_settings.get_widget("entry_settings_qemuname").get_text()
#        path = self.dialog_settings.get_widget("entry_settings_qemupath").get_text()
#        #print 'name: ' + str(name)
#        #print 'path: ' + str(path)
#        entryindex = self.settings_search_cdromdevice(qemulist, str(path), "index")
#        entry_name = name
#        
#        if entryindex != "None":
#            model = qemulist.get_model()
#            selectIter = model.get_iter(entryindex)
#            #print str(selectIter)
#            #print "entryindex" + str(entryindex)
#            model.remove(selectIter)
#            #self.bookmarks.remove((entry_name, entry_path))
#            self.settings["qemuapps"].remove((name, path))
#            #self.toolbutton_remove_bookmark.set_sensitive(False)
#            self.dialog_settings.get_widget("entry_settings_qemuname").set_text("")
#            self.dialog_settings.get_widget("entry_settings_qemupath").set_text("")
#        else:
#            print "no enty " + str(name)  + " found"
#        return str(entry_name) 
    
#    def on_checkbuttonDlinuxboot_toggled(self, widget):
#        state = widget.get_active()
#        if state == True:
#            self.frame_dlinuxboot.show()
#            self.buttonHideDlinuxboot.show()
#            self.buttonHideDlinuxboot.set_label(_("Hide settings"))
#            self.table_imagedevice.hide()
#            self.filechooserbuttonHDA.set_filename(str(self.currentimage))
#            self.filechooserbuttonHDA.set_sensitive(True)
#        else:
#            self.frame_dlinuxboot.hide()
#            self.buttonHideDlinuxboot.hide()
#            self.table_imagedevice.show()
#            self.filechooserbuttonHDA.unselect_all()
#            #print "hda image: " + str(self.image_settings[self.currentimage].hda_image)
#            if self.currimage_settings.bootmedium == "hda":
#                self.filechooserbuttonHDA.unselect_all()
#                self.filechooserbuttonHDA.set_sensitive(False)
#            else:
#                orighda = None
#                try:
#                    orighda = self.image_settings[self.currentimage].hda_image
#                    settingsvar = self.currentimage
#                except:
#                    try:
#                        orighda = self.image_settings[self.selected_bookmark].hda_image
#                        settingsvar = self.selected_bookmark
#                    except:    
#                        orighda = None
#                if self.currentimage == orighda:
#                    self.filechooserbuttonHDA.unselect_all()
#                elif self.image_settings[settingsvar].hda_image != None and self.image_settings[settingsvar].hda_image != 'None':
#                    self.filechooserbuttonHDA.set_filename(self.image_settings[settingsvar].hda_image)
#                   
#        #self.vpaned_mainwindow.set_position(900)
#        self.set_dlinuxboot()
#        if self.restoreaction == False:
#            self.toggle_storebuttons(True, "on_checkbuttonDlinuxboot_toggled")        
#        
#    def on_buttonHideDlinuxboot_clicked(self, widget):
#        if self.frame_dlinuxboot.get_property('visible'):
#            self.frame_dlinuxboot.hide()
#            widget.set_label(_("Show settings"))
#        else:
#            self.frame_dlinuxboot.show()
#            widget.set_label(_("Hide settings"))
#        #self.vpaned_mainwindow.set_position(900)
    
         
    def init_about(self, widget):
        donateurl = "http://qemulator.createweb.de/index.php4?aliasdoc=210"
        self.dialog_about = gtk.glade.XML(self.gladefile, "dialog_about", APP)
        self.dialog_about_widget = self.dialog_about.get_widget("dialog_about")
   
        logo_file = None
        logo_file = self.sharedir + "/logo3.png"
        #print "Logo: " + logo_file
        logopixbuf = gtk.gdk.pixbuf_new_from_file(logo_file)
        #self.logo_mainwindow.set_from_file(logo_file)           
        self.dialog_about_widget.set_logo(logopixbuf)
        hurl = "http://qemulator.createweb.de"
        wlabel = "qemulator home"
        gtk.about_dialog_set_url_hook(self.open_website, hurl)
        dic = {"on_dialog_about_response" : self.dialog_about_response,
        }
        self.dialog_about.signal_autoconnect(dic)    
        
    def on_item_about_activate(self, widget):
        donateurl = "http://qemulator.createweb.de/index.php4?aliasdoc=210"
        self.dialog_about = gtk.glade.XML(self.gladefile, "dialog_about", APP)
        self.dialog_about_widget = self.dialog_about.get_widget("dialog_about")
   
        logo_file = None
        logo_file = self.sharedir + "/logo3.png"
        #print "Logo: " + logo_file
        logopixbuf = gtk.gdk.pixbuf_new_from_file(logo_file)
        #self.logo_mainwindow.set_from_file(logo_file)           
        self.dialog_about_widget.set_logo(logopixbuf)
        hurl = "http://qemulator.createweb.de"
        wlabel = "qemulator home"
        gtk.about_dialog_set_url_hook(self.open_website, hurl)
        dic = {"on_dialog_about_response" : self.dialog_about_response,
        }
        self.dialog_about.signal_autoconnect(dic)              

    def dialog_about_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CLOSE:
            widget.destroy ()
            pass    
        if response == gtk.RESPONSE_APPLY:
            self.dodonate()
            pass          
        
    def dodonate(self, *widget):
        donateurl = "http://qemulator.createweb.de/index.php4?aliasdoc=210"
        #print "donation clicked: " + donateurl
        browser = Webbrowser()  
        browser.url = donateurl
        browser.target = "new window"
        browser.start()   
        
    def init_create_image(self, widget, returnfunc=None):
        newimage = None
        self.createimage = CreateImage(self.imagespath, returnfunc) 
        #newimage = createimage.newimage
        #while self.last_created_image == None:
        #    return  
        try:      
            self.refresh_ilist()
        except:
            pass
        #print 'New image created at: ' + str(newimage)
        return newimage  
    
#    def return_created_image(self, *widget):
#        newimage = None
#        newimage = self.createimage.return_newimage()
#        self.last_created_image = newimage
#        return newimage              
            
#    def init_create_image2(self, widget):
#        
#        self.dialog_create_image = gtk.glade.XML(self.gladefile, "dialog_create_image", APP)
#        ## widgets of the new image dialog
#        
#        self.filechooserbutton_newimage_dest = self.dialog_create_image.get_widget("filechooserbutton_newimage_dest")
#        self.entry_newimage_name = self.dialog_create_image.get_widget("entry_newimage_name")
#        self.combobox_newimage_format = self.dialog_create_image.get_widget("combobox_newimage_format")
#        self.spinbutton_newimage_size = self.dialog_create_image.get_widget("spinbutton_newimage_size")
#        self.combobox_newimage_sizeunit = self.dialog_create_image.get_widget("combobox_newimage_sizeunit")
#        self.button_create_image = self.dialog_create_image.get_widget("button_create_image")        
#        
#        self.newimagename = ""
#        self.combobox_newimage_sizeunit.set_active(0)
#        self.set_newimagesize()
#        self.combobox_newimage_format.set_active(0)
#        self.set_newimageformat()      
#        self.filechooserbutton_newimage_dest.set_filename(self.imagespath)
#        self.set_newimage_folder()
#        dic = {"on_dialog_create_image_response" : self.dialog_create_image_response
#        # handlers for the new image dialog
#        , "on_filechooserbutton_newimage_dest_selection_changed" : self.set_newimage_folder
#        , "on_entry_newimage_name_changed" : self.set_newimage_name
#        , "on_combobox_newimage_format_changed" : self.set_newimageformat
#        , "on_spinbutton_newimage_size_changed" : self.set_newimagesize
#        , "on_combobox_newimage_sizeunit_changed" : self.set_newimagesize
#        , "on_button_create_image_clicked" : self.create_newimage
#        }
#        self.dialog_create_image.signal_autoconnect(dic)  
#        
#    def set_newimage_folder(self, *widget):
#        self.newimagepath = self.filechooserbutton_newimage_dest.get_filename()
#        #print "path: " + self.newimagepath
#        
#    def set_newimage_name(self, *widget):
#        self.newimagename = self.entry_newimage_name.get_text() 
#        #print "name: " + self.newimagename    
#        
#    def set_newimageformat(self, *widget):
#        #self.newimageformat = self.combobox_newimage_format.get_active()
#        active = self.combobox_newimage_format.get_active()
#        model = self.combobox_newimage_format.get_model()
#        row = model[active]
#        self.newimageformat = row[0]
#        
#    def set_newimagesize(self, *widget):
#        sizevalue = self.spinbutton_newimage_size.get_value()
#        #sizeunit = self.combobox_newimage_sizeunit.get_active()
#        active = self.combobox_newimage_sizeunit.get_active()
#        model = self.combobox_newimage_sizeunit.get_model()
#        row = model[active]
#        sizeunit = row[0]
#        
#        if sizeunit == "KB":
#            self.newimage_size = str(int(sizevalue))
#        elif sizeunit == "MB":
#            self.newimage_size = str(int(sizevalue)) + "M"
#        elif sizeunit == "GB":
#            self.newimage_size = str(int(sizevalue)) + "G" 
#        else:
#            self.newimage_size = str(int(sizevalue))
#        #print "size: " + self.newimage_size
#        
#    def create_newimage(self, widget):
#        if self.newimagename != "":
#            newimagetarget = self.newimagepath + "/" + self.newimagename
#            if self.newimageformat != "Auto":
#                formatcommand = "-f " + self.newimageformat
#            else:
#                formatcommand = ""
#            command = "qemu-img create " + formatcommand + " " + newimagetarget + " " + self.newimage_size
#            #print command
#            runcreate = os.popen(command).read()
#            message = command + "\n" + str(runcreate)
#            #print str(message)
#            #self.init_messages_dialog(str(message))
#            infodialog = qml_tools.Dialog("longtext", message, 'Result:') 
#            #self.messagesbuffer.set_text(str(message))
#            self.refresh_ilist()
#            return newimagetarget
#        else:
#            message = _('No name given for the new image!\nplease enter a name and try again.')
#            #self.init_messages_dialog(message)
#            infodialog = qml_tools.Dialog("longtext", message, 'Error:') 
#            return None
#            
#    def dialog_create_image_response(self, widget, response, *entry):    
#        if response == gtk.RESPONSE_CLOSE:
#            widget.destroy ()
#            pass 
            
#    def init_messages_dialog(self, message, *title):
#        self.dialog_messages = gtk.glade.XML(self.gladefile, "dialog_messages", APP)
#        #if title:
#        #    self.dialog_messages.set_title(title)
#        self.textview_messages = self.dialog_messages.get_widget("textview_messages")
#        self.messagesbuffer = self.textview_messages.get_buffer()
#        self.messagesbuffer.set_text(message)
#        
#        dic = {"on_dialog_messages_response" : self.dialog_messages_response,        
#        }
#        self.dialog_messages.signal_autoconnect(dic)         
#        
#    def dialog_messages_response(self, widget, response, *entry):    
#        if response == gtk.RESPONSE_CLOSE:
#            widget.destroy ()
#            pass   
        
    #def select_networkcard(self, widget, path, view_column):
    def select_networkcard(self, widget):
        sel = self.treeview_redirects.get_selection()
        sel.unselect_all()

    #def select_networkredir(self, widget, path, view_column):
    def select_networkredir(self, widget):
        sel = self.treeview_networkcards.get_selection()
        sel.unselect_all()

    def init_networksetup(self, widget):
        GoOn = False        
        button = widget.get_name()
        if button == "toolbutton_network_netcard_add":
            mode = "add"
            response = self.dialog_add_netcard_response
            GoOn = True
        #if button == "button_network_edit":
        #    mode = "edit"
        if button == "toolbutton_network_netcard_edit":
            mode = "edit_card"
            response = self.dialog_edit_netcard_response
        if button == "toolbutton_network_redir_edit":
            mode = "edit_redir"                        
            response = self.dialog_network_edit_redirect_response
        if mode == "edit": # depreciated
            try:
                model, iter = self.treeview_networkcards.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))
                GoOn = True
            except:
                print "No network card selected"
                GoOn = False
                try:
                    model, iter = self.treeview_redirects.get_selection().get_selected()
                    counter = int(model.get_string_from_iter(iter))
                    self.init_network_redirect(widget)
                    GoOn = False
                except:
                    print "No redirect selected"
                    GoOn = False
        if mode == "edit_card":
            try:
                model, iter = self.treeview_networkcards.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))
                GoOn = True
            except:
                print "No network card selected"
                GoOn = False
        if mode == "edit_redir":
            try:
                model, iter = self.treeview_redirects.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))
                self.init_network_redirect(widget)
                GoOn = False
            except:
                print "No redirect selected"
                GoOn = False                                  
        if GoOn == True:
            self.tmpnetwork = qml_network.Network()
            self.dialog_newnetcard = gtk.glade.XML(self.gladefile, "dialog_newnetcard", APP)
            self.dialog_newnetcard_widget = self.dialog_newnetcard.get_widget("dialog_newnetcard")
            ## widgets of the new image dialog
            self.combobox_networktype = self.dialog_newnetcard.get_widget("combobox_networktype")
            self.combobox_networktype.set_active(0)
            
            self.entry_network_ip = self.dialog_newnetcard.get_widget("entry_network_ip")
            self.spinbutton_network_port = self.dialog_newnetcard.get_widget("spinbutton_network_port")
            self.entry_network_macaddr = self.dialog_newnetcard.get_widget("entry_network_macaddr")
            self.spinbutton_network_vlan = self.dialog_newnetcard.get_widget("spinbutton_network_vlan")
            self.entry_network_tuntapscript = self.dialog_newnetcard.get_widget("entry_network_tuntapscript")        
            self.button__network_open_tuntap_file = self.dialog_newnetcard.get_widget("button__network_open_tuntap_file")
            self.entry_network_ifacename = self.dialog_newnetcard.get_widget("entry_network_ifacename")
            self.spinbutton_network_filedescriptor = self.dialog_newnetcard.get_widget("spinbutton_network_filedescriptor")
            
            dic = {"on_combobox_networktype_changed" : self.select_networktype
            , "on_entry_network_ip_changed" : self.set_network_ip
            , "on_spinbutton_network_port_changed" : self.set_network_port
            , "on_entry_network_macaddr_changed" : self.set_network_mac
            , "on_spinbutton_network_vlan_changed" : self.set_network_vlan
            , "on_entry_network_tuntapscript_changed" : self.set_network_ttscript
            , "on_entry_network_ifacename_changed" : self.set_network_ifname
            , "on_spinbutton_network_filedescriptor_changed" : self.set_network_ttfiledesc
            , "on_dialog_newnetcard_response" : response
            }
            self.dialog_newnetcard.signal_autoconnect(dic)  
            self.select_networktype(self.combobox_networktype)
            
            if mode == "edit_card" or mode == "edit_redir":
                self.dialog_newnetcard_widget.set_title(_("Edit selected network card"))
                self.network_editcard = self.currimage_settings.networksetup[counter]
                self.tmpnetwork = self.network_editcard
                
                searchentry = self.search_combolist(self.combobox_networktype, self.network_editcard.ntype)
                if searchentry != "":
                    self.combobox_networktype.set_active(searchentry)
                
                self.entry_network_ip.set_text(str(self.network_editcard.ip))
                self.spinbutton_network_port.set_value(int(self.network_editcard.port))
                self.entry_network_macaddr.set_text(str(self.network_editcard.mac))
                self.spinbutton_network_vlan.set_value(int(self.network_editcard.vlan))
                self.entry_network_tuntapscript.set_text(str(self.network_editcard.ttscript))
                self.entry_network_ifacename.set_text(str(self.network_editcard.ifname))
                self.spinbutton_network_filedescriptor.set_text(str(self.network_editcard.ttfiledesc))
        
    def dialog_add_netcard_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CANCEL:
            self.tmpnetwork = []
            widget.destroy ()
        if response == gtk.RESPONSE_OK:
            self.currimage_settings.networksetup.append(self.tmpnetwork)
            
            self.refresh_networkcards()
            self.tmpnetwork = []
            #print "Network device stored"
            widget.destroy ()
            self.toggle_storebuttons(True, "dialog_add_netcard_response")
            
    def dialog_edit_netcard_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CANCEL:
            self.tmpnetwork = []
            widget.destroy ()
        if response == gtk.RESPONSE_OK:
            self.network_editcard = self.tmpnetwork
            self.tmpnetwork = []
            self.refresh_networkcards()
            #print "Network device changed"
            widget.destroy ()
            self.toggle_storebuttons(True, "dialog_edit_netcard_response")           
            
    def remove_netcard(self, widget):
        GoOn = True
        try:
            model, iter = self.treeview_networkcards.get_selection().get_selected()
            counter = int(model.get_string_from_iter(iter))
        except:
            print "No network card selected for remove"
            GoOn = False
            try:
                model, iter = self.treeview_redirects.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))
                self.remove_redirect(widget)
                GoOn = False
            except:
                print "No redirect selected for remove"
                GoOn = False           
        if GoOn == True:
            ip = model.get_value(iter, 0)
            port = model.get_value(iter, 1)
            vlan = model.get_value(iter, 2)
            counter = int(model.get_string_from_iter(iter))
            del self.currimage_settings.networksetup[counter]
            self.refresh_networkcards()
            self.toggle_storebuttons(True, "remove_netcard")             
        
    def select_networktype(self, widget):
        active = widget.get_active()
        model = widget.get_model()
        row = model[active]
        item = row[0]
        self.tmpnetwork.ntype = item
        time.sleep(0.1)
        if item == "Open a TUN/TAP interface":
            self.entry_network_ip.set_sensitive(False)
            self.spinbutton_network_port.set_sensitive(False)
            self.entry_network_tuntapscript.set_sensitive(True)
            self.button__network_open_tuntap_file.set_sensitive(True)
            self.entry_network_ifacename.set_sensitive(True)
            self.spinbutton_network_filedescriptor.set_sensitive(False)
        elif item == "Use an already open TUN/TAP interface":
            self.entry_network_ip.set_sensitive(False)
            self.spinbutton_network_port.set_sensitive(False)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(True)
        elif item == "Open a listening TCP socket":
            self.entry_network_ip.set_sensitive(True)
            self.spinbutton_network_port.set_sensitive(True)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(False)
        elif item == "Use an already open TCP socket":
            self.entry_network_ip.set_sensitive(False)
            self.spinbutton_network_port.set_sensitive(False)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(True)
        elif item == "Connect to listening  TCP socket":
            self.entry_network_ip.set_sensitive(True)
            self.spinbutton_network_port.set_sensitive(True)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(False)
        elif item == "Create shared VLAN via UDP multicast socket":  
            self.entry_network_ip.set_sensitive(True)
            self.spinbutton_network_port.set_sensitive(True)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(False)
        elif item == "Use an already open UDP multicast socket":
            self.entry_network_ip.set_sensitive(False)
            self.spinbutton_network_port.set_sensitive(False)
            self.entry_network_tuntapscript.set_sensitive(False)
            self.button__network_open_tuntap_file.set_sensitive(False)
            self.entry_network_ifacename.set_sensitive(False)
            self.spinbutton_network_filedescriptor.set_sensitive(True)
        else:
            pass          
        
    def set_network_ip(self, widget):
        ip = widget.get_text()
        self.tmpnetwork.ip = ip
        
    def set_network_port(self, *widget):
        value = self.spinbutton_network_port.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.tmpnetwork.port = valint       
        
    def set_network_mac(self, widget):
        mac = widget.get_text()
        self.tmpnetwork.mac = mac  
        
    def set_network_vlan(self, *widget): 
        value = self.spinbutton_network_vlan.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.tmpnetwork.vlan = valint         
        
    def set_network_ttscript(self, widget):
        ttscript = widget.get_text()
        self.tmpnetwork.ttscript = ttscript
        #print "Set tmpnetwork tun/tap script to: " + str(self.tmpnetwork.ttscript)     
        
    def set_network_ifname(self, widget):
        ifname = widget.get_text()
        self.tmpnetwork.ifname = ifname
        #print "Set tmpnetwork interface name to: " + str(self.tmpnetwork.ifname)  
        
    def set_network_ttfiledesc(self, widget):
        value = self.spinbutton_network_filedescriptor.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.tmpnetwork.ttfiledesc = valint        
        
    def on_entryNetworkHostname_changed(self, widget):
            network_hostname = widget.get_text()
            #print "Set Network hostname to: " + network_hostname
            self.currimage_settings.usernetwork.hostname = network_hostname 
            if self.restoreaction == False:
                self.toggle_storebuttons(True, "on_entryNetworkHostname_changed")    
            
    def on_spinbuttonUsernetVlan_changed(self, widget):
            value = self.spinbuttonUsernetVlan.get_text()
            c = 0
            while value == "" and c < 100:
                c = c + 1
                return False
            valint = int(value)
            self.currimage_settings.usernetwork.vlan = valint            
            if self.restoreaction == False:
                self.toggle_storebuttons(True, "on_spinbuttonUsernetVlan_changed")                                                  

    def toggle_networkuse(self, widget): 
        wname = widget.get_name()
        if wname == "radiobutton_network_nonet":
            self.currimage_settings.networkmode = "nonet"
            self.frame_network_usermode.hide()
            self.frame_network_custom.hide()
            self.filechooserbuttonNetworkSmbshare.set_sensitive(False)
            self.checkbuttonSmbshare.set_sensitive(False)
        else:
            self.filechooserbuttonNetworkSmbshare.set_sensitive(True)
            self.checkbuttonSmbshare.set_sensitive(True)
           
        if wname == "radiobutton_network_usermode":
            self.currimage_settings.networkmode = "usermode"
            self.frame_network_usermode.show()
            self.frame_network_custom.hide()             
        if wname == "radiobutton_network_customsetup":
            self.currimage_settings.networkmode = "custom"
            self.frame_network_usermode.hide()
            self.frame_network_custom.show()
        
    def vpane_doubleclick(self, widget, event):
        
        if self.settingsvisible == "visible":
            if event.type == gtk.gdk._2BUTTON_PRESS:
                time.sleep(0.1)
                self.toggle_settingsview()
        else:
            if event.button == 1:
                time.sleep(0.1)
                self.toggle_settingsview()
                
    def show_settings(self, *widget):
        if self.settingsvisible != "visible":
            #gtk.gdk.threads_enter()
            self.switch_settingsview("show")
            #gtk.gdk.threads_leave()
            
    def hide_settings(self, *widget):
        if self.settingsvisible == "visible":
            #gtk.gdk.threads_enter()
            self.switch_settingsview("hide")                          
            #gtk.gdk.threads_leave()
            
    def toggle_settingsview(self, *widget):
        if self.settingsvisible == "visible":
            #gtk.gdk.threads_enter()
            self.switch_settingsview("hide")
            #gtk.gdk.threads_leave()
            
        else:
            #gtk.gdk.threads_enter()
            self.switch_settingsview("show")
            #gtk.gdk.threads_leave()
            
    def menu_toggle_settings_autohide(self, widget):
        self.settings_autohide = widget.get_active()

    def menu_toggle_settings_autoshow(self, widget):
        self.settings_autoshow = widget.get_active()

    def toggle_settings_autohide(self, status):
        self.checkbutton_autohide_settings.set_active(status)
        #print "settings_autohide toggled: " + str(status)

    def toggle_settings_autoshow(self, status):
        self.checkbutton_autoshow_settings.set_active(status)
        #print "settings_autoshow toggled: " + str(status)

    def switch_settingsview(self, showhide):
        change = False
        button_icon = gtk.Image()
        
        if showhide == "show":
            if self.item_show_settings.get_property('visible'):
                width, height = self.mainwindow.get_size()
                newpos = height - 450
                self.vpaned_mainwindow.set_position(newpos)
                self.viewport_settings_hardware.resize_children()
                self.item_show_settings.hide()
                self.item_hide_settings.show()
    
                settingstxt = _("hide settings")
                settingstt = _("hide configuration panel for selected boot image")
    
                button_icon.set_from_icon_name("gtk-go-down", gtk.ICON_SIZE_BUTTON)
    
                self.settingsvisible = "visible"
                change = True
        if showhide == "hide":
            if self.item_hide_settings.get_property('visible'):
                self.vpaned_mainwindow.set_position(1200)
                self.item_show_settings.show()
                self.item_hide_settings.hide()
                
                settingstxt = _("show settings")
                settingstt = _("show configuration panel for selected boot image")
    
                button_icon.set_from_icon_name("gtk-go-up", gtk.ICON_SIZE_BUTTON)
    
                self.settingsvisible = "hidden"
                change = True
        if change == True:
            self.button_togglesettings.set_image(button_icon)
            self.button_togglesettings.set_label(settingstxt)
            tooltips.set_tip(self.button_togglesettings, settingstt)

    def refresh_networkcards(self, *event):
        #print "refreshing network cards"
        model = self.treeview_networkcards.get_model()
        model.clear()
        currnet = self.currimage_settings.networksetup
        if currnet != []:
            for netcard in currnet:
                ip = netcard.ip
                port = netcard.port
                vlan = netcard.vlan
                ntype = netcard.ntype
                model.append(row=(ip,port,vlan,ntype))
        self.treeview_networkcards.set_model(model) 
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "refresh_networkcards")                       
           
    def create_model_networkcards(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING)
        for item in data:
            iter = store.append()
            ip = item[0]
            port = item[1]
            vlan = item[2]
            ntype = item[3]
            store.set(iter, 0, item[0], 1, item[1], 2, item[2], 3, item[3])
        return store    

    def add_columns_networkcards(self, treeview, model):
        #renderer = gtk.CellRendererToggle()
        column0 = gtk.TreeViewColumn(_('IP'), gtk.CellRendererText(), text=0)
        column0.set_resizable(True)
        column1 = gtk.TreeViewColumn(_('Port'), gtk.CellRendererText(), text=1)
        column1.set_resizable(True)
        column2 = gtk.TreeViewColumn(_('VLAN'), gtk.CellRendererText(), text=2)
        column2.set_resizable(True)
        column3 = gtk.TreeViewColumn(_('Network Type'), gtk.CellRendererText(), text=3)
        column3.set_resizable(True)
        treeview.append_column(column0)   
        treeview.append_column(column1)        
        treeview.append_column(column2) 
        treeview.append_column(column3)  
        
## All functions for Network redirections ##

    def init_network_redirect(self, widget):
        GoOn = True     
        button = widget.get_name()
        if button == "toolbutton_network_redir_add":
            mode = "add"
            response = self.dialog_network_add_redirect_response
        if button == "toolbutton_network_redir_edit":
            mode = "edit"
            response = self.dialog_network_edit_redirect_response       
        if mode == "edit":
            try:
                model, iter = self.treeview_redirects.get_selection().get_selected()
                counter = int(model.get_string_from_iter(iter))
            except:
                print "No redirect selected"
                GoOn = False
                
        if GoOn == True:
            self.tmpredir = qml_network.Network_Redirection()
            self.tmpredir.protocol = "TCP"
            
            self.dialog_new_redirect = gtk.glade.XML(self.gladefile, "dialog_new_redirect", APP)
            self.dialog_new_redirect_widget = self.dialog_new_redirect.get_widget("dialog_new_redirect")
            ## widgets of the new image dialog
            self.radiobutton_redirect_TCP = self.dialog_new_redirect.get_widget("radiobutton_redirect_TCP")
            self.radiobutton_redirect_UDP = self.dialog_new_redirect.get_widget("radiobutton_redirect_UDP")
            self.spinbutton_redirect_sport = self.dialog_new_redirect.get_widget("spinbutton_redirect_sport")            
            self.entry_redirect_gIP = self.dialog_new_redirect.get_widget("entry_redirect_gIP")
            self.spinbutton_redirect_dport = self.dialog_new_redirect.get_widget("spinbutton_redirect_dport")        
            self.button_redirect_add = self.dialog_new_redirect.get_widget("button_redirect_add")
            dic = {"on_radiobutton_redirect_TCP_toggled" : self.set_redir_prot
            , "on_radiobutton_redirect_UDP_toggled" : self.set_redir_prot
            , "on_spinbutton_redirect_sport_changed" : self.set_redir_sport
            , "on_entry_redirect_gIP_changed" : self.set_redir_ip
            , "on_spinbutton_redirect_dport_changed" : self.set_redir_dport
            , "on_dialog_new_redirect_response" : response
            }
            self.dialog_new_redirect.signal_autoconnect(dic)
            if mode == "edit":
                self.button_redirect_add.set_label("Apply")
                image = gtk.Image()
                image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
                self.button_redirect_add.set_image(image)
                self.dialog_new_redirect_widget.set_title("Edit selected redirection")
                self.network_editredir = self.currimage_settings.networkredirs[counter]
                self.tmpredir = self.network_editredir
                
                if self.network_editredir.protocol == "tcp":
                    self.radiobutton_redirect_TCP.set_active(True)
                if self.network_editredir.protocol == "udp":
                    self.radiobutton_redirect_UDP.set_active(True)                    
                self.spinbutton_redirect_sport.set_value(int(self.network_editredir.sport))
                self.entry_redirect_gIP.set_text(str(self.network_editredir.ip))
                self.spinbutton_redirect_dport.set_value(int(self.network_editredir.dport))
                   
     
    def dialog_network_add_redirect_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CLOSE:
            self.tmpredir = []
            widget.destroy () 
        if response == gtk.RESPONSE_APPLY:
            self.currimage_settings.networkredirs.append(copy(self.tmpredir))
            self.refresh_redirects()
            self.toggle_storebuttons(True, "dialog_network_add_redirect_response")
            
    def dialog_network_edit_redirect_response(self, widget, response, *entry):    
        if response == gtk.RESPONSE_CLOSE:
            self.tmpredir = []
            widget.destroy ()
        if response == gtk.RESPONSE_APPLY:
            self.network_editredir = copy(self.tmpredir)
            self.refresh_redirects()
            self.toggle_storebuttons(True, "dialog_network_edit_redirect_response")
            
    def refresh_redirects(self, *event):
        model = self.treeview_redirects.get_model()
        model.clear()
        curredirs = self.currimage_settings.networkredirs
        if self.currimage_settings.networkredirs != []:
            for redir in curredirs:
                protocol = redir.protocol
                sport = redir.sport
                ip = redir.ip
                dport = redir.dport
                model.append(row=(protocol,sport,ip,dport))

    def create_model_redirects(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING,
                          gobject.TYPE_STRING)
        for item in data:
            iter = store.append()
            protocol = item[0]
            sport = item[1]
            ip = item[2]
            dport = item[3]

            store.set(iter, 0, item[0], 1, item[1], 2, item[2], 3, item[3])
        return store    

    def add_columns_redirects(self, treeview, model):
    
        #renderer = gtk.CellRendererToggle()
        column0 = gtk.TreeViewColumn(_('Protocol'), gtk.CellRendererText(), text=0)
        column0.set_resizable(True)
        column1 = gtk.TreeViewColumn(_('Source port'), gtk.CellRendererText(), text=1)
        column1.set_resizable(True)
        column2 = gtk.TreeViewColumn(_('Guest IP'), gtk.CellRendererText(), text=2)
        column2.set_resizable(True)
        column3 = gtk.TreeViewColumn(_('Dest. port'), gtk.CellRendererText(), text=3)
        column3.set_resizable(True)
        treeview.append_column(column0)   
        treeview.append_column(column1)        
        treeview.append_column(column2) 
        treeview.append_column(column3)  

    def set_redir_prot(self, widget):
        wname = widget.get_name()
        
        if wname == "radiobutton_redirect_TCP":
            self.tmpredir.protocol = "tcp"
        elif wname == "radiobutton_redirect_UDP":
            self.tmpredir.protocol = "udp"

    def set_redir_sport(self, *widget):
        value = self.spinbutton_redirect_sport.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.tmpredir.sport = valint           
        
    def set_redir_ip(self, widget):
        ip = widget.get_text()
        self.tmpredir.ip = ip
        #print "Set tmpredir ip to: " + str(self.tmpredir.ip)          
        
    def set_redir_dport(self, *widget):
        port = int(self.spinbutton_redirect_dport.get_value())
        #print "changed dport to: " + str(port)
        self.tmpredir.dport = port 
        value = self.spinbutton_redirect_dport.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
        self.tmpredir.dport = valint           
        
    def remove_redirect(self, widget):
        try:
            model, iter = self.treeview_redirects.get_selection().get_selected()
            protocol = model.get_value(iter, 0)
            sport = model.get_value(iter, 1)
            ip = model.get_value(iter, 2)
            dport = model.get_value(iter, 3)
            counter = int(model.get_string_from_iter(iter))
            del self.currimage_settings.networkredirs[counter]
            self.refresh_redirects()  
            self.toggle_storebuttons(True, "remove_redirect")
        except:
            print "No redirection selected"       
            
    def on_checkbuttonSmbshare_toggled(self, widget):    
        if widget == self.checkbuttonSmbshare:
            self.currimage_settings.smbsettings.usesmb = widget.get_active()
        elif widget == self.filechooserbuttonNetworkSmbshare:
            self.currimage_settings.smbsettings.smbpath = widget.get_filename()  
        if self.restoreaction == False:
            self.toggle_storebuttons(True, "on_checkbuttonSmbshare_toggled")
            
    def on_filechooserbuttonNetworkSmbshare_selection_changed(self, widget):
        self.on_checkbuttonSmbshare_toggled(widget)
        
    def run_jobmanager(self, *widget):
        jobmanager = qml_tools.DelayedActions(self.open_jobmanager)
        #jobmanager = qml_tools.DelayedGUIactions(self.open_jobmanager)
        jobmanager.start()
                
    def open_jobmanager(self, *widget):
        selected_job_name = self.selected_job[0]
        selected_job_path = self.selected_job[1]
        selected_job_pid = self.selected_job[2]
        selected_job_pty = self.selected_job[3]
        selected_job_displaymode = self.selected_job[4]
        selected_job_runstat = self.selected_job[5]
        #selected_job_name = selected_job_path
        
        #print "JOB: " + str(self.selected_job)
        
        try:
            if self.image_settings[selected_job_path]:
               image_settings = self.image_settings[selected_job_path] 
        except:
            image_settings = None

        #if len(self.selected_job) == 6:
        #    selected_job_name = self.selected_job[5]        
        if self.jobmanagers.has_key(selected_job_pid):
            #print "Jobmanager for " + str(selected_job_pid) + " only hidden, no new instance will be raised"
            self.jobmanagers[selected_job_pid].dialog_jobmonitor.show()
            if tray != None:
                tray.traymenu_item[selected_job_pid].set_active(True)
        else:
            #print "Jobmanager for " + str(selected_job_pid) + " not open, new instance will be raised"
            #print "Jobmanager job " + str(self.selected_job)
            self.jobmanagers[selected_job_pid] = qml_controlmon.ControlMonitor(self.selected_job, image_settings, tray, self.joblist, self.close_jobmanager)
            self.jobmanagers[selected_job_pid].start()
            
            if tray != None:
                #print "job: " + str(self.selected_job)
                tray.create_trayentry_jobmanager(self.selected_job)
        
    def close_jobmanager(self, pid):
        if tray != None:
            tray.remove_trayentry_jobmanager(pid)
        del self.jobmanagers[pid]      
        
    def check_firstrun(self):
        if os.path.exists(self.homedir):
            #print "homedir '" + self.homedir + "' allready exists"
            pass
        else:
            print "homedir '" + self.homedir + "' will be created"
            os.mkdir(self.homedir)
            
        if os.path.exists(self.configdir):
            #print "configdir '" + self.configdir + "' allready exists"
            pass
        else:
            print "configdir '" + self.configdir + "' will be created"
            os.mkdir(self.configdir)            
                    
        if os.path.exists(self.icondirs[1]):
            #print "icondir '" + self.icondirs[1] + "' allready exists"
            pass
        else:
            print "icondir '" + self.icondirs[1] + "' will be created"
            os.mkdir(self.icondirs[1])
            icons=os.listdir(self.icondirs[0])
            for iconam in icons:
                #print str(iconam)
                srcicon = self.icondirs[0] + "/" + iconam
                dsticon = self.icondirs[1] + "/" + iconam
                #print srcicon + " to"
                #print dsticon
                if os.path.isfile(srcicon):
                    shutil.copy(srcicon, dsticon)
                    
    def open_website(self, widget, event=None, url="http://qemulator.createweb.de"):
        browser = Webbrowser()  
        browser.url = url
        browser.target = "new window"
        browser.start()

class QemuConfig:  
    def __init__ (self, image=None):
        #self.currentimage = image
        self.main_image = image
        self.emusystem = ""
        self.machine = ""
        self.kqemu_param = ""
        self.bootmedium = "cdrom"
        self.boot_driveletter = "d"
        self.cdrmedium = None
        self.cdrimage = None
        self.cdrmode = "nocd"
        self.hda_image = None  
        self.hdb_image = None
        self.hdc_image = None
        self.hdd_image = None
        self.fda_image = None
        self.fdb_image = None
        self.soundhw = ""
        self.vgamode = ""
        self.usevnc = False
        self.vncdisplay = 1
        self.useusb = False
        self.novga = False
        self.fullscreenmode = False
        self.dlinuxboot = False
        self.kernelimage = None
        self.kernelcmd = ""
        self.initrd = None
        self.snapshotmode = False
        self.noacpi = False
        self.noreboot = False
        self.startpaused = False
        self.cpus = 1
        self.daemonize = False
        self.waitgdb = False
        self.gdbport = None
        self.pidfile = None
        self.optionrom = None
        self.localtimemode = False
        self.memory = 128
        self.customoptions = ""
        self.bootfromcd = False
        self.networksetup = []
        self.networkmode = "usermode"
        self.networkredirs = []
        self.network_hostname = "emu"
        self.usernetwork = qml_network.Network_Usernet()
        self.smbsettings = qml_network.Network_SMB()
        ''' xtras '''
        self.redirect_serial = ''
        self.redirect_parallel = ''
        self.audioenvironment = 'Default'
        
#class Joblist(Thread):
class Joblist:         
    def __init__(self, treeview, joblist_data = []):
        #Thread.__init__(self)
        self.configdir = configdir
        self.treeview = treeview
        self.joblist_data = []
        self.jobmanagers = {}
        
    def run(self):
        pass
                  
    def create_model_joblist(self, data):
        store = gtk.ListStore(gobject.TYPE_STRING,
                              gobject.TYPE_STRING,
                              gobject.TYPE_STRING,
                              gobject.TYPE_STRING,
                              gobject.TYPE_STRING,
                              gobject.TYPE_STRING)
        for item in data:
            if item != 0:
                iter = store.append()
                name = item[0]
                ipath = item[1]
                pid = item[2]
                pts = item[3]
                
                displaymode = item[4]
                runstat = item[5]
                #if len(item) == 6:
                #    name = item[5]
                #else:
                #    name = '--'
                store.set(iter,  0, name, 1, ipath, 2, pid, 3, pts, 4, displaymode, 5, runstat)
        return store  
   
    def add_columns_joblist(self, treeview, model):
    
        #renderer = gtk.CellRendererToggle()
        columns = []
        columns.append(gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0))
        #column0.set_resizable(True)        
        columns.append(gtk.TreeViewColumn(_('Boot image'), gtk.CellRendererText(), text=1))
        #column1.set_resizable(True)
        columns.append(gtk.TreeViewColumn(_('PID'), gtk.CellRendererText(), text=2))
        #column2.set_resizable(True)
        columns.append(gtk.TreeViewColumn(_('PTS'), gtk.CellRendererText(), text=3))
        #column3.set_resizable(True)
        columns.append(gtk.TreeViewColumn(_('Display'), gtk.CellRendererText(), text=4))
        #column4.set_resizable(True)
        columns.append(gtk.TreeViewColumn(_('running'), gtk.CellRendererText(), text=5))
        #column5.set_resizable(True)
        for column in columns:
            column.set_resizable(True)
            treeview.append_column(column)    

        
    def buildtree_joblist(self, *widget):    
        data = self.joblist_data
        model = self.create_model_joblist(data) 
        self.add_columns_joblist(self.treeview, model)
        self.treeview.set_model(model)
        
    def refresh_joblist(self, *widget):    
            data = self.joblist_data
            model1 = self.treeview.get_model()
            try:
                model1.clear()
                #print "model joblist cleared"
            except:
                #print "model joblist empty, not cleared"
                pass
            model = self.create_model_joblist(data)
            setmodel = self.treeview.set_model(model)
            time.sleep(0.01)
            self.store_joblist()
            
    def pause_job(self, widget, job): 
        pts = job[3] 
        ptsin = qml_ptsmanager.PtsMan(pts, "stop").start()
        for jobs in self.joblist_data:
            if jobs != []:
                print "pause_job check: " + str(jobs[1])
                if jobs[3] == pts:
                    print "pause_job found: " + str(jobs[3]) + " == " + str(pts)
                    jindex = self.joblist_data.index([jobs[0], jobs[1], jobs[2], jobs[3], jobs[4], jobs[5]])
                    self.joblist_data[jindex] = [jobs[0], jobs[1], jobs[2], jobs[3], jobs[4], "0"]
                    print "jobstop: " + str(self.joblist_data[jindex][3])
                else:
                    print "pause_job not found: " + str(jobs[3]) + " != " + str(pts)
        #if self.refresh_joblist != None:
        try:
            print "refreshed joblist"
            self.refresh_joblist()
        except:
            pass
        print "job paused: " + str(pts)
         
    def cont_job(self, widget, job):
        pts = job[3]
        ptsin = qml_ptsmanager.PtsMan(pts, "cont").start()
        for jobs in self.joblist_data:
            if jobs != []:
                print "cont_job check: " + str(jobs[1])
                if jobs[3] == pts:
                    print "cont_job found: " + str(jobs[3]) + " == " + str(pts)
                    jindex = self.joblist_data.index([jobs[0], jobs[1], jobs[2], jobs[3], jobs[4], jobs[5]])
                    self.joblist_data[jindex] = [jobs[0], jobs[1], jobs[2], jobs[3], jobs[4], "1"]
#        if self.refresh_joblist != None:
#            self.refresh_joblist()    
        try:
            print "refreshed joblist"
            self.refresh_joblist()
        except:
            pass
        print "job continued" + str(pts)               
    
    def reset_job(self, widget, job):
        pts = job[3]
        ptsin = qml_ptsmanager.PtsMan(pts, "system_reset").start() 
        print "reset done"    
        
    def stop_job(self, widget, job):        
        pts = job[3]
        ptsin = qml_ptsmanager.PtsMan(pts, "quit").start()        
        
    def search_job(self, pid, pts=None):
        index = None
        if not self.joblist_data or self.joblist_data == []:
            index = None
        else:
            for job in self.joblist_data:
                #print "searching for: " + str(job)
                if pts == None:
                    if job[2] == pid:
                        #print "found match: " + str(job[0]) + " = " + str(pid)
                        index = self.joblist_data.index(job)
                        break
                else:
                    if job[2] == pid and job[3] == pts:
                        #print "found match: " + str(job[0]) + " = " + str(pid) + " " + str(job[1]) + "=" + str(pts)
                        index = self.joblist_data.index(job)
                        break
        return index
    
    def add_job(self, job):
        #print 'widget: ' + str(widget)
        #print 'response: ' + str(response)
        #pid = job[0]
        pts = job[3]
        #ipath = job[2]
        #displaymode = job[3]
        #pts = str(pts)
        #runstat = 1
        self.joblist_data.append(job)
        self.refresh_joblist()
        #print str(self.joblist_data)  
 
    def remove_job(self, pid, pts):
        entry_pts = pts
        entryindex = self.search_job(pid, pts)

        if entryindex != "None":
            del self.joblist_data[entryindex]
        self.refresh_joblist()
        
    def load_joblist(self):
         self.joblist_data = getfromfile("joblist")
         #print "loaded joblist data: " + str(self.joblist_data)
         if self.joblist_data == {}:
             self.joblist_data = []
         self.refresh_joblist()
         #return self.joblist_data
         
    def store_joblist(self):
        if self.joblist_data == [] or self.joblist_data == "":
            if os.path.exists(configdir + "/joblist"):
                remjoblist = os.remove(configdir + "/joblist")
        else:
            storetofile(self.joblist_data, "joblist")
        
    def remove_job2(self, job):
        pid = job[0]
        pts = job[1]
        image = job[2]
        entryindex = self.search_job(pid, pts)
        if entryindex != None:
            del self.joblist_data[entryindex]

            if len(qemulator.jobmanagers) != 0: 
                kpid = str(pid)
                try:
                    qemulator.jobmanagers[kpid].jobmonitor_close()
                except:
                    pass
        else:
            pass
        time.sleep(0.1)
        self.refresh_joblist()

class QemuGetPts ( Thread ):
    def __init__ (self, pid, childout, childerr):
        Thread.__init__(self)
        self.childout = childout
        self.childerr = childerr
        self.errormessage = ""
        self.pid = pid
    def run(self):
        #print "QemuOutThread aufgerufen"
        errormessage = ""
        checkpid = os.popen("ps -e | grep " + str(self.pid)).readlines()
        
#        print 'reading output:'
#        message = ''
#        c = 0
#        while c < 100:
#            lineout = self.childout.readline() 
#            lineout = string.strip(lineout)
#            message = message + lineout
#            print 'line: \"' + lineout + '\"'
#            if lineout == "4096": break     
#            c = c+1 
        
        
        #print "daemon id checkstat: " + str(checkpid)
        if checkpid != []:
            while 1:
#                if self.childerr != None:
                linerr = self.childerr.readline()
#                else:
#                    linerr = self.childout.readline()
                errormessage = errormessage + linerr
                #print 'linerr: ' + linerr
                if linerr == "": break
                #print linerr
                m = re.search("/dev/pts/\d+", linerr)
                if m != None:
                    self.currentpts = m.group()
                    self.errormessage = errormessage
                    break
        self.errormessage = errormessage
        #return self.errormessage
        
class QemuWatcher ( Thread ):

    def __init__ (self, rem_func=None):
        #time.sleep(2)
        Thread.__init__(self)
        self.rem_func = rem_func
        self.joblist = []
        self.status = "stopped"

    def run(self):
        #self.status = "running"
        print "watcher daemon started"
        while self.joblist != []:
            self.status = "running"
            for job in self.joblist:
                checkpid = ""
                pid = job[0]
                pts = job[1]
                image = job[2]
                checkpid = os.popen("ps -e | grep " + str(pid)).readlines()
                #print "daemon id checkstat: " + str(checkpid)
                if os.path.exists(pts) and checkpid != "":
                   #print "daemon pts found: " + str(pts)
                   pass              
                else: 
                    print pts + " not found - removed from daemon list"
                    delindex = self.joblist.index(job)
                    
                    del self.joblist[delindex]
                    if self.rem_func != None:
                        gtk.gdk.threads_enter()
                        dofunc = self.rem_func(job)
                        gtk.gdk.threads_leave()
                    #del self.joblist[delindex]
                    break
            if qemulator.dorun != True:
                print "mainapp closed, exit watcher daemon"
                break 
            time.sleep(3)
        self.status = "stopped"
        print "no more jobs left - daemon QUIT"
    
class Bookmark:        
    def __init__(self):
        #print "bookmarks caller: " + str(caller)
        self.name = "new machine"
        self.icondir = icondirs[0]
        self.icon = self.icondir + "/default.png"    
        self.path = ""
        self.haveconfig = False
        #self.pixmapdir = qemulator.pixmapdir
        self.pixmapdir = pixmapdir
        #print "bookmarks pixmapdir " + pixmapdir
        #print "bookmarks self.pixmapdir " + self.pixmapdir
    def get_modeldata(self):
        self.pixmapdir = pixmapdir
        icon = None
        try:
            icon = gtk.gdk.pixbuf_new_from_file(self.icon)
        except:
            icon = None
        if self.haveconfig == True:
            config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-yes.png')
        else:
            config_icon = gtk.gdk.pixbuf_new_from_file(self.pixmapdir + '/gtk-no.png')
        modeldata = [icon, self.name, self.path, config_icon]
        return modeldata
    def check_haveconfig(self, bootimage):
        haveconfig = False
        try:
            if self.image_settings[bootimage]:
                #print "Config for " + str(bootimage) + " found"
                haveconfig = True
            else:
                #print "No config for " + str(bootimage) + " found"
                haveconfig = False
        except:       
            #print "No config for " + str(bootimage) + " found"
            haveconfig = False
        return haveconfig
                                                
class Webbrowser ( Thread ):
    def __init__ (self):
        Thread.__init__(self)
        self.url = "http://qemulator.createweb.de"
        self.target = "new window"

    def run(self):
        self.open_website(self.url, self.target)  

    def open_website(self, url, target):
        if target == "new window":
            newin = 1
        else:
            newin = 0
        runweb = webbrowser.open(self.url, new=newin)
         
class TrayMenuitem(gtk.CheckMenuItem):
    def init(self, label=None, use_underline=True):
        self.label = label
        self.use_underline = use_underline
    
        self.job = None
        if self.job != None:
            self.path = job[0]
            self.pid = job[1]
            self.pts = job[2]
            
##class Dialog ( Thread ):
#class Dialogold:
#    def __init__ (self, type, text, title=None, returnfunc=None, return_args=[]):
#        #Thread.__init__(self)
#        self.type = type
#        self.text = text
                                

class Tray ( Thread ):

    def __init__ (self):
        Thread.__init__(self) 
        self.traymenu_item = {}
        self.gladefile = libdir + "/qemulator.glade"
          
    def run(self):   
        self.init_tray()

    def init_tray(self):
        gtk.gdk.threads_enter()
        self.wTree_tray_menu = gtk.glade.XML(self.gladefile,"tray_menu", APP)
        self.tray_menu = self.wTree_tray_menu.get_widget("tray_menu")
        self.traymen_item_exit = self.wTree_tray_menu.get_widget("item_exit")
        
        self.dic_menu_tray = {"on_item_exit_activate" : qemulator.exit_app_event      
        }
        self.wTree_tray_menu.signal_autoconnect(self.dic_menu_tray) 
        self.tray_icon = trayicon.TrayIcon("Qemulator")
        eventbox = gtk.EventBox()
        self.tray_icon.add(eventbox)

        eventbox.connect("button_press_event", self.on_tray_button_press_event)
        eventbox.connect("button_release_event", self.on_tray_button_release_event)

        icon_file = pixmapdir + "/trayicon.png"
        image = gtk.Image()
        image.set_from_file(icon_file)
        image.set_pixel_size(gtk.ICON_SIZE_SMALL_TOOLBAR)
        eventbox.add(image)
        
        self.tray_menu.set_title("Qemulator")
        tearoffitem = gtk.TearoffMenuItem()
        self.tray_menu.prepend(tearoffitem)
        self.tray_menu.append(gtk.SeparatorMenuItem()) 
        
        self.tray_menu.show_all()
        self.tray_icon.show_all()       
        
        gtk.gdk.threads_leave()
        
    def popup_menu(self, args):
        self.tray_menu.show_all()
        self.tray_icon.show_all()
        self.tray_menu.popup(None, None, None, 0, 0)
        return 1
    
    def resize_popup(self, widget=None, *event):
        print "resizing popup"

    def on_tray_button_press_event(self, *args):
        event = args[1]
        if args[1].button == 1:
            if qemulator.mainwindow.get_property('visible'):
                qemulator.mainwindow.hide()
            else:
                qemulator.mainwindow.present()

    def on_tray_button_release_event(self, *args):
        #print "args: " + str(args) + " --type " + str(args[1].type)

        if args[1].button == 3:
            self.popup_menu(args)               
            
    def create_trayentry_jobmanager(self, job):
        selected_job_name = job[0]
        selected_job_path = job[1]
        selected_job_name = selected_job_path
        selected_job_pid = job[2]
        #if len(job) == 6:
        
        jobname = "Monitor for: " + str(selected_job_name)

        self.traymenu_item[selected_job_pid] = TrayMenuitem(jobname, False)
        self.traymenu_item[selected_job_pid].set_active(True) 
        self.traymenu_item[selected_job_pid].job = job
        self.tray_menu.append(self.traymenu_item[selected_job_pid])
        self.traymenu_item[selected_job_pid].connect("button_press_event", self.on_tray_entry_jobman)
        self.tray_menu.show_all()
        
    def on_tray_entry_jobman(self, *args):
        #print "args: " + str(args)
        widget = args[0]
        wname = widget.get_name()
        job = widget.job
        #print "job: " + str(job)
        selected_job_pid = job[2]
        jobmonitor = qemulator.jobmanagers[selected_job_pid]
        if jobmonitor.dialog_jobmonitor.get_property('visible'):
            jobmonitor.to_tray(widget)
        else:
            jobmonitor.restore_from_tray(widget)    
        
    def remove_trayentry_jobmanager(self, pid):
        #print "Item " + str(self.traymenu_item[pid]) + " destroyed"
        self.traymenu_item[pid].destroy()
        self.tray_menu.show_all() 
        
def load_settings(): 
    #print "load_settings called"
    settings = {}
    settings["cdromdrives"] = [("CD-rom", "/dev/cdrom"),]
    settings["qemuapps"] = [("x86", "qemu"), 
    ("x86_64", "qemu-system-x86_64"),
    ("ppc", "qemu-system-ppc"),
    ("arm", "qemu-system-arm"), 
    ("mips", "qemu-system-mips"),
    ("mipsel", "qemu-system-mipsel"),
    ("sparc", "qemu-system-sparc"),]
    settings["monitor_hotkeys"] = ["ctrl-alt-f1", 
                                   "ctrl-alt-f2", 
                                   "ctrl-alt-f3",
                                   "ctrl-alt-f4",
                                   "ctrl-alt-f5",
                                   "ctrl-alt-f6",
                                   "ctrl-alt-f7",
                                   "ctrl-alt-delete"]
    settings["usetray"] = True
    settings["closetotray"] = False
    settings["controlmon_totray"] = False
    settings["controlmon_ministart"] = False
    settings["controlmon_ontop"] = False
    
    settings["imagespath"] = os.path.expanduser('~/')
    settings["default_iconsize"] = 32
    settings["settings_autoshow"] = True
    settings["settings_autohide"] = True
    settings["helperapps_vncviewer"] = "vncviewer"
    settings["helperapps_vncpassfile"] = ""    
    settings["helperapps_imageviewer"] = "eog"
    settings["helperapps_audioplayer"] = "xmms" 
    
    ## special settings ###
    
    outdata = getfromfile("mainsettings")
        
    if outdata  != {} and outdata != "":
        settings.update(outdata)
        #print "loaded settings from file"       
    return settings                       
                             
def filter_devs(settings):
    filter = gtk.FileFilter()
    for volume in settings["cdromdrives"]:
        pattern = volume[1].replace ( '/dev/', '' ) 
        filter.add_pattern(pattern)
        filter.set_name(_("Only configured devices"))
    return filter

def filter_shall(*settings):
    filter = gtk.FileFilter()
    pattern = '*'
    filter.add_pattern(pattern)
    filter.set_name(_("All Files"))
    return filter    

def reload_settings():
    settings = {}
    settings = load_settings()
    #print "Get settings from reload_settings function" 
    
def run_command(command):
        if command != '':
            child_stdin, child_stdout, child_stderr = os.popen3(command)
            child_stdin.close()    
            errormesg = child_stderr.readlines()
            resultmesg = child_stdout.readlines()
            if errormesg != []:
                #self.general_error = True
                print "Error: " + str(errormesg)
                returnmesg = errormesg
            else:
                returnmesg = resultmesg
        else:
            returnmesg = "no command given!"
            child_stderr.close()
            child_stdout.close()            
        return returnmesg  
    
def qemu_version(*widget):
#    version = '0.9.0'
#    return version
    helpmessage = run_command('qemu --help')   
    versionexp = re.compile('(\ version\ )([0-9\.]+)')
    versolate = "\g<2>"
    
    for line in helpmessage:
        versionrender = versionexp.search(line)
        if versionrender != None and versionrender != '':
            versionstr = versionrender.group()
            version = versionexp.sub(versolate, versionstr)
            
            return version
            break      

if __name__ == "__main__":
      
    settings = {}
    settings = load_settings()       

    splashscreen = Splashscreen()
    splashscreen.start()
    time.sleep(1.0)
 
    
    qemulator = Qemulator(settings)
    #gobject.idle_add(qemulator.start)
    qemulator.start()    
    #time.sleep(0.1)
    tray = None
    if nognomextras != True and settings["usetray"] == True:
        tray = Tray()
        #gobject.idle_add(tray.start)
        tray.start()
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
    

