#!/usr/bin/env python
# encoding=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.

import os
from os import path
import sys
import gobject
import string
import re
import time
import threading
from threading import Thread
from threading import Lock

## Import Qemulator classes 
import qemulator
import qml_ptsmanager
import qml_filehandlers

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', '' ) 
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"

APP = 'Qemulator'
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"

class ControlMonitor(Thread):		
	def __init__(self, job, currimage_settings, tray, joblist, callback_close_func=None):
		Thread.__init__(self)	
		#gtk.gdk.threads_init()
		self.settings = qemulator.load_settings()
		print "loaded settings in controlmon"
		self.qemu_commandset = 'old'
		self.jobman_volumes_list = []
		self.jobmessage = []
		self.usbhost_list = []
		self.usbguest_list = []
		self.snapshots_list = []
		#self.jobman_volumes_list = []
		self.job = job
		print 'Opened monitor with job: ' + str(self.job)
		self.job_name = self.job[0]
		self.jobimage = self.job[1]
		#self.job_name = self.jobimage
		self.translated_name = self.jobimage.replace ( '/', '_' )
		self.pid = self.job[2]
		self.pts = self.job[3]
		self.displaymode = job[4]
		self.runstat = self.job[5]
		self.statefiles_dir = homedir + "/statefiles"
		self.screenshot_dir = homedir + "/screenshots"
		self.capture_dir = homedir + "/capture"		
		self.storedstates = []
		self.currimage_settings = currimage_settings
		self.tray = tray
		self.callback_close_func = callback_close_func
		#if len(job) == 6:
		#	self.job_name = self.job[0]
		
		self.joblist = joblist
		if joblist != None:
			self.joblist_data =  self.joblist.joblist_data
			self.refresh_joblist = self.joblist.refresh_joblist
		self.stateshandler = qml_filehandlers.Statefiles(self.jobimage, self.settings)
		self.sceenshothandler = qml_filehandlers.Screenshots(self.jobimage, self.settings)
		self.capturehandler = qml_filehandlers.Wavecaptures(self.jobimage, self.settings)
		
		print "------ Control monitor opened -----------------------------------"
		print "job: " + str(self.job)
		print "jobimage: " + str(self.jobimage)
		print "pid: " + str(self.pid)
		print "pts: " + str(self.pts)
		print "runstat: " + str(self.runstat)

		self.basedir = basedir.replace ( '/bin', '' ) 
		self.basedir = self.basedir.replace ( '/lib/qemulator', '' ) 
		
			
		print "basedir: " + self.basedir
			
		self.bindir = self.basedir + "/bin"
		print "bindir: " + self.bindir
		self.libdir = self.basedir + "/lib/qemulator"
		print "libdir: " + self.libdir
		self.sharedir = self.basedir + "/share/qemulator"
		print "sharedir: " + self.sharedir 
		self.homedir = os.path.expanduser('~/.qemulator')
		self.configdir = self.homedir + "/config"
		print "configdir: " + self.configdir		   
					
		self.gladefile = self.libdir + "/qemulator.glade"
		
		self.qemu_version = qemulator.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 old command set'
		    self.qemu_commandset = 'old' 		
	
	def run(self):
		self.preload_gui()	
		self.init_jobmanager()
		
	def preload_gui(self):
		gtk.gdk.threads_enter()
		self.wTree = gtk.glade.XML(self.gladefile, "dialog_jobmonitor", APP)
		self.dialog_jobmonitor = self.wTree.get_widget("dialog_jobmonitor")
		self.dialog_jobmonitor.set_keep_above(self.settings["controlmon_ontop"])
		#self.dialog_jobmonitor.set_gravity(gtk.gdk.GRAVITY_NORTH_WEST)

		self.toolbutton_pause_job = self.wTree.get_widget("toolbutton_pause_job")
		self.toolbutton_rerun_job = self.wTree.get_widget("toolbutton_rerun_job")
		self.toolbutton_stop_job = self.wTree.get_widget("toolbutton_stop_job")
		self.toolbutton_reset_job = self.wTree.get_widget("toolbutton_reset_job")
		self.toolbutton_vnc = self.wTree.get_widget("toolbutton_vnc")
		vncicon = gtk.Image()
		vncicon.set_from_file(pixmapdir + '/vnc20.png')
		vncicon.set_pixel_size(gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.toolbutton_vnc.set_icon_widget( vncicon )
		vncicon.show_all()
		self.toggletoolbutton_notebook = self.wTree.get_widget("toggletoolbutton_notebook")
		self.toolbutton_tray = self.wTree.get_widget("toolbutton_tray")	
	 				
		self.label_jobtitle = self.wTree.get_widget("label_jobtitle")
		self.notebook_controlconsole = self.wTree.get_widget("notebook_controlconsole")
		
		self.treeview_usbhost = self.wTree.get_widget("treeview_usbhost")
		self.treeview_usbguest = self.wTree.get_widget("treeview_usbguest")
		self.treeview_jobmon_volumes = self.wTree.get_widget("treeview_jobmon_volumes")

		self.filechooserbutton_jobmon_cdrom = self.wTree.get_widget("filechooserbutton_jobmon_cdrom")
		self.filechooserbutton_jobmon_fda = self.wTree.get_widget("filechooserbutton_jobmon_fda")
		self.filechooserbutton_jobmon_fdb = self.wTree.get_widget("filechooserbutton_jobmon_fdb")
		
		self.filechooserbutton_jobmon_cdrom.set_current_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_cdrom.add_shortcut_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_cdrom.add_shortcut_folder("/dev/")
		
		self.filechooserbutton_jobmon_fda.set_current_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_fda.add_shortcut_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_fda.add_shortcut_folder("/dev/")
		
		self.filechooserbutton_jobmon_fdb.set_current_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_fdb.add_shortcut_folder(self.settings["imagespath"])
		self.filechooserbutton_jobmon_fdb.add_shortcut_folder("/dev/")
		
		self.button_jobmon_eject_fda = self.wTree.get_widget("button_jobmon_eject_fda")
		self.button_jobmon_eject_fdb = self.wTree.get_widget("button_jobmon_eject_fdb")
		self.button_jobmon_eject_cdrom = self.wTree.get_widget("button_jobmon_eject_cdrom")
		
		self.button_jobmon_apply_fda = self.wTree.get_widget("button_jobmon_apply_fda") 
		self.button_jobmon_apply_fdb = self.wTree.get_widget("button_jobmon_apply_fdb") 
		self.button_jobmon_apply_cdrom = self.wTree.get_widget("button_jobmon_apply_cdrom") 
		
		self.action_area_controlconsole = self.wTree.get_widget("action_area_controlconsole")
		self.button_refresh = self.wTree.get_widget("button_refresh")
		
		self.menu_widgets_volumes = gtk.glade.XML(self.gladefile,"menu_popup_volumes", APP)
		self.menu_popup_volumes = self.menu_widgets_volumes.get_widget("menu_popup_volumes")
		self.item_eject_volume = self.menu_widgets_volumes.get_widget("item_eject")
		
		self.menu_widgets_usbhost = gtk.glade.XML(self.gladefile,"menu_popup_usbhost", APP)
		self.menu_popup_usbhost = self.menu_widgets_usbhost.get_widget("menu_popup_usbhost")
		self.item_attach_device_usbhost = self.menu_widgets_usbhost.get_widget("item_attach_device")
		
		self.menu_widgets_usbguest = gtk.glade.XML(self.gladefile,"menu_popup_usbguest", APP)
		self.menu_popup_usbguest = self.menu_widgets_usbguest.get_widget("menu_popup_usbguest")
		self.item_detach_device_usbguest = self.menu_widgets_usbguest.get_widget("item_detach_device")
		
		
		self.button_mouse_up = self.wTree.get_widget("button_mouse_up")
		icon1 = gtk.Image()
		icon1.set_from_file(pixmapdir + '/cursor_up.png')
		self.button_mouse_up.set_image( icon1 )
		
		self.button_mouse_upright = self.wTree.get_widget("button_mouse_upright")
		icon2 = gtk.Image()
		icon2.set_from_file(pixmapdir + '/cursor_upright.png')
		self.button_mouse_upright.set_image( icon2 )
		
		self.button_mouse_right = self.wTree.get_widget("button_mouse_right")
		icon3 = gtk.Image()
		icon3.set_from_file(pixmapdir + '/cursor_right.png')
		self.button_mouse_right.set_image( icon3 )
		
		self.button_mouse_downright = self.wTree.get_widget("button_mouse_downright")
		icon4 = gtk.Image()
		icon4.set_from_file(pixmapdir + '/cursor_downright.png')
		self.button_mouse_downright.set_image( icon4 )
		
		self.button_mouse_down = self.wTree.get_widget("button_mouse_down")
		icon5 = gtk.Image()
		icon5.set_from_file(pixmapdir + '/cursor_down.png')
		self.button_mouse_down.set_image( icon5 )
		
		self.button_mouse_downleft = self.wTree.get_widget("button_mouse_downleft")
		icon6 = gtk.Image()
		icon6.set_from_file(pixmapdir + '/cursor_downleft.png')
		self.button_mouse_downleft.set_image( icon6 )
		
		self.button_mouse_left = self.wTree.get_widget("button_mouse_left")
		icon7 = gtk.Image()
		icon7.set_from_file(pixmapdir + '/cursor_left.png')
		self.button_mouse_left.set_image( icon7 )
		
		self.button_mouse_upleft = self.wTree.get_widget("button_mouse_upleft")
		icon8 = gtk.Image()
		icon8.set_from_file(pixmapdir + '/cursor_upleft.png')
		self.button_mouse_upleft.set_image( icon8 )
		
		self.spinbutton_mouseamount = self.wTree.get_widget("spinbutton_mouseamount")
		
		self.textview_monitor_console = self.wTree.get_widget("textview_monitor_console")
		self.entry_console_command = self.wTree.get_widget("entry_console_command")

		self.entry_sendkeys = self.wTree.get_widget("entry_sendkeys")
		self.button_sendkeys = self.wTree.get_widget("button_sendkeys")
		self.combobox_sendkeys = self.wTree.get_widget("combobox_sendkeys")
		
		hotkeys_model = self.combobox_sendkeys.get_model()
		hotkeys_model.clear()
		
		hotkeys_model.prepend(row=("",))
		for name in self.settings["monitor_hotkeys"]:
		    hotkeys_model.append(row=(name,))
		    self.combobox_sendkeys.set_model(hotkeys_model)		
		
		self.entry_statename = self.wTree.get_widget("entry_statename")
		self.button_savestate = self.wTree.get_widget("button_savestate")
		self.treeview_statefiles = self.wTree.get_widget("treeview_statefiles")
		self.button_loadstate = self.wTree.get_widget("button_loadstate")
		self.button_delstate = self.wTree.get_widget("button_delstate")
		self.button_apply_snapshot = self.wTree.get_widget("button_apply_snapshot")
		
		self.entry_screenshot = self.wTree.get_widget("entry_screenshot")
		self.iconview_screenshots = self.wTree.get_widget("iconview_screenshots")
		self.toolbutton_storescreenshot = self.wTree.get_widget("toolbutton_storescreenshot")
		self.toolbutton_viewscreenshot = self.wTree.get_widget("toolbutton_viewscreenshot")
		self.toolbutton_deletescreenshot = self.wTree.get_widget("toolbutton_deletescreenshot")
		## Setup initial values and states for all widgets  
		self.combobox_audiofreq = self.wTree.get_widget("combobox_audiofreq")
		self.combobox_audiobitrate = self.wTree.get_widget("combobox_audiobitrate")
		self.spinbutton_audiochannels = self.wTree.get_widget("spinbutton_audiochannels")
		self.entry_capturename = self.wTree.get_widget("entry_capturename")
		self.toggletoolbutton_record = self.wTree.get_widget("toggletoolbutton_record")
		self.toolbutton_playaudio = self.wTree.get_widget("toolbutton_playaudio")
		self.toolbutton_trashaudio = self.wTree.get_widget("toolbutton_trashaudio")
		self.treeview_capture = self.wTree.get_widget("treeview_capture")

		self.label_jobtitle.set_markup("<b>" + _("Emulation: ") + self.job_name + " | " + self.jobimage + "</b>")
		if self.tray == None:
	 		self.toolbutton_tray.hide()
	 		
		if str(self.runstat) == "1":
			#print "**** its running yea!************"
			self.toolbutton_rerun_job.set_sensitive(False)	
			self.toolbutton_pause_job.set_sensitive(True)
		else:
			#print "###### PAUSED # " + self.runstat + " ##################"
			self.toolbutton_rerun_job.set_sensitive(True)	
			self.toolbutton_pause_job.set_sensitive(False)
			
 	 	if self.settings["controlmon_ministart"] == True:
 	 		#gtk.gdk.threads_enter()	 			
	 		self.toggletoolbutton_notebook.set_active(False)
	 		#time.sleep(0.1)
	 		#gtk.gdk.threads_enter()
	 		self.toggle_notebook()
	 		#gtk.gdk.threads_leave()
	 		#time.sleep(0.3)
 		else:
 			self.toggletoolbutton_notebook.set_active(True)
 			#time.sleep(0.1)
 			#gtk.gdk.threads_enter()
	 		self.toggle_notebook()
	 		#gtk.gdk.threads_leave()	
		#time.sleep(0.3)
		gtk.gdk.threads_leave()	
		dicjobmon = {
	 	#"on_dialog_jobmonitor_destroy_event" : self.to_tray
 		"on_dialog_jobmonitor_delete_event" : self.jobmon_delete
 		#, "on_dialog_jobmonitor_destroy" : self.to_tray
	 	, "on_dialog_jobmonitor_response" : self.dialog_jobmonitor_response
		, "on_toolbutton_stop_job_clicked" : self.stop_job
		, "on_toolbutton_pause_job_clicked" : self.pause_job
		, "on_toolbutton_rerun_job_clicked" : self.cont_job	
		, "on_toolbutton_reset_job_clicked" : self.reset_job
		, "on_toolbutton_vnc_clicked" : self.run_vncviewer
		, "on_toggletoolbutton_notebook_toggled" :self.toggle_notebook
		, "on_toolbutton_tray_clicked" : self.to_tray
		
		, "on_notebook_controlconsole_switch_page" : self.notebook_controlconsole_change
		
		, "on_treeview_usbhost_button_press_event"  : self.pop_up_usbhost
		, "on_treeview_usbguest_button_press_event"  : self.pop_up_usbguest
		, "on_treeview_jobmon_volumes_button_press_event"  : self.pop_up_volumes
		

		, "on_button_jobmon_apply_fda_clicked" : self.jobman_change_volume
		, "on_button_jobmon_apply_fdb_clicked" : self.jobman_change_volume
		, "on_button_jobmon_apply_cdrom_clicked" : self.jobman_change_volume
		
		, "on_button_jobmon_eject_cdrom_clicked" : self.clear_filechooser
		, "on_button_jobmon_eject_fda_clicked" : self.clear_filechooser
		, "on_button_jobmon_eject_fdb_clicked" : self.clear_filechooser
		
		
		, "on_button_send_command_clicked" : self.launch_monitor_command
		
		, "on_button_savestate_clicked" : self.store_statefile
		, "on_button_loadstate_clicked" : self.loadstatefile_clicked
		, "on_button_delstate_clicked" : self.deletestatefile_clicked
		, "on_button_apply_snapshot_clicked" : self.apply_snapshot_clicked
		
		, "on_toolbutton_storescreenshot_clicked" : self.store_screenshot
		, "on_iconview_screenshots_button_press_event"  : self.run_imageviewer
		, "on_toolbutton_viewscreenshot_clicked"  : self.run_imageviewer
		, "on_toolbutton_deletescreenshot_clicked"  : self.delete_screenshot_clicked
		
		, "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_button_mouse_up_clicked" : self.move_mouse
		, "on_button_mouse_upright_clicked" : self.move_mouse
		, "on_button_mouse_right_clicked" : self.move_mouse
		, "on_button_mouse_downright_clicked" : self.move_mouse
		, "on_button_mouse_down_clicked" : self.move_mouse
		, "on_button_mouse_downleft_clicked" : self.move_mouse
		, "on_button_mouse_left_clicked" : self.move_mouse
		, "on_button_mouse_upleft_clicked" : self.move_mouse

		, "on_button_sendkeys_clicked" : self.send_keys
		, "on_combobox_sendkeys_changed" : self.hot_keys
		
		, "on_button_refresh_clicked" : self.refreshmon
		, "on_combobox_quickcommand_changed" : self.quick_monitor_command
		# , "on_attach_device_activate" :  self.usbhost_attach
		}
		self.wTree.signal_autoconnect(dicjobmon)  
		
		dic_menu_volumes = {"on_item_eject_activate" : self.volume_eject,
		}
		self.menu_widgets_volumes.signal_autoconnect(dic_menu_volumes)
		
		dic_menu_usbhost = {"on_attach_device_activate" : self.usbhost_attach,
		}
		self.menu_widgets_usbhost.signal_autoconnect(dic_menu_usbhost)
		
		dic_menu_usbguest = {"on_detach_device_activate" : self.usbguest_detach,
		}
		self.menu_widgets_usbguest.signal_autoconnect(dic_menu_usbguest) 			
    			

	def init_jobmanager(self, *widget):
		gtk.gdk.threads_enter()
		self.combobox_audiofreq.set_active(0)
	 	self.combobox_audiobitrate.set_active(1)			
		## Init functions	
		
		if self.qemu_commandset == 'old':
			self.stateshandler.load_statefiles()
			ddata = self.stateshandler.statefiles_displaynames(self.storedstates)
			statesmodel = self.create_model_statefiles(ddata)
			self.treeview_statefiles.set_model(statesmodel)
			self.add_columns_statefiles(self.treeview_statefiles, statesmodel)
		else:
			#self.refresh_snapshots_list()
			statesmodel = self.create_model_snapshots(self.snapshots_list)
			self.treeview_statefiles.set_model(statesmodel)
			self.add_columns_snapshots(self.treeview_statefiles, statesmodel)	 
			#statesmodel.append(row=(_('wait') + " " + _('loading usb_guest devices')," "," "))		
									
		
		sshata = self.sceenshothandler.load_screenshots()
		self.add_columns_screenshots(self.iconview_screenshots)
		screensmodel = self.create_model_screenshots(sshata)
		self.iconview_screenshots.set_model(screensmodel)
		
		self.storedcapts = self.capturehandler.load_captures()
		cdata = self.capturehandler.captures_displaynames(self.storedcapts)
		captmodel = self.create_model_capture(cdata)
		self.treeview_capture.set_model(captmodel)
		self.add_columns_capture(self.treeview_capture, captmodel)		
		
		
		vmodel = self.create_model_jobmon_volumes(self.jobman_volumes_list)
		self.treeview_jobmon_volumes.set_model(vmodel)
		self.add_columns_jobmon_volumes(self.treeview_jobmon_volumes, vmodel)   
		#vmodel.append(row=(" ",_('wait') + " " + _('loading mounted block devices')))
		
		hmodel = self.create_model_usbhost(self.usbhost_list)
		self.treeview_usbhost.set_model(hmodel)
		self.add_columns_usbhost(self.treeview_usbhost, hmodel)		 
		hmodel.append(row=(" ",_('wait') + " " + _('loading usb_host devices')))
		
		
		gmodel = self.create_model_usbguest(self.usbguest_list)
		self.treeview_usbguest.set_model(gmodel)
		self.add_columns_usbguest(self.treeview_usbguest, gmodel)	 
		gmodel.append(row=(_('wait') + " " + _('loading usb_guest devices')," "," "))		
		
		if self.displaymode == "vnc":
			self.toolbutton_vnc.show()
			
		try:
		    self.filechooserbutton_jobmon_cdrom.add_shortcut_folder(self.settings["imagespath"])
		except:
		    pass
		try:
		    self.filechooserbutton_jobmon_cdrom.add_shortcut_folder("/dev/")
		except:
		    pass
		self.filechooserbutton_jobmon_cdrom.add_filter(qemulator.filter_shall(self.settings))
		self.filechooserbutton_jobmon_cdrom.add_filter(qemulator.filter_devs(self.settings))		   
		try:
		    self.filechooserbutton_jobmon_fda.add_shortcut_folder(self.settings["imagespath"])
		except:
		    pass
		try:
		    self.filechooserbutton_jobmon_fda.add_shortcut_folder("/dev/")
		except:
		    pass 
		self.filechooserbutton_jobmon_fda.add_filter(qemulator.filter_shall(self.settings))
		self.filechooserbutton_jobmon_fda.add_filter(qemulator.filter_devs(self.settings))		   
		try:
		    self.filechooserbutton_jobmon_fdb.add_shortcut_folder(self.settings["imagespath"])
		except:
		    pass
		try:
		    self.filechooserbutton_jobmon_fdb.add_shortcut_folder("/dev/")
		except:
		    pass
		self.filechooserbutton_jobmon_fdb.add_filter(qemulator.filter_shall(self.settings))
		self.filechooserbutton_jobmon_fdb.add_filter(qemulator.filter_devs(self.settings))		   	   		   
		#time.sleep(0.2)
		self.refreshmon()
		#gtk.gdk.threads_enter()
		self.dialog_jobmonitor.show()
		
		gtk.gdk.threads_leave()

	def clear_filechooser(self, widget):
	
		if widget == self.button_jobmon_eject_fda:
		    fcb = self.filechooserbutton_jobmon_fda 
		elif widget == self.button_jobmon_eject_fdb:
		    fcb = self.filechooserbutton_jobmon_fdb             
		elif widget == self.button_jobmon_eject_cdrom:
		    fcb = self.filechooserbutton_jobmon_cdrom
		else:
		    fcb = None
		if fcb != None:    
		    fcb.unselect_all()
		    fcb.set_current_folder(self.settings["imagespath"])		

#	def check_bookmark(self):
#	    outdata = qemulator.getfromfile("bookmarks")
#	    if outdata  == { } or outdata == "":
#	        bookmarks = []
#	    else:
#	        bookmarks = outdata
#		#print "bookmarks: " + str(bookmarks)
#		if bookmarks != []:        		
#			for bookmark in bookmarks:
#			    try:
#			        if self.jobimage == bookmark.name:
#			            print "Bookmark by name: " + str(bookmark.name)
#			            self.job_name = bookmark.name
#			        elif self.jobimage == bookmark.path:
#			            print "Bookmark by path: " + str(bookmark.name)
#			            self.job_name = bookmark.name			            
#			    except:
#			    	pass	

	def refreshmon(self, *widget):
		self.refresh_volumes_list()
		time.sleep(0.2)
		self.refresh_usbhost_list()
		time.sleep(0.2)
		self.refresh_usbguest_list()
		time.sleep(0.2)
		self.refresh_screenshots()
		time.sleep(0.2)
		self.refresh_captures()		
		time.sleep(0.2)
		if self.qemu_commandset == 'old':
			self.refresh_statefiles()
		else:
			self.refresh_snapshots_list()

		
	def toggle_notebook(self, *widget):
		actstate = self.toggletoolbutton_notebook.get_active()
		print "toggle_notebook: " + str(actstate)
		#time.sleep(0.1)
		if actstate == True:
			#gtk.gdk.threads_enter()
			self.dialog_jobmonitor.set_size_request(550, 420)
			#time.sleep(0.2)	
			self.dialog_jobmonitor.resize(550, 420)
			self.notebook_controlconsole.show_all()
			#time.sleep(0.2)
			self.action_area_controlconsole.show_all()
			#gtk.gdk.threads_leave()
			
		elif actstate == False:
			#gtk.gdk.threads_enter()
			self.dialog_jobmonitor.set_size_request(290, 65)
			self.dialog_jobmonitor.resize(290, 65)
			#time.sleep(0.2)
			self.action_area_controlconsole.hide()
			#time.sleep(0.2)	
			self.notebook_controlconsole.hide()
			#gtk.gdk.threads_leave()
		return

	def to_tray(self, widget, *event):
		if self.tray != None:
			if self.dialog_jobmonitor.get_property('visible'):
				self.tray.tray_menu.show_all()
				self.tray.tray_icon.show_all()
				self.position = self.dialog_jobmonitor.get_position()
				self.dialog_jobmonitor.hide()
			if widget == self.toolbutton_tray:
				self.tray.traymenu_item[self.pid].set_active(False)
		return True
	
	def restore_from_tray(self, widget, *event):
		if self.tray != None:
			if not self.dialog_jobmonitor.get_property('visible'):
				
				self.tray.tray_menu.show_all()
				self.tray.tray_icon.show_all()
				self.dialog_jobmonitor.move(self.position[0], self.position[1])
				self.dialog_jobmonitor.set_keep_above(self.settings["controlmon_ontop"])
				self.dialog_jobmonitor.show()	
		return True			
		
	def jobmonitor_close(self):
		if self.callback_close_func	!= None:
			self.callback_close_func(self.pid)
			time.sleep(0.2)
		self.dialog_jobmonitor.destroy ()
		
	def jobmon_delete(self, widget, response, *entry):
		if self.tray != None and self.settings["controlmon_totray"] == True:
			print "tray used, hiding to tray"
			self.position = self.dialog_jobmonitor.get_position()
			self.dialog_jobmonitor.hide()

			#gtk.gdk.threads_enter()
			self.tray.traymenu_item[self.pid].set_active(False)
			#print "Status:"
			#print self.tray.traymenu_item[self.pid].get_active()			
			#gtk.gdk.threads_leave()
			time.sleep(0.2)
			return True
		else:
			print "tray use disabled closing"
			if self.tray != None:
				self.tray.remove_trayentry_jobmanager(self.pid)
				time.sleep(0.2)
			if self.callback_close_func	!= None:
				self.callback_close_func(self.pid)
			widget.destroy ()
			return False			

	def dialog_jobmonitor_response(self, widget, response, *entry):	
		if response == gtk.RESPONSE_CLOSE:
			widget.destroy ()
			if self.callback_close_func	!= None:
				self.callback_close_func(self.pid)
			return False
		
	def notebook_controlconsole_change(self, widget, *event):
		seltab = event[1]	 
		
	def create_model_jobmon_volumes(self, data):
		store = gtk.ListStore(gobject.TYPE_STRING,
						  gobject.TYPE_STRING)
		data.sort()	
		
		for item in data:
			if len(item) == 2:
				iter = store.append()
				itempath = item[0]
				itemname = item[1]
				#print itempath
				#print itemname
				store.set(iter, 0, item[0], 1, item[1])
			else:
				pass
		return store	  
	
	def add_columns_jobmon_volumes(self, treeview, model):
	
		renderer = gtk.CellRendererToggle()
		column = gtk.TreeViewColumn(_('Device'), gtk.CellRendererText(), text=0)
		
		column2 = gtk.TreeViewColumn(_('Mounted Volume'), gtk.CellRendererText(), text=1)
		treeview.append_column(column)   
		treeview.append_column(column2)		
		
	def create_model_usbhost(self, data):
		store = gtk.ListStore(gobject.TYPE_STRING,
						  gobject.TYPE_STRING)
		data.sort()
		
		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_usbhost(self, treeview, model):
		
			renderer = gtk.CellRendererToggle()
			column = gtk.TreeViewColumn(_('Type'), gtk.CellRendererText(), text=0)
			column2 = gtk.TreeViewColumn(_('Device'), gtk.CellRendererText(), text=1)
			treeview.append_column(column)   
			treeview.append_column(column2)	
		
	def create_model_usbguest(self, data):
		store = gtk.ListStore(gobject.TYPE_STRING,
						  gobject.TYPE_STRING,
						  gobject.TYPE_STRING)
		data.sort()
		try:
			for item in data:
				iter = store.append()
				device = item[0]
				string.strip(device)
				usbtype = item[1]
				string.strip(usbtype)
				name = item[2]
				string.strip(name)
				#print device
				#print usbtype
				#print name
				store.set(iter, 0, item[0], 1, item[1], 2, item[2])
			return store		  
		except:
			print "recieved no correct data for treemodel creation"
	   
	def add_columns_usbguest(self, treeview, model):
	
		renderer = gtk.CellRendererToggle()
		column = gtk.TreeViewColumn(_('Device'), gtk.CellRendererText(), text=0)
		column2 = gtk.TreeViewColumn(_('Type'), gtk.CellRendererText(), text=1)
		column3 = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=2)
		treeview.append_column(column)   
		treeview.append_column(column2)	   
		treeview.append_column(column3)
		
	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 treemodel creation"
	   
	def add_columns_statefiles(self, treeview, model):
	
		renderer = gtk.CellRendererToggle()
		column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0)
		treeview.append_column(column)	
		
	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 jobman_change_volume(self, widget):
		wname = widget.get_name()
		if wname == 'button_jobmon_apply_fda':
			volume = "fda"
			fcb = self.filechooserbutton_jobmon_fda
		if wname == 'button_jobmon_apply_fdb':
			volume = "fdb"
			fcb = self.filechooserbutton_jobmon_fdb
		if wname == 'button_jobmon_apply_cdrom':
			volume = "cdrom"
			fcb = self.filechooserbutton_jobmon_cdrom
		
		cdrpath = fcb.get_filename()
		image = None
		if cdrpath != "None" and cdrpath != None:
			image = cdrpath   
		if image != "" and image != None:
	
			command = "change " + str(volume) + " " + str(image)
			c = 0
			ptsin = qml_ptsmanager.PtsMan(self.pts, command )
			ptsin.start()
			c = 0
			#print "waiting for thread PtsMan"
			while ptsin.isAlive() and c < 10000:
				print "- " + str(c)
				c = c+1
				#print "waiting for thread PtsMan - " + str(c)
				time.sleep(0.05)
			ptsin.stop()        
			time.sleep(0.3)
			c = 0
			
			refreshcommand = "info block"
			ptsin = RefreshConsole(self.pts, refreshcommand, self.refresh_volumes_command)     
			ptsin.start()
			#print "waiting for thread RefreshConsole"
			while ptsin.isAlive() and c < 200:
				print "- " + str(c)
				c = c+1			
				#print "waiting for thread RefreshConsole - " + str(c)
				time.sleep(0.2)
		else:
			print "no device selected!"  
			
	def launch_monitor_command(self, widget, *event):  
		#print "monitor command launched: " + str(widget)
		command = self.entry_console_command.get_text()
		refreshlist = RefreshConsole(self.pts, command, self.refresh_monitor_command)	 
		refreshlist.start()	
		c = 0
		while refreshlist.isAlive() and c < 200:
			c = c+1
			#print "waiting for thread RefreshConsole - " + str(c)
			time.sleep(0.2)	
	  	#print "Status refreshlist: " + str(refreshlist.isAlive())

	def quick_monitor_command(self, widget, *event):  
		active = widget.get_active()
		model = widget.get_model()
		row = model[active]
		item = row[0]		
		#print "monitor command launched: " + str(item)
		self.entry_console_command.set_text(item)		   
		self.launch_monitor_command(widget)  
		
	def refresh_monitor_command(self, data):  
	    commandbuffer = gtk.TextBuffer()
	    #data = self.outlist
	    outlist = filter(None, data)
	    outlist.sort()	
	    outext = ""	 
	    for dev in outlist:
	        print str(dev)
	        outext = outext + dev + "\n" 
	    commandbuffer.set_text(outext)
	    self.textview_monitor_console.set_buffer(commandbuffer)
	    time.sleep(0.1)
	    
	def run_vncviewer(self, widget, event=None):
		if event == None or event.type == gtk.gdk._2BUTTON_PRESS:
			vncviewer = self.settings["helperapps_vncviewer"]
			vncpassfile = self.settings["helperapps_vncpassfile"]
			vncdisplay = self.currimage_settings.vncdisplay
			if vncpassfile != "":
				command = vncviewer + " -passwd " + vncpassfile + " :" + str(vncdisplay)
			else:
				command = vncviewer + " :" + str(vncdisplay)
			print command
			runit = qml_filehandlers.RunExternalApp(command)
			runit.start()			    
	    
	def stop_job(self, widget):
		job = self.job
		self.joblist.stop_job(widget, self.job)
		self.dialog_jobmonitor.destroy ()	    

	def reset_job(self, widget):
		job = self.job
		self.joblist.reset_job(widget, self.job)		
	    
	def pause_job(self, widget):
		job = self.job
		self.joblist.pause_job(widget, self.job)
		self.toolbutton_rerun_job.set_sensitive(True)	
		self.toolbutton_pause_job.set_sensitive(False)
		
	def cont_job(self, widget):
		job = self.job
		self.joblist.cont_job(widget, self.job)
		self.toolbutton_rerun_job.set_sensitive(False)	
		self.toolbutton_pause_job.set_sensitive(True)

	def refresh_volumes_list(self, widget=None, event=None):
		#print "monitor command launched: " + str(widget)
		command = "info block"
		refreshlist = RefreshConsole(self.pts, command, self.refresh_volumes_command)     
		refreshlist.start() 
		c = 0
		while refreshlist.isAlive() and c < 200:
			#print "waiting for thread RefreshConsole - " + str(c)
			c = c+1
			time.sleep(0.2)
	    
	def refresh_volumes_command(self, data):  
		outlist = filter(None, data)
		lc = 0
		self.usbguest_list = []			
		self.jobman_volumes_list = []
		for line in outlist:
			devdata = line.split(": ", 1)
			self.jobman_volumes_list.append(devdata)				
			lc = lc+1
		
		if self.jobman_volumes_list != []:
		    self.refresh_volumes()        
	    
	def refresh_volumes(self, *widget):    
	    data=self.jobman_volumes_list
	    model = self.create_model_jobmon_volumes(data)    
	    self.treeview_jobmon_volumes.set_model(model)    			
         
	def refresh_usbhost_list(self, widget=None, event=None):  
		#print "monitor command launched: " + str(widget)
		command = "info usbhost"
		refreshlist = RefreshConsole(self.pts, command, self.refresh_usbhost_command)     
		refreshlist.start() 
		c = 0 
		while refreshlist.isAlive() and c < 200:
			#print "waiting for thread RefreshConsole - " + str(c)
			c = c+1
			time.sleep(0.2)				      
	    
	def refresh_usbhost_command(self, data):
	    outlist = filter(None, data)
	    lc = 0
	    self.usbhost_list = []
	    for line in outlist:
	        line = line.replace ( 'u"\u001B"', '' )
	        nodevs = re.search(_('Timeout'), line)
	        if nodevs != None:
	            devdata = line.split(", ", 1)
	            self.usbhost_list.append(devdata)
	        else:
	            if lc%2 == 0:
	                #print line
	                line1 = line
	            else:
	                devadr = re.search("[0-9a-f]{4}\:[0-9a-f]{4}", line)
	                if devadr != None:
	                    self.usbhost_list.append([line1,line,devadr.group()])
	                else:
	                    self.usbhost_list.append([line,line1,""])                
	        lc = lc+1   
	    self.refresh_usbhost()  
	    
	def refresh_usbhost(self, *widget):
	        data=self.usbhost_list
	        data.sort()
	        model = self.create_model_usbhost(data)    
	        self.treeview_usbhost.set_model(model)    
	  
	def refresh_usbguest_list(self, widget=None, event=None):
		#print "monitor command launched: " + str(widget)
		command = "info usb"
		refreshlist = RefreshConsole(self.pts, command, self.refresh_usbguest_command)     
		refreshlist.start() 
		c = 0
		while refreshlist.isAlive() and c < 200:
			#print "waiting for thread RefreshConsole - " + str(c)
			c = c+1
			time.sleep(0.2)				    
	    
	def refresh_usbguest_command(self, data):  
	    outlist = filter(None, data)
	    lc = 0
	    self.usbguest_list = []
	    for line in outlist:
	        line = line.replace ( 'u"\u001B"', '' )
	        nodevs = re.search(_('Timeout'), line)
	        string.strip(line)
	        #print "line split/sep: " + str(line)
	        devadr = re.search("Device", line)
	        if devadr != None:
	            #print "devadr: " + str(devadr.group())
	            #print "line splitted"
	            devdata = line.split(", ", 2)
	            self.usbguest_list.append(devdata)
	        else:   
	            #print "line sepparated manually"
	            devdata = [str(line),"-","-"]  
	            self.usbguest_list.append(devdata)
	        #print "line: " + str(line)               
	        lc = lc+1
	    if self.usbguest_list != []:
	        self.refresh_usbguest()        
	    
	def refresh_usbguest(self, *widget):
	    data=self.usbguest_list
	    data.sort()
	    model = self.create_model_usbguest(data)    
	    self.treeview_usbguest.set_model(model)
				
	def pop_up_usbhost(self, widget, event):
		
		if event.button == 3:
			sel = self.treeview_usbhost.get_selection().get_selected()
			model = self.treeview_usbhost.get_model()
			self.selected_usb_hostdev = model.get_value(sel[1], 1)
			self.menu_popup_usbhost.popup(None, None, None, 3, 0)	
			
	def pop_up_usbguest(self, widget, event):
		
		if event.button == 3:
			sel = self.treeview_usbguest.get_selection().get_selected()
			#print "iter: " + str(sel[1])
			model = self.treeview_usbguest.get_model()
			try:
				self.selected_usb_guestdev = model.get_value(sel[1], 0)
				#print str(self.selected_usb_guestdev)				
			except:
				print "no guest usbdevice selected"
				self.selected_usb_guestdev = ""
			self.menu_popup_usbguest.popup(None, None, None, 3, 0)	  
			
	def pop_up_volumes(self, widget, event):
		
		if event.button == 3:
			sel = self.treeview_jobmon_volumes.get_selection().get_selected()
			#print "iter: " + str(sel[1])
			model = self.treeview_jobmon_volumes.get_model()
			try:
				self.selected_volume = model.get_value(sel[1], 0)
				#print str(self.selected_volume)		   
				self.menu_popup_volumes.popup(None, None, None, 3, 0)		 
			except:
				print "no volume selected"
				self.selected_volume = ""					
		
	def usbhost_attach(self, widget):
		selection = self.selected_usb_hostdev
		if selection != "":
			devadr = re.search("[0-9a-f]{4}\:[0-9a-f]{4}", selection).group()
			#print "devadr to add: " + devadr
			addcommand = "usb_add host:" + str(devadr)
			#lockit = threading.Lock()
			ptsin = qml_ptsmanager.PtsMan(self.pts, addcommand)
			ptsin.start()
			
			c = 0
			while ptsin.isAlive() and c < 2000:
				#print "waiting for thread ptsin"
				c = c+1
				time.sleep(0.05)
			ptsin.stop()
			#print "write done! --------------------------------"
			refreshcommand = "info usb"
			ptsin = RefreshConsole(self.pts, refreshcommand, self.refresh_usbguest_command)     
			ptsin.start()
		else:
			print "no device selected!"
		
	def usbguest_detach(self, widget):
		selection = self.selected_usb_guestdev
		if selection != "":
			devadr = re.search("[0-9]+\.[0-9]+", selection).group()
			string.strip(devadr)
			delcommand = "usb_del " + str(devadr)
			ptsin = qml_ptsmanager.PtsMan(self.pts, delcommand)
			ptsin.start()
			c = 0
			while ptsin.isAlive() and c < 1800:
				#print "waiting for thread ptsin"
				c = c+1
				time.sleep(0.05)
			ptsin.stop()
			#print "detach command done!"
			
			refreshcommand = "info usb"
			ptsin = RefreshConsole(self.pts, refreshcommand, self.refresh_usbguest_command)     
			ptsin.start()
		else:
			print "no device selected!"		
			
	def volume_eject(self, widget):
		selection = str(self.selected_volume)

		if selection != "":
			command = "eject " + str(selection)
			c = 0
			ptsin = qml_ptsmanager.PtsMan(self.pts, command)
			ptsin.start()
			c = 0
			while ptsin.isAlive() and c < 1800:
				#print "waiting for thread ptsin"
				c = c+1
				time.sleep(0.05)	
			time.sleep(0.5)
			ptsin.stop()		
			refreshcommand = "info block"
			ptsin = RefreshConsole(self.pts, refreshcommand, self.refresh_volumes_command)     
			ptsin.start()
		else:
			print "no device selected!"	
			
	def apply_snapshot_clicked(self, *widget):
		#self.translated_name = self.jobimage.replace ( '/', '_' )
		#thisjobdir = self.statefiles_dir + "/" + self.translated_name
		#diplayed_name = str(filename.replace ( '_', ' ' ))
		#abs_path = path.abspath(thisjobdir + "/" + filename)
		
		command = "commit"
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 60:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.5)
		ptsin.stop()
			
	def store_statefile(self, widget):
		if self.qemu_commandset == 'old':
			entryname = self.entry_statename.get_text()
			if entryname != "":
				thisjobdir = self.statefiles_dir + "/" + self.translated_name
				if not os.path.exists(self.statefiles_dir):
					os.mkdir(self.statefiles_dir)
				if not os.path.exists(thisjobdir):
					os.mkdir(thisjobdir)
				filename = str(entryname.replace ( ' ', '_' ))
				abs_path = path.abspath(thisjobdir + "/" + filename)
				
				command = "savevm " + abs_path
				ptsin = qml_ptsmanager.PtsMan(self.pts, command)
				ptsin.start()
				c = 0
				#print "waiting for input..."
				while ptsin.isAlive() and c < 60:
					#print "waiting for thread PtsMan"
					c = c+1
					print "- " + str(c)
					time.sleep(0.5)
				ptsin.stop()
				#print "got it!"		
				self.refresh_statefiles()
				#print "state stored: " + str(abs_path)
			else:
				print "No name given for the statefile!"
		else:
			self.store_snapshot(widget)				
			
	def store_snapshot(self, widget):
		entryname = self.entry_statename.get_text()
		tagname = str(entryname.replace ( ' ', '_' ))
		command = "savevm " + tagname
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 100:
			#print "waiting for thread PtsMan"
			c = c+1
			print "- " + str(c)
			time.sleep(0.5)
		ptsin.stop()
		time.sleep(0.3)
		#print "got it!"		
		#self.refresh_snapshots()
		self.refresh_snapshots_list()
		#print "state stored: " + str(abs_path)			
      
	def run_statefile(self, filename):
		#self.translated_name = self.jobimage.replace ( '/', '_' )
		thisjobdir = self.statefiles_dir + "/" + self.translated_name
		#diplayed_name = str(filename.replace ( '_', ' ' ))
		abs_path = path.abspath(thisjobdir + "/" + filename)
		
		command = "loadvm " + abs_path
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 60:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.5)
		ptsin.stop()
		
	def run_snapshot(self, snapshotid):
		command = "loadvm " + snapshotid
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 60:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.5)
		ptsin.stop()		

	def loadstatefile_clicked(self, widget):
		model, iter = self.treeview_statefiles.get_selection().get_selected()
		row = model[iter]
		item = row[0]
		
		#print "realname: " + str(realname)
		if self.qemu_commandset == 'old':
			realname = str(item.replace ( ' ', '_' ))
			self.run_statefile(realname)
		else:
			self.run_snapshot(item)

	def deletestatefile_clicked(self, widget):
		error = False
		try:
			model, iter = self.treeview_statefiles.get_selection().get_selected()
			row = model[iter]
			if self.qemu_commandset == 'old':
				item = row[0]
			else:
				item = row[0]
				tag = row[1]
		except:
			error = True
			dialogtext = "<b>No file selected to delete</b>"
			delrequest = qemulator.Dialog("message", dialogtext)
		if error != True:
			dialogtitle = "Confirm delete"
			if self.qemu_commandset == 'old':
				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
				delrequest = qemulator.Dialog("request", dialogtext, dialogtitle, self.delete_statefile, [realname])
			else:
				#realname = str(tag)
				dialogtext = "<b>Do you really want to delete the\n"\
				"selected snapshot?</b>\n\n"\
				"Snapshot: " + item + " " + tag
				delrequest = qemulator.Dialog("request", dialogtext, dialogtitle, self.delete_snapshot, [item])		

	def delete_statefile(self, filename):
		self.stateshandler.delete_statefile(filename)
		self.refresh_statefiles()
		
	def delete_snapshot(self, snapshotid):
		command = "delvm " + snapshotid
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 60:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.5)
		ptsin.stop()
		self.refresh_snapshots_list()			
	       
	def refresh_statefiles(self, *widget): 
		if self.qemu_commandset == 'old':    
			data = self.stateshandler.load_statefiles()
			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 refresh_snapshots(self, *widget):
		print 'refreshing snapshots'
		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"
		refreshlist = RefreshConsole(self.pts, command, self.refresh_snapshots_command)     
		refreshlist.start() 
		c = 0
		while refreshlist.isAlive() and c < 200:
			#print "waiting for thread RefreshConsole - " + str(c)
			c = c+1
			time.sleep(0.2)				    
	    
	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_screenshots(self, data):
		model = gtk.ListStore(str, gtk.gdk.Pixbuf)
		data.sort()
		try:
			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)
				time.sleep(0.1)
				model.append([filename, icon])
			return model		  
		except:
			print "recieved no correct data for treemodel creation"
	   
	def add_columns_screenshots(self, iconview=None):
		iniconview = iconview
		iniconview.set_text_column(0)
		iniconview.set_pixbuf_column(1)
		
	def refresh_screenshots(self, *widget):    
		print "refreshing screenshots..."
		data = self.sceenshothandler.load_screenshots()
		print "data: " + str(data)
		model = self.create_model_screenshots(data)
		self.iconview_screenshots.set_model(model) 			
	
	def store_screenshot(self, widget):
		entryname = self.entry_screenshot.get_text()
		if entryname != "":
			thisjobdir = self.screenshot_dir + "/" + self.translated_name
			if not os.path.exists(self.screenshot_dir):
				os.mkdir(self.screenshot_dir)
			if not os.path.exists(thisjobdir):
				os.mkdir(thisjobdir)
			filename = str(entryname.replace ( ' ', '_' ) + ".ppm")
			abs_path = path.abspath(thisjobdir + "/" + filename)
			
			command = "screendump " + abs_path
			ptsin = qml_ptsmanager.PtsMan(self.pts, command)
			ptsin.start()
			c = 0
			#print "waiting for input..."
			while ptsin.isAlive() and c < 60:
				#print "waiting for thread ptsin"
				c = c+1
				#print "- " + str(c)
				time.sleep(0.5)
			ptsin.stop()
			#print "got it!"		
			#self.refresh_screenshots()
			self.refresh_screenshots()
			#print "screenshot stored: " + str(abs_path)	
		else:
			print "No name for screenshot given!"		
			
	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 = qemulator.Dialog("message", dialogtext)
		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 = qemulator.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)
			    
	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 treemodel creation"
	   
	def add_columns_capture(self, treeview, model):
	
		renderer = gtk.CellRendererToggle()
		column = gtk.TreeViewColumn(_('Name'), gtk.CellRendererText(), text=0)
		treeview.append_column(column)						    
			    
	def toggle_capture(self, widget):
		if widget.get_active() == True:
			tooltips.set_tip(self.toggletoolbutton_record, _("Stop capture"))
			self.toggletoolbutton_record.show_all()
			self.start_capture()
			time.sleep(0.5)
			self.combobox_audiobitrate.set_sensitive(False)
			self.combobox_audiofreq.set_sensitive(False)
			self.spinbutton_audiochannels.set_sensitive(False)
			self.toolbutton_playaudio.set_sensitive(False)
		else:
			tooltips.set_tip(self.toggletoolbutton_record, _("Start capture"))	
			self.toggletoolbutton_record.show_all()	
			self.stop_capture()
			time.sleep(0.5)
			self.combobox_audiobitrate.set_sensitive(True)
			self.combobox_audiofreq.set_sensitive(True)
			self.spinbutton_audiochannels.set_sensitive(True)
			self.toolbutton_playaudio.set_sensitive(True)
			self.refresh_captures()
			    
	def start_capture(self, *widget):
		entryname = self.entry_capturename.get_text()
		if entryname != "":
			thisjobdir = self.capture_dir + "/" + self.translated_name
			if not os.path.exists(self.capture_dir):
				os.mkdir(self.capture_dir)
			if not os.path.exists(thisjobdir):
				os.mkdir(thisjobdir)
			filename = str(entryname.replace ( ' ', '_' ) + ".wav")
			abs_path = path.abspath(thisjobdir + "/" + filename)
			actfreq = str(self.combobox_audiofreq.get_active())
			model = self.combobox_audiofreq.get_model()
			row = model[actfreq]
			smpfreq = row[0]			
			
			actrate = str(self.combobox_audiobitrate.get_active())
			model = self.combobox_audiobitrate.get_model()
			row = model[actrate]
			smprate = row[0]
						
			channels = self.spinbutton_audiochannels.get_text()
			command = "wavcapture " + abs_path + " " + smpfreq + " " + smprate + " " + channels 
			ptsin = qml_ptsmanager.PtsMan(self.pts, command)
			ptsin.start()
			c = 0
			#print "waiting for input..."
			while ptsin.isAlive() and c < 60:
				#print "waiting for thread ptsin"
				c = c+1
				time.sleep(0.5)
			ptsin.stop()
			#print "got it!"		
			#print "capture started: " + str(abs_path)	
		else:
			print "No name for wave file given!"
			
	def stop_capture(self, *widget):
		captureindex = 0
		command = "stopcapture " + str(captureindex )
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		#print "waiting for input..."
		while ptsin.isAlive() and c < 60:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.5)
		ptsin.stop()
		#print "got it!"		
		#print "capture stopped! " + str(captureindex)	

	def refresh_captures(self, *widget):    
		data = self.capturehandler.load_captures()
		ddata = self.capturehandler.captures_displaynames(data)
		model = self.create_model_capture(ddata)
		self.treeview_capture.set_model(model)
		
	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 = qemulator.Dialog("message", dialogtext)
		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 = qemulator.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 move_mouse(self, widget, *event):
		amount = self.spinbutton_mouseamount.get_value_as_int()
		if widget == self.button_mouse_up:
			xval = 0
			yval = -amount
			
		if widget == self.button_mouse_upright:
			xval = amount
			yval = -amount
			
		if widget == self.button_mouse_right:
			xval = amount
			yval = 0
			
		if widget == self.button_mouse_downright:
			xval = amount
			yval = amount
			
		if widget == self.button_mouse_down:
			xval = 0
			yval = amount
			
		if widget == self.button_mouse_downleft:
			xval = -amount
			yval = amount
			
		if widget == self.button_mouse_left:
			xval = -amount
			yval = 0
			
		if widget == self.button_mouse_upleft:
			xval = -amount
			yval = -amount
		
		command = "mouse_move " + str(xval) + " " + str(yval)
		ptsin = qml_ptsmanager.PtsMan(self.pts, command)
		ptsin.start()
		c = 0
		time.sleep(0.1)
		#print "waiting for input..."
		while ptsin.isAlive() and c < 200:
			#print "waiting for thread ptsin"
			c = c+1
			time.sleep(0.1)
		ptsin.stop()
		#print "got it!"
			
	def send_keys(self, widget, *event):
		keystring = string.strip(self.entry_sendkeys.get_text())
		
		if keystring != None and keystring != "":
			#print "Key command launched: " + str(keystring)
			command = "sendkey " + keystring
			ptsin = qml_ptsmanager.PtsMan(self.pts, command)
			ptsin.start()
			c = 0
			#print "waiting for input..."
			while ptsin.isAlive() and c < 1800:
				#print "waiting for thread ptsin"
				c = c+1
				time.sleep(0.05)
			ptsin.stop()
			#print "got it!"
				
	def hot_keys(self, widget, *event): 
		active = widget.get_active()
		model = widget.get_model()
		row = model[active]
		keystring = row[0]	
		
		if keystring != None and keystring != "":	
			#print "Hotkey command launched: " + str(keystring)	
			self.entry_sendkeys.set_text(keystring)
			self.send_keys(widget, event)
		widget.set_active(0)
		
class RunExternalApp ( Thread ):
	def __init__ (self, command):
		Thread.__init__(self)
		self.command = command 	
		#print "Run App called with command: " + str(self.command)
	def run(self):
		runit = os.popen(self.command, 'r')
		print str(runit)
		#print "command done!"   		

class RefreshConsole ( Thread ):
    def __init__ (self, pts, command, return_func=None):
    	Thread.__init__(self)
    	self.pts = pts
    	self.command = command
    	self.return_func = return_func
    	self.outlist = []  
    			
    def run(self):
        ptsin = qml_ptsmanager.PtsMan(self.pts, self.command)
        ptsin.start()
        c = 0
        #print "waiting for inputreturn of command: " + str(self.command)
        time.sleep(0.2)
        while ptsin.isAlive() and c < 100:
        	#print "waiting for thread ptsin"
        	c = c+1
        	time.sleep(0.5)
		#print "got it!"
		ptsin.stop()
		#print "Status ptsin: " + str(ptsin.isAlive())
        	
        if ptsin.outlist == [] or ptsin.outlist == ['']:
            print "Command repeated no response"
            #self.outlist.append(_('No return, for now some commands are not available or don\'t throw a return value.'))   
            self.outlist = ["Command repeated no response"]
        else:
        	self.outlist = filter(None, ptsin.outlist)				
        data = self.outlist			
        if self.return_func != None:
        	#time.sleep(0.2)
        	#gtk.gdk.threads_enter()
        	dofunc = self.return_func(data)
        	#gtk.gdk.threads_leave()
        	#time.sleep(0.2)
    	else:
    		return data 

        									   