diff --git a/daemon.py b/daemon.py index 80c5fdd..d3d9b4c 100644 --- a/daemon.py +++ b/daemon.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ wicd - wireless connection daemon implementation. This module implements the wicd daemon that provides network @@ -94,7 +93,7 @@ class LogWriter: """ global logging_enabled - data = data.encode('utf-8') + data = data.decode('utf-8').encode('utf-8') if len(data) <= 0: return if logging_enabled: if self.eol: @@ -158,7 +157,7 @@ class ConnectionWizard(dbus.service.Object): # Scan since we just got started if auto_connect: print "autoconnecting...",str(self.GetWirelessInterface()[5:]) - print self.AutoConnect(True) + self.AutoConnect(True) else: print "--no-scan detected, not autoconnecting..." @@ -180,7 +179,6 @@ class ConnectionWizard(dbus.service.Object): version = '1.4.0' print 'returned version number',version return version - #end function Hello @dbus.service.method('org.wicd.daemon') def SetWiredInterface(self,interface): @@ -192,7 +190,6 @@ class ConnectionWizard(dbus.service.Object): config.read(self.app_conf) config.set("Settings","wired_interface",interface) config.write(open(self.app_conf,"w")) - #end function SetWiredInterface @dbus.service.method('org.wicd.daemon') def SetWirelessInterface(self,interface): @@ -205,7 +202,6 @@ class ConnectionWizard(dbus.service.Object): config.set("Settings","wireless_interface",interface) configfile = open(self.app_conf,"w") config.write(configfile) - #end function SetWirelessInterface @dbus.service.method('org.wicd.daemon') def SetWPADriver(self,driver): @@ -266,21 +262,18 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon') def GetWPADriver(self): ''' Returns the wpa driver the daemon is using ''' - print 'returned wpa driver' return str(self.wifi.wpa_driver) #end function GetWPADriver @dbus.service.method('org.wicd.daemon') def GetWiredInterface(self): ''' Returns the wired interface ''' - print 'returning wired interface' return str(self.wired.wired_interface) #end function GetWiredInterface @dbus.service.method('org.wicd.daemon') def GetWirelessInterface(self): ''' Returns the wireless interface the daemon is using ''' - print 'returning wireless interface to client' return str(self.wifi.wireless_interface) #end function GetWirelessInterface @@ -356,9 +349,9 @@ class ConnectionWizard(dbus.service.Object): if self.GetWirelessInterface() != None: for x, network in enumerate(self.LastScan): if bool(self.LastScan[x]["has_profile"]): - print str(self.LastScan[x]["essid"]) + ' has profile' + print self.LastScan[x]["essid"] + ' has profile' if bool(self.LastScan[x].get('automatic')): - print 'trying to automatically connect to...',str(self.LastScan[x]["essid"]) + print 'trying to automatically connect to...',self.LastScan[x]["essid"] self.ConnectWireless(x) time.sleep(1) return @@ -428,7 +421,7 @@ class ConnectionWizard(dbus.service.Object): for i, network in enumerate(scan): self.ReadWirelessNetworkProfile(i) - # This is unfinished so not on dbus yet + # This is unfinished so not on dbus yet def AutoConnectScan(self): ''' Scan for networks and for known hidden networks @@ -528,8 +521,9 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetWirelessProperty(self,networkid,property): - '''retrieves wireless property from the network specified''' + ''' Retrieves wireless property from the network specified ''' value = self.LastScan[networkid].get(property) + if self.debug_mode == 1: print 'returned wireless network',networkid,'property',property,'of value',value try: value = value.encode('utf-8') @@ -540,7 +534,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def SetWirelessProperty(self,networkid,property,value): - '''sets property to value in network specified''' + ''' Sets property to value in network specified ''' #simple - set the value of the item in our current data #to the value the client asked for print 'setting wireless network',networkid,'property',property,'to value',value @@ -549,7 +543,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def DetectWirelessInterface(self): - '''returns an automatically detected wireless interface''' + ''' Returns an automatically detected wireless interface ''' iface = self.wifi.DetectWirelessInterface() print 'automatically detected wireless interface',iface return str(iface) @@ -557,7 +551,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentSignalStrength(self): - '''returns the current signal strength''' + ''' Returns the current signal strength ''' try: strength = int(self.wifi.GetSignalStrength()) except: @@ -567,7 +561,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentDBMStrength(self): - ''' returns the current dbm signal strength ''' + ''' Returns the current dbm signal strength ''' try: dbm_strength = int(self.wifi.GetDBMStrength()) except: @@ -576,7 +570,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentNetwork(self): - '''returns the current network''' + ''' Returns the current network ''' current_network = str(self.wifi.GetCurrentNetwork()) print current_network return current_network @@ -588,7 +582,6 @@ class ConnectionWizard(dbus.service.Object): currentESSID = self.GetCurrentNetwork() for x in xrange(0,len(self.LastScan)): if self.LastScan[x]['essid'] == currentESSID: - print 'current network found, id is ',x return x print 'returning -1, current network not found' return -1 @@ -610,7 +603,7 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetForcedDisconnect(self): - '''returns whether wireless was dropped by user, or for some other reason''' + ''' Returns whether wireless was dropped by user, or for some other reason ''' return self.forced_disconnect #end function GetForcedDisconnect @@ -633,6 +626,7 @@ class ConnectionWizard(dbus.service.Object): # If connecting_thread exists, then check for it's # status, if it doesn't, we aren't connecting. status = self.wifi.connecting_thread.is_connecting + if self.debug_mode == 1: print 'wireless connecting',status return status else: @@ -642,27 +636,26 @@ class ConnectionWizard(dbus.service.Object): @dbus.service.method('org.wicd.daemon.wireless') def GetWirelessIP(self): - '''returns the IP that the wireless interface has''' + ''' Returns the IP that the wireless interface has ''' ip = self.wifi.GetIP() + if self.debug_mode == 1: print 'returning wireless ip',ip return ip #end function GetWirelessIP @dbus.service.method('org.wicd.daemon.wireless') def CheckWirelessConnectingMessage(self): - '''returns the wireless interface's status message''' + ''' Returns the wireless interface's status message ''' if not self.wifi.connecting_thread == None: stat = self.wifi.connecting_thread.GetStatus() - print 'wireless connect status',stat return stat else: - print 'wireless connect status',False return False #end function CheckWirelessConnectingMessage @dbus.service.method('org.wicd.daemon.wireless') def CancelConnect(self): - '''cancels the wireless connection attempt''' + ''' Cancels the wireless connection attempt ''' print 'canceling connection attempt' if not self.wifi.connecting_thread == None: self.wifi.connecting_thread.ShouldDie = True @@ -676,6 +669,7 @@ class ConnectionWizard(dbus.service.Object): def GetWiredIP(self): '''returns the wired interface\'s ip address''' ip = self.wired.GetIP() + if self.debug_mode == 1: print 'returning wired ip',ip return ip #end function GetWiredIP @@ -687,9 +681,11 @@ class ConnectionWizard(dbus.service.Object): #if connecting_thread exists, then check for it's #status, if it doesn't exist, we aren't connecting status = self.wired.connecting_thread.is_connecting + if self.debug_mode == 1: print 'wired connecting',status return status else: + if self.debug_mode == 1: print 'wired connecting',False return False #end function CheckIfWiredConnecting @@ -745,10 +741,8 @@ class ConnectionWizard(dbus.service.Object): '''returns the wired interface\'s status message''' if not self.wired.connecting_thread == None: status = self.wired.connecting_thread.GetStatus() - print 'wired connect status',status return status else: - print 'wired connect status',False return False #end function CheckWiredConnectingMessage @@ -756,6 +750,7 @@ class ConnectionWizard(dbus.service.Object): def SetWiredProperty(self,property,value): if self.WiredNetwork: self.WiredNetwork[property] = misc.Noneify(value) + if self.debug_mode == 1: print 'set',property,'to',misc.Noneify(value) return True else: @@ -767,6 +762,7 @@ class ConnectionWizard(dbus.service.Object): def GetWiredProperty(self,property): if self.WiredNetwork: value = self.WiredNetwork.get(property) + if self.debug_mode == 1: print 'returned',property,'with value of',value,'to client...' return value else: @@ -1041,7 +1037,8 @@ class ConnectionWizard(dbus.service.Object): def __printReturn(self,text,value): '''prints the specified text followed by the specified value, then returns value''' - print text,value + if self.debug_mode == 1: + print text,value return value #end function __printReturn diff --git a/gui.py b/gui.py index efe98b1..43d750f 100644 --- a/gui.py +++ b/gui.py @@ -1,4 +1,22 @@ #!/usr/bin/python + +# +# Copyright (C) 2007 Adam Blackburn +# Copyright (C) 2007 Dan O'Reilly +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License Version 2 as +# published by the Free Software Foundation. +# +# 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, see . +# + import os import sys import wpath @@ -99,7 +117,11 @@ language['use_static_dns'] = _('Use Static DNS') language['use_encryption'] = _('Use Encryption') language['advanced_settings'] = _('Advanced Settings') language['wired_network'] = _('Wired Network') -language['wired_network_instructions'] = _('To connect to a wired network, you must create a network profile. To create a network profile, type a name that describes this network, and press Add.') +language['wired_network_instructions'] = _('To connect to a wired network, you \ + must create a network profile. To \ + create a network profile, type a \ + name that describes this network, \ + and press Add.') language['automatic_connect'] = _('Automatically connect to this network') language['secured'] = _('Secured') language['unsecured'] = _('Unsecured') @@ -445,8 +467,6 @@ class NetworkEntry(gtk.Expander): #start with all disabled, then they will be enabled later self.checkboxStaticIP.set_active(False) self.checkboxStaticDNS.set_active(False) - print 'using global dns:',daemon.GetUseGlobalDNS() - #self.checkboxGlobalDNS.set_active(bool(int(daemon.GetUseGlobalDNS()))) def setDefaults(self,widget=None,event=None): #after the user types in the IP address, @@ -469,19 +489,15 @@ class NetworkEntry(gtk.Expander): self.checkboxStaticIP.set_active(True) self.checkboxStaticDNS.set_active(True) self.checkboxStaticDNS.set_sensitive(False) - print 'enabling ip' else: self.checkboxStaticIP.set_active(False) self.checkboxStaticDNS.set_active(False) self.checkboxStaticDNS.set_sensitive(True) - print 'disabling ip' if not stringToNone(self.txtDNS1.get_text()) == None: self.checkboxStaticDNS.set_active(True) - print 'enabling dns' else: self.checkboxStaticDNS.set_active(False) - print 'disabling dns' #blankify stuff! #this will properly disable @@ -507,15 +523,15 @@ class NetworkEntry(gtk.Expander): self.txtGateway.set_sensitive(self.checkboxStaticIP.get_active()) def toggleDNSCheckbox(self,widget=None): - print 'dns checkbox toggled',self.checkboxStaticDNS.get_active() - #should disable the static DNS boxes + # Should disable the static DNS boxes if self.checkboxStaticIP.get_active() == True: self.checkboxStaticDNS.set_active(self.checkboxStaticIP.get_active()) self.checkboxStaticDNS.set_sensitive(False) self.checkboxGlobalDNS.set_sensitive(self.checkboxStaticDNS.get_active()) if self.checkboxStaticDNS.get_active() == True: - self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) #if global dns is on, don't use local dns + # If global dns is on, don't use local dns + self.txtDNS1.set_sensitive(not self.checkboxGlobalDNS.get_active()) self.txtDNS2.set_sensitive(not self.checkboxGlobalDNS.get_active()) self.txtDNS3.set_sensitive(not self.checkboxGlobalDNS.get_active()) else: @@ -640,8 +656,8 @@ class WiredNetworkEntry(NetworkEntry): config.SaveWiredNetworkProfile(self.comboProfileNames.get_active_text()) def changeProfile(self,widget): - if self.comboProfileNames.get_active() > -1: #this way the name doesn't change - # #everytime someone types something in + # Make sure the name doesn't change everytime someone types something + if self.comboProfileNames.get_active() > -1: if self.isFullGUI == False: return print "changing profile..." @@ -675,7 +691,6 @@ class WirelessNetworkEntry(NetworkEntry): print "ESSID : " + wireless.GetWirelessProperty(networkID,"essid") self.set_label(wireless.GetWirelessProperty(networkID,"essid")) self.essid = wireless.GetWirelessProperty(networkID,"essid") - print "making a new network entry..." #make the vbox to hold the encryption stuff self.vboxEncryptionInformation = gtk.VBox(False,0) @@ -689,8 +704,7 @@ class WirelessNetworkEntry(NetworkEntry): self.lblMode = GreyLabel() self.hboxStatus = gtk.HBox(False,5) self.checkboxAutoConnect = gtk.CheckButton(language['automatic_connect']) - self.checkboxAutoConnect.connect("toggled",self.updateAutoConnect) #so that the autoconnect box is - #toggled + self.checkboxAutoConnect.connect("toggled",self.updateAutoConnect) self.hboxStatus.pack_start(self.lblStrength,fill=False,expand=True) self.hboxStatus.pack_start(self.lblEncryption,fill=False,expand=True) @@ -759,7 +773,8 @@ class WirelessNetworkEntry(NetworkEntry): self.show_all() def updateAutoConnect(self,widget): - wireless.SetWirelessProperty(self.networkID,"automatic",self.checkboxAutoConnect.get_active()) + wireless.SetWirelessProperty(self.networkID,"automatic", + self.checkboxAutoConnect.get_active()) config.SaveWirelessNetworkProperty(self.networkID,"automatic") def toggleEncryption(self,widget=None): @@ -778,7 +793,6 @@ class WirelessNetworkEntry(NetworkEntry): self.comboEncryption.set_active(0) ID == 0 for x in methods[ID][2]: - print x box = None if language.has_key(methods[ID][2][x][0]): box = LabelEntry(language[methods[ID][2][x][0].lower().replace(' ','_')]) @@ -1143,8 +1157,6 @@ class appGui: def update_statusbar(self): #should update the status bar #every couple hundred milliseconds - if not daemon.GetDebugMode(): - config.DisableLogging() #stop log file spam wireless_ip = wireless.GetWirelessIP() #do this so that it doesn't lock up. don't know how or why this works #but it does so we leave it alone :) wiredConnecting = wired.CheckIfWiredConnecting() @@ -1181,19 +1193,13 @@ class appGui: ('$A',network).replace ('$B',daemon.FormatSignalForPrinting(strength)).replace ('$C',wireless_ip)) - if not daemon.GetDebugMode(): - config.EnableLogging() return True wired_ip = wired.GetWiredIP() if wired_ip: if wired.CheckPluggedIn(): self.statusID = self.status_bar.push(1,language['connected_to_wired'].replace('$A',wired_ip)) - if not daemon.GetDebugMode(): - config.EnableLogging() return True self.statusID = self.status_bar.push(1,language['not_connected']) - if not daemon.GetDebugMode(): - config.EnableLogging() return True def refresh_networks(self,widget=None,fresh=True,hidden=None): @@ -1215,12 +1221,12 @@ class appGui: wireless.SetHiddenNetworkESSID(noneToString(hidden)) wireless.Scan() - print wireless.GetNumberOfNetworks() + num_networks = wireless.GetNumberOfNetworks() instructLabel = self.wTree.get_widget("label_instructions") - if wireless.GetNumberOfNetworks() > 0: + if num_networks > 0: instructLabel.show() - for x in range(0,wireless.GetNumberOfNetworks()): + for x in range(0,num_networks): if printLine: sep = gtk.HSeparator() self.network_list.pack_start(sep,padding=10,expand=False,fill=False) diff --git a/misc.py b/misc.py index 1074c29..d3f5e91 100644 --- a/misc.py +++ b/misc.py @@ -55,7 +55,7 @@ def RunRegex(regex, string): return None def log(text): - log = self.LogWriter() + log = LogWriter() log.write(text + "\n") def WriteLine(my_file, text): @@ -215,6 +215,19 @@ def get_gettext(): _ = lang.gettext return _ + +def to_unicode(x): + try: # This may never fail, but let's be safe + default_encoding = locale.getpreferredencoding() + except: + default_encoding = None + if default_encoding: + return x.decode(default_encoding).encode('utf-8') + else: + return x.decode('utf-8').encode('utf-8') + + + class LogWriter(): """ A class to provide timestamped logging. """ def __init__(self): @@ -260,7 +273,7 @@ class LogWriter(): self.file.write( data.replace('\n', '\n' + self.get_time() + ' :: ')) if self.eol: self.file.write('\n') - self.file.flush() + self.file.close() def get_time(self): @@ -273,4 +286,4 @@ class LogWriter(): return ''.join([ str(x[0]).rjust(4,'0'), '/', str(x[1]).rjust(2,'0'), '/', str(x[2]).rjust(2,'0'), ' ', str(x[3]).rjust(2,'0'), ':', - str(x[4]).rjust(2,'0'), ':', str(x[5]).rjust(2,'0')]) \ No newline at end of file + str(x[4]).rjust(2,'0'), ':', str(x[5]).rjust(2,'0')]) diff --git a/networking.py b/networking.py index e40e689..0655285 100644 --- a/networking.py +++ b/networking.py @@ -150,7 +150,6 @@ class Wireless(Controller): self.wpa_driver = None - def Scan(self, essid=None): """ Scan for available wireless networks. @@ -208,6 +207,7 @@ class Wireless(Controller): self.wpa_driver) return wiface.GetSignalStrength() + def GetDBMStrength(self): """ Get the dBm signal strength of the current network. @@ -476,7 +476,7 @@ class WirelessConnectThread(ConnectThread): self.network.SetWiredProperty("lastused", True) config.SaveWiredNetworkProfile(self.profilename) - #execute post-connection script if necessary + # Execute post-connection script if necessary if misc.Noneify(self.after_script): print 'Executing post-connection script' misc.ExecuteScript(self.after_script) @@ -655,7 +655,7 @@ class WiredConnectThread(ConnectThread): wnettools.SetDNS(self.network.get('dns1'), self.network.get('dns2'), self.network.get('dns3')) - #execute post-connection script if necessary + # Execute post-connection script if necessary if misc.Noneify(self.after_script): print 'executing post connection script' misc.ExecuteScript(self.after_script) diff --git a/wicd.py b/wicd.py index f3e52a9..6def663 100755 --- a/wicd.py +++ b/wicd.py @@ -105,6 +105,7 @@ class TrayIcon(): self.tr = self.EdgyTrayIconGUI(use_tray) self.icon_info = self.TrayConnectionInfo(self.tr) + class TrayConnectionInfo(): ''' class for updating the tray icon status ''' def __init__(self, tr): @@ -140,11 +141,13 @@ class TrayIcon(): return True return False + def check_for_wireless_connection(self, wireless_ip): ''' Checks for an active wireless connection - Checks for and updates the tray icon for an active wireless connection - Returns True if wireless connection is active, False otherwise. + Checks for and updates the tray icon for an active + wireless connection. Returns True if wireless connection + is active, and False otherwise. ''' if wireless.GetWirelessIP() is None: @@ -153,16 +156,17 @@ class TrayIcon(): # Reset this, just in case self.tried_reconnect = False - # Try getting signal strength, default to 0 if something goes wrong. + # Try getting signal strength, and default to 0 + # if something goes wrong. try: if daemon.GetSignalDisplayType() == 0: - wireless_signal = int(wireless.GetCurrentSignalStrength()) + wifi_signal = int(wireless.GetCurrentSignalStrength()) else: - wireless_signal = int(wireless.GetCurrentDBMStrength()) + wifi_signal = int(wireless.GetCurrentDBMStrength()) except: - wireless_signal = 0 + wifi_signal = 0 - if wireless_signal == 0: + if wifi_signal == 0: # If we have no signal, increment connection loss counter. # If we haven't gotten any signal 4 runs in a row (12 seconds), # try to reconnect. @@ -175,11 +179,11 @@ class TrayIcon(): # Only update if the signal strength has changed because doing I/O # calls is expensive, and the icon flickers - if (wireless_signal != self.last_strength or + if (wifi_signal != self.last_strength or self.network != wireless.GetCurrentNetwork()): - self.last_strength = wireless_signal - # Set the string to '' so that when it is put in "high-signal" + - # lock + ".png", there will be nothing + self.last_strength = wifi_signal + # Set the string to '' so that when it is put in + # "high-signal" + lock + ".png", there will be nothing lock = '' # cur_net_id needs to be checked because a negative value @@ -194,21 +198,18 @@ class TrayIcon(): # Update the tooltip and icon picture self.network = str(wireless.GetCurrentNetwork()) daemon.SetCurrentInterface(daemon.GetWirelessInterface()) - str_signal = daemon.FormatSignalForPrinting(str(wireless_signal)) + str_signal = daemon.FormatSignalForPrinting(str(wifi_signal)) self.tr.set_tooltip(language['connected_to_wireless'] .replace('$A', self.network) .replace('$B', str_signal) .replace('$C', str(wireless_ip))) - self.set_signal_image(wireless_signal, lock) + self.set_signal_image(wifi_signal, lock) return True + def update_tray_icon(self): ''' Updates the tray icon and current connection status ''' - # Disable logging if debugging isn't on to prevent log spam - if not daemon.GetDebugMode(): - config.DisableLogging() - # First check for an active wired network, then for an # active wireless network. If neither is found, change # icon to reflect that and run auto_reconnect() @@ -216,8 +217,8 @@ class TrayIcon(): wired_found = self.check_for_wired_connection(wired_ip) if not wired_found: self.still_wired = False # We're not wired any more - wireless_ip = wireless.GetWirelessIP() - wireless_found = self.check_for_wireless_connection(wireless_ip) + wifi_ip = wireless.GetWirelessIP() + wireless_found = self.check_for_wireless_connection(wifi_ip) if not wireless_found: # No connection at all self.tr.set_from_file("images/no-signal.png") if daemon.CheckIfConnecting(): @@ -233,39 +234,43 @@ class TrayIcon(): return True + def set_signal_image(self, wireless_signal, lock): - ''' Sets the tray icon picture for an active wireless connection ''' + ''' Sets the tray icon image for an active wireless connection ''' if wireless_signal == 0: # We handle a signal of 0 the same regardless of dBm or % # signal strength. Set the image based on connection loss # counter, and then return so the counter isn't reset. if self.connection_lost_counter < 4: - self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + img_file = (wpath.images + "bad-signal" + lock + ".png") else: - self.tr.set_from_file(wpath.images + "no-signal.png") + img_file = (wpath.images + "no-signal.png") + self.tr.set_from_file(img_file) return elif daemon.GetSignalDisplayType() == 0: if wireless_signal > 75: - self.tr.set_from_file(wpath.images + "high-signal" + lock + ".png") + img_file = (wpath.images + "high-signal" + lock + ".png") elif wireless_signal > 50: - self.tr.set_from_file(wpath.images + "good-signal" + lock + ".png") + img_file = (wpath.images + "good-signal" + lock + ".png") elif wireless_signal > 25: - self.tr.set_from_file(wpath.images + "low-signal" + lock + ".png") + img_file = (wpath.images + "low-signal" + lock + ".png") elif wireless_signal > 0: - self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + img_file = (wpath.images + "bad-signal" + lock + ".png") else: if wireless_signal >= -60: - self.tr.set_from_file(wpath.images + "high-signal" + lock + ".png") + img_file = (wpath.images + "high-signal" + lock + ".png") elif wireless_signal >= -70: - self.tr.set_from_file(wpath.images + "good-signal" + lock + ".png") + img_file = (wpath.images + "good-signal" + lock + ".png") elif wireless_signal >= -80: - self.tr.set_from_file(wpath.images + "low-signal" + lock + ".png") + img_file = (wpath.images + "low-signal" + lock + ".png") else: - self.tr.set_from_file(wpath.images + "bad-signal" + lock + ".png") + img_file = (wpath.images + "bad-signal" + lock + ".png") # Since we have a signal, we should reset # the connection loss counter. + self.tr.set_from_file(img_file) self.connection_lost_counter = 0 + def auto_reconnect(self): ''' Automatically reconnects to a network if needed @@ -274,7 +279,8 @@ class TrayIcon(): should that fail will simply run AutoConnect() ''' - if wireless.GetAutoReconnect() and not daemon.CheckIfConnecting() and \ + if wireless.GetAutoReconnect() and \ + not daemon.CheckIfConnecting() and \ not wireless.GetForcedDisconnect(): print 'Starting automatic reconnect process' # First try connecting through ethernet @@ -287,7 +293,8 @@ class TrayIcon(): cur_net_id = wireless.GetCurrentNetworkID() if cur_net_id > -1: # Needs to be a valid network if not self.tried_reconnect: - print 'Trying to reconnect to last used wireless network' + print 'Trying to reconnect to last used wireless \ + network' wireless.ConnectWireless(cur_net_id) self.tried_reconnect = True elif wireless.CheckIfWirelessConnecting() == False: @@ -296,7 +303,8 @@ class TrayIcon(): daemon.AutoConnect(True) else: daemon.AutoConnect(True) - + + class TrayIconGUI(): def __init__(self): menu = ''' @@ -328,18 +336,22 @@ class TrayIcon(): self.menu = self.manager.get_widget('/Menubar/Menu/About').props.parent self.gui_win = None + def on_activate(self, data=None): ''' Opens the wicd GUI ''' self.toggle_wicd_gui() + def on_quit(self, widget=None): ''' Closes the tray icon ''' sys.exit(0) + def on_preferences(self, data=None): ''' Opens the wicd GUI ''' self.toggle_wicd_gui() + def on_about(self, data = None): ''' Opens the About Dialog ''' dialog = gtk.AboutDialog() @@ -350,6 +362,7 @@ class TrayIcon(): dialog.run() dialog.destroy() + def set_from_file(self, path = None): ''' Sets a new tray icon picture ''' if not self.use_tray: return @@ -357,6 +370,7 @@ class TrayIcon(): self.current_icon_path = path gtk.StatusIcon.set_from_file(self, path) + def toggle_wicd_gui(self): ''' Toggles the wicd GUI ''' if self.gui_win == None: @@ -389,18 +403,21 @@ class TrayIcon(): self.tray.add(self.eb) self.tray.show_all() + def tray_clicked(self, widget, event): ''' Handles tray mouse click events ''' if event.button == 1: self.open_wicd_gui() if event.button == 3: self.menu.popup(None, None, None, event.button, event.time) - + + def set_from_file(self, str): ''' Calls set_from_file on the gtk.Image for the tray icon ''' if not self.use_tray: return self.pic.set_from_file(str) - + + def set_tooltip(self, str): ''' Sets the tooltip for the gtk.ToolTips associated with this @@ -409,6 +426,7 @@ class TrayIcon(): if not self.use_tray: return self.tooltip.set_tip(self.eb, str) + class EdgyTrayIconGUI(gtk.StatusIcon, TrayIconGUI): ''' Class for creating the wicd tray icon ''' def __init__(self, use_tray=True): @@ -428,10 +446,12 @@ class TrayIcon(): self.set_from_file("images/no-signal.png") self.set_tooltip("Initializing wicd...") + def on_popup_menu(self, status, button, time): ''' Opens the right click menu for the tray icon ''' self.menu.popup(None, None, None, button, time) + def set_from_file(self, path = None): ''' Sets a new tray icon picture ''' if not self.use_tray: return @@ -450,6 +470,7 @@ Arguments: \t-h\t--help\t\tPrint this help. """ + def main(argv): """ The main frontend program. @@ -460,8 +481,7 @@ def main(argv): use_tray = True try: - opts, args = getopt.getopt(sys.argv[1:], 'nh', - ['help', 'no-tray']) + opts, args = getopt.getopt(sys.argv[1:], 'nh', ['help', 'no-tray']) except getopt.GetoptError: # Print help information and exit usage() @@ -475,8 +495,8 @@ def main(argv): use_tray = False # Redirect stderr and stdout for logging purposes - #sys.stderr = log - #sys.stdout = log + sys.stderr = log + sys.stdout = log # Set up the tray icon GUI and backend tray_icon = TrayIcon(use_tray) @@ -498,5 +518,6 @@ def main(argv): mainloop = gobject.MainLoop() mainloop.run() + if __name__ == '__main__': main(sys.argv) diff --git a/wnettools.py b/wnettools.py index f7538bf..e188a7c 100644 --- a/wnettools.py +++ b/wnettools.py @@ -90,7 +90,7 @@ def GetWirelessInterfaces(): class Interface(object): """ Control a network interface. """ - def __init__(self, iface, verbose=True): + def __init__(self, iface, verbose=False): """ Initialise the object. Keyword arguments: @@ -182,7 +182,7 @@ class Interface(object): """ cmd = 'ifconfig ' + self.iface - if self.verbose: print cmd + #if self.verbose: print cmd output = misc.Run(cmd) return misc.RunRegex(ip_pattern,output) @@ -190,7 +190,7 @@ class Interface(object): class WiredInterface(Interface): """ Control a wired network interface. """ - def __init__(self, iface, verbose=True): + def __init__(self, iface, verbose=False): """ Initialise the wired network interface class. Keyword arguments: @@ -217,7 +217,7 @@ class WiredInterface(Interface): class WirelessInterface(Interface): """ Control a wireless network interface. """ - def __init__(self, iface, verbose=True, wpa_driver='wext'): + def __init__(self, iface, verbose=False, wpa_driver='wext'): """ Initialise the wireless network interface class. Keyword arguments: @@ -276,7 +276,9 @@ class WirelessInterface(Interface): # Only use sections where there is an ESSID. if cell.count('ESSID:') > 0: # Add this network to the list of networks - access_points.append(self._ParseAccessPoint(cell, ralink_info)) + entry = self._ParseAccessPoint(cell, ralink_info) + if entry is not None: + access_points.append(entry) return access_points @@ -325,6 +327,7 @@ class WirelessInterface(Interface): lines = lines[2:] return lines + def _ParseAccessPoint(self, cell, ralink_info): """ Parse a single cell from the output of iwlist. @@ -339,11 +342,14 @@ class WirelessInterface(Interface): """ ap = {} - # ESSID - Switch '' to 'Hidden' to remove # brackets that can mix up formatting. ap['essid'] = misc.RunRegex(essid_pattern, cell) - ap['essid'] = ap['essid'].encode('utf-8') + try: + ap['essid'] = misc.to_unicode(ap['essid']) + except UnicodeDecodeError, UnicodeEncodeError: + print 'Unicode problem with current network essid, ignoring!!' + return None if ap['essid'] == '': ap['essid'] = 'Hidden' ap['hidden'] = True @@ -400,6 +406,7 @@ class WirelessInterface(Interface): return ap + def _ParseRalinkAccessPoint(self, ap, ralink_info, cell): """ Parse encryption and signal strength info for ralink cards @@ -579,7 +586,7 @@ class WirelessInterface(Interface): """ cmd = 'iwconfig ' + self.iface - if self.verbose: print cmd + # if self.verbose: print cmd output = misc.Run(cmd) strength = misc.RunRegex(strength_pattern,output) if strength == None: @@ -587,6 +594,7 @@ class WirelessInterface(Interface): return strength + def GetDBMStrength(self): """ Get the dBm signal strength of the current network. @@ -600,6 +608,7 @@ class WirelessInterface(Interface): dbm_strength = misc.RunRegex(signaldbm_pattern,output) return dbm_strength + def GetCurrentNetwork(self): """ Get the essid of the current network.