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

##    Qemulator - 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.
from os import path
import os
import sys
import string
import pickle
from copy import copy
import time
import gobject
import qemulator
import qml_tools

try:
    import pygtk
    pygtk.require("2.0")
    
except:
      print "pygtk 2.0 is not installed"
try:
    import gtk
    import gtk.glade
    
except:
    print "gtk and/or glade is not installed - exiting..."
    sys.exit(1)
    
try:
    import gettext
    import locale
except:
    print "locale and/or gettext for language support not installed"
    sys.exit(1)        
    
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)   

basedir = basedir.replace ( '/bin', '' ) 
basedir = basedir.replace ( '/lib/qemulator', '' )
pixmapdir = basedir + "/share/pixmaps/qemulator"

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() 

homedir = os.path.expanduser('~/.qemulator')
configdir = homedir + "/config"
libdir = basedir + "/lib/qemulator"    
   
class Installwizzard:
    def __init__(self, qemulator_instance, callback_func=None):
        self.basedir = basedir 
        self.sharedir = self.basedir + "/share/qemulator"
        self.homedir = os.path.expanduser('~/.qemulator')
        self.icondirs = [self.sharedir + "/icons",self.homedir + "/icons"]
        self.default_machine_icon = self.icondirs[0] + "/default.png"
        self.pixmapdir = pixmapdir
        self.qemulator_instance = qemulator_instance
        self.imagespath = qemulator_instance.imagespath
        self.callback_func = callback_func
        self.newimagetarget = None
        self.gladefile = libdir + "/qemulator.glade"
        self.sighandlers = {}
        self.installname = None
        self.currentimage = None        
        self.bootimage = None
        self.installsystem = None
        self.bookmarkname = None
        self.hdcmode = 'hdc'
        self.bootvolume = 'hda'        
        self.statushints = {}
        self.currimage_settings = qemulator.QemuConfig()
        
        self.init_gui()        

    def init_gui(self):
        GoOn = False
        mode = "add"
        #menuitem = widget.get_name()
        #print "menuitem: " + str(menuitem)

        response = self.add_bookmark_response
   
        self.wTree = gtk.glade.XML(self.gladefile, "dialog_installwizzard", APP)
        self.dialog_installwizzard = self.wTree.get_widget("dialog_installwizzard")
        #self.dialog_installwizzard.set_response_sensitive(gtk.RESPONSE_APPLY, False)
        #self.dialog_installwizzard.set_keep_above(True)
        self.notebook_instwizzard = self.wTree.get_widget("notebook_instwizzard")
        self.button_back = self.wTree.get_widget("button_back")    
        self.button_next = self.wTree.get_widget("button_next")
        self.button_apply = self.wTree.get_widget("button_apply")
        self.button_apply.hide()
        self.button_close = self.wTree.get_widget("button_close")
        self.button_close.hide()    
        self.button_launch = self.wTree.get_widget("button_launch")  
        #Name_field = self.wTree.get_widget("entry_bookmark_name")
        self.entry_bookmark_name = self.wTree.get_widget("entry_bookmark_name")
        #self.Path_field = self.wTree.get_widget("entry_bookmark_path")
        self.entry_bookmark_path = self.wTree.get_widget("entry_bookmark_path")
        self.entry_bootimage_path = self.wTree.get_widget("entry_bootimage_path")
        self.filechooserbutton_machine_icon = self.wTree.get_widget("filechooserbutton_machine_icon")
        image_iconpreview = self.wTree.get_widget("image_iconpreview")
        button_create_image = self.wTree.get_widget("button_create_image")
        #Path_field.set_text(inpath)
        self.label_installsystem = self.wTree.get_widget("label_installsystem")
        self.vbox_entrypage = self.wTree.get_widget("vbox_entrypage")
        self.hbox_notify_noinstall = self.wTree.get_widget("hbox_notify_noinstall")
        self.button_refresh_installwizzard = self.wTree.get_widget("button_refresh_installwizzard")
        self.comboboxImagedevice = self.wTree.get_widget("comboboxImagedevice")
        self.comboboxEmusystemQuick = self.wTree.get_widget("comboboxEmusystemQuick")
        self.spinbuttonMemoryQuick = self.wTree.get_widget("spinbuttonMemoryQuick")
        self.labelStatusmessage = self.wTree.get_widget("labelStatusmessage")
        self.labelStatusName = self.wTree.get_widget("labelStatusName")
        self.labelStatusMachine = self.wTree.get_widget("labelStatusMachine")
        self.labelStatusBootmedium = self.wTree.get_widget("labelStatusBootmedium")
        #self.okbutton = self.wTree.get_widget("okbutton")
        
        #self.label_installsystem.set_text(str(self.installsystem))
        
        self.label_installmedium = self.wTree.get_widget("label_installmedium")
        self.label_bootimage = self.wTree.get_widget("label_bootimage")
        
        self.installsystem = self.get_installsystem()
        
        if self.installsystem == None or self.installsystem == '':
            self.vbox_entrypage.hide()
            self.hbox_notify_noinstall.show_all()
            self.button_next.set_sensitive(False)
        else:
            self.vbox_entrypage.show_all()
            self.hbox_notify_noinstall.hide()
            self.button_next.set_sensitive(True)
            

        iconpath = path.abspath(self.default_machine_icon)
        self.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 = self.entry_bookmark_name.get_text()
        Path = self.entry_bookmark_path.get_text()
        self.bootimage = self.entry_bootimage_path.get_text()
        self.set_bootimage(self.bootimage)
        dic = {"on_dialog_installwizzard_response" : response
               , "on_button_refresh_installwizzard_clicked" : self.on_button_refresh_installwizzard_clicked
               , "on_button_back_clicked" : self.on_button_back_clicked
               , "on_button_next_clicked" : self.on_button_next_clicked
               , "on_toolbutton_launch_clicked" : self.on_toolbutton_launch_clicked
               , "on_buttonNewmachineBootimage_clicked" : self.fileChooser_bootimage
               , "on_filechooserbutton_machine_icon_selection_changed" : self.update_bm_iconprev
               , "on_entry_bookmark_name_changed" : self.on_entry_bookmark_name_changed
               , "on_comboboxEmusystemQuick_changed" : self.on_comboboxEmusystemQuick_changed
               , "on_spinbuttonMemoryQuick_changed" : self.on_spinbuttonMemoryQuick_changed
               , "on_entry_bookmark_path_changed" : self.on_entry_bookmark_path_changed
               , "on_comboboxImagedevice_changed" : self.on_comboboxImagedevice_changed
               
               
               
        }
        self.wTree.signal_autoconnect(dic)
        
        self.set_model_comboboxEmusystem()
        
        #eventbox.connect("button_press_event", self.on_tray_button_press_event)
        self.sighandlers['entry_bookmark_path'] = button_create_image.connect("button_press_event",  self.init_bookmark_image, self.return_created_bookmark_image) 
        self.dialog_installwizzard.show()
        
    def on_entry_bookmark_name_changed(self, *widget):
        fname = self.entry_bookmark_name.get_text()
        if fname != "":
            self.bookmarkname = fname
#            self.notebook_bookmarks.set_sensitive(True)
            #self.okbutton.set_sensitive(True)
        else:
            self.bookmarkname = None
#            self.notebook_bookmarks.set_sensitive(False)
        self.check_status() 
        
    def on_comboboxEmusystemQuick_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.qemulator_instance.emusystem_path_by_name(self.currimage_settings.emusystem)
        #self.get_soundhw()
        #self.refresh_soundhw()
#        if self.advancedmode == True:
#            self.comboboxEmusystemQuick.set_active(active)    
        self.get_machines()
        #self.refresh_machineslist()
        self.currimage_settings.machine = self.machineslist[0][1]
        print 'set machine to: ' + str(self.currimage_settings.machine)
        self.check_status() 
        
    def set_model_comboboxEmusystem(self):            
        sysmodel = self.comboboxEmusystemQuick.get_model()
        try:
            sysmodel.clear()
        except:
            #print "nothing to clear"
            pass
        for commands in self.qemulator_instance.settings["qemuapps"]:
            name = commands[0]
            path = commands[1]
            #print "path: " + name + " - " + path
            
            sysmodel.append(row=(name,))
        #self.comboboxEmusystem.set_model(sysmodel)  
         
        self.comboboxEmusystemQuick.set_model(sysmodel)
        #self.comboboxEmusystem.set_active(0);  
        self.comboboxEmusystemQuick.set_active(0); 
        self.currimage_settings.emusystem = self.qemulator_instance.settings["qemuapps"][0][0]            
                   
        

            
    def get_machines(self, *event):
        #print "get machine"  
        #print "qemu system: " + str(self.qemubin)
        prog = os.popen(str(self.qemubin) + " -M ?")
        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 on_spinbuttonMemoryQuick_changed(self, widget, *data):
        value = self.spinbuttonMemoryQuick.get_text()
        c = 0
        while value == "" and c < 100:
            c = c + 1
            return False
        valint = int(value)
#        if self.advancedmode == False:
        self.currimage_settings.memory = valint
#            self.spinbuttonMemory.set_value(self.currimage_settings.memory) 

    def on_entry_bookmark_path_changed(self, *widget):
#        if self.advancedmode == False:
        file = self.entry_bookmark_path.get_text()
        self.bootimage = str(file)
        self.set_bookmark_boottype(file) 
            
    def set_bookmark_boottype(self, imagefile):
        #comboboxImagedevice = self.wTree.get_widget("comboboxImagedevice")
        #label_suggestions = self.wTree.get_widget("label_suggestions")  
        fileparser = qml_tools.ImageInfo()
        #print 'file: ' + str(imagefile)
        #qemuinfo = fileparser.get_qemuimg_info(str(imagefile))
        #print 'qemu info: ' + str(qemuinfo)
        print 'image file: ' + str(imagefile)
        fileinfo = fileparser.get_file_info(str(imagefile))
        print 'file info: ' + str(fileinfo)
        if fileinfo['medium'] == 'hda':
            self.comboboxImagedevice.set_active(0)
            #self.bootvolume = fileinfo['medium']
            #self.quickset_bootimage(fileinfo['medium'])
        if fileinfo['medium'] == 'cdrom':
            self.comboboxImagedevice.set_active(1) 
            #self.bootvolume = fileinfo['medium']
            #self.quickset_bootimage(fileinfo['medium']) 
        if fileinfo['medium'] == 'fda':
            self.comboboxImagedevice.set_active(2)
            #self.bootvolume = fileinfo['medium']
            #self.quickset_bootimage(fileinfo['medium'])
        if fileinfo.has_key('suggestion'):
            #label_suggestions.set_text(fileinfo['suggestion']) 
            self.statushints['hint_bootimage'] = fileinfo['suggestion']
        self.quickset_bootimage()
        
    def on_comboboxImagedevice_changed(self, *widget):
#        if self.advancedmode == False:
        #self.bootvolume = str(self.comboboxImagedevice.get_active())
        #self.currimage_settings.cdrmode
        active = self.comboboxImagedevice.get_active()
        model = self.comboboxImagedevice.get_model()
        row = model[active]
        bootvolume = str(row[0])
        self.bootvolume = bootvolume
        print 'catched bootvolume: ' + str(bootvolume)
        self.quicktoggle_boot(bootvolume)
#            self.bootvolume = str(row[0])
#            self.bootimage = self.entry_bookmark_path.get_text()
        print 'changed bootvolume: ' + self.bootvolume
            #self.quickset_bootimage(self.bootvolume)
            
    def quicktoggle_boot(self, bootvolume):
        print 'qtoggle bootvolume: \"' + str(bootvolume) + '\"'
        if bootvolume == 'hda':
            self.quickset_hdaboot()
        elif bootvolume == 'cdrom':
            self.quickset_cdromboot()
        elif bootvolume == 'fda':
            self.quickset_fdaboot()
        else:
            print 'bootvolume: ' + str(bootvolume) + ' fits nothing'
        print 'qtoggled bootvolume: ' + self.bootvolume
        
    def quickset_bootimage(self, *bootvolume):
        if self.bootimage != '' and self.bootimage != None:
            print 'quick changed for bootimage: ' + str(self.bootimage)
            if self.bootvolume == 'hda':
                self.quickset_hdaboot()
            elif self.bootvolume == 'cdrom':
                self.quickset_cdromboot()

            elif self.bootvolume == 'fda':
                self.quickset_fdaboot()
                
            #self.switch_hdcicon()
        self.check_status()
         
    def quickset_cdromboot(self):
#        self.comboboxMediatypeHDC.set_active(1)
#        #time.sleep(0.1)
#        #self.currimage_settings.cdrmode
#        self.comboboxMediatypeHDC.set_sensitive(False)
        print 'quickset_cdromboot cdrmode: ' + str(self.currimage_settings.cdrmode)
        self.currimage_settings.cdrimage = self.bootimage
        print 'quickset_cdromboot bootimage: ' + str(self.bootimage)
        self.set_hdc_bootimage()
        # if self.currimage_settings.cdrmode == 'image':
#        if self.currimage_settings.cdrmode == 'image':
#            self.filechooserbuttonHDC.set_filename(path.abspath(self.bootimage))
#        self.radiobuttonBootHDC.set_active(True)
        self.currimage_settings.main_image = self.bootimage
        self.currimage_settings.bootmedium = self.bootvolume
        self.currimage_settings.boot_driveletter = 'd'
        self.currimage_settings.hdc_image = None                
        self.currimage_settings.hda_image = None
        self.currimage_settings.fda_image = None
#        if self.filechooserbuttonHDA.get_filename() == self.bootimage:
#            self.filechooserbuttonHDA.unselect_all()
#        if self.filechooserbuttonFDA.get_filename() == self.bootimage:                    
#            self.filechooserbuttonFDA.unselect_all()                
#        self.frameDlinuxboot.hide()
        self.check_status()   
        
    def quickset_hdaboot(self):
        self.currimage_settings.hda_image = self.bootimage
#        try:
#            self.filechooserbuttonHDA.set_filename(path.abspath(self.bootimage))
#        except:
#            pass
#        self.radiobuttonBootHDA.set_active(True)
        
        self.currimage_settings.main_image = self.bootimage
        self.currimage_settings.bootmedium = self.bootvolume
        self.currimage_settings.boot_driveletter = 'c'
        self.currimage_settings.hdc_image = None
        self.currimage_settings.cdrimage = None
        #self.currimage_settings.cdrmedium = None
        self.currimage_settings.fda_image = None

        
    def quickset_fdaboot(self):
        self.currimage_settings.fda_image = self.bootimage

        
        self.currimage_settings.main_image = self.bootimage
        self.currimage_settings.bootmedium = self.bootvolume
        self.currimage_settings.boot_driveletter = 'a'
        self.currimage_settings.hda_image = None
        self.currimage_settings.hdc_image = None
        self.currimage_settings.cdrimage = None

           
        self.comboboxMediatypeHDC.set_active(0)
        self.frameDlinuxboot.hide()
        self.comboboxMediatypeHDC.set_sensitive(True)  
        
    def set_hdc_bootimage(self):
        print 'cdrmedium: ' + str(self.currimage_settings.cdrmedium)
        print 'cdrimage: ' + str(self.currimage_settings.cdrimage)
        print 'hdc_image: ' + str(self.currimage_settings.hdc_image)
        print 'cdrmode: ' + str(self.currimage_settings.cdrmode)
        
        if self.currimage_settings.cdrmode == 'mount':
        #if self.hdcmode == 'cdrom':
            #self.bootimage = self.currimage_settings.cdrmedium
            self.currimage_settings.main_image = self.qemulator_instance.cdrom_path_by_name(self.currimage_settings.cdrmedium)
            self.bootimage = self.currimage_settings.main_image
            self.currimage_settings.cdrimage = None
            self.currimage_settings.hdc_image = None
        else:
            self.bootimage = self.currimage_settings.cdrimage
            self.currimage_settings.main_image = self.bootimage
            self.currimage_settings.cdrimage = self.bootimage
        print 'bootimage for hdc: ' + str(self.bootimage)                
        
    def get_installsystem(self):
        installname = None
        currentimage = None
        bookmark = self.qemulator_instance.selected_bookmark
        currentimage = self.qemulator_instance.currentimage
        if currentimage != None:
            installname = str(currentimage)        
            if bookmark != None:
                installname = str(bookmark)  
            self.installname = installname
            currentimage = currentimage
            self.set_currentimage(currentimage)
            self.label_installsystem.set_text(str(installname))
        return installname
    
    def on_button_refresh_installwizzard_clicked(self, widget):
        self.installsystem = self.get_installsystem()
        print 'Installsystem: ' + str(self.installsystem)
        if self.installsystem == None or self.installsystem == '':
            self.vbox_entrypage.hide()
            self.hbox_notify_noinstall.show_all()
            self.button_next.set_sensitive(False)
        else:
            self.vbox_entrypage.show_all()
            self.hbox_notify_noinstall.hide() 
            self.button_next.set_sensitive(True) 
        bootimage = self.entry_bootimage_path.get_text()
        self.set_bootimage(bootimage)
        #self.label_installsystem.set_text(str(self.installsystem))
    
    def on_button_back_clicked(self, *widget):
        
        self.notebook_instwizzard.prev_page()
        currentpage = self.notebook_instwizzard.get_current_page()
        print 'switched to page' + str(currentpage)
        if currentpage == 1:
            self.button_close.hide()
            self.button_apply.hide()
            self.button_next.show_all()
        if currentpage == 2:
            self.button_close.hide()
            self.button_apply.show_all()
            self.button_next.hide()           

    def on_button_next_clicked(self, widget, *event):
        lastpage = self.notebook_instwizzard.get_current_page()
        self.notebook_instwizzard.next_page()
        currentpage = self.notebook_instwizzard.get_current_page()
        bootimage = self.entry_bootimage_path.get_text()
        self.set_bootimage(bootimage)
        #self.Path_field.set_text(str(self.bootimage))
        print 'switched to page' + str(currentpage)
        if currentpage == 1:
            self.label_installmedium.set_text(str(self.currentimage))
            self.label_bootimage.set_text(str(self.bootimage))
            self.button_apply.hide()                                          
        if currentpage == 2:
            self.check_status()
            self.button_apply.show_all()
            self.button_next.hide()
        if currentpage == 3:
            self.button_close.show_all()
            self.button_apply.hide()
            self.button_next.hide()
            
    def set_bootimage(self, bootimage):
        self.bootimage = bootimage
        self.label_bootimage.set_text(str(self.bootimage))
        self.entry_bookmark_path.set_text(str(self.bootimage))
        self.entry_bootimage_path.set_text(str(self.bootimage))
        
    def set_currentimage(self, currentimage):
        self.currentimage = currentimage
        self.label_installmedium.set_text(str(self.currentimage))      
            
    def on_toolbutton_launch_clicked(self, *widget):
        self.currimage_settings = self.qemulator_instance.currimage_settings
        oldhda = copy(self.currimage_settings.hda_image)
        self.currimage_settings.hda_image = self.bootimage
        self.qemucommand = self.qemulator_instance.qemu_command('Managed')
        self.qemulator_instance.run_qemu(self.qemulator_instance.toolbutton_launch)
        self.currimage_settings.hda_image = oldhda
        #dialogtext = str(self.qemucommand)
        #request = qml_tools.Dialog("info", dialogtext, "Qemu commandline for installation")
        
        
    def fileChooser_bootimage(self, widget):
        
        dic = {"on_filechooserdialogUniversal_response" : self.fileChooser_bootimage_response
        }
        
        wTree = gtk.glade.XML(self.gladefile, "filechooserdialogUniversal", APP)
        self.filechooserdialog_openimage = wTree.get_widget("filechooserdialogUniversal")
        self.filechooserdialog_openimage.set_current_folder(self.qemulator_instance.settings["imagespath"])
        #self.filechooserdialog_openimage = gtk.glade.XML(self.gladefile, "filechooserdialog_openimage", APP)
        self.filechooserdialog_openimage.add_filter(qemulator.filter_shall())
        self.filechooserdialog_openimage.add_filter(qemulator.filter_devs(self.qemulator_instance.settings))
        self.filechooserdialog_openimage.set_filter(qemulator.filter_shall())
        try:        
            self.filechooserdialog_openimage.add_shortcut_folder(self.qemulator_instance.settings["imagespath"])
        except:
            pass 
        try:        
            self.filechooserdialog_openimage.add_shortcut_folder("/dev/")         
        except:
            pass         
        wTree.signal_autoconnect(dic)
        self.filechooserdialog_openimage.show() 
        
    def fileChooser_bootimage_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_bootimage(str(file))
            return file      
        elif response == gtk.RESPONSE_CANCEL:
            widget.destroy ()   
            return None               
        return None  
    
    def delete_openimagedialog(self):
        pass                      
    
    def init_bookmark_image(self, widget, event, returnfunc):
        self.qemulator_instance.init_create_image(widget, returnfunc)
        
    def return_created_bookmark_image(self, newimage):
        #newimage = None
        #newimage = self.createimage.return_newimage()
        #self.last_created_image = newimage
        #Path_field = self.wTree.get_widget("entry_bookmark_path")
        #entry_path = str(Path_field.get_text())
        self.entry_bookmark_path.set_text(str(newimage))
        self.entry_bootimage_path.set_text(str(newimage))
        return newimage  
    
    def update_bm_iconprev(self, widget):
        #filechooserbutton_machine_icon = self.wTree.get_widget("filechooserbutton_machine_icon")
        image_iconpreview = self.wTree.get_widget("image_iconpreview")
        entry_icon = str(self.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 add_bookmark_response(self, widget, response, *entry):
        entryname = self.entry_bookmark_name
        entrypath = self.entry_bookmark_path
        entry_icon = str(self.filechooserbutton_machine_icon.get_filename())
        entry_icon_pixbuf = gtk.gdk.pixbuf_new_from_file(entry_icon)
        
        entry_name = str(entryname.get_text())
        entry_path = self.currimage_settings.main_image
        if response == gtk.RESPONSE_OK or response == gtk.RESPONSE_APPLY: 
            print 'goon response: ' + str(response) 
            checkdouble = self.qemulator_instance.checkexist_bookmark(entry_name)
            #print 'doublecheck: ' + str(checkdouble)
            if checkdouble == True:
                dialogtext = "<b>" + _("A Machine with this name allready exists, please choose another one") + "</b>"
                delrequest = qml_tools.Dialog("error", dialogtext, "Name exists")
            else:  
                #self.get_final_machine()             
                newbookmark = qemulator.Bookmark()
                newbookmark.icon = entry_icon
                newbookmark.name = entry_name
                newbookmark.path = entry_path
                newbookmark.haveconfig = True
                try:
                    self.qemulator_instance.bookmarks.append(newbookmark)
                except:
                    self.qemulator_instance.bookmarks = [(newbookmark)]
                self.qemulator_instance.storetofile(self.qemulator_instance.bookmarks, "bookmarks")
                time.sleep(0.2)
                self.store_emu_settings()
                self.qemulator_instance.refresh_bookmarks()
                self.qemulator_instance.notebook_mainlists.set_current_page(0)
                self.qemulator_instance.show_settings()
                self.qemulator_instance.select_bookmark(entry_name)
                
                #widget.destroy()
                self.on_button_next_clicked(self.button_next)
                #return entry_name                  
                
        if response == gtk.RESPONSE_CANCEL:
            print 'close response: ' + str(response)
            widget.destroy() 
        else: 
            print 'any response: ' + str(response) 
            #return None               
        #return True
    
    def store_emu_settings(self):
        self.image_settings = self.qemulator_instance.image_settings
        newvals = vars(self.currimage_settings)
        for key in newvals.keys():
            var = key
            val = newvals[key]
        self.image_settings[self.bookmarkname] = self.currimage_settings
        storedata = self.image_settings
        filename = "image_settings"
        self.qemulator_instance.storetofile(storedata, filename)     
    
    def check_status(self):
        name_set = False
        system_set = False
        boot_set = False
        all_set = False
        
        text_notset = "<span foreground=\"red\">" + _("Not set") + "</span>"
        text_bootstat = text_notset
        ## check name
        if self.bookmarkname != None and self.bookmarkname != '':
            name_set = True
            text_name = "<span foreground=\"#189100\">" + str(self.bookmarkname) + "</span>"
            text_namehint = ""
            try:
                del self.statushints['hint_name']
            except:
                pass
            
        else:
            text_name = text_notset
            text_namehint = "<b>" + _("Please set a name for the machine") + "</b>"
            self.statushints['hint_name'] = text_namehint
            
        
        # check bootset
        if self.check_bootstatus() == True:
            boot_set = True
            text_boothint = ""
            text_bootstat = "<span foreground=\"#189100\">" + str(self.bootimage) + "</span>"
            try:
                del self.statushints['hint_boot']
            except:
                pass            
        else:
            #text_bootstat = ""
            text_bootstat = text_notset
            if self.bootvolume != None:
                text_boothint = "<b>" + _("Please select an image or medium to boot the system from.") + "</b>"
                self.statushints['hint_boot'] = text_boothint
        
        ## check system arch.        
        if self.currimage_settings.emusystem != None and self.currimage_settings.emusystem != '':
            system_set = True
            text_machine = "<span foreground=\"#189100\">" + self.currimage_settings.emusystem + "</span>"
        else:
            text_machine = text_notset            
            
        self.labelStatusName.set_markup(text_name)
        self.labelStatusMachine.set_markup(text_machine)
        self.labelStatusBootmedium.set_markup(text_bootstat)
        if name_set == True and boot_set == True and system_set == True:
            all_set = True        
#        if self.advancedmode == False:
        if all_set == True:
            text_boothint = "<b><span foreground=\"#189100\">" + _("All required settings are done. The machine is ready to be stored.") + "</span></b>"
            self.statushints['hint_boot'] = text_boothint
        ### print out statusmessage
        statusmessage = ''
        if self.notebook_instwizzard.get_current_page() == 3:
            if self.statushints.has_key('hint_name'):
                statusmessage = statusmessage + self.statushints['hint_name'] + '\n\n'
            if self.statushints.has_key('hint_bootimage'):
                statusmessage = statusmessage + self.statushints['hint_bootimage'] + '\n\n'
            if self.statushints.has_key('hint_boot'):
                statusmessage = statusmessage + self.statushints['hint_boot'] + '\n'
                
            if statusmessage != "":
                traypopalive = False
                try:
                    if self.traypop.alive == True:
                        traypopalive = True
                        print 'gettext: ' + str(self.traypop.labelPopuptext.get_label())
                        print 'statusmessage: ' + str(statusmessage)
                        if self.traypop.labelPopuptext.get_label() != statusmessage:
                            print 'popup new text!'
                            self.traypop.close_balloon()
                            traypopalive = False
                except:
                    traypopalive = False
                if traypopalive == False:
                    self.traypop = qml_tools.PopupInfo(statusmessage, 12)        
    
            self.statushints = {}
        if all_set == True:
            self.button_apply.set_sensitive(True)
        else:
            self.button_apply.set_sensitive(False)
    
    def check_bootstatus(self):
        isset = False
        if self.bootvolume == 'cdrom':
            print 'cdrmedium: \"' + str(self.currimage_settings.cdrmedium) + '\"'
            if self.currimage_settings.cdrmedium != None and self.currimage_settings.cdrmedium != '' and self.currimage_settings.cdrmedium != 'None':
                isset = True
            elif self.currimage_settings.cdrimage != None and self.currimage_settings.cdrimage != '' and self.currimage_settings.cdrimage != 'None':
                isset = True
        elif self.bootvolume == 'hda':
            if self.currimage_settings.hda_image != None and self.currimage_settings.hda_image != '' and self.currimage_settings.hda_image != 'None':
                isset = True
        elif self.bootvolume == 'fda':
            if self.currimage_settings.fda_image != None and self.currimage_settings.fda_image != '' and self.currimage_settings.fda_image != 'None':
                isset = True
        elif self.bootvolume == 'dlinux':
            if self.currimage_settings.kernelimage != None and self.currimage_settings.kernelimage != '' and self.currimage_settings.kernelimage != 'None':
                isset = True                
        else:
            isset = False
        return isset          