1
0
mirror of https://github.com/gryf/wicd.git synced 2026-03-14 13:45:51 +01:00

Style changes for python files

This commit is contained in:
2020-08-01 11:25:13 +02:00
parent c401f2963b
commit 40a7a8ac5d
32 changed files with 2775 additions and 2614 deletions

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env python3
""" configscript -- Configure the scripts for a particular network.
"""configscript -- Configure the scripts for a particular network.
Script for configuring the scripts for a network passed in as a
command line argument. This needs to run a separate process because
@@ -8,7 +7,6 @@ editing scripts requires root access, and the GUI/Tray are typically
run as the current user.
"""
#
# Copyright (C) 2007-2009 Adam Blackburn
# Copyright (C) 2007-2009 Dan O'Reilly
@@ -46,7 +44,7 @@ wired_conf = wpath.etc + 'wired-settings.conf'
def none_to_blank(text):
""" Converts special string cases to a blank string.
"""Converts special string cases to a blank string.
If text is None, 'None', or '' then this method will
return '', otherwise it will just return str(text).
@@ -57,47 +55,48 @@ def none_to_blank(text):
else:
return str(text)
def blank_to_none(text):
""" Convert an empty or null string to 'None'. """
"""Convert an empty or null string to 'None'."""
if text in ("", None):
return "None"
else:
return str(text)
def get_script_info(network, network_type):
""" Read script info from disk and load it into the configuration dialog """
"""
Read script info from disk and load it into the configuration dialog
"""
info = {}
if network_type == "wired":
con = ConfigManager(wired_conf)
if con.has_section(network):
info["pre_entry"] = con.get(network, "beforescript", None)
info["post_entry"] = con.get(network, "afterscript", None)
info["pre_disconnect_entry"] = con.get(network,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(network,
"postdisconnectscript", None)
section = network
else:
bssid = wireless.GetWirelessProperty(int(network), "bssid")
con = ConfigManager(wireless_conf)
if con.has_section(bssid):
info["pre_entry"] = con.get(bssid, "beforescript", None)
info["post_entry"] = con.get(bssid, "afterscript", None)
info["pre_disconnect_entry"] = con.get(bssid,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(bssid,
"postdisconnectscript", None)
section = bssid
if con.has_section(section):
info["pre_entry"] = con.get(section, "beforescript", None)
info["post_entry"] = con.get(section, "afterscript", None)
info["pre_disconnect_entry"] = con.get(section,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(section,
"postdisconnectscript", None)
return info
def write_scripts(network, network_type, script_info):
""" Writes script info to disk and loads it into the daemon. """
"""Writes script info to disk and loads it into the daemon."""
if network_type == "wired":
con = ConfigManager(wired_conf)
con.set(network, "beforescript", script_info["pre_entry"])
con.set(network, "afterscript", script_info["post_entry"])
con.set(network, "predisconnectscript",
script_info["pre_disconnect_entry"])
script_info["pre_disconnect_entry"])
con.set(network, "postdisconnectscript",
script_info["post_disconnect_entry"])
script_info["post_disconnect_entry"])
con.write()
wired.ReloadConfig()
wired.ReadWiredNetworkProfile(network)
@@ -108,17 +107,17 @@ def write_scripts(network, network_type, script_info):
con.set(bssid, "beforescript", script_info["pre_entry"])
con.set(bssid, "afterscript", script_info["post_entry"])
con.set(bssid, "predisconnectscript",
script_info["pre_disconnect_entry"])
script_info["pre_disconnect_entry"])
con.set(bssid, "postdisconnectscript",
script_info["post_disconnect_entry"])
script_info["post_disconnect_entry"])
con.write()
wireless.ReloadConfig()
wireless.ReadWirelessNetworkProfile(int(network))
wireless.SaveWirelessNetworkProfile(int(network))
def main (argv):
""" Runs the script configuration dialog. """
def main(argv):
"""Runs the script configuration dialog."""
if len(argv) < 2:
print('Network id to configure is missing, aborting.')
sys.exit(1)

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env python3
""" gui -- The main wicd GUI module.
"""gui -- The main wicd GUI module.
Module containing the code for the main wicd GUI.
@@ -26,6 +25,7 @@ Module containing the code for the main wicd GUI.
import os
import sys
import time
from gi.repository import GLib as gobject
import gtk
from itertools import chain
@@ -50,7 +50,7 @@ DBUS_AVAIL = False
def setup_dbus(force=True):
""" Initialize DBus. """
"""Initialize DBus."""
global bus, daemon, wireless, wired, DBUS_AVAIL
try:
dbusmanager.connect_to_dbus()
@@ -65,11 +65,8 @@ def setup_dbus(force=True):
try:
dbusmanager.connect_to_dbus()
except DBusException:
error(
None,
_("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages.")
)
error(None, _("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages."))
return False
else:
return False
@@ -86,25 +83,21 @@ def setup_dbus(force=True):
def handle_no_dbus(from_tray=False):
""" Handle the case where no DBus is available. """
"""Handle the case where no DBus is available."""
global DBUS_AVAIL
DBUS_AVAIL = False
if from_tray:
return False
print("Wicd daemon is shutting down!")
error(
None,
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
error(None, _('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'), block=False)
return False
class WiredProfileChooser:
""" Class for displaying the wired profile chooser. """
"""Class for displaying the wired profile chooser."""
def __init__(self):
""" Initializes and runs the wired profile chooser. """
"""Initializes and runs the wired profile chooser."""
# Import and init WiredNetworkEntry to steal some of the
# functions and widgets it uses.
wired_net_entry = WiredNetworkEntry()
@@ -163,18 +156,19 @@ class WiredProfileChooser:
def get_wireless_prop(net_id, prop):
""" Get wireless property. """
"""Get wireless property."""
return wireless.GetWirelessProperty(net_id, prop)
class appGui(object):
""" The main wicd GUI class. """
"""The main wicd GUI class."""
def __init__(self, standalone=False, tray=None):
""" Initializes everything needed for the GUI. """
"""Initializes everything needed for the GUI."""
setup_dbus()
if not daemon:
errmsg = _("Error connecting to wicd service via D-Bus. "
"Please ensure the wicd service is running.")
"Please ensure the wicd service is running.")
d = gtk.MessageDialog(parent=None,
flags=gtk.DIALOG_MODAL,
type=gtk.MESSAGE_ERROR,
@@ -255,11 +249,11 @@ class appGui(object):
self.window.connect('key-release-event', self.key_event)
daemon.SetGUIOpen(True)
bus.add_signal_receiver(self.dbus_scan_finished, 'SendEndScanSignal',
'org.wicd.daemon.wireless')
'org.wicd.daemon.wireless')
bus.add_signal_receiver(self.dbus_scan_started, 'SendStartScanSignal',
'org.wicd.daemon.wireless')
'org.wicd.daemon.wireless')
bus.add_signal_receiver(self.update_connect_buttons, 'StatusChanged',
'org.wicd.daemon')
'org.wicd.daemon')
bus.add_signal_receiver(self.handle_connection_results,
'ConnectResultsSent', 'org.wicd.daemon')
bus.add_signal_receiver(lambda: setup_dbus(force=False),
@@ -276,12 +270,12 @@ class appGui(object):
self.refresh_clicked()
def handle_connection_results(self, results):
""" Handle connection results. """
"""Handle connection results."""
if results not in ['success', 'aborted'] and self.is_visible:
error(self.window, language[results], block=False)
def create_adhoc_network(self, widget=None):
""" Shows a dialog that creates a new adhoc network. """
"""Shows a dialog that creates a new adhoc network."""
print("Starting the Ad-Hoc Network Creation Process...")
dialog = gtk.Dialog(
title=_('Create an Ad-Hoc Network'),
@@ -336,8 +330,8 @@ class appGui(object):
"WEP",
self.key_entry.entry.get_text(),
self.chkbox_use_encryption.get_active(),
False # chkbox_use_ics.get_active())
)
False) # chkbox_use_ics.get_active())
dialog.destroy()
def forget_network(self, widget=None):
@@ -359,7 +353,8 @@ class appGui(object):
if entry[1] != 'None':
networks.append(entry)
else:
networks.append((entry[0], _('Global settings for this ESSID')))
networks.append((entry[0],
_('Global settings for this ESSID')))
tree = gtk.TreeView(model=networks)
tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
@@ -395,9 +390,8 @@ class appGui(object):
flags=gtk.DIALOG_MODAL,
type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_YES_NO,
message_format=_('Are you sure you want to discard' +
' settings for the selected networks?')
)
message_format=_('Are you sure you want to discard '
'settings for the selected networks?'))
confirm.format_secondary_text('\n'.join(to_remove['essid']))
response = confirm.run()
if response == gtk.RESPONSE_YES:
@@ -408,11 +402,11 @@ class appGui(object):
dialog.destroy()
def toggle_encrypt_check(self, widget=None):
""" Toggles the encryption key entry box for the ad-hoc dialog. """
"""Toggles the encryption key entry box for the ad-hoc dialog."""
self.key_entry.set_sensitive(self.chkbox_use_encryption.get_active())
def switch_rfkill(self, widget=None):
""" Switches wifi card on/off. """
"""Switches wifi card on/off."""
wireless.SwitchRfKill()
if wireless.GetRfKillEnabled():
self.rfkill_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
@@ -422,7 +416,7 @@ class appGui(object):
self.rfkill_button.set_label(_('Switch Off Wi-Fi'))
def disconnect_all(self, widget=None):
""" Disconnects from any active network. """
"""Disconnects from any active network."""
def handler(*args):
gobject.idle_add(self.all_network_list.set_sensitive, True)
@@ -430,7 +424,7 @@ class appGui(object):
daemon.Disconnect(reply_handler=handler, error_handler=handler)
def about_dialog(self, widget, event=None):
""" Displays an about dialog. """
"""Displays an about dialog."""
dialog = gtk.AboutDialog()
dialog.set_name("Wicd")
dialog.set_version(daemon.Hello())
@@ -446,13 +440,13 @@ class appGui(object):
dialog.destroy()
def key_event(self, widget, event=None):
""" Handle key-release-events. """
"""Handle key-release-events."""
if event.state & gtk.gdk.CONTROL_MASK and \
gtk.gdk.keyval_name(event.keyval) in ["w", "q"]:
self.exit()
def settings_dialog(self, widget, event=None):
""" Displays a general settings dialog. """
"""Displays a general settings dialog."""
if not self.pref:
self.pref = PreferencesDialog(self, self.wTree)
else:
@@ -462,7 +456,7 @@ class appGui(object):
self.pref.hide()
def connect_hidden(self, widget):
""" Prompts the user for a hidden network, then scans for it. """
"""Prompts the user for a hidden network, then scans for it."""
dialog = gtk.Dialog(
title=('Hidden Network'),
flags=gtk.DIALOG_MODAL,
@@ -485,9 +479,8 @@ class appGui(object):
dialog.destroy()
def cancel_connect(self, widget):
""" Alerts the daemon to cancel the connection process. """
#should cancel a connection if there
#is one in progress
"""Alerts the daemon to cancel the connection process."""
# should cancel a connection if there is one in progress
cancel_button = self.wTree.get_object("cancel_button")
cancel_button.set_sensitive(False)
daemon.CancelConnect()
@@ -495,19 +488,19 @@ class appGui(object):
daemon.SetForcedDisconnect(True)
def pulse_progress_bar(self):
""" Pulses the progress bar while connecting to a network. """
"""Pulses the progress bar while connecting to a network."""
if not self.pulse_active:
return False
if not self.is_visible:
return True
try:
gobject.idle_add(self.wTree.get_object("progressbar").pulse)
except:
except Exception:
pass
return True
def update_statusbar(self):
""" Triggers a status update in wicd-monitor. """
"""Triggers a status update in wicd-monitor."""
if not self.is_visible:
return True
@@ -519,7 +512,7 @@ class appGui(object):
return True
def _do_statusbar_update(self, state, info):
""" Actually perform the statusbar update. """
"""Actually perform the statusbar update."""
if not self.is_visible:
return True
@@ -534,7 +527,7 @@ class appGui(object):
return True
def set_wired_state(self, info):
""" Set wired state. """
"""Set wired state."""
if self.connecting:
# Adjust our state from connecting->connected.
self._set_not_connecting_state()
@@ -544,7 +537,7 @@ class appGui(object):
return True
def set_wireless_state(self, info):
""" Set wireless state. """
"""Set wireless state."""
if self.connecting:
# Adjust our state from connecting->connected.
self._set_not_connecting_state()
@@ -555,7 +548,7 @@ class appGui(object):
return True
def set_not_connected_state(self, info):
""" Set not connected state. """
"""Set not connected state."""
if self.connecting:
# Adjust our state from connecting->not-connected.
self._set_not_connecting_state()
@@ -563,7 +556,7 @@ class appGui(object):
return True
def _set_not_connecting_state(self):
""" Set not-connecting state. """
"""Set not-connecting state."""
if self.connecting:
if self.update_cb:
gobject.source_remove(self.update_cb)
@@ -577,7 +570,7 @@ class appGui(object):
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID)
def set_connecting_state(self, info):
""" Set connecting state. """
"""Set connecting state."""
if not self.connecting:
if self.update_cb:
gobject.source_remove(self.update_cb)
@@ -595,12 +588,12 @@ class appGui(object):
stat = wireless.CheckWirelessConnectingMessage()
gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat))
elif info[0] == "wired":
gobject.idle_add(self.set_status, _('Wired Network') + ': '
+ wired.CheckWiredConnectingMessage())
gobject.idle_add(self.set_status, _('Wired Network') + ': ' +
wired.CheckWiredConnectingMessage())
return True
def update_connect_buttons(self, state=None, x=None, force_check=False):
""" Updates the connect/disconnect buttons for the GUI.
"""Updates the connect/disconnect buttons for the GUI.
If force_check is given, update the buttons even if the
current network state is the same as the previous.
@@ -622,11 +615,11 @@ class appGui(object):
self.prev_state = state
def set_status(self, msg):
""" Sets the status bar message for the GUI. """
"""Sets the status bar message for the GUI."""
self.statusID = self.status_bar.push(1, msg)
def dbus_scan_finished(self):
""" Calls for a non-fresh update of the gui window.
"""Calls for a non-fresh update of the gui window.
This method is called after a wireless scan is completed.
@@ -636,20 +629,20 @@ class appGui(object):
gobject.idle_add(self.refresh_networks, None, False, None)
def dbus_scan_started(self):
""" Called when a wireless scan starts. """
"""Called when a wireless scan starts."""
if not DBUS_AVAIL:
return
self.network_list.set_sensitive(False)
def _remove_items_from_vbox(self, vbox):
""" Remove items fro a VBox. """
"""Remove items fro a VBox."""
for z in vbox:
vbox.remove(z)
z.destroy()
del z
def refresh_clicked(self, widget=None):
""" Kick off an asynchronous wireless scan. """
"""Kick off an asynchronous wireless scan."""
if not DBUS_AVAIL or self.connecting:
return
self.refreshing = True
@@ -665,7 +658,7 @@ class appGui(object):
wirednet = WiredNetworkEntry()
self.wired_network_box.pack_start(wirednet, False, False)
wirednet.connect_button.connect("clicked", self.connect,
"wired", 0, wirednet)
"wired", 0, wirednet)
wirednet.disconnect_button.connect("clicked", self.disconnect,
"wired", 0, wirednet)
wirednet.advanced_button.connect("clicked",
@@ -681,7 +674,7 @@ class appGui(object):
wireless.Scan(False)
def refresh_networks(self, widget=None, fresh=True, hidden=None):
""" Refreshes the network list.
"""Refreshes the network list.
If fresh=True, scans for wireless networks and displays the results.
If a ethernet connection is available, or the user has chosen to,
@@ -742,7 +735,7 @@ class appGui(object):
self.refreshing = False
def save_settings(self, nettype, networkid, networkentry):
""" Verifies and saves the settings for the network entry. """
"""Verifies and saves the settings for the network entry."""
entry = networkentry.advanced_dialog
opt_entlist = []
req_entlist = []
@@ -762,7 +755,7 @@ class appGui(object):
lblent.set_text(lblent.get_text().strip())
if not misc.IsValidIP(lblent.get_text()):
error(self.window, _('Invalid address in $A entry.').
replace('$A', lblent.label.get_label()))
replace('$A', lblent.label.get_label()))
return False
# Optional entries, only check for validity if they're entered.
@@ -770,7 +763,7 @@ class appGui(object):
lblent.set_text(lblent.get_text().strip())
if lblent.get_text() and not misc.IsValidIP(lblent.get_text()):
error(self.window, _('Invalid address in $A entry.').
replace('$A', lblent.label.get_label()))
replace('$A', lblent.label.get_label()))
return False
# Now save the settings.
@@ -785,7 +778,7 @@ class appGui(object):
return True
def edit_advanced(self, widget, ttype, networkid, networkentry):
""" Display the advanced settings dialog.
"""Display the advanced settings dialog.
Displays the advanced settings dialog and saves any changes made.
If errors occur in the settings, an error message will be displayed
@@ -797,12 +790,13 @@ class appGui(object):
dialog.set_values()
dialog.show_all()
while True:
if self.run_settings_dialog(dialog, ttype, networkid, networkentry):
if self.run_settings_dialog(dialog, ttype, networkid,
networkentry):
break
dialog.hide()
def run_settings_dialog(self, dialog, nettype, networkid, networkentry):
""" Runs the settings dialog.
"""Runs the settings dialog.
Runs the settings dialog and returns True if settings are saved
successfully, and false otherwise.
@@ -817,32 +811,27 @@ class appGui(object):
return True
def check_encryption_valid(self, networkid, entry):
""" Make sure that encryption settings are properly filled in. """
"""Make sure that encryption settings are properly filled in."""
# Make sure no entries are left blank
if entry.chkbox_encryption.get_active():
encryption_info = entry.encryption_info
for entry_info in list(encryption_info.values()):
if entry_info[0].entry.get_text() == "" and \
entry_info[1] == 'required':
error(
self.window,
"%s (%s)" %
(_('Required encryption information is missing.'),
entry_info[0].label.get_label())
)
error(self.window, "%s (%s)" %
(_('Required encryption information is missing.'),
entry_info[0].label.get_label()))
return False
# Make sure the checkbox is checked when it should be
elif not entry.chkbox_encryption.get_active() and \
wireless.GetWirelessProperty(networkid, "encryption"):
error(
self.window,
_('This network requires encryption to be enabled.')
)
elif (not entry.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption")):
error(self.window, _('This network requires encryption to be '
'enabled.'))
return False
return True
def _wait_for_connect_thread_start(self):
""" Wait for the connect thread to start. """
"""Wait for the connect thread to start."""
self.wTree.get_object("progressbar").pulse()
if not self._connect_thread_started:
return True
@@ -852,12 +841,12 @@ class appGui(object):
return False
def connect(self, widget, nettype, networkid, networkentry):
""" Initiates the connection process in the daemon. """
"""Initiates the connection process in the daemon."""
def handler(*args):
self._connect_thread_started = True
def setup_interface_for_connection():
""" Initialize interface for connection. """
"""Initialize interface for connection."""
cancel_button = self.wTree.get_object("cancel_button")
cancel_button.set_sensitive(True)
self.all_network_list.set_sensitive(False)
@@ -886,7 +875,7 @@ class appGui(object):
misc.timeout_add(100, self._wait_for_connect_thread_start, milli=True)
def disconnect(self, widget, nettype, networkid, networkentry):
""" Disconnects from the given network.
"""Disconnects from the given network.
Keyword arguments:
widget -- The disconnect button that was pressed.
@@ -911,7 +900,7 @@ class appGui(object):
error_handler=handler)
def wait_for_events(self, amt=0):
""" Wait for any pending gtk events to finish before moving on.
"""Wait for any pending gtk events to finish before moving on.
Keyword arguments:
amt -- a number specifying the number of ms to wait before checking
@@ -923,7 +912,7 @@ class appGui(object):
gtk.main_iteration()
def exit(self, widget=None, event=None):
""" Hide the wicd GUI.
"""Hide the wicd GUI.
This method hides the wicd GUI and writes the current window size
to disc for later use. This method normally does NOT actually
@@ -947,7 +936,7 @@ class appGui(object):
return True
def show_win(self):
""" Brings the GUI out of the hidden state.
"""Brings the GUI out of the hidden state.
Method to show the wicd GUI, alert the daemon that it is open,
and refresh the network list.

View File

@@ -1,4 +1,4 @@
""" guiutil - A collection of commonly used gtk/gui functions and classes. """
"""guiutil - A collection of commonly used gtk/gui functions and classes."""
#
# Copyright (C) 2007 - 2009 Adam Blackburn
# Copyright (C) 2007 - 2009 Dan O'Reilly
@@ -38,7 +38,7 @@ if wpath.no_use_notifications:
def can_use_notify():
""" Check whether WICD is allowed to use notifications. """
"""Check whether WICD is allowed to use notifications."""
use_notify = os.path.exists(os.path.join(os.path.expanduser('~/.wicd'),
'USE_NOTIFICATIONS')
)
@@ -46,9 +46,9 @@ def can_use_notify():
def error(parent, message, block=True):
""" Shows an error dialog. """
"""Shows an error dialog."""
def delete_event(dialog, i):
""" Handle dialog destroy. """
"""Handle dialog destroy."""
dialog.destroy()
if can_use_notify() and not block:
@@ -67,9 +67,9 @@ def error(parent, message, block=True):
def alert(parent, message, block=True):
""" Shows an warning dialog. """
"""Shows an warning dialog."""
def delete_event(dialog, i):
""" Handle dialog destroy. """
"""Handle dialog destroy."""
dialog.destroy()
dialog = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
@@ -84,12 +84,12 @@ def alert(parent, message, block=True):
def string_input(prompt, secondary, textbox_label):
""" Dialog with a label and an entry. """
"""Dialog with a label and an entry."""
# based on a version of a PyGTK text entry from
# http://ardoris.wordpress.com/2008/07/05/pygtk-text-entry-dialog/
def dialog_response(entry, dialog, response):
""" Handle dialog response. """
"""Handle dialog response."""
dialog.response(response)
dialog = gtk.MessageDialog(
@@ -128,21 +128,21 @@ def string_input(prompt, secondary, textbox_label):
class SmallLabel(gtk.Label):
""" Small GtkLabel. """
"""Small GtkLabel."""
def __init__(self, text=''):
gtk.Label.__init__(self, text)
self.set_size_request(50, -1)
class LeftAlignedLabel(gtk.Label):
"""GtkLabel with text aligned to left. """
"""GtkLabel with text aligned to left."""
def __init__(self, label=None):
gtk.Label.__init__(self, label)
self.set_alignment(0.0, 0.5)
class LabelEntry(gtk.HBox):
""" A label on the left with a textbox on the right. """
"""A label on the left with a textbox on the right."""
def __init__(self, text):
gtk.HBox.__init__(self)
self.entry = gtk.Entry()
@@ -160,37 +160,37 @@ class LabelEntry(gtk.HBox):
self.show()
def set_text(self, text):
""" Set text of the GtkEntry. """
"""Set text of the GtkEntry."""
# For compatibility...
self.entry.set_text(text)
def get_text(self):
""" Get text of the GtkEntry. """
"""Get text of the GtkEntry."""
return self.entry.get_text()
def set_auto_hidden(self, value):
""" Set auto-hide of the text of GtkEntry. """
"""Set auto-hide of the text of GtkEntry."""
self.entry.set_visibility(False)
self.auto_hide_text = value
def show_characters(self, widget=None, event=None):
""" When the box has focus, show the characters. """
"""When the box has focus, show the characters."""
if self.auto_hide_text and widget:
self.entry.set_visibility(True)
def set_sensitive(self, value):
""" Set sensitivity of the widget. """
"""Set sensitivity of the widget."""
self.entry.set_sensitive(value)
self.label.set_sensitive(value)
def hide_characters(self, widget=None, event=None):
""" When the box looses focus, hide them. """
"""When the box looses focus, hide them."""
if self.auto_hide_text and widget:
self.entry.set_visibility(False)
class GreyLabel(gtk.Label):
""" Creates a grey gtk.Label. """
"""Creates a grey gtk.Label."""
def __init__(self):
gtk.Label.__init__(self)
@@ -200,7 +200,7 @@ class GreyLabel(gtk.Label):
class ProtectedLabelEntry(gtk.HBox):
""" A LabelEntry with a CheckButton that protects the entry text. """
"""A LabelEntry with a CheckButton that protects the entry text."""
def __init__(self, label_text):
gtk.HBox.__init__(self)
self.entry = gtk.Entry()
@@ -223,28 +223,28 @@ class ProtectedLabelEntry(gtk.HBox):
self.show()
def set_entry_text(self, text):
""" Set text of the GtkEntry. """
"""Set text of the GtkEntry."""
# For compatibility...
self.entry.set_text(text)
def get_entry_text(self):
""" Get text of the GtkEntry. """
"""Get text of the GtkEntry."""
return self.entry.get_text()
def set_sensitive(self, value):
""" Set sensitivity of the widget. """
"""Set sensitivity of the widget."""
self.entry.set_sensitive(value)
self.label.set_sensitive(value)
self.check.set_sensitive(value)
def click_handler(self, widget=None, event=None):
""" Handle clicks. """
"""Handle clicks."""
active = self.check.get_active()
self.entry.set_visibility(active)
class LabelCombo(gtk.HBox):
""" A label on the left with a combobox on the right. """
"""A label on the left with a combobox on the right."""
def __init__(self, text):
gtk.HBox.__init__(self)
@@ -263,26 +263,26 @@ class LabelCombo(gtk.HBox):
self.show()
def get_active(self):
""" Return the selected item in the GtkComboBox. """
"""Return the selected item in the GtkComboBox."""
return self.combo.get_active()
def set_active(self, index):
""" Set given item in the GtkComboBox. """
"""Set given item in the GtkComboBox."""
self.combo.set_active(index)
def get_active_text(self):
""" Return the selected item's text in the GtkComboBox. """
"""Return the selected item's text in the GtkComboBox."""
return self.combo.get_active_text()
def get_model(self):
""" Return the GtkComboBox's model. """
"""Return the GtkComboBox's model."""
return self.combo.get_model()
def set_model(self, model=None):
""" Set the GtkComboBox's model. """
"""Set the GtkComboBox's model."""
self.combo.set_model(model)
def set_sensitive(self, value):
""" Set sensitivity of the widget. """
"""Set sensitivity of the widget."""
self.combo.set_sensitive(value)
self.label.set_sensitive(value)

View File

@@ -1,4 +1,4 @@
""" netentry -- Network entry widgets for the GUI.
"""netentry -- Network entry widgets for the GUI.
This module provides GUI widgets used to represent wired and wireless
entries in the GUI's network list, as well as any settings dialogs
@@ -23,9 +23,9 @@ contained within them.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import gtk
import os
import wicd.misc as misc
import wicd.wpath as wpath
@@ -43,7 +43,7 @@ wireless = None
def setup_dbus():
""" Initialize DBus. """
"""Initialize DBus."""
global daemon, wireless, wired
daemon = dbusmanager.get_interface('daemon')
wireless = dbusmanager.get_interface('wireless')
@@ -51,9 +51,9 @@ def setup_dbus():
class AdvancedSettingsDialog(gtk.Dialog):
""" Advanced settings dialog. """
"""Advanced settings dialog."""
def __init__(self, network_name=None):
""" Build the base advanced settings dialog.
"""Build the base advanced settings dialog.
This class isn't used by itself, instead it is used as a parent for
the WiredSettingsDialog and WirelessSettingsDialog.
@@ -109,7 +109,7 @@ class AdvancedSettingsDialog(gtk.Dialog):
script_image = gtk.Image()
script_image.set_from_stock(gtk.STOCK_EXECUTE, 4)
script_image.set_padding(4, 0)
#self.script_button.set_alignment(.5, .5)
# self.script_button.set_alignment(.5, .5)
self.script_button.set_image(script_image)
self.script_button.set_label(_('Scripts'))
@@ -158,7 +158,7 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.chkbox_static_dns.set_active(False)
def set_default_size(self):
""" Set default window size. """
"""Set default window size."""
width, height = self.get_size()
s_height = gtk.gdk.screen_height()
if s_height < 768:
@@ -168,7 +168,7 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.resize(int(width), int(height))
def set_defaults(self, widget=None, event=None):
""" Put some default values into entries to help the user out. """
"""Put some default values into entries to help the user out."""
self.txt_ip.set_text(self.txt_ip.get_text().strip())
ip = self.txt_ip.get_text() # For easy typing :)
netmask = self.txt_netmask
@@ -195,7 +195,7 @@ class AdvancedSettingsDialog(gtk.Dialog):
error(None, _('Invalid IP address entered.'))
def reset_static_checkboxes(self):
""" Enable the right stuff. """
"""Enable the right stuff."""
if stringToNone(self.txt_ip.get_text()):
self.chkbox_static_ip.set_active(True)
self.chkbox_static_dns.set_active(True)
@@ -216,7 +216,7 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.toggle_global_dns_checkbox()
def toggle_ip_checkbox(self, widget=None):
"""Toggle entries/checkboxes based on the static IP checkbox. """
"""Toggle entries/checkboxes based on the static IP checkbox."""
# Should disable the static IP text boxes, and also enable the DNS
# checkbox when disabled and disable when enabled.
if self.chkbox_static_ip.get_active():
@@ -230,33 +230,33 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.txt_gateway.set_sensitive(self.chkbox_static_ip.get_active())
def toggle_dns_checkbox(self, widget=None):
""" Toggle entries and checkboxes based on the static dns checkbox. """
"""Toggle entries and checkboxes based on the static dns checkbox."""
# Should disable the static DNS boxes
if self.chkbox_static_ip.get_active():
self.chkbox_static_dns.set_active(True)
self.chkbox_static_dns.set_sensitive(False)
self.chkbox_global_dns.set_sensitive(self.chkbox_static_dns.
get_active())
get_active())
l = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3, self.txt_domain,
self.txt_search_dom]
search_list = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3,
self.txt_domain, self.txt_search_dom]
if self.chkbox_static_dns.get_active():
# If global dns is on, don't use local dns
for w in l:
for w in search_list:
w.set_sensitive(not self.chkbox_global_dns.get_active())
else:
for w in l:
for w in search_list:
w.set_sensitive(False)
self.chkbox_global_dns.set_active(False)
def toggle_dhcp_hostname_checkbox(self, widget=None):
""" Set widget sensitivity. """
"""Set widget sensitivity."""
self.txt_dhcp_hostname.set_sensitive(
self.chkbox_use_dhcp_hostname.get_active())
def toggle_global_dns_checkbox(self, widget=None):
""" Set the DNS entries' sensitivity based on the Global checkbox. """
"""Set the DNS entries' sensitivity based on the Global checkbox."""
global_dns_active = daemon.GetUseGlobalDNS()
if not global_dns_active and self.chkbox_global_dns.get_active():
error(
@@ -270,19 +270,21 @@ class AdvancedSettingsDialog(gtk.Dialog):
w.set_sensitive(not self.chkbox_global_dns.get_active())
def toggle_encryption(self, widget=None):
""" Toggle the encryption combobox based on the encryption checkbox. """
"""
Toggle the encryption combobox based on the encryption checkbox.
"""
active = self.chkbox_encryption.get_active()
self.vbox_encrypt_info.set_sensitive(active)
self.combo_encryption.set_sensitive(active)
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
super(AdvancedSettingsDialog, self).destroy()
self.destroy()
del self
def save_settings(self, networkid=None):
""" Save settings common to wired and wireless settings dialogs. """
"""Save settings common to wired and wireless settings dialogs."""
if self.chkbox_static_ip.get_active():
self.set_net_prop("ip", noneToString(self.txt_ip.get_text()))
self.set_net_prop(
@@ -305,8 +307,8 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns1", noneToString(self.txt_dns_1.get_text()))
self.set_net_prop("dns2", noneToString(self.txt_dns_2.get_text()))
self.set_net_prop("dns3", noneToString(self.txt_dns_3.get_text()))
elif self.chkbox_static_dns.get_active() and \
self.chkbox_global_dns.get_active():
elif (self.chkbox_static_dns.get_active() and
self.chkbox_global_dns.get_active()):
self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True)
else:
@@ -319,11 +321,11 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns3", '')
self.set_net_prop('usedhcphostname',
self.chkbox_use_dhcp_hostname.get_active())
self.set_net_prop(
"dhcphostname",noneToString(self.txt_dhcp_hostname.get_text()))
self.set_net_prop("dhcphostname", noneToString(self.txt_dhcp_hostname.
get_text()))
def change_encrypt_method(self, widget=None):
""" Load all the entries for a given encryption method. """
"""Load all the entries for a given encryption method."""
for z in self.vbox_encrypt_info:
z.destroy() # Remove stuff in there already
ID = self.combo_encryption.get_active()
@@ -358,23 +360,26 @@ class AdvancedSettingsDialog(gtk.Dialog):
box.entry.set_text(noneToBlankString(
wired.GetWiredProperty(field[0])))
else:
box.entry.set_text(noneToBlankString(
wireless.GetWirelessProperty(self.networkID, field[0])))
box.entry.set_text(
noneToBlankString(wireless.
GetWirelessProperty(self.networkID,
field[0])))
self.vbox_encrypt_info.show_all()
class WiredSettingsDialog(AdvancedSettingsDialog):
""" Wired settings dialog. """
"""Wired settings dialog."""
def __init__(self, name):
""" Build the wired settings dialog. """
"""Build the wired settings dialog."""
AdvancedSettingsDialog.__init__(self, _('Wired Network'))
# So we can test if we are wired or wireless (for
# change_encrypt_method())
self.wired = True
## This section is largely copied from WirelessSettingsDialog, but with
## some changes
# This section is largely copied from WirelessSettingsDialog, but with
# some changes
#
# Set up encryption stuff
self.combo_encryption = gtk.combo_box_new_text()
self.chkbox_encryption = gtk.CheckButton(_('Use Encryption'))
@@ -405,11 +410,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.prof_name = name
def set_net_prop(self, option, value):
""" Sets the given option to the given value for this network. """
"""Sets the given option to the given value for this network."""
wired.SetWiredProperty(option, value)
def edit_scripts(self, widget=None, event=None):
""" Launch the script editting dialog. """
"""Launch the script editting dialog."""
profile = self.prof_name
cmdend = [os.path.join(wpath.gtk, "configscript.py"), profile, "wired"]
if os.getuid() != 0:
@@ -418,12 +423,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
prog_num=daemon.GetSudoApp()
)
if not cmdbase:
error(None,
_('Could not find a graphical sudo program. '
'The script editor could not be launched. '
"You'll have to edit scripts directly your configuration "
"file.")
)
error(None, _("Could not find a graphical sudo program. "
"The script editor could not be launched. "
"You'll have to edit scripts directly your "
"configuration "
"file."))
return
cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase)
@@ -431,7 +435,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
misc.LaunchAndWait(cmdend)
def set_values(self):
""" Fill in the Gtk.Entry objects with the correct values. """
"""Fill in the Gtk.Entry objects with the correct values."""
self.txt_ip.set_text(self.format_entry("ip"))
self.txt_netmask.set_text(self.format_entry("netmask"))
self.txt_gateway.set_text(self.format_entry("gateway"))
@@ -457,7 +461,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.toggle_encryption()
def save_settings(self, networkid=None):
""" Save settings to disk. """
"""Save settings to disk."""
# Check encryption info
encrypt_info = self.encryption_info
self.set_net_prop(
@@ -495,11 +499,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
return True
def format_entry(self, label):
""" Helper method to fetch and format wired properties. """
"""Helper method to fetch and format wired properties."""
return noneToBlankString(wired.GetWiredProperty(label))
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
self.disconnect(self.des)
super(WiredSettingsDialog, self).destroy_called()
self.destroy()
@@ -507,9 +511,9 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
class WirelessSettingsDialog(AdvancedSettingsDialog):
""" Wireless settings dialog. """
"""Wireless settings dialog."""
def __init__(self, networkID):
""" Build the wireless settings dialog. """
"""Build the wireless settings dialog."""
AdvancedSettingsDialog.__init__(
self, wireless.GetWirelessProperty(networkID, 'essid'))
# So we can test if we are wired or wireless (for
@@ -555,8 +559,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types):
self.combo_encryption.append_text(enc_type['name'])
if enc_type['type'] == \
wireless.GetWirelessProperty(networkID, "enctype"):
if enc_type['type'] == wireless.GetWirelessProperty(networkID,
"enctype"):
activeID = x
self.combo_encryption.set_active(activeID)
if activeID != -1:
@@ -580,29 +584,26 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.des = self.connect("destroy", self.destroy_called)
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
self.disconnect(self.des)
super(WirelessSettingsDialog, self).destroy_called()
self.destroy()
del self
def edit_scripts(self, widget=None, event=None):
""" Launch the script editting dialog. """
"""Launch the script editting dialog."""
cmdend = [os.path.join(wpath.gtk, "configscript.py"),
str(self.networkID), "wireless"]
str(self.networkID), "wireless"]
if os.getuid() != 0:
cmdbase = misc.get_sudo_cmd(
_('You must enter your password to configure scripts'),
prog_num=daemon.GetSudoApp()
)
if not cmdbase:
error(
None,
_('Could not find a graphical sudo program. '
'The script editor could not be launched. '
"You'll have to edit scripts directly your "
"configuration file.")
)
error(None, _("Could not find a graphical sudo program. The "
"script editor could not be launched. You'll "
"have to edit scripts directly your "
"configuration file."))
return
cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase)
@@ -610,11 +611,11 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
misc.LaunchAndWait(cmdend)
def set_net_prop(self, option, value):
""" Sets the given option to the given value for this network. """
"""Sets the given option to the given value for this network."""
wireless.SetWirelessProperty(self.networkID, option, value)
def set_values(self):
""" Set the various network settings to the right values. """
"""Set the various network settings to the right values."""
networkID = self.networkID
self.txt_ip.set_text(self.format_entry(networkID, "ip"))
self.txt_netmask.set_text(self.format_entry(networkID, "netmask"))
@@ -636,15 +637,12 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.chkbox_encryption.set_active(
bool(wireless.GetWirelessProperty(networkID, 'encryption')))
self.chkbox_global_settings.set_active(
bool(
wireless.GetWirelessProperty(networkID, 'use_settings_globally')
)
)
bool(wireless.GetWirelessProperty(networkID,
'use_settings_globally')))
self.chkbox_use_dhcp_hostname.set_active(
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname')))
dhcphname = wireless.GetWirelessProperty(networkID, "dhcphostname")
if dhcphname is None:
dhcphname = os.uname()[1]
@@ -704,8 +702,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key,
noneToString(entry_info[0].entry.get_text()))
elif not self.chkbox_encryption.get_active() and \
wireless.GetWirelessProperty(networkid, "encryption"):
elif (not self.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it.
error(self, _('This network requires encryption to be enabled.'))
return False
@@ -735,14 +733,15 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
return True
def format_entry(self, networkid, label):
""" Helper method for fetching/formatting wireless properties. """
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class NetworkEntry(gtk.HBox):
""" Network entry. """
"""Network entry."""
def __init__(self):
""" Base network entry class.
"""Base network entry class.
Provides gtk objects used by both the WiredNetworkEntry and
WirelessNetworkEntry classes.
@@ -793,16 +792,16 @@ class NetworkEntry(gtk.HBox):
self.expander_vbox.pack_start(self.buttons_hbox)
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
super(NetworkEntry, self).destroy()
self.destroy()
del self
class WiredNetworkEntry(NetworkEntry):
""" Wired network entry. """
"""Wired network entry."""
def __init__(self):
""" Load the wired network entry. """
"""Load the wired network entry."""
NetworkEntry.__init__(self)
# Center the picture and pad it a bit
self.image.set_padding(0, 0)
@@ -819,13 +818,15 @@ class WiredNetworkEntry(NetworkEntry):
self.button_add = gtk.Button(stock=gtk.STOCK_ADD)
self.button_delete = gtk.Button(stock=gtk.STOCK_DELETE)
self.profile_help = gtk.Label(
_('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.')
)
self.chkbox_default_profile = gtk.CheckButton(
_('Use as default profile (overwrites any previous default)'))
self.profile_help = gtk.Label(_('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.'))
self.chkbox_default_profile = gtk.CheckButton(_('Use as default '
'profile (overwrites '
'any previous '
'default)'))
self.combo_profile_names = gtk.combo_box_new_text()
# Format the profile help label.
@@ -881,7 +882,7 @@ class WiredNetworkEntry(NetworkEntry):
self.wireddis = self.connect("destroy", self.destroy_called)
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
self.disconnect(self.wireddis)
self.advanced_dialog.destroy_called()
del self.advanced_dialog
@@ -890,11 +891,11 @@ class WiredNetworkEntry(NetworkEntry):
del self
def save_wired_settings(self):
""" Save wired network settings. """
"""Save wired network settings."""
return self.advanced_dialog.save_settings()
def check_enable(self):
""" Disable objects if the profile list is empty. """
"""Disable objects if the profile list is empty."""
profile_list = wired.GetWiredProfileList()
if not profile_list:
self.button_delete.set_sensitive(False)
@@ -902,7 +903,7 @@ class WiredNetworkEntry(NetworkEntry):
self.advanced_button.set_sensitive(False)
def update_connect_button(self, state, apbssid=None):
""" Update the connection/disconnect button for this entry. """
"""Update the connection/disconnect button for this entry."""
if state == misc.WIRED:
self.disconnect_button.show()
self.connect_button.hide()
@@ -911,7 +912,7 @@ class WiredNetworkEntry(NetworkEntry):
self.connect_button.show()
def add_profile(self, widget):
""" Add a profile to the profile list. """
"""Add a profile to the profile list."""
response = string_input(
"Enter a profile name", "The profile name will not be used by the "
"computer. It allows you to easily distinguish between different "
@@ -941,12 +942,12 @@ class WiredNetworkEntry(NetworkEntry):
self.advanced_button.set_sensitive(True)
def remove_profile(self, widget):
""" Remove a profile from the profile list. """
"""Remove a profile from the profile list."""
print("removing profile")
profile_name = self.combo_profile_names.get_active_text()
wired.DeleteWiredNetworkProfile(profile_name)
self.combo_profile_names.remove_text(self.combo_profile_names.
get_active())
get_active())
self.combo_profile_names.set_active(0)
self.advanced_dialog.prof_name = \
self.combo_profile_names.get_active_text()
@@ -962,7 +963,7 @@ class WiredNetworkEntry(NetworkEntry):
self.profile_help.hide()
def toggle_default_profile(self, widget):
""" Change the default profile. """
"""Change the default profile."""
if self.chkbox_default_profile.get_active():
# Make sure there is only one default profile at a time
wired.UnsetWiredDefault()
@@ -972,7 +973,7 @@ class WiredNetworkEntry(NetworkEntry):
self.combo_profile_names.get_active_text())
def change_profile(self, widget):
""" Called when a new profile is chosen from the list. """
"""Called when a new profile is chosen from the list."""
# Make sure the name doesn't change everytime someone types something
if self.combo_profile_names.get_active() > -1:
if not self.is_full_gui:
@@ -989,14 +990,14 @@ class WiredNetworkEntry(NetworkEntry):
self.chkbox_default_profile.set_active(to_bool(is_default))
def format_entry(self, label):
""" Help method for fetching/formatting wired properties. """
"""Help method for fetching/formatting wired properties."""
return noneToBlankString(wired.GetWiredProperty(label))
class WirelessNetworkEntry(NetworkEntry):
""" Wireless network entry. """
"""Wireless network entry."""
def __init__(self, networkID):
""" Build the wireless network entry. """
"""Build the wireless network entry."""
NetworkEntry.__init__(self)
self.networkID = networkID
@@ -1061,7 +1062,7 @@ class WirelessNetworkEntry(NetworkEntry):
self.wifides = self.connect("destroy", self.destroy_called)
def _escape(self, val):
""" Escapes special characters so they're displayed correctly. """
"""Escapes special characters so they're displayed correctly."""
return val.replace("&", "&amp;"). \
replace("<", "&lt;"). \
replace(">", "&gt;"). \
@@ -1069,11 +1070,11 @@ class WirelessNetworkEntry(NetworkEntry):
replace('"', "&quot;")
def save_wireless_settings(self, networkid):
""" Save wireless network settings. """
"""Save wireless network settings."""
return self.advanced_dialog.save_settings(networkid)
def update_autoconnect(self, widget=None):
""" Called when the autoconnect checkbox is toggled. """
"""Called when the autoconnect checkbox is toggled."""
wireless.SetWirelessProperty(
self.networkID,
"automatic",
@@ -1082,7 +1083,7 @@ class WirelessNetworkEntry(NetworkEntry):
wireless.SaveWirelessNetworkProperty(self.networkID, "automatic")
def update_neverconnect(self, widget=None):
""" Called when the neverconnect checkbox is toggled. """
"""Called when the neverconnect checkbox is toggled."""
wireless.SetWirelessProperty(
self.networkID,
"never",
@@ -1097,7 +1098,7 @@ class WirelessNetworkEntry(NetworkEntry):
self.connect_button.set_sensitive(True)
def destroy_called(self, *args):
""" Clean up everything. """
"""Clean up everything."""
self.disconnect(self.wifides)
self.advanced_dialog.destroy_called()
del self.advanced_dialog
@@ -1106,7 +1107,7 @@ class WirelessNetworkEntry(NetworkEntry):
del self
def update_connect_button(self, state, apbssid):
""" Update the connection/disconnect button for this entry. """
"""Update the connection/disconnect button for this entry."""
if to_bool(self.format_entry(self.networkID, "never")):
self.connect_button.set_sensitive(False)
if not apbssid:
@@ -1120,7 +1121,7 @@ class WirelessNetworkEntry(NetworkEntry):
self.connect_button.show()
def set_signal_strength(self, strength, dbm_strength):
""" Set the signal strength displayed in the WirelessNetworkEntry. """
"""Set the signal strength displayed in the WirelessNetworkEntry."""
if strength:
strength = int(strength)
else:
@@ -1162,7 +1163,7 @@ class WirelessNetworkEntry(NetworkEntry):
self.image.show()
def set_encryption(self, on, ttype):
""" Set the encryption value for the WirelessNetworkEntry. """
"""Set the encryption value for the WirelessNetworkEntry."""
if on and ttype:
self.lbl_encryption.set_label(str(ttype))
if on and not ttype:
@@ -1171,16 +1172,17 @@ class WirelessNetworkEntry(NetworkEntry):
self.lbl_encryption.set_label(_('Unsecured'))
def set_channel(self, channel):
""" Set the channel value for the WirelessNetworkEntry. """
"""Set the channel value for the WirelessNetworkEntry."""
self.lbl_channel.set_label(_('Channel') + ' ' + str(channel))
def format_entry(self, networkid, label):
""" Helper method for fetching/formatting wireless properties. """
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class WirelessInformationDialog(gtk.Dialog):
""" Wireless information dialog. """
"""Wireless information dialog."""
def __init__(self, networkID, parent):
gtk.Dialog.__init__(self, parent=parent)
@@ -1243,7 +1245,7 @@ class WirelessInformationDialog(gtk.Dialog):
self.destroy()
def set_signal_strength(self, strength, dbm_strength):
""" Set the signal strength displayed in the WirelessNetworkEntry. """
"""Set the signal strength displayed in the WirelessNetworkEntry."""
if strength is not None:
strength = int(strength)
else:
@@ -1283,11 +1285,11 @@ class WirelessInformationDialog(gtk.Dialog):
self.lbl_strength.set_label(disp_strength + ending)
def set_mac_address(self, address):
""" Set the MAC address for the WirelessNetworkEntry. """
"""Set the MAC address for the WirelessNetworkEntry."""
self.lbl_mac.set_label(str(address))
def set_encryption(self, on, ttype):
""" Set the encryption value for the WirelessNetworkEntry. """
"""Set the encryption value for the WirelessNetworkEntry."""
if on and ttype:
self.lbl_encryption.set_label(str(ttype))
if on and not ttype:
@@ -1296,13 +1298,14 @@ class WirelessInformationDialog(gtk.Dialog):
self.lbl_encryption.set_label(_('Unsecured'))
def set_channel(self, channel):
""" Set the channel value for the WirelessNetworkEntry. """
"""Set the channel value for the WirelessNetworkEntry."""
self.lbl_channel.set_label(_('Channel') + ' ' + str(channel))
def set_mode(self, mode):
""" Set the mode value for the WirelessNetworkEntry. """
"""Set the mode value for the WirelessNetworkEntry."""
self.lbl_mode.set_label(str(mode))
def format_entry(self, networkid, label):
""" Helper method for fetching/formatting wireless properties. """
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3
""" prefs -- Wicd Preferences Dialog.
"""prefs -- Wicd Preferences Dialog.
Displays the main settings dialog window for wicd and
handles recieving/sendings the settings from/to the daemon.
@@ -23,10 +23,14 @@ handles recieving/sendings the settings from/to the daemon.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import gtk
from gi.repository import GObject as gobject
import os
try:
import pynotify
except ImportError:
pynotify = None
from wicd import misc
from wicd import wpath
@@ -42,7 +46,7 @@ USER_SETTINGS_DIR = os.path.expanduser('~/.wicd/')
def setup_dbus():
""" Initialize DBus. """
"""Initialize DBus."""
global daemon, wireless, wired
daemon = dbusmanager.get_interface('daemon')
wireless = dbusmanager.get_interface('wireless')
@@ -50,7 +54,7 @@ def setup_dbus():
class PreferencesDialog(object):
""" Class for handling the wicd preferences dialog window. """
"""Class for handling the wicd preferences dialog window."""
def __init__(self, parent, wTree):
setup_dbus()
self.parent = parent
@@ -108,7 +112,7 @@ class PreferencesDialog(object):
self.load_preferences_diag()
def _setup_external_app_radios(self, radio_list, get_method, set_method):
""" Generic function for setting up external app radios. """
"""Generic function for setting up external app radios."""
# Disable radios for apps that aren't installed.
for app in radio_list[1:]:
app.set_sensitive(daemon.GetAppAvailable(app.get_label()))
@@ -122,7 +126,7 @@ class PreferencesDialog(object):
radio_list[misc.AUTO].set_active(True)
def load_preferences_diag(self):
""" Loads data into the preferences Dialog. """
"""Loads data into the preferences Dialog."""
self.wiredcheckbox.set_active(daemon.GetAlwaysShowWiredInterface())
self.reconnectcheckbox.set_active(daemon.GetAutoReconnect())
@@ -208,9 +212,7 @@ class PreferencesDialog(object):
))
# if pynotify isn't installed disable the option
try:
import pynotify
except ImportError:
if not pynotify:
self.notificationscheckbox.set_active(False)
self.notificationscheckbox.set_sensitive(False)
@@ -223,23 +225,23 @@ class PreferencesDialog(object):
self.wTree.get_object("notebook2").set_current_page(0)
def run(self):
""" Runs the preferences dialog window. """
"""Runs the preferences dialog window."""
return self.dialog.run()
def hide(self):
""" Hides the preferences dialog window. """
"""Hides the preferences dialog window."""
self.dialog.hide()
def destroy(self):
""" Destroy dialog. """
"""Destroy dialog."""
self.dialog.destroy()
def show_all(self):
""" Shows the preferences dialog window. """
"""Shows the preferences dialog window."""
self.dialog.show()
def save_results(self):
""" Pushes the selected settings to the daemon. """
"""Pushes the selected settings to the daemon."""
daemon.SetUseGlobalDNS(self.useGlobalDNSCheckbox.get_active())
# Strip whitespace from DNS entries
for i in [self.dns1Entry, self.dns2Entry, self.dns3Entry,
@@ -328,13 +330,13 @@ class PreferencesDialog(object):
self.notificationscheckbox.get_active()
def set_label(self, glade_str, label):
""" Sets the label for the given widget in wicd.glade. """
"""Sets the label for the given widget in wicd.glade."""
self.wTree.get_object(glade_str).set_label(label)
def prep_settings_diag(self):
""" Set up anything that doesn't have to be persisted later. """
"""Set up anything that doesn't have to be persisted later."""
def build_combobox(lbl):
""" Sets up a ComboBox using the given widget name. """
"""Sets up a ComboBox using the given widget name."""
liststore = gtk.ListStore(gobject.TYPE_STRING)
combobox = self.wTree.get_object(lbl)
combobox.clear()
@@ -345,7 +347,7 @@ class PreferencesDialog(object):
return combobox
def setup_label(name, lbl=""):
""" Sets up a label for the given widget name. """
"""Sets up a label for the given widget name."""
widget = self.wTree.get_object(name)
# if lbl:
# widget.set_label(lbl)
@@ -354,12 +356,18 @@ class PreferencesDialog(object):
return widget
# External Programs tab
# self.wTree.get_object("gen_settings_label").set_label(_('General Settings'))
# self.wTree.get_object("ext_prog_label").set_label(_('External Programs'))
# self.wTree.get_object("dhcp_client_label").set_label(_('DHCP Client'))
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link Detection'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') + ":")
# self.wTree.get_object("gen_settings_label").set_label(_('General '
# 'Settings'))
# self.wTree.get_object("ext_prog_label").set_label(_('External '
# 'Programs'))
# self.wTree.get_object("dhcp_client_label").set_label(_('DHCP '
# 'Client'))
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link '
# 'Detection'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table '
# 'Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') +
# ":")
# entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label")
# entryWiredAutoMethod.set_label('Wired Autoconnect Setting:')
@@ -374,7 +382,8 @@ class PreferencesDialog(object):
# self.set_label("pref_search_dom_label", "%s:" % _('Search domain'))
# self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface'))
# self.set_label("pref_wired_label", "%s:" % _('Wired Interface'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant Driver'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant '
# 'Driver'))
self.dialog = self.wTree.get_object("pref_dialog")
self.dialog.set_title(_('Preferences'))
@@ -384,46 +393,36 @@ class PreferencesDialog(object):
width = 450
self.dialog.resize(width, int(gtk.gdk.screen_height() / 2))
self.wiredcheckbox = setup_label(
"pref_always_check",
_('''Always show wired interface''')
)
self.wiredcheckbox = setup_label("pref_always_check",
_('''Always show wired interface'''))
self.preferwiredcheckbox = setup_label("pref_prefer_wired_check",
"prefer_wired")
self.reconnectcheckbox = setup_label("pref_auto_check",
_('Automatically reconnect on connection loss'))
_('Automatically reconnect on '
'connection loss'))
self.showneverconnectcheckbox = setup_label(
"pref_show_never_connect_check",
_('Show never connect networks')
)
"pref_show_never_connect_check", _('Show never connect networks'))
self.debugmodecheckbox = setup_label("pref_debug_check",
_('Enable debug mode'))
self.displaytypecheckbox = setup_label(
"pref_dbm_check",
_('Use dBm to measure signal strength')
)
"pref_dbm_check", _('Use dBm to measure signal strength'))
self.verifyapcheckbox = setup_label(
"pref_verify_ap_check",
_('Ping static gateways after connecting to verify association')
)
_('Ping static gateways after connecting to verify association'))
self.usedefaultradiobutton = setup_label(
"pref_use_def_radio",
_('Use default profile on wired autoconnect')
)
_('Use default profile on wired autoconnect'))
self.showlistradiobutton = setup_label(
"pref_prompt_radio",
_('Prompt for profile on wired autoconnect')
)
_('Prompt for profile on wired autoconnect'))
self.lastusedradiobutton = setup_label(
"pref_use_last_radio",
_('Use last used profile on wired autoconnect')
)
_('Use last used profile on wired autoconnect'))
self.notificationscheckbox = setup_label(
"pref_use_libnotify",
_('Display notifications about connection status')
)
_('Display notifications about connection status'))
# DHCP Clients
self.dhcpautoradio = setup_label(
@@ -434,8 +433,8 @@ class PreferencesDialog(object):
self.udhcpcradio = self.wTree.get_object("udhcpc_radio")
# Wired Link Detection Apps
self.linkautoradio = setup_label(
"link_auto_radio", _('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio",
_('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio")
self.ethtoolradio = setup_label("ethtool_radio")
self.miitoolradio = setup_label("miitool_radio")
@@ -447,8 +446,8 @@ class PreferencesDialog(object):
self.routeflushradio = setup_label("route_flush_radio")
# Graphical Sudo Apps
self.sudoautoradio = setup_label(
"sudo_auto_radio", _('Automatic (recommended)'))
self.sudoautoradio = setup_label("sudo_auto_radio",
_('Automatic (recommended)'))
self.gksudoradio = setup_label("gksudo_radio")
self.kdesuradio = setup_label("kdesu_radio")
self.ktsussradio = setup_label("ktsuss_radio")
@@ -487,7 +486,6 @@ class PreferencesDialog(object):
self.backendcombo.append_text(x)
def be_combo_changed(self, combo):
""" Update the description label for the given backend. """
"""Update the description label for the given backend."""
self.backendcombo.set_tooltip_text(
self.be_descriptions[self.backends[combo.get_active()]]
)
self.be_descriptions[self.backends[combo.get_active()]])

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env python3
""" wicd - wireless connection daemon frontend implementation
"""wicd - wireless connection daemon frontend implementation
This module implements a usermode frontend for wicd. It updates connection
information, provides an (optional) tray icon, and allows for launching of
@@ -11,7 +10,8 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
and updates connection status.
class TrayIconGUI() -- Child class of TrayIcon which implements the tray.
icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI.
class IndicatorTrayIconGUI() -- Implements the tray icon using appindicator.Indicator.
class IndicatorTrayIconGUI() -- Implements the tray icon using
appindicator.Indicator.
class StatusTrayIconGUI() -- Implements the tray icon using a
gtk.StatusIcon.
class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon.
@@ -37,31 +37,27 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import gtk
from gi.repository import GLib as gobject
import atexit
import getopt
import os
import pango
import atexit
import sys
from dbus import DBusException
import gtk
from gi.repository import GLib as gobject
import pango
import pygtk
pygtk.require('2.0')
USE_APP_INDICATOR = True
try:
import appindicator
except ImportError:
USE_APP_INDICATOR = False
appindicator = None
HAS_NOTIFY = True
try:
import pynotify
if not pynotify.init("Wicd"):
HAS_NOTIFY = False
except ImportError:
HAS_NOTIFY = False
pynotify = None
# Wicd specific imports
from wicd import wpath
@@ -72,6 +68,12 @@ from guiutil import error, can_use_notify
from wicd.translations import _
pygtk.require('2.0')
if pynotify and not pynotify.init("Wicd"):
pynotify = None
ICON_AVAIL = True
USE_EGG = False
# Import egg.trayicon if we're using an older gtk version
@@ -80,8 +82,8 @@ if not hasattr(gtk, "StatusIcon"):
import egg.trayicon
USE_EGG = True
except ImportError:
print(('Unable to load tray icon: Missing both egg.trayicon and ' + \
'gtk.StatusIcon modules.'))
print('Unable to load tray icon: Missing both egg.trayicon and '
'gtk.StatusIcon modules.')
ICON_AVAIL = False
misc.RenameProcess("wicd-client")
@@ -97,21 +99,18 @@ theme.append_search_path(wpath.images)
def catchdbus(func):
""" Decorator to catch DBus exceptions. """
"""Decorator to catch DBus exceptions."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except DBusException as e:
if e.get_dbus_name() is not None and \
"DBus.Error.AccessDenied" in e.get_dbus_name():
error(
None,
_('Unable to contact the Wicd daemon due to an access '
'denied error from DBus. Please check that your user is '
'in the $A group.').
replace("$A", "<b>" + wpath.wicd_group + "</b>")
)
#raise
error(None,
_('Unable to contact the Wicd daemon due to an access '
'denied error from DBus. Please check that your user '
'is in the $A group.').replace("$A", "<b>%s</b>" %
wpath.wicd_group))
raise DBusException(e)
else:
print(("warning: ignoring exception %s" % e))
@@ -124,7 +123,7 @@ def catchdbus(func):
class NetworkMenuItem(gtk.ImageMenuItem):
""" Network menu item. """
"""Network menu item."""
def __init__(self, lbl, is_active=False):
gtk.ImageMenuItem.__init__(self)
self.label = gtk.Label(lbl)
@@ -139,7 +138,7 @@ class NetworkMenuItem(gtk.ImageMenuItem):
class TrayIcon(object):
""" Base Tray Icon class.
"""Base Tray Icon class.
Base Class for implementing a tray icon to display network status.
@@ -152,7 +151,7 @@ class TrayIcon(object):
self.max_snd_gain = 10000
self.max_rcv_gain = 10000
if USE_APP_INDICATOR:
if appindicator:
self.tr = self.IndicatorTrayIconGUI(self)
elif USE_EGG:
self.tr = self.EggTrayIconGUI(self)
@@ -172,7 +171,7 @@ class TrayIcon(object):
return self.tr.is_embedded() # pylint: disable-msg=E1103
def get_bandwidth_bytes(self):
""" Gets the amount of byte sent sine the last time I checked """
"""Gets the amount of byte sent sine the last time I checked"""
dev_dir = '/sys/class/net/'
iface = daemon.GetCurrentInterface()
@@ -191,9 +190,9 @@ class TrayIcon(object):
self.cur_rcvbytes = -1
class TrayConnectionInfo(object):
""" Class for updating the tray icon status. """
"""Class for updating the tray icon status."""
def __init__(self, parent, tr, animate=True):
""" Initialize variables needed for the icon status methods. """
"""Initialize variables needed for the icon status methods."""
self.last_strength = -2
self.still_wired = False
self.network = ''
@@ -237,15 +236,15 @@ class TrayIcon(object):
self.tr.set_tooltip(_('Not connected'))
elif (self.network_type == "wireless"):
self.tr.set_tooltip(_('Connected to $A at $B (IP: $C)')
.replace('$A', self.network_name)
.replace('$B', self.network_str)
.replace('$C', self.network_addr))
.replace('$A', self.network_name)
.replace('$B', self.network_str)
.replace('$C', self.network_addr))
elif (self.network_type == "wired"):
self.tr.set_tooltip(_('Connected to wired network (IP: $A)')
.replace('$A', self.network_addr))
.replace('$A', self.network_addr))
elif (self.network_type == "killswitch"):
self.tr.set_tooltip(_('Not connected') + "(" +
_('Wireless Kill Switch Enabled') + ")")
_('Wireless Kill Switch Enabled') + ")")
elif (self.network_type == "no_daemon"):
self.tr.set_tooltip(_('Wicd daemon unreachable'))
@@ -276,19 +275,19 @@ class TrayIcon(object):
@catchdbus
def wired_profile_chooser(self):
""" Launch the wired profile chooser. """
"""Launch the wired profile chooser."""
gui.WiredProfileChooser()
daemon.SetNeedWiredProfileChooser(False)
def set_wired_state(self, info):
""" Sets the icon info for a wired state. """
"""Sets the icon info for a wired state."""
wired_ip = info[0]
self.network_addr = str(info[0])
self.network_type = "wired"
self.tr.set_from_name('wired')
#status_string = _('Connected to wired network (IP: $A)'). \
# replace('$A',wired_ip)
#self.tr.set_tooltip(status_string)
# status_string = _('Connected to wired network (IP: $A)'). \
# replace('$A',wired_ip)
# self.tr.set_tooltip(status_string)
self._show_notification(_('Wired Network'),
_('Connection established'),
'network-wired')
@@ -297,7 +296,7 @@ class TrayIcon(object):
@catchdbus
def set_wireless_state(self, info):
""" Sets the icon info for a wireless state. """
"""Sets the icon info for a wireless state."""
lock = ''
wireless_ip = info[0]
self.network = info[1]
@@ -313,11 +312,11 @@ class TrayIcon(object):
if wireless.GetWirelessProperty(cur_net_id, "encryption"):
lock = "-lock"
# status_string = (_('Connected to $A at $B (IP: $C)')
#.replace('$A', self.network)
# .replace('$B', sig_string)
# .replace('$C', str(wireless_ip)))
#self.tr.set_tooltip(status_string)
# status_string = (_('Connected to $A at $B (IP: $C)')
# .replace('$A', self.network)
# .replace('$B', sig_string)
# .replace('$C', str(wireless_ip)))
# self.tr.set_tooltip(status_string)
self.set_signal_image(int(strength), lock)
self._show_notification(self.network,
_('Connection established'),
@@ -326,15 +325,14 @@ class TrayIcon(object):
self.update_tooltip()
def set_connecting_state(self, info):
""" Sets the icon info for a connecting state. """
"""Sets the icon info for a connecting state."""
wired = False
if info[0] == 'wired' and len(info) == 1:
cur_network = _('Wired Network')
wired = True
else:
cur_network = info[1]
status_string = _('Connecting') + " to " + \
cur_network + "..."
status_string = _('Connecting') + " to " + cur_network + "..."
self.update_tooltip()
# self.tr.set_tooltip(status_string)
self.tr.set_from_name('no-signal')
@@ -349,13 +347,13 @@ class TrayIcon(object):
@catchdbus
def set_not_connected_state(self, info=None):
""" Set the icon info for the not connected state. """
"""Set the icon info for the not connected state."""
self.tr.set_from_name('no-signal')
if not DBUS_AVAIL:
status = _('Wicd daemon unreachable')
elif wireless.GetKillSwitchEnabled():
status = (_('Not connected') + " (" +
_('Wireless Kill Switch Enabled') + ")")
_('Wireless Kill Switch Enabled') + ")")
else:
status = _('Not connected')
# self.tr.set_tooltip(status)
@@ -364,7 +362,7 @@ class TrayIcon(object):
@catchdbus
def update_tray_icon(self, state=None, info=None):
""" Updates the tray icon and current connection status. """
"""Updates the tray icon and current connection status."""
if not DBUS_AVAIL:
return False
@@ -392,7 +390,7 @@ class TrayIcon(object):
@catchdbus
def set_signal_image(self, wireless_signal, lock):
""" Sets the tray icon image for an active wireless connection. """
"""Sets the tray icon image for an active wireless connection."""
if self.animate:
TrayIcon.get_bandwidth_bytes(self.parent)
prefix = self.get_bandwidth_activity()
@@ -421,7 +419,7 @@ class TrayIcon(object):
@catchdbus
def get_bandwidth_activity(self):
""" Determines what network activity state we are in. """
"""Determines what network activity state we are in."""
transmitting = False
receiving = False
@@ -467,7 +465,7 @@ class TrayIcon(object):
return 'idle-'
def is_network_active(self, bytes, max_gain, last_bytes):
""" Determines if a network is active.
"""Determines if a network is active.
Determines if a network is active by looking at the
number of bytes sent since the previous check. This method
@@ -494,7 +492,7 @@ class TrayIcon(object):
return (active, max_gain, last_bytes)
class TrayIconGUI(object):
""" Base Tray Icon UI class.
"""Base Tray Icon UI class.
Implements methods and variables used by both egg/StatusIcon
tray icons.
@@ -533,12 +531,12 @@ class TrayIcon(object):
self.manager.insert_action_group(actg, 0)
self.manager.add_ui_from_string(menu)
self.menu = (self.manager.get_widget('/Menubar/Menu/Quit').
props.parent)
props.parent)
self.gui_win = None
self.current_icon_name = None
self._is_scanning = False
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
if not USE_APP_INDICATOR:
if not appindicator:
net_menuitem.connect("activate", self.on_net_menu_activate)
self.parent = parent
@@ -547,35 +545,35 @@ class TrayIcon(object):
self.conn_info_txt = ''
def tray_scan_started(self):
""" Callback for when a wireless scan is started. """
"""Callback for when a wireless scan is started."""
if not DBUS_AVAIL:
return
self._is_scanning = True
self.init_network_menu()
def tray_scan_ended(self):
""" Callback for when a wireless scan finishes. """
"""Callback for when a wireless scan finishes."""
if not DBUS_AVAIL:
return
self._is_scanning = False
self.populate_network_menu()
def on_activate(self, data=None):
""" Opens the wicd GUI. """
"""Opens the wicd GUI."""
if DBUS_AVAIL:
self.toggle_wicd_gui()
else:
#error(None,
#_('The wicd daemon is unavailable, so your request '
# 'cannot be completed'))
# error(None,
# _('The wicd daemon is unavailable, so your request '
# 'cannot be completed'))
pass
def on_quit(self, widget=None):
""" Closes the tray icon. """
"""Closes the tray icon."""
sys.exit(0)
def on_about(self, data=None):
""" Opens the About Dialog. """
"""Opens the About Dialog."""
dialog = gtk.AboutDialog()
dialog.set_name('Wicd Tray Icon')
dialog.set_version('2.0')
@@ -585,7 +583,7 @@ class TrayIcon(object):
dialog.destroy()
def on_conn_info(self, data=None):
""" Opens the Connection Information Dialog """
"""Opens the Connection Information Dialog"""
window = gtk.Dialog(
"Wicd Connection Info",
None,
@@ -625,8 +623,8 @@ class TrayIcon(object):
window.destroy()
self.cont = 'Stop'
def update_conn_info_win(self, l):
""" Updates the information in the connection summary window """
def update_conn_info_win(self, *args):
"""Updates the information in the connection summary window"""
if (self.cont == "Stop"):
return False
@@ -635,24 +633,17 @@ class TrayIcon(object):
# Choose info for the data
if state == misc.WIRED:
text = (_('''$A
$B KB/s
$C KB/s''')
text = (_("$A\n$B KB/s\n$C KB/s")
.replace('$A', str(info[0])) # IP
.replace('$B', str(rx)) # RX
.replace('$C', str(tx))) # TX
elif state == misc.WIRELESS:
text = (_('''$A
$B
$C
$D
$E KB/s
$F KB/s''')
text = (_("$A\n$B\n$C\n$D\n$E KB/s\n$F KB/s")
.replace('$A', str(info[1])) # SSID
.replace('$B', str(info[4])) # Speed
.replace('$C', str(info[0])) # IP
.replace('$D',
daemon.FormatSignalForPrinting(str(info[2])))
daemon.FormatSignalForPrinting(str(info[2])))
.replace('$E', str(rx))
.replace('$F', str(tx)))
else:
@@ -661,18 +652,10 @@ $F KB/s''')
# Choose info for the labels
self.list[0].set_text('\n' + text)
if state == misc.WIRED:
self.list[1].set_text(_('''Wired
IP:
RX:
TX:'''))
self.list[1].set_text(_("Wired\nIP:\nRX:\nTX:"))
elif state == misc.WIRELESS:
self.list[1].set_text(_('''Wireless
SSID:
Speed:
IP:
Strength:
RX:
TX:'''))
self.list[1].set_text(_("Wireless\nSSID:\nSpeed:\nIP:\n"
"Strength:\nRX:\nTX:"))
elif state == misc.CONNECTING:
self.list[1].set_text(_('Connecting'))
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
@@ -699,9 +682,9 @@ TX:'''))
def _add_item_to_menu(self, net_menu, lbl, type_, n_id, is_connecting,
is_active):
""" Add an item to the network list submenu. """
"""Add an item to the network list submenu."""
def network_selected(widget, net_type, net_id):
""" Callback method for a menu item selection. """
"""Callback method for a menu item selection."""
if net_type == "__wired__":
wired.ConnectWired()
else:
@@ -712,10 +695,10 @@ TX:'''))
if type_ == "__wired__":
image.set_from_icon_name("network-wired",
gtk.ICON_SIZE_SMALL_TOOLBAR)
gtk.ICON_SIZE_SMALL_TOOLBAR)
else:
image.set_from_icon_name(self._get_img(n_id),
gtk.ICON_SIZE_SMALL_TOOLBAR)
gtk.ICON_SIZE_SMALL_TOOLBAR)
item.set_image(image)
del image
item.connect("activate", network_selected, type_, n_id)
@@ -727,9 +710,9 @@ TX:'''))
@catchdbus
def _get_img(self, net_id):
""" Determines which image to use for the wireless entries. """
"""Determines which image to use for the wireless entries."""
def fix_strength(val, default):
""" Assigns given strength to a default value if needed. """
"""Assigns given strength to a default value if needed."""
return val and int(val) or default
def get_prop(prop):
@@ -761,7 +744,7 @@ TX:'''))
@catchdbus
def on_net_menu_activate(self, item):
""" Trigger a background scan to populate the network menu.
"""Trigger a background scan to populate the network menu.
Called when the network submenu is moused over. We
sleep briefly, clear pending gtk events, and if
@@ -781,7 +764,7 @@ TX:'''))
@catchdbus
def _trigger_scan_if_needed(self, item):
""" Trigger a scan if the network menu is being hovered over. """
"""Trigger a scan if the network menu is being hovered over."""
while gtk.events_pending():
gtk.main_iteration()
if item.state != gtk.STATE_PRELIGHT:
@@ -791,7 +774,7 @@ TX:'''))
@catchdbus
def populate_network_menu(self, data=None):
""" Populates the network list submenu. """
"""Populates the network list submenu."""
def get_prop(net_id, prop):
return wireless.GetWirelessProperty(net_id, prop)
@@ -812,8 +795,8 @@ TX:'''))
is_active = True
else:
is_active = False
self._add_item_to_menu(submenu, "Wired Network", "__wired__", 0,
is_connecting, is_active)
self._add_item_to_menu(submenu, "Wired Network", "__wired__",
0, is_connecting, is_active)
sep = gtk.SeparatorMenuItem()
submenu.append(sep)
sep.show()
@@ -821,8 +804,8 @@ TX:'''))
if num_networks > 0:
skip_never_connect = not daemon.GetShowNeverConnect()
for x in range(0, num_networks):
if skip_never_connect and \
misc.to_bool(get_prop(x,"never")):
if (skip_never_connect and
misc.to_bool(get_prop(x, "never"))):
continue
essid = get_prop(x, "essid")
if status == misc.WIRELESS and info[1] == essid:
@@ -841,7 +824,7 @@ TX:'''))
net_menuitem.show()
def init_network_menu(self):
""" Set the right-click network menu to the scanning state. """
"""Set the right-click network menu to the scanning state."""
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
submenu = net_menuitem.get_submenu()
self._clear_menu(submenu)
@@ -853,13 +836,13 @@ TX:'''))
net_menuitem.show()
def _clear_menu(self, menu):
""" Clear the right-click menu. """
"""Clear the right-click menu."""
for item in menu.get_children():
menu.remove(item)
item.destroy()
def toggle_wicd_gui(self):
""" Toggles the wicd GUI. """
"""Toggles the wicd GUI."""
if not self.gui_win:
self.gui_win = gui.appGui(tray=self)
elif not self.gui_win.is_visible:
@@ -870,7 +853,7 @@ TX:'''))
if USE_EGG:
class EggTrayIconGUI(TrayIconGUI):
""" Tray Icon for gtk < 2.10.
"""Tray Icon for gtk < 2.10.
Uses the deprecated egg.trayicon module to implement the tray icon.
Since it relies on a deprecated module, this class is only used
@@ -893,7 +876,7 @@ TX:'''))
self.tray.show_all()
def tray_clicked(self, widget, event):
""" Handles tray mouse click events. """
"""Handles tray mouse click events."""
if event.button == 1:
self.toggle_wicd_gui()
elif event.button == 3:
@@ -901,7 +884,7 @@ TX:'''))
self.menu.popup(None, None, None, event.button, event.time)
def set_from_file(self, val=None):
""" Calls set_from_file on the gtk.Image for the tray icon. """
"""Calls set_from_file on the gtk.Image for the tray icon."""
self.pic.set_from_file(
os.path.join(
wpath.images, 'hicolor/22x22/status/%s.png' % val
@@ -909,7 +892,7 @@ TX:'''))
)
def set_tooltip(self, val):
""" Set the tooltip for this tray icon.
"""Set the tooltip for this tray icon.
Sets the tooltip for the gtk.ToolTips associated with this
tray icon.
@@ -918,7 +901,7 @@ TX:'''))
self.tooltip.set_tip(self.eb, val)
def visible(self, val):
""" Set if the icon is visible or not.
"""Set if the icon is visible or not.
If val is True, makes the icon visible, if val is False,
hides the tray icon.
@@ -931,7 +914,7 @@ TX:'''))
if hasattr(gtk, "StatusIcon"):
class StatusTrayIconGUI(gtk.StatusIcon, TrayIconGUI):
""" Class for creating the wicd tray icon on gtk > 2.10.
"""Class for creating the wicd tray icon on gtk > 2.10.
Uses gtk.StatusIcon to implement a tray icon.
@@ -948,19 +931,19 @@ TX:'''))
self.set_tooltip("Initializing wicd...")
def on_popup_menu(self, status, button, timestamp):
""" Opens the right click menu for the tray icon. """
"""Opens the right click menu for the tray icon."""
self.init_network_menu()
self.menu.popup(None, None, gtk.status_icon_position_menu,
button, timestamp, self)
button, timestamp, self)
def set_from_name(self, name=None):
""" Sets a new tray icon picture. """
"""Sets a new tray icon picture."""
if name != self.current_icon_name:
self.current_icon_name = name
gtk.StatusIcon.set_from_icon_name(self, name)
def visible(self, val):
""" Set if the icon is visible or not.
"""Set if the icon is visible or not.
If val is True, makes the icon visible, if val is False,
hides the tray icon.
@@ -968,18 +951,20 @@ TX:'''))
"""
self.set_visible(val)
if USE_APP_INDICATOR:
if appindicator:
class IndicatorTrayIconGUI(gtk.StatusIcon, TrayIconGUI):
""" Class for creating the wicd AppIndicator.
"""Class for creating the wicd AppIndicator.
This is required on recent versions of Unity (>=13.04).
Uses appindicator.Indicator to implement a tray icon.
"""
def __init__(self, parent):
TrayIcon.TrayIconGUI.__init__(self, parent)
self.ind = appindicator.Indicator(
"wicd", "wicd-gtk", appindicator.CATEGORY_SYSTEM_SERVICES, wpath.images)
self.ind = appindicator.Indicator("wicd", "wicd-gtk",
appindicator.
CATEGORY_SYSTEM_SERVICES,
wpath.images)
self.current_icon_name = ''
# Rescaning when hovering over the net_menu doesn't work.
@@ -1008,34 +993,37 @@ TX:'''))
self.ind.set_menu(self.menu)
def on_rescan(self, *data):
""" Triggers a network rescan that updates the 'Connect' menu when the 'Rescan' menu item is selected. """
"""Triggers a network rescan that updates the 'Connect' menu
when the 'Rescan' menu item is selected.
"""
self.init_network_menu()
wireless.Scan(False)
def set_from_file(self, path=None):
""" Sets a new tray icon picture. """
"""Sets a new tray icon picture."""
if path != self.current_icon_path:
self.current_icon_path = path
self.ind.set_icon(path)
def set_from_name(self, name=None):
""" Sets a new tray icon picture. """
"""Sets a new tray icon picture."""
if name != self.current_icon_name:
self.current_icon_name = name
self.ind.set_icon(name)
def visible(self, val):
""" Set if the icon is visible or not.
"""Set if the icon is visible or not.
If val is True, makes the icon visible, if val is False,
hides the tray icon.
"""
self.ind.set_status(val and appindicator.STATUS_ACTIVE or appindicator.STATUS_PASSIVE)
self.ind.set_status(val and appindicator.STATUS_ACTIVE or
appindicator.STATUS_PASSIVE)
def set_tooltip(self, str):
""" Set the tooltip for this tray icon.
"""Set the tooltip for this tray icon.
Since AppIndicators do not support tooltips, actually
sets the label for the top menu item associated with
this tray icon.
@@ -1045,8 +1033,8 @@ TX:'''))
def usage():
""" Print usage information. """
print(("""
"""Print usage information."""
print("""
wicd %s
wireless (and wired) connection daemon front-end.
@@ -1056,27 +1044,25 @@ Arguments:
\t-h\t--help\t\tPrint this help information.
\t-a\t--no-animate\tRun the tray without network traffic tray animations.
\t-o\t--only-notifications\tDon't display anything except notifications.
""" % wpath.version))
""" % wpath.version)
def setup_dbus(force=True):
""" Initialize DBus. """
"""Initialize DBus."""
global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id
print("Connecting to daemon...")
try:
dbusmanager.connect_to_dbus()
except DBusException:
if force:
print(("Can't connect to the daemon, trying to start it " + \
"automatically..."))
print("Can't connect to the daemon, trying to start it "
"automatically...")
misc.PromptToStartDaemon()
try:
dbusmanager.connect_to_dbus()
except DBusException:
error(None,
_("Could not connect to wicd's D-Bus interface. Check "
"the wicd log for error messages.")
)
error(None, _("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages."))
return False
else:
return False
@@ -1094,7 +1080,7 @@ def setup_dbus(force=True):
def on_exit():
""" Handle GUI exit. """
"""Handle GUI exit."""
if DBUS_AVAIL:
try:
daemon.SetGUIOpen(False)
@@ -1103,24 +1089,21 @@ def on_exit():
def handle_no_dbus():
""" Called when dbus announces its shutting down. """
"""Called when dbus announces its shutting down."""
global DBUS_AVAIL, lost_dbus_id
DBUS_AVAIL = False
gui.handle_no_dbus(from_tray=True)
print("Wicd daemon is shutting down!")
lost_dbus_id = misc.timeout_add(5,
lambda: error(None,
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
)
err_msg = _('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.')
lost_dbus_id = misc.timeout_add(5, lambda: error(None, err_msg,
block=False))
return False
@catchdbus
def main(argv):
""" The main frontend program.
"""The main frontend program.
Keyword arguments:
argv -- The arguments passed to the script.