#!/usr/bin/python
# -*- coding: utf-8 -*-
## Current Version: 0.6
# v 0.1 - v 0.3 - generated by wxGlade 0.6.3 on Mon Jan 19 23:36:46 2009
# v 0.4 and higher - gui generated by Glade v.3

'''
DEVELOPMENT REFERENCE NOTES:
    PART: Fixed issue with acerhk_info not updating properly. Still need to fix
        the issue with it taking two tries to return the correct info in the driver
        information window.
    v 0.6 Objective
    [X]  Prompt to add acerhk to /etc/modules
    
    v 0.7 Objective
    []  Incorporate Code to check for new mail
'''

'''
To Do:
DONE a.  Test Error Message System Out (internal -- try with pref button)
DONE b.  Figure out how to get error message to show on start
DONE c.  Figure out how to build second window with preference settings
PART d.  Mail LED -- Trigger with poll of pop3 account for mail
    [x] Mail Settings Dialog
    [] Implement Mail Check using settings from dialog
DONE e.  Update About Dialog to reflect more appropriate information and 
    reduce repetition of info (ie: email address and author on main dialog) 
DONE e.1. Reference the rfswitch link at sourceforge
f.  Research and integrate the other driver similar to acerhk
    [x] Established variable for driver ID
    [] Enhance driver selection as option in GUI
    [] Enhance code to set key variables for command variations with drivers
g.  Driver Status -- On / Off
h.  Compare driver info file and new file 
    [?] Why?
DONE i.  make hiden config folder and store driver info file there (prep for Configuration_settings_file  
DONE j.  Modprobe for acerhk driver not loaded.
k.  
z.  LEARN how to manage variables across classes and modules without using the global keyword.

'''


''' 
 --------------------------------------------------------------------------

 AcerHKgui v.0.6 - GUI interaction with acerhk driver
 
 Major changes in v.0.6:
    *  Enhanced modprobe features of 0.5
        - Checks for modprobe success.
        - Alerts if modprobe unsuccessful.
        - If modprobe success, added option to modify the /etc/modules file
        - Checks to see if /etc/modules already has 'acerhk' 
            in it, if so, will not add again
            
 Written 
    Python 2.5.2
    pyGTK
    
 Copyright (C) 2009 Arick McNiel
 <https://sourceforge.net/projects/acerhkgui>

 --------------------------------------------------------------------------

 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 modules    **********************************
import pygtk
pygtk.require("2.0")
import gtk, gobject
import gtk.glade
import os, sys, commands
import subprocess
import pickle

# Initialize Global and Config Variables    **********

## ** NOTE TO .ZIP USER ** :: "CONFIG IF INSTALLED FROM ZIP TO LOCATION"
icon_path = os.path.expanduser("/usr/share/acerhkgui/")

## ** NOTE: Do not modify this path
config_path = os.path.expanduser("~/.config/acerhkgui/acerhkgui.conf")

# Initialize Dictionary Used to Save Config values
config_dict = {}

# Imported from Saved Config File    *****************
acerhk_path = None
email_system = None #Reserved for future use
email_user = None #Reserved for future use
email_pass = None #Reserved for future use
email_server = None #Reserved for future use
email_port = None #Reserved for future use
# Variable is established in anticipation of utilization of acerhkgui for alternate, but similar driver
acerhkgui_driver_type = None #implemented for alternate driver support

# Not Imported from Saved Config File ****************
acerhk_info = None
acerhk_driver_status_wireless = None  #Reserved for future use as radio status
acerhk_driver_status_bluetooth = None #Reserved for future use as radio status
acerhk_path_found = False #Assumes the path is not found by default

# TODO: The following two variables will be used as the program is expanded to function with the other driver that works similar to the acerhk driver
bluetooth = 'blueled' #assigns the driver to generic name "bluetooth"
wireless = 'wirelessled' #assigns the driver to generic name "wireless"

# Name of glade file and path (path is same as icon_path above)
name_gladefile = "%sacerhkgui.glade" % icon_path 
name_prefs_gladefile = "%sacerhkgui-prefs.glade" % icon_path

# Initialize TEMP Variables for Use in Config Dialog
#temp_acerhk_path = None 
#temp_email_system = None
#temp_email_user = None
#temp_email_pass = None
#temp_email_server = None
#temp_email_port = None
#temp_acerhkgui_driver_type = None

# DEFINED GLOBAL FUNCTIONS    ************************

def print_prog_info():
    '''Print the program information to the terminal.'''
    print    
    print "   -=**  The Acer Hot Key GUI   **=-"
    print "      *  Command Line Feedback  *"
    print "------**************************------------------"
    print "You can get the latest version at sourceforge.net"
    print "https://sourceforge.net/projects/acerhkgui"
    print "--------------*-*-*-*-*-*-------------------------"
    print 
    
def acerhk_do(device, action):
    '''This function takes the device (bluetooth, wireless) and action (on, off)
    as argument to create the action desired.  Returns nothing at this point, but
    may in future versions when the device status is indicated in the GUI.'''
    # TODO: Determine how to generalize this to support two different drivers, probably will use a flag set from the preferences dialog.  Being set will reasign the value of the "device"... Hmmmmm :)
    if device == "blueled":
        radio = 'Bluetooth'
    elif device == 'wirelessled':
        radio = 'Wireless'
    elif device == "led": #New Mail Implementation
        radio = 'New Mail'
    else:
        radio = 'Error'
    print 'Send -- %s :: %s' % (radio, action)
    acerhk_command = 'echo "%s" > %s%s%s' % (action, acerhk_path, '/', device)
    #subprocess.Popen(acerhk_command, shell=True) # This was commented out to test the subprocess.call option instead of the subprocess.Popen
    subprocess.call(acerhk_command, shell=True)
    
#Functions below were moved from AcerhkguiApp Class

def check_system(self, check_path):
    '''
    Check for acerhk module at expected location.
    If not there, try running modprobe, provide error message for GUI display
    Provide output to CLI for debug/user feedback when running from CLI
    '''
    
    check_path = str(check_path)
    
    # If path and file don't exist, try running modprobe
    #    if not os.path.exists(check_path + '/info'):
    #        message="The AcerHK module was not found. \n\nAttempting to run 'modprobe' to load driver.\nYour sudo password will be required."
    #        error_messageDriver(self, message)
    #        subprocess.call('gksudo modprobe acerhk', shell=True)
        
    # If path exists, return 'True'
    if os.path.exists(check_path + '/info'):
        print 'AcerHK driver found at: %s' % check_path
        print ' '
        found = True
        return found
        
    # If path does not exist, return 'False'    
    elif not os.path.exists(check_path + '/info'):
        print 'The acerhk driver was not found!'
        print 'The GUI will not function!'
        found = False
        return found
    
    return

def check_system_modprobe(self, check_path):
    '''
    This function attempts to load the acerhk module if the driver is not found.
    If the user wishes to run modprobe, it will ask for the sudo password, and run
    modprobe for the appropriate driver.  Presently only AcerHK driver is supported.
    After running modprobe, it will check for success by seing if acerhk is listed
    in the output of 'lsmod.'  Post message based on success or fail.  
    '''
    if acerhkgui_driver_type == "Acer HK":
        if not os.path.exists(check_path + '/info'):
            message="The AcerHK module was not found. \n\nAttempting to run 'modprobe' to load driver.\nYour sudo password will be required."
            error_messageDriver(self, message)
            subprocess.call('gksudo modprobe acerhk', shell=True)
            #Check to see if module is loaded.
            modinfo = commands.getoutput('lsmod')
            
            if "acerhk" in modinfo:
                message = "Modprobe was successful! \n\nAcerhk is now loaded."
                print_message(self,message)
                error_messageDriver(self,message)
                check_system_modprobe_add2mod(self)
            
            else:
                message = "NOTE:  The acerhk module failed to load!\n\nYour hardware maynot be compatable!\n\nCheck website http://rfswitch.sourceforge.net \nfor more information."
                print_message(self,message)
                error_messageDriver(self,message)
                
        return
    
    ## Add additional checks for acerhkgui_driver_type
    print "Current driver was not checked for modprobe: " + acerhkgui_driver_type
    return

def check_system_modprobe_add2mod(self):
    '''
    This function will update the /etc/modules file by adding acerhk to it
    and preclude the need to run modprobe after every system restart.  This function
    will ask if user wants to update the modules file.  It also checks to ensure
    the modules file does not already have 'acerhk' in it.
    '''
    
    message = "Would you like to add 'acerhk' to\nyour /etc/modules file?\n\nAcerHK GUI just finished running modprobe.\n\nIf this is the first time, it is recommended\nthat you test AcerHK GUI to ensure that it functions\nby pressing NO.\n\nIf this is a second and successful first run, answer YES\nto modify your /etc/modules file with acerhk."
    
    print_message(self, message) #Log to Terminal
    # Show GUI Error Message at start-up if error found with driver.        
    config_dialog = gtk.MessageDialog(parent=None, flags=0,
                        type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO,
                            message_format=message)
    
    response=config_dialog.run()
    
    if response == gtk.RESPONSE_YES: 
        '''
        Update computer /etc/modules with acerhk.  First, check /etc/modules for
        acerhk.  If found, print message, that exists already and end.
        '''
        
        #Read /etc/modules
        fin = open('/etc/modules','r')
        modcheck = fin.read()
        
        if "acerhk" not in modcheck:
            
            command = 'sudo sh -c "echo acerhk >> /etc/modules"'
            
            subprocess.call(command, shell=True)
            message = "***********************************************************\nThe /etc/modules file was updated.\nYou can review file from terminal with following command:\n  cat /etc/modules\n***********************************************************"
            print_message(self,message)
            error_messageDriver(self,message)
            
        else: #acerhk was found in the /etc/modules file
            message = "***********************************************************\nThe /etc/modules file already has acerhk in it.\n\nFor some reason, the driver is not loading.  Your hardware\nmay not be compatable with the acerhk driver.\n***********************************************************"
            print_message(self,message)
            error_messageDriver(self,message)
            
        config_dialog.destroy()
        
    elif response == gtk.RESPONSE_NO:
        message = "***********************************************************\nYou have choosen NOT to modify your /etc/modules file.\n\nYou can manually modify your /etc/modules file by adding\n'acerhk' to the bottom of your /etc/modules file.\n\nAlternately, after verifying the functionality of your\ncomputer, you can re-run acerhk after rebooting and select\nYES from the prompt.\n***********************************************************"
        print_message(self,message)
        error_messageDriver(self,message)
        config_dialog.destroy()
        
    return

def config_exists(self):
    global config_path
    #global config_dict -- Shouldn't need this because the dict is made and then saved and then loaded to the global values from the load_prefs() function.
    
    if os.path.isfile(config_path) == True:
        print "Config file exists already. Loading saved preferences..."
        load_prefs()
        return
    else:
        print "no config file existed, making directory and saving default prefs"
        new_config = os.path.expanduser("~/.config/acerhkgui")
        os.makedirs(new_config, mode=0777)
        config_dict = {'icon_path' : '/usr/share/acerhkgui/',
            'acerhk_path' : '/proc/driver/acerhk',
            'email_system' : '0',
            'email_user' : 'New User',
            'email_pass' : 'Password',
            'email_server' : 'pop3.server.com',
            'email_port' : '995',
            'acerhkgui_driver_type' : 'Acer HK'
            }
        save_prefs(self, config_dict)
        return
    print "Config_Exists:: Ooops"
    return

def get_acerhk_driver_info(self):
    # Added check for old acerhkdriverinfo.txt file and remove if exists
    info_file = os.path.expanduser('~/.acerhkdriverinfo.txt')
    if os.path.isfile(info_file) == True:
        rm_info_file = 'rm ' + info_file
        print rm_info_file
        subprocess.call(rm_info_file, shell=True) # Clean up after previous install
        message = "A previous version of Acerhkgui was installed.\n\nDue to changes in this version, the .acerhkdriverinfo.txt file\nwas moved to the ~/.config/acerhkgui/ directory.\n\nRemoved old driver info file (.acerhkdriverinfo.txt) in user\'s home directory.\n\nHousekeeping Complete."
        print_message (self, message)
        error_messageDriver (self, message)
        
    # Create command string to write the driver info to text file
    acerhk_command = 'cat %s/info > ~/.config/acerhkgui/acerhkdriverinfo.txt' % (acerhk_path)
    # Send command string to system
    subprocess.call(acerhk_command, shell=True) # Creates driver info file
    # Create new command string to store output in variable
    acerhk_command = 'cat %s/info' % (acerhk_path)
    #store driver info in variable for GUI use.
    info = commands.getoutput(acerhk_command)
    #print the status info on the terminal
    print_message(self, info)
    #return contents of 'info' to placed called from
    return info
# Functions to be implemented:

def get_bt_status():
    pass

def get_wifi_status():
    pass
    
def check_mail():
    pass

def load_prefs():
    '''This function reads the saved config file and transfers the values to global variables.'''
    # Use Global variables
    global acerhk_path
    global email_system
    global email_user
    global email_pass
    global email_server
    global email_port
    global config_dict
    global acerhkgui_driver_type

    # load config file into dictionary
    acerhkgui_config_file = os.path.expanduser('~/.config/acerhkgui/acerhkgui.conf')
    f = file(acerhkgui_config_file)
    config_dict = pickle.load(f) 
    
    #Then Read Contents of Dict file and assign to system global variables
    acerhk_path = config_dict['acerhk_path']
    email_system = config_dict['email_system']
    email_user = config_dict['email_user']
    email_pass = config_dict['email_pass']
    email_server = config_dict['email_server']
    email_port = config_dict['email_port']
    acerhkgui_driver_type = config_dict['acerhkgui_driver_type']

    print "Configuration Loaded..."
    
    return

def save_prefs(self, config_dict):
    global config_path
    #global config_dict
    
    if os.path.isfile(config_path) == True:
        back_config_path = config_path + ".bak"
        backup_config = 'cp ' + config_path + ' ' + back_config_path
        print "Executing Backup:  " + back_config_path
        subprocess.call(backup_config, shell=True) # Clean up after previous install
    
    f = file(config_path, 'w')
    pickle.dump(config_dict, f)
    f.close()
    print "New Configuration Saved!"
    
    load_prefs()
    return

# Message Functions:
def print_message(self, message):
    '''Function takes string (message) and outputs string to terminal
    window.  Serves as alternate feedback source.'''
    # log to terminal window
    print "***********************************************************"
    print message
    print "***********************************************************"
    print   
        
def error_messageDriver(self, message):
    '''Essentially same as standard error message, but function creates
    new window and displays error message before execution of gtk.main.
    This was necessary (in my knowledge) in order to present errors using GUI
    before gtk.main starts.  Takes string (message), creates dialog
    and displays string in GUI dialog.'''
    
    print_message(self, message) #Log to Terminal
    # Show GUI Error Message at start-up if error found with driver.        
    error_dialog = gtk.MessageDialog(parent=None, flags=0,
                        type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_OK,
                            message_format=message)
    error_dialog.run()
    error_dialog.destroy()

##FIXME: For some reason, this function does not want to work, whereas the 
##error_messageDriver function does work.
def error_message(self, message):
    '''function takes string (message), creates dialog and displays string.'''
    print_message(self, message) #Log to Terminal
    # create an error message dialog and display modally to the user
    '''error_dialog = gtk.MessageDialog(None, 
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                    gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)'''
    error_dialog = gtk.MessageDialog(self.window1, 
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                    gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)
    error_dialog.run()
    error_dialog.destroy() 

# Preferences Class    *******************************
class AcerhkguiPref(object):
    
    # DEFINED FUNCTIONS    *******************************
    
    # General Functions:
    
    #The following function will pull the text associated with the key value in the combobox
    #Presently not utilized, but functions correctly
    def get_active_text(self, combobox):
        '''Pulls text of the GUI combobox widget instead of the selection index. Takes the name of combobox as argument.'''
        model = combobox.get_model()
        active = combobox.get_active()
        if active < 0:
            return None
        return model[active][0]
    
    def apply_prefs(self):
        '''Save variables to persistent file and apply to current variables'''
        # Use Global Variables and Global TEMP_Variables
        global config_dict
        global config_path
        global acerhk_info
        
        # These are working values for the Preferences Dialog
        global temp_acerhk_path
        global temp_email_system
        global temp_email_user
        global temp_email_pass
        global temp_email_server
        global temp_email_port
        global temp_acerhkgui_driver_type ##FIXME: No GUI Interface Presently. Alt Driver support not implemented yet.
        
        # Collect values from text fields in preferences and assign to temp_[variable]
        temp_acerhk_path=self.gui_acerhk_path.get_text()
        ##NOTE: This does pull the name, but difficulty and possibly no value in not just using the index
        #print temp_email_system
        #combo=self.gui_email_system
        #temp_email_system=self.get_active_text(combo)
        #print temp_email_system
        ##End Sample -------------
        ##This will pull the index of combobox selection
        temp_email_system=self.gui_email_system.get_active()
        temp_email_user=self.gui_email_user.get_text() 
        temp_email_pass=self.gui_email_pass.get_text()
        temp_email_server=self.gui_email_server.get_text()
        temp_email_port=self.gui_email_port.get_text()
        ##FIXME:  No alternate Driver Support implemented yet
        ##temp_acerhkgui_driver_type=self.gui_acerhkgui_driver_type.get_text() #NOTE: Not implemented in GUI
        
        # Test the driver path in case entered by other means besides browsing to location and verify driver exists.
        new_acerhk_driver_found = check_system(self, str(temp_acerhk_path))
        if new_acerhk_driver_found == False:
            message = "The acerhk driver was not found at:\n  %s.\n\nThe GUI will not function!\n\nTroubleshooting Tip:  Use 'sudo locate wirelessled' to find driver path\n and borwse to path." % (temp_acerhk_path)
            error_messageDriver(self, message)
            acerhk_info = "Error: Driver Not Found \n\nPlease set path to driver on the 'Driver Path' tab.\n\nIf not know, run the following code in terminal::\n  sudo locate wirelessled\n\nYou should now know where it is on your system, but if not found,\ntry rerunning it again after executin this code::\n  sudo updatedb. \nAlternately, you may need to run code::\n  sudo modprobe acerhk\nand then re-run acerhkgui."
        else:
            #Update acerhk_info variable
            acerhk_info = get_acerhk_driver_info(self)

        #Update config_dict with temp values from preferences dialog
        config_dict['acerhk_path'] = temp_acerhk_path
        config_dict['email_system'] = temp_email_system
        config_dict['email_user'] = temp_email_user
        config_dict['email_pass'] = temp_email_pass
        config_dict['email_server'] = temp_email_server
        config_dict['email_port'] = temp_email_port
        ##FIXME:  No alternate Driver Support implemented yet.
        ##Value preset when first run.
        ##FIXME: No GUI interface presently
        config_dict['temp_acerhkgui_driver_type'] = temp_acerhkgui_driver_type 
        
        #Save config file
        save_prefs(self, config_dict)
        #Reload Prefs from file -- not really needed because updated global variables with temp variables above
        load_prefs()
        return
    
    def select_path(self):
        print "***********************************************************"
        print "Select Path"
        global acerhk_path
        path_name = acerhk_path
        chooser = gtk.FileChooserDialog("Select Path to 'acerhk' driver.",
                        self.acerhkprefs,
                        gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, 
                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        chooser.set_size_request(600, 350)
        response = chooser.run()

        if response == gtk.RESPONSE_OK: 
            path_name = chooser.get_filename()
            path_name = str(path_name)
            self.gui_acerhk_path.set_text(path_name)
            print "Selected Driver Path:  " + path_name
            print "***********************************************************"
        elif response == gtk.RESPONSE_CANCEL:
            print
            print "***********************************************************"
            print "No File Selected -- File Selection Cancelled"
            print "***********************************************************"
            print

        new_acerhk_driver_found = check_system(self, str(path_name))
        
        if new_acerhk_driver_found == False:
            message = "The acerhk driver was not found at:\n  %s.\n\nThe GUI will not function!\n\nTroubleshooting Tip:  Use 'sudo locate wirelessled' to find driver path\n and borwse to path." % (path_name)
            error_messageDriver(self, message)

        chooser.destroy()
        return path_name
        
    # Callback functions from events:
    
    def on_openfilebutton_clicked(self, variable):
        
        global temp_acerhk_path
        temp_acerhk_path = self.select_path()
    
    def on_pref_apply_clicked(self, void):
        print "Apply Clicked on Preferences Dialog."

        self.apply_prefs()
        self.acerhkprefs.destroy()
    
    def gtk_widget_destroy(self, void):
        self.acerhkprefs.destroy()
        
    # Destroy AcerHK when window is closed by Window Controls
    def on_acerhkprefs_destroy(self, widget, data=None):
        message = 'Destroy Preferences Box'
        print_message(self, message) 
        self.acerhkprefs.destroy()
    
    def __init__(self):
        print 'The Preference Dialog should launch -- beginning of init'

        # CLASS VARIABLES    *********************************
        global acerhk_info
        global name_prefs_gladefile
        
        global acerhk_path
        global email_system
        global email_user
        global email_pass
        global email_server
        global email_port
        global acerhkgui_driver_type

        global temp_acerhk_path
        global temp_email_system
        global temp_email_user
        global temp_email_pass
        global temp_email_server
        global temp_email_port
        global temp_acerhkgui_driver_type
        
        #Assign Global Variable to temp_ variable for use until changes Applied    
        temp_acerhk_path = acerhk_path
        temp_email_system = email_system
        temp_email_user = email_user
        temp_email_pass = email_pass
        temp_email_server = email_server
        temp_email_port = email_port
        temp_acerhkgui_driver_type = acerhkgui_driver_type

        what_not_work = "Presently, the 'New Mail Notifier' does not work.\n\nWhile the tab is functional in that you see data and\ncan input data, it has no effect on\nthe program or your commputer mail led."
        error_messageDriver(self, what_not_work)

        # Prepare GUI Launch     *****************************
        widget_list = [
            'acerhkprefs'
            ]

        handlers = [
            'on_acerhkprefs_destroy',
            'on_pref_apply_clicked',
            'on_openfilebutton_clicked',
            'gtk_widget_destroy'
            ]
            
        prefs_window = 'acerhkprefs'
        wTree = gtk.glade.XML(name_prefs_gladefile, prefs_window, 'AcerHK GUI Preferences')

        dic = {}
        for h in handlers:
            dic[h] = eval("self.%s" % h)
        
        wTree.signal_autoconnect(dic)

        # get the widgets which will be referenced in callbacks        
        for w in widget_list:
            setattr(self, w, wTree.get_widget(w))

        '''self.wTree = gtk.glade.XML(gladeFile)
        self.entryForText = self.wTree.get_widget("name_of_text_widget_in_glade_file")

        To put text into the glade file you need to get the buffer then use 
        set_text(). You can do it all in one command like this:
        self.entryForText.get_buffer().set_text("blah")'''

        self.acerhkInfo = wTree.get_widget("acerhkInfo")
        self.gui_acerhk_path = wTree.get_widget("gui_acerhk_path")
        self.gui_email_system = wTree.get_widget("gui_email_system")
        self.gui_email_user = wTree.get_widget("gui_email_user")
        self.gui_email_pass = wTree.get_widget("gui_email_pass")
        self.gui_email_server = wTree.get_widget("gui_email_server")
        self.gui_email_port = wTree.get_widget("gui_email_port")
        
        # set values for display in gui
        self.acerhkInfo.get_buffer().set_text(acerhk_info)
        self.gui_acerhk_path.set_text(temp_acerhk_path)
        ##NOTE:
        #Current List: 0=POP3 and 1=GMail
        self.gui_email_system.set_active(int(temp_email_system)) #NOTE: This is COMBO Box
        self.gui_email_user.set_text(temp_email_user)
        self.gui_email_pass.set_text(temp_email_pass)
        self.gui_email_server.set_text(temp_email_server)
        self.gui_email_port.set_text(temp_email_port)
        
        # Show the GUI
        self.acerhkprefs.show()

# Main Class    **************************************
class AcerhkguiApp(object):
    
    # DEFINED FUNCTIONS **********************************
    # General Functions:
        
    # Callbacks from events:
    def bpressedOn(self, event):
        '''Send Signal to AcerHK Driver to Turn Bluetooth On.'''
        acerhk_do(bluetooth, "on")

    def bpressedOff(self, event): 
        '''Send Signal to AcerHK Driver to Turn Bluetooth Off.'''
        acerhk_do(bluetooth, "off")

    def wpressedOn(self, event):
        '''Send Signal to AcerHK Driver to Turn Wireless On.'''
        acerhk_do(wireless, "on")

    def wpressedOff(self, event):
        '''Send Signal to AcerHK Driver to Turn Wireless Off.'''
        acerhk_do(wireless, "off")
        
    def on_preferences_clicked(self, event):
        '''Initiate the Preferences Dialog.'''
        print '** Preferences Dialog Started: GUI required to view. **'
        prefs_dialog = AcerhkguiPref()

    def pressedAbout(self, menuitem, data=None):
        '''Launch Dialogue Box with About Information.'''
        if self.about_dialog: 
            self.about_dialog.present()
            return
        
        authors = [
        "Arick R. McNiel <arickmcniel at yahoo dot com>"
        ]

        about_dialog = gtk.AboutDialog()
        about_dialog.set_transient_for(self.window1)
        about_dialog.set_destroy_with_parent(True)
        about_dialog.set_name("Acerhkgui")
        about_dialog.set_version("0.6")
        about_dialog.set_copyright("Copyright \xc2\xa9 2009 Arick McNiel")
        about_dialog.set_website("https://sourceforge.net/projects/acerhkgui")
        about_dialog.set_comments('A GUI frontend for acerhk.\n\nThis program was written to simplify the use of the AcerHK\ndriver.  I wrote it as my first project and to meet a need to be \nable to turn on/off my Wireless/Bluetooth Radios.\n\nIt enables turning on and off the BT Device from a GUI\ninterface.  I hope that it benefits many people.\n\nIf it does not work for you, check out the following links:\nhttp://rfswitch.sourceforge.net/?page=laptop_matrix\nhttp://sourceforge.net/projects/acerhk/\n\n*********\n\nRun from command line for \nCLI feedback and troubleshooting.\n')
        about_dialog.set_authors            (authors)
        about_dialog.set_logo_icon_name     (gtk.STOCK_ABOUT)
        
        # callbacks for destroying the 'about' dialog
        def close(dialog, response, editor):
            editor.about_dialog = None
            dialog.destroy()
            
        def delete_event(dialog, event, editor):
            editor.about_dialog = None
            return True
                    
        about_dialog.connect("response", close, self)
        about_dialog.connect("delete-event", delete_event, self)
        
        self.about_dialog = about_dialog
        about_dialog.show()

    # Termination Functions:
           
    # Exit AcerHK Applet on press of "OK" (This is new)
    def pressedOk(self, event): # wxGlade: MyFrame1.<event_handler>
        print '----------------------------------------------------'
        print "Thanks for using AcerHK GUI (acerhkgui).  I hope it was helpful!"
        print '===================================================='
        exit()

    # Destroy AcerHK when window is closed by Window Controls
    def on_window1_destroy(self, widget, data=None):
        message = 'Thanks for using AcerHK GUI (acerhkgui).\nI hope it was helpful!.'
        print_message(self, message)
        gtk.main_quit()
        
    # MAIN Program    ************************************
    def __init__(self, void):
        
        # Default Values
        self.filename = None
        self.about_dialog = None
        global acerhk_info
        
        # Pre-GUI Launch Code    *****************************

        '''Prints information to terminal and checks the system for the
        required drivers.  Returns GUI Error Message if driver not found.
        Gets information from the acerhk driver, stores in variable and 
        prints to screen.'''
        
        # Print program information on the screen.
        print_prog_info()   
        
        # Check for configuration file.
        config_exists(self)
        
        # Check the system for driver information and update driver found flag
        # First check and see if driver is at path, if not, execute modprobe
        check_system_modprobe(self, acerhk_path)
        # Check to see if driver already loaded and/or if modprobe was successful and set flag
        acerhk_driver_found = (check_system(self, acerhk_path))
        
        if acerhk_driver_found == False:
            message = "The acerhk driver was not found at:\n  %s.\n\nThe GUI will not function!\n\nTroubleshooting Tip:  Use 'sudo locate wirelessled' to find driver path and borwse to path." % (acerhk_path)
            error_messageDriver(self, message)
            acerhk_info = "Error: Driver Not Found \n\nPlease set path to driver on the 'Driver Path' tab.\n\nIf not know, run the following code in terminal::\n  sudo locate wirelessled\n\nYou should now know where it is on your system, but if not found,\ntry rerunning it again after executin this code::\n  sudo updatedb. \nAlternately, you may need to run code::\n  sudo modprobe acerhk\nand then re-run acerhkgui."
        else:
            acerhk_info = get_acerhk_driver_info(self)
      
        #=====================================================
        # Prepare GUI Launch     *****************************
        #-----------------------------------------------------  
        widget_list = [
            'window1'
            ]

        handlers = [
            'bpressedOn',
            'bpressedOff',
            'wpressedOn',
            'wpressedOff',
            'pressedAbout',
            'pressedOk',
            'on_preferences_clicked',
            'on_window1_destroy'
            ]
            
        top_window = 'window1'
        wTree = gtk.glade.XML(name_gladefile, top_window, 'AcerHK GUI')

        dic = {}
        for h in handlers:
            dic[h] = eval("self.%s" % h)
        
        wTree.signal_autoconnect(dic)

        # get the widgets which will be referenced in callbacks        
        for w in widget_list:
            setattr(self, w, wTree.get_widget(w))

        self.window1.show()

# Main Loop:::     ***********************************

if __name__ == "__main__":
    control = AcerhkguiApp(0)
    gtk.main()
